"
+ ]
+ },
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "Enter to start fit\n"
+ ]
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ "\n",
+ " \n",
+ " \n",
+ " FCN = 647820214.703428 \n",
+ " TOTAL NCALL = 331 \n",
+ " NCALLS = 331 \n",
+ " \n",
+ " \n",
+ " EDM = 8.820816855092605 \n",
+ " GOAL EDM = 1e-05 \n",
+ " \n",
+ " UP = 1.0 \n",
+ " \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " Valid \n",
+ " Valid Param \n",
+ " Accurate Covar \n",
+ " PosDef \n",
+ " Made PosDef \n",
+ " \n",
+ " \n",
+ " False \n",
+ " True \n",
+ " True \n",
+ " True \n",
+ " False \n",
+ " \n",
+ " \n",
+ " Hesse Fail \n",
+ " HasCov \n",
+ " Above EDM \n",
+ " \n",
+ " Reach calllim \n",
+ " \n",
+ " \n",
+ " False \n",
+ " True \n",
+ " True \n",
+ " \n",
+ " False \n",
+ " \n",
+ "
\n",
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ "\n",
+ " \n",
+ " \n",
+ " + \n",
+ " Name \n",
+ " Value \n",
+ " Parab Error \n",
+ " Minos Error- \n",
+ " Minos Error+ \n",
+ " Limit- \n",
+ " Limit+ \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 1 \n",
+ " intensity \n",
+ " 0.11346 \n",
+ " 1.91572e-06 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 2 \n",
+ " igauss1cen \n",
+ " 512 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 3 \n",
+ " igauss1sig \n",
+ " 4000 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 4 \n",
+ " iblur1 \n",
+ " 4.617 \n",
+ " 0.00037373 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.0 \n",
+ " 20.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 5 \n",
+ " scalex \n",
+ " 0.6 \n",
+ " 0.05 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.4 \n",
+ " 1.2 \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 6 \n",
+ " scaley \n",
+ " 1 \n",
+ " 0.05 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.8 \n",
+ " 1.2 \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 7 \n",
+ " rotation \n",
+ " 0.01 \n",
+ " 0.005 \n",
+ " 0 \n",
+ " 0 \n",
+ " -0.06 \n",
+ " 0.06 \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 8 \n",
+ " transx \n",
+ " 120.793 \n",
+ " 0.000220781 \n",
+ " 0 \n",
+ " 0 \n",
+ " -400.0 \n",
+ " 400.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 9 \n",
+ " transy \n",
+ " -3.33798 \n",
+ " 0.000126792 \n",
+ " 0 \n",
+ " 0 \n",
+ " -50.0 \n",
+ " 50.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 10 \n",
+ " shear \n",
+ " 0.01 \n",
+ " 0.001 \n",
+ " 0 \n",
+ " 0 \n",
+ " -0.2 \n",
+ " 0.2 \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 11 \n",
+ " igauss2cen \n",
+ " 512 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 12 \n",
+ " igauss2sig \n",
+ " 4000 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ "\n",
+ " \n",
+ " \n",
+ " FCN = 366891588.18902636 \n",
+ " TOTAL NCALL = 1466 \n",
+ " NCALLS = 1466 \n",
+ " \n",
+ " \n",
+ " EDM = 5.111809229073948 \n",
+ " GOAL EDM = 1e-05 \n",
+ " \n",
+ " UP = 1.0 \n",
+ " \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " Valid \n",
+ " Valid Param \n",
+ " Accurate Covar \n",
+ " PosDef \n",
+ " Made PosDef \n",
+ " \n",
+ " \n",
+ " False \n",
+ " True \n",
+ " False \n",
+ " False \n",
+ " True \n",
+ " \n",
+ " \n",
+ " Hesse Fail \n",
+ " HasCov \n",
+ " Above EDM \n",
+ " \n",
+ " Reach calllim \n",
+ " \n",
+ " \n",
+ " False \n",
+ " True \n",
+ " True \n",
+ " \n",
+ " False \n",
+ " \n",
+ "
\n",
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ "\n",
+ " \n",
+ " \n",
+ " + \n",
+ " Name \n",
+ " Value \n",
+ " Parab Error \n",
+ " Minos Error- \n",
+ " Minos Error+ \n",
+ " Limit- \n",
+ " Limit+ \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 1 \n",
+ " intensity \n",
+ " 0.107823 \n",
+ " 1.62851e-06 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 2 \n",
+ " igauss1cen \n",
+ " 512 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 3 \n",
+ " igauss1sig \n",
+ " 4000 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 4 \n",
+ " iblur1 \n",
+ " 1.73655 \n",
+ " 0.000144802 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.0 \n",
+ " 20.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 5 \n",
+ " scalex \n",
+ " 0.633168 \n",
+ " 9.92501e-07 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.4 \n",
+ " 1.2 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 6 \n",
+ " scaley \n",
+ " 1.02911 \n",
+ " 5.15605e-06 \n",
+ " 0 \n",
+ " 0 \n",
+ " 0.8 \n",
+ " 1.2 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 7 \n",
+ " rotation \n",
+ " -0.0123541 \n",
+ " 1.75243e-06 \n",
+ " 0 \n",
+ " 0 \n",
+ " -0.06 \n",
+ " 0.06 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 8 \n",
+ " transx \n",
+ " 98.5647 \n",
+ " 0.000776996 \n",
+ " 0 \n",
+ " 0 \n",
+ " -400.0 \n",
+ " 400.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 9 \n",
+ " transy \n",
+ " 4.06022 \n",
+ " 0.000310021 \n",
+ " 0 \n",
+ " 0 \n",
+ " -50.0 \n",
+ " 50.0 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 10 \n",
+ " shear \n",
+ " -0.00541015 \n",
+ " 2.00018e-05 \n",
+ " 0 \n",
+ " 0 \n",
+ " -0.2 \n",
+ " 0.2 \n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " 11 \n",
+ " igauss2cen \n",
+ " 512 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ " \n",
+ " 12 \n",
+ " igauss2sig \n",
+ " 4000 \n",
+ " 2 \n",
+ " 0 \n",
+ " 0 \n",
+ " \n",
+ " \n",
+ " FIXED \n",
+ " \n",
+ " \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " \n",
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "javascript": [
+ "/* Put everything inside the global mpl namespace */\n",
+ "window.mpl = {};\n",
+ "\n",
+ "mpl.get_websocket_type = function() {\n",
+ " if (typeof(WebSocket) !== 'undefined') {\n",
+ " return WebSocket;\n",
+ " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
+ " return MozWebSocket;\n",
+ " } else {\n",
+ " alert('Your browser does not have WebSocket support.' +\n",
+ " 'Please try Chrome, Safari or Firefox \u2265 6. ' +\n",
+ " 'Firefox 4 and 5 are also supported but you ' +\n",
+ " 'have to enable WebSockets in about:config.');\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
+ " this.id = figure_id;\n",
+ "\n",
+ " this.ws = websocket;\n",
+ "\n",
+ " this.supports_binary = (this.ws.binaryType != undefined);\n",
+ "\n",
+ " if (!this.supports_binary) {\n",
+ " var warnings = document.getElementById(\"mpl-warnings\");\n",
+ " if (warnings) {\n",
+ " warnings.style.display = 'block';\n",
+ " warnings.textContent = (\n",
+ " \"This browser does not support binary websocket messages. \" +\n",
+ " \"Performance may be slow.\");\n",
+ " }\n",
+ " }\n",
+ "\n",
+ " this.imageObj = new Image();\n",
+ "\n",
+ " this.context = undefined;\n",
+ " this.message = undefined;\n",
+ " this.canvas = undefined;\n",
+ " this.rubberband_canvas = undefined;\n",
+ " this.rubberband_context = undefined;\n",
+ " this.format_dropdown = undefined;\n",
+ "\n",
+ " this.image_mode = 'full';\n",
+ "\n",
+ " this.root = $('
');\n",
+ " this._root_extra_style(this.root)\n",
+ " this.root.attr('style', 'display: inline-block');\n",
+ "\n",
+ " $(parent_element).append(this.root);\n",
+ "\n",
+ " this._init_header(this);\n",
+ " this._init_canvas(this);\n",
+ " this._init_toolbar(this);\n",
+ "\n",
+ " var fig = this;\n",
+ "\n",
+ " this.waiting = false;\n",
+ "\n",
+ " this.ws.onopen = function () {\n",
+ " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
+ " fig.send_message(\"send_image_mode\", {});\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " }\n",
+ "\n",
+ " this.imageObj.onload = function() {\n",
+ " if (fig.image_mode == 'full') {\n",
+ " // Full images could contain transparency (where diff images\n",
+ " // almost always do), so we need to clear the canvas so that\n",
+ " // there is no ghosting.\n",
+ " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
+ " }\n",
+ " fig.context.drawImage(fig.imageObj, 0, 0);\n",
+ " };\n",
+ "\n",
+ " this.imageObj.onunload = function() {\n",
+ " this.ws.close();\n",
+ " }\n",
+ "\n",
+ " this.ws.onmessage = this._make_on_message_function(this);\n",
+ "\n",
+ " this.ondownload = ondownload;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_header = function() {\n",
+ " var titlebar = $(\n",
+ " '
');\n",
+ " var titletext = $(\n",
+ " '
');\n",
+ " titlebar.append(titletext)\n",
+ " this.root.append(titlebar);\n",
+ " this.header = titletext[0];\n",
+ "}\n",
+ "\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_canvas = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var canvas_div = $('
');\n",
+ "\n",
+ " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
+ "\n",
+ " function canvas_keyboard_event(event) {\n",
+ " return fig.key_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
+ " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
+ " this.canvas_div = canvas_div\n",
+ " this._canvas_extra_style(canvas_div)\n",
+ " this.root.append(canvas_div);\n",
+ "\n",
+ " var canvas = $(' ');\n",
+ " canvas.addClass('mpl-canvas');\n",
+ " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
+ "\n",
+ " this.canvas = canvas[0];\n",
+ " this.context = canvas[0].getContext(\"2d\");\n",
+ "\n",
+ " var rubberband = $(' ');\n",
+ " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
+ "\n",
+ " var pass_mouse_events = true;\n",
+ "\n",
+ " canvas_div.resizable({\n",
+ " start: function(event, ui) {\n",
+ " pass_mouse_events = false;\n",
+ " },\n",
+ " resize: function(event, ui) {\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " stop: function(event, ui) {\n",
+ " pass_mouse_events = true;\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " });\n",
+ "\n",
+ " function mouse_event_fn(event) {\n",
+ " if (pass_mouse_events)\n",
+ " return fig.mouse_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " rubberband.mousedown('button_press', mouse_event_fn);\n",
+ " rubberband.mouseup('button_release', mouse_event_fn);\n",
+ " // Throttle sequential mouse events to 1 every 20ms.\n",
+ " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
+ "\n",
+ " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
+ " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
+ "\n",
+ " canvas_div.on(\"wheel\", function (event) {\n",
+ " event = event.originalEvent;\n",
+ " event['data'] = 'scroll'\n",
+ " if (event.deltaY < 0) {\n",
+ " event.step = 1;\n",
+ " } else {\n",
+ " event.step = -1;\n",
+ " }\n",
+ " mouse_event_fn(event);\n",
+ " });\n",
+ "\n",
+ " canvas_div.append(canvas);\n",
+ " canvas_div.append(rubberband);\n",
+ "\n",
+ " this.rubberband = rubberband;\n",
+ " this.rubberband_canvas = rubberband[0];\n",
+ " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
+ " this.rubberband_context.strokeStyle = \"#000000\";\n",
+ "\n",
+ " this._resize_canvas = function(width, height) {\n",
+ " // Keep the size of the canvas, canvas container, and rubber band\n",
+ " // canvas in synch.\n",
+ " canvas_div.css('width', width)\n",
+ " canvas_div.css('height', height)\n",
+ "\n",
+ " canvas.attr('width', width);\n",
+ " canvas.attr('height', height);\n",
+ "\n",
+ " rubberband.attr('width', width);\n",
+ " rubberband.attr('height', height);\n",
+ " }\n",
+ "\n",
+ " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
+ " // upon first draw.\n",
+ " this._resize_canvas(600, 600);\n",
+ "\n",
+ " // Disable right mouse context menu.\n",
+ " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
+ " return false;\n",
+ " });\n",
+ "\n",
+ " function set_focus () {\n",
+ " canvas.focus();\n",
+ " canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " window.setTimeout(set_focus, 100);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items) {\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) {\n",
+ " // put a spacer in here.\n",
+ " continue;\n",
+ " }\n",
+ " var button = $(' ');\n",
+ " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
+ " 'ui-button-icon-only');\n",
+ " button.attr('role', 'button');\n",
+ " button.attr('aria-disabled', 'false');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ "\n",
+ " var icon_img = $(' ');\n",
+ " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
+ " icon_img.addClass(image);\n",
+ " icon_img.addClass('ui-corner-all');\n",
+ "\n",
+ " var tooltip_span = $(' ');\n",
+ " tooltip_span.addClass('ui-button-text');\n",
+ " tooltip_span.html(tooltip);\n",
+ "\n",
+ " button.append(icon_img);\n",
+ " button.append(tooltip_span);\n",
+ "\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " var fmt_picker_span = $(' ');\n",
+ "\n",
+ " var fmt_picker = $(' ');\n",
+ " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
+ " fmt_picker_span.append(fmt_picker);\n",
+ " nav_element.append(fmt_picker_span);\n",
+ " this.format_dropdown = fmt_picker[0];\n",
+ "\n",
+ " for (var ind in mpl.extensions) {\n",
+ " var fmt = mpl.extensions[ind];\n",
+ " var option = $(\n",
+ " ' ', {selected: fmt === mpl.default_extension}).html(fmt);\n",
+ " fmt_picker.append(option)\n",
+ " }\n",
+ "\n",
+ " // Add hover states to the ui-buttons\n",
+ " $( \".ui-button\" ).hover(\n",
+ " function() { $(this).addClass(\"ui-state-hover\");},\n",
+ " function() { $(this).removeClass(\"ui-state-hover\");}\n",
+ " );\n",
+ "\n",
+ " var status_bar = $('');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
+ " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
+ " // which will in turn request a refresh of the image.\n",
+ " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_message = function(type, properties) {\n",
+ " properties['type'] = type;\n",
+ " properties['figure_id'] = this.id;\n",
+ " this.ws.send(JSON.stringify(properties));\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_draw_message = function() {\n",
+ " if (!this.waiting) {\n",
+ " this.waiting = true;\n",
+ " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " var format_dropdown = fig.format_dropdown;\n",
+ " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
+ " fig.ondownload(fig, format);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
+ " var size = msg['size'];\n",
+ " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
+ " fig._resize_canvas(size[0], size[1]);\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
+ " var x0 = msg['x0'];\n",
+ " var y0 = fig.canvas.height - msg['y0'];\n",
+ " var x1 = msg['x1'];\n",
+ " var y1 = fig.canvas.height - msg['y1'];\n",
+ " x0 = Math.floor(x0) + 0.5;\n",
+ " y0 = Math.floor(y0) + 0.5;\n",
+ " x1 = Math.floor(x1) + 0.5;\n",
+ " y1 = Math.floor(y1) + 0.5;\n",
+ " var min_x = Math.min(x0, x1);\n",
+ " var min_y = Math.min(y0, y1);\n",
+ " var width = Math.abs(x1 - x0);\n",
+ " var height = Math.abs(y1 - y0);\n",
+ "\n",
+ " fig.rubberband_context.clearRect(\n",
+ " 0, 0, fig.canvas.width, fig.canvas.height);\n",
+ "\n",
+ " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
+ " // Updates the figure title.\n",
+ " fig.header.textContent = msg['label'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
+ " var cursor = msg['cursor'];\n",
+ " switch(cursor)\n",
+ " {\n",
+ " case 0:\n",
+ " cursor = 'pointer';\n",
+ " break;\n",
+ " case 1:\n",
+ " cursor = 'default';\n",
+ " break;\n",
+ " case 2:\n",
+ " cursor = 'crosshair';\n",
+ " break;\n",
+ " case 3:\n",
+ " cursor = 'move';\n",
+ " break;\n",
+ " }\n",
+ " fig.rubberband_canvas.style.cursor = cursor;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
+ " fig.message.textContent = msg['message'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
+ " // Request the server to send over a new figure.\n",
+ " fig.send_draw_message();\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
+ " fig.image_mode = msg['mode'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Called whenever the canvas gets updated.\n",
+ " this.send_message(\"ack\", {});\n",
+ "}\n",
+ "\n",
+ "// A function to construct a web socket function for onmessage handling.\n",
+ "// Called in the figure constructor.\n",
+ "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
+ " return function socket_on_message(evt) {\n",
+ " if (evt.data instanceof Blob) {\n",
+ " /* FIXME: We get \"Resource interpreted as Image but\n",
+ " * transferred with MIME type text/plain:\" errors on\n",
+ " * Chrome. But how to set the MIME type? It doesn't seem\n",
+ " * to be part of the websocket stream */\n",
+ " evt.data.type = \"image/png\";\n",
+ "\n",
+ " /* Free the memory for the previous frames */\n",
+ " if (fig.imageObj.src) {\n",
+ " (window.URL || window.webkitURL).revokeObjectURL(\n",
+ " fig.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
+ " evt.data);\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
+ " fig.imageObj.src = evt.data;\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var msg = JSON.parse(evt.data);\n",
+ " var msg_type = msg['type'];\n",
+ "\n",
+ " // Call the \"handle_{type}\" callback, which takes\n",
+ " // the figure and JSON message as its only arguments.\n",
+ " try {\n",
+ " var callback = fig[\"handle_\" + msg_type];\n",
+ " } catch (e) {\n",
+ " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " if (callback) {\n",
+ " try {\n",
+ " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
+ " callback(fig, msg);\n",
+ " } catch (e) {\n",
+ " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
+ " }\n",
+ " }\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
+ "mpl.findpos = function(e) {\n",
+ " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
+ " var targ;\n",
+ " if (!e)\n",
+ " e = window.event;\n",
+ " if (e.target)\n",
+ " targ = e.target;\n",
+ " else if (e.srcElement)\n",
+ " targ = e.srcElement;\n",
+ " if (targ.nodeType == 3) // defeat Safari bug\n",
+ " targ = targ.parentNode;\n",
+ "\n",
+ " // jQuery normalizes the pageX and pageY\n",
+ " // pageX,Y are the mouse positions relative to the document\n",
+ " // offset() returns the position of the element relative to the document\n",
+ " var x = e.pageX - $(targ).offset().left;\n",
+ " var y = e.pageY - $(targ).offset().top;\n",
+ "\n",
+ " return {\"x\": x, \"y\": y};\n",
+ "};\n",
+ "\n",
+ "/*\n",
+ " * return a copy of an object with only non-object keys\n",
+ " * we need this to avoid circular references\n",
+ " * http://stackoverflow.com/a/24161582/3208463\n",
+ " */\n",
+ "function simpleKeys (original) {\n",
+ " return Object.keys(original).reduce(function (obj, key) {\n",
+ " if (typeof original[key] !== 'object')\n",
+ " obj[key] = original[key]\n",
+ " return obj;\n",
+ " }, {});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.mouse_event = function(event, name) {\n",
+ " var canvas_pos = mpl.findpos(event)\n",
+ "\n",
+ " if (name === 'button_press')\n",
+ " {\n",
+ " this.canvas.focus();\n",
+ " this.canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " var x = canvas_pos.x;\n",
+ " var y = canvas_pos.y;\n",
+ "\n",
+ " this.send_message(name, {x: x, y: y, button: event.button,\n",
+ " step: event.step,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ "\n",
+ " /* This prevents the web browser from automatically changing to\n",
+ " * the text insertion cursor when the button is pressed. We want\n",
+ " * to control all of the cursor setting manually through the\n",
+ " * 'cursor' event from matplotlib */\n",
+ " event.preventDefault();\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " // Handle any extra behaviour associated with a key event\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.key_event = function(event, name) {\n",
+ "\n",
+ " // Prevent repeat events\n",
+ " if (name == 'key_press')\n",
+ " {\n",
+ " if (event.which === this._key)\n",
+ " return;\n",
+ " else\n",
+ " this._key = event.which;\n",
+ " }\n",
+ " if (name == 'key_release')\n",
+ " this._key = null;\n",
+ "\n",
+ " var value = '';\n",
+ " if (event.ctrlKey && event.which != 17)\n",
+ " value += \"ctrl+\";\n",
+ " if (event.altKey && event.which != 18)\n",
+ " value += \"alt+\";\n",
+ " if (event.shiftKey && event.which != 16)\n",
+ " value += \"shift+\";\n",
+ "\n",
+ " value += 'k';\n",
+ " value += event.which.toString();\n",
+ "\n",
+ " this._key_event_extra(event, name);\n",
+ "\n",
+ " this.send_message(name, {key: value,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
+ " if (name == 'download') {\n",
+ " this.handle_save(this, null);\n",
+ " } else {\n",
+ " this.send_message(\"toolbar_button\", {name: name});\n",
+ " }\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
+ " this.message.textContent = tooltip;\n",
+ "};\n",
+ "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
+ "\n",
+ "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
+ "\n",
+ "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
+ " // Create a \"websocket\"-like object which calls the given IPython comm\n",
+ " // object with the appropriate methods. Currently this is a non binary\n",
+ " // socket, so there is still some room for performance tuning.\n",
+ " var ws = {};\n",
+ "\n",
+ " ws.close = function() {\n",
+ " comm.close()\n",
+ " };\n",
+ " ws.send = function(m) {\n",
+ " //console.log('sending', m);\n",
+ " comm.send(m);\n",
+ " };\n",
+ " // Register the callback with on_msg.\n",
+ " comm.on_msg(function(msg) {\n",
+ " //console.log('receiving', msg['content']['data'], msg);\n",
+ " // Pass the mpl event to the overriden (by mpl) onmessage function.\n",
+ " ws.onmessage(msg['content']['data'])\n",
+ " });\n",
+ " return ws;\n",
+ "}\n",
+ "\n",
+ "mpl.mpl_figure_comm = function(comm, msg) {\n",
+ " // This is the function which gets called when the mpl process\n",
+ " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
+ "\n",
+ " var id = msg.content.data.id;\n",
+ " // Get hold of the div created by the display call when the Comm\n",
+ " // socket was opened in Python.\n",
+ " var element = $(\"#\" + id);\n",
+ " var ws_proxy = comm_websocket_adapter(comm)\n",
+ "\n",
+ " function ondownload(figure, format) {\n",
+ " window.open(figure.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " var fig = new mpl.figure(id, ws_proxy,\n",
+ " ondownload,\n",
+ " element.get(0));\n",
+ "\n",
+ " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
+ " // web socket which is closed, not our websocket->open comm proxy.\n",
+ " ws_proxy.onopen();\n",
+ "\n",
+ " fig.parent_element = element.get(0);\n",
+ " fig.cell_info = mpl.find_output_cell(\"
\");\n",
+ " if (!fig.cell_info) {\n",
+ " console.error(\"Failed to find cell for figure\", id, fig);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var output_index = fig.cell_info[2]\n",
+ " var cell = fig.cell_info[0];\n",
+ "\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
+ " fig.root.unbind('remove')\n",
+ "\n",
+ " // Update the output cell to use the data from the current canvas.\n",
+ " fig.push_to_output();\n",
+ " var dataURL = fig.canvas.toDataURL();\n",
+ " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
+ " // the notebook keyboard shortcuts fail.\n",
+ " IPython.keyboard_manager.enable()\n",
+ " $(fig.parent_element).html(' ');\n",
+ " fig.close_ws(fig, msg);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.close_ws = function(fig, msg){\n",
+ " fig.send_message('closing', msg);\n",
+ " // fig.ws.close()\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
+ " // Turn the data on the canvas into data in the output cell.\n",
+ " var dataURL = this.canvas.toDataURL();\n",
+ " this.cell_info[1]['text/html'] = ' ';\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Tell IPython that the notebook contents must change.\n",
+ " IPython.notebook.set_dirty(true);\n",
+ " this.send_message(\"ack\", {});\n",
+ " var fig = this;\n",
+ " // Wait a second, then push the new image to the DOM so\n",
+ " // that it is saved nicely (might be nice to debounce this).\n",
+ " setTimeout(function () { fig.push_to_output() }, 1000);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items){\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) { continue; };\n",
+ "\n",
+ " var button = $(' ');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " // Add the status bar.\n",
+ " var status_bar = $(' ');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "\n",
+ " // Add the close button to the window.\n",
+ " var buttongrp = $('
');\n",
+ " var button = $(' ');\n",
+ " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
+ " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
+ " buttongrp.append(button);\n",
+ " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
+ " titlebar.prepend(buttongrp);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(el){\n",
+ " var fig = this\n",
+ " el.on(\"remove\", function(){\n",
+ "\tfig.close_ws(fig, {});\n",
+ " });\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(el){\n",
+ " // this is important to make the div 'focusable\n",
+ " el.attr('tabindex', 0)\n",
+ " // reach out to IPython and tell the keyboard manager to turn it's self\n",
+ " // off when our div gets focus\n",
+ "\n",
+ " // location in version 3\n",
+ " if (IPython.notebook.keyboard_manager) {\n",
+ " IPython.notebook.keyboard_manager.register_events(el);\n",
+ " }\n",
+ " else {\n",
+ " // location in version 2\n",
+ " IPython.keyboard_manager.register_events(el);\n",
+ " }\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " var manager = IPython.notebook.keyboard_manager;\n",
+ " if (!manager)\n",
+ " manager = IPython.keyboard_manager;\n",
+ "\n",
+ " // Check for shift+enter\n",
+ " if (event.shiftKey && event.which == 13) {\n",
+ " this.canvas_div.blur();\n",
+ " event.shiftKey = false;\n",
+ " // Send a \"J\" for go to next cell\n",
+ " event.which = 74;\n",
+ " event.keyCode = 74;\n",
+ " manager.command_mode();\n",
+ " manager.handle_keydown(event);\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " fig.ondownload(fig, null);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.find_output_cell = function(html_output) {\n",
+ " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
+ " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
+ " // IPython event is triggered only after the cells have been serialised, which for\n",
+ " // our purposes (turning an active figure into a static one), is too late.\n",
+ " var cells = IPython.notebook.get_cells();\n",
+ " var ncells = cells.length;\n",
+ " for (var i=0; i= 3 moved mimebundle to data attribute of output\n",
+ " data = data.data;\n",
+ " }\n",
+ " if (data['text/html'] == html_output) {\n",
+ " return [cell, data, j];\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "// Register the function which deals with the matplotlib target/channel.\n",
+ "// The kernel may be null if the page has been refreshed.\n",
+ "if (IPython.notebook.kernel != null) {\n",
+ " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
+ "}\n"
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ }
+ ],
+ "prompt_number": 6
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "# save as default transformation for run (used when reloading without initAlign keywork)\n",
+ "r.saveTransform();"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "Saving roi and transformation parameter to mecl3616_init_pars//run0190_transform.npy\n"
+ ]
+ }
+ ],
+ "prompt_number": 7
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "# do more shots without fitting (using last r.initAlign)\n",
+ "# the return value is a list with lots of stuff for each shot\n",
+ "res = r.doShots(slice(100),doFit=False)\n",
+ "print(list(res.keys()))\n"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "FOM for best alignment 0.11\n",
+ "['parameters', 'p2', 'p1', 'fom', 'ratio']\n"
+ ]
+ }
+ ],
+ "prompt_number": 8
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "print(list(res[\"parameters\"].keys()))"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "['igauss1cen', 'scalex', 'transx', 'intensity', 'igauss2cen', 'shear', 'iblur1', 'scaley', 'rotation', 'igauss1sig', 'transy', 'igauss2sig']\n"
+ ]
+ }
+ ],
+ "prompt_number": 9
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "alignment.plotRatios(res[\"ratio\"])\n",
+ "ref = np.nanmedian(res[\"ratio\"],axis=0)\n",
+ "trash = plt.xlim(400,600)\n",
+ "trash = plt.ylim(0,2)"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "javascript": [
+ "/* Put everything inside the global mpl namespace */\n",
+ "window.mpl = {};\n",
+ "\n",
+ "mpl.get_websocket_type = function() {\n",
+ " if (typeof(WebSocket) !== 'undefined') {\n",
+ " return WebSocket;\n",
+ " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
+ " return MozWebSocket;\n",
+ " } else {\n",
+ " alert('Your browser does not have WebSocket support.' +\n",
+ " 'Please try Chrome, Safari or Firefox \u2265 6. ' +\n",
+ " 'Firefox 4 and 5 are also supported but you ' +\n",
+ " 'have to enable WebSockets in about:config.');\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
+ " this.id = figure_id;\n",
+ "\n",
+ " this.ws = websocket;\n",
+ "\n",
+ " this.supports_binary = (this.ws.binaryType != undefined);\n",
+ "\n",
+ " if (!this.supports_binary) {\n",
+ " var warnings = document.getElementById(\"mpl-warnings\");\n",
+ " if (warnings) {\n",
+ " warnings.style.display = 'block';\n",
+ " warnings.textContent = (\n",
+ " \"This browser does not support binary websocket messages. \" +\n",
+ " \"Performance may be slow.\");\n",
+ " }\n",
+ " }\n",
+ "\n",
+ " this.imageObj = new Image();\n",
+ "\n",
+ " this.context = undefined;\n",
+ " this.message = undefined;\n",
+ " this.canvas = undefined;\n",
+ " this.rubberband_canvas = undefined;\n",
+ " this.rubberband_context = undefined;\n",
+ " this.format_dropdown = undefined;\n",
+ "\n",
+ " this.image_mode = 'full';\n",
+ "\n",
+ " this.root = $('
');\n",
+ " this._root_extra_style(this.root)\n",
+ " this.root.attr('style', 'display: inline-block');\n",
+ "\n",
+ " $(parent_element).append(this.root);\n",
+ "\n",
+ " this._init_header(this);\n",
+ " this._init_canvas(this);\n",
+ " this._init_toolbar(this);\n",
+ "\n",
+ " var fig = this;\n",
+ "\n",
+ " this.waiting = false;\n",
+ "\n",
+ " this.ws.onopen = function () {\n",
+ " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
+ " fig.send_message(\"send_image_mode\", {});\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " }\n",
+ "\n",
+ " this.imageObj.onload = function() {\n",
+ " if (fig.image_mode == 'full') {\n",
+ " // Full images could contain transparency (where diff images\n",
+ " // almost always do), so we need to clear the canvas so that\n",
+ " // there is no ghosting.\n",
+ " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
+ " }\n",
+ " fig.context.drawImage(fig.imageObj, 0, 0);\n",
+ " };\n",
+ "\n",
+ " this.imageObj.onunload = function() {\n",
+ " this.ws.close();\n",
+ " }\n",
+ "\n",
+ " this.ws.onmessage = this._make_on_message_function(this);\n",
+ "\n",
+ " this.ondownload = ondownload;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_header = function() {\n",
+ " var titlebar = $(\n",
+ " '
');\n",
+ " var titletext = $(\n",
+ " '
');\n",
+ " titlebar.append(titletext)\n",
+ " this.root.append(titlebar);\n",
+ " this.header = titletext[0];\n",
+ "}\n",
+ "\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_canvas = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var canvas_div = $('
');\n",
+ "\n",
+ " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
+ "\n",
+ " function canvas_keyboard_event(event) {\n",
+ " return fig.key_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
+ " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
+ " this.canvas_div = canvas_div\n",
+ " this._canvas_extra_style(canvas_div)\n",
+ " this.root.append(canvas_div);\n",
+ "\n",
+ " var canvas = $(' ');\n",
+ " canvas.addClass('mpl-canvas');\n",
+ " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
+ "\n",
+ " this.canvas = canvas[0];\n",
+ " this.context = canvas[0].getContext(\"2d\");\n",
+ "\n",
+ " var rubberband = $(' ');\n",
+ " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
+ "\n",
+ " var pass_mouse_events = true;\n",
+ "\n",
+ " canvas_div.resizable({\n",
+ " start: function(event, ui) {\n",
+ " pass_mouse_events = false;\n",
+ " },\n",
+ " resize: function(event, ui) {\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " stop: function(event, ui) {\n",
+ " pass_mouse_events = true;\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " });\n",
+ "\n",
+ " function mouse_event_fn(event) {\n",
+ " if (pass_mouse_events)\n",
+ " return fig.mouse_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " rubberband.mousedown('button_press', mouse_event_fn);\n",
+ " rubberband.mouseup('button_release', mouse_event_fn);\n",
+ " // Throttle sequential mouse events to 1 every 20ms.\n",
+ " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
+ "\n",
+ " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
+ " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
+ "\n",
+ " canvas_div.on(\"wheel\", function (event) {\n",
+ " event = event.originalEvent;\n",
+ " event['data'] = 'scroll'\n",
+ " if (event.deltaY < 0) {\n",
+ " event.step = 1;\n",
+ " } else {\n",
+ " event.step = -1;\n",
+ " }\n",
+ " mouse_event_fn(event);\n",
+ " });\n",
+ "\n",
+ " canvas_div.append(canvas);\n",
+ " canvas_div.append(rubberband);\n",
+ "\n",
+ " this.rubberband = rubberband;\n",
+ " this.rubberband_canvas = rubberband[0];\n",
+ " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
+ " this.rubberband_context.strokeStyle = \"#000000\";\n",
+ "\n",
+ " this._resize_canvas = function(width, height) {\n",
+ " // Keep the size of the canvas, canvas container, and rubber band\n",
+ " // canvas in synch.\n",
+ " canvas_div.css('width', width)\n",
+ " canvas_div.css('height', height)\n",
+ "\n",
+ " canvas.attr('width', width);\n",
+ " canvas.attr('height', height);\n",
+ "\n",
+ " rubberband.attr('width', width);\n",
+ " rubberband.attr('height', height);\n",
+ " }\n",
+ "\n",
+ " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
+ " // upon first draw.\n",
+ " this._resize_canvas(600, 600);\n",
+ "\n",
+ " // Disable right mouse context menu.\n",
+ " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
+ " return false;\n",
+ " });\n",
+ "\n",
+ " function set_focus () {\n",
+ " canvas.focus();\n",
+ " canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " window.setTimeout(set_focus, 100);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items) {\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) {\n",
+ " // put a spacer in here.\n",
+ " continue;\n",
+ " }\n",
+ " var button = $(' ');\n",
+ " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
+ " 'ui-button-icon-only');\n",
+ " button.attr('role', 'button');\n",
+ " button.attr('aria-disabled', 'false');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ "\n",
+ " var icon_img = $(' ');\n",
+ " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
+ " icon_img.addClass(image);\n",
+ " icon_img.addClass('ui-corner-all');\n",
+ "\n",
+ " var tooltip_span = $(' ');\n",
+ " tooltip_span.addClass('ui-button-text');\n",
+ " tooltip_span.html(tooltip);\n",
+ "\n",
+ " button.append(icon_img);\n",
+ " button.append(tooltip_span);\n",
+ "\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " var fmt_picker_span = $(' ');\n",
+ "\n",
+ " var fmt_picker = $(' ');\n",
+ " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
+ " fmt_picker_span.append(fmt_picker);\n",
+ " nav_element.append(fmt_picker_span);\n",
+ " this.format_dropdown = fmt_picker[0];\n",
+ "\n",
+ " for (var ind in mpl.extensions) {\n",
+ " var fmt = mpl.extensions[ind];\n",
+ " var option = $(\n",
+ " ' ', {selected: fmt === mpl.default_extension}).html(fmt);\n",
+ " fmt_picker.append(option)\n",
+ " }\n",
+ "\n",
+ " // Add hover states to the ui-buttons\n",
+ " $( \".ui-button\" ).hover(\n",
+ " function() { $(this).addClass(\"ui-state-hover\");},\n",
+ " function() { $(this).removeClass(\"ui-state-hover\");}\n",
+ " );\n",
+ "\n",
+ " var status_bar = $('');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
+ " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
+ " // which will in turn request a refresh of the image.\n",
+ " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_message = function(type, properties) {\n",
+ " properties['type'] = type;\n",
+ " properties['figure_id'] = this.id;\n",
+ " this.ws.send(JSON.stringify(properties));\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_draw_message = function() {\n",
+ " if (!this.waiting) {\n",
+ " this.waiting = true;\n",
+ " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " var format_dropdown = fig.format_dropdown;\n",
+ " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
+ " fig.ondownload(fig, format);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
+ " var size = msg['size'];\n",
+ " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
+ " fig._resize_canvas(size[0], size[1]);\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
+ " var x0 = msg['x0'];\n",
+ " var y0 = fig.canvas.height - msg['y0'];\n",
+ " var x1 = msg['x1'];\n",
+ " var y1 = fig.canvas.height - msg['y1'];\n",
+ " x0 = Math.floor(x0) + 0.5;\n",
+ " y0 = Math.floor(y0) + 0.5;\n",
+ " x1 = Math.floor(x1) + 0.5;\n",
+ " y1 = Math.floor(y1) + 0.5;\n",
+ " var min_x = Math.min(x0, x1);\n",
+ " var min_y = Math.min(y0, y1);\n",
+ " var width = Math.abs(x1 - x0);\n",
+ " var height = Math.abs(y1 - y0);\n",
+ "\n",
+ " fig.rubberband_context.clearRect(\n",
+ " 0, 0, fig.canvas.width, fig.canvas.height);\n",
+ "\n",
+ " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
+ " // Updates the figure title.\n",
+ " fig.header.textContent = msg['label'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
+ " var cursor = msg['cursor'];\n",
+ " switch(cursor)\n",
+ " {\n",
+ " case 0:\n",
+ " cursor = 'pointer';\n",
+ " break;\n",
+ " case 1:\n",
+ " cursor = 'default';\n",
+ " break;\n",
+ " case 2:\n",
+ " cursor = 'crosshair';\n",
+ " break;\n",
+ " case 3:\n",
+ " cursor = 'move';\n",
+ " break;\n",
+ " }\n",
+ " fig.rubberband_canvas.style.cursor = cursor;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
+ " fig.message.textContent = msg['message'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
+ " // Request the server to send over a new figure.\n",
+ " fig.send_draw_message();\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
+ " fig.image_mode = msg['mode'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Called whenever the canvas gets updated.\n",
+ " this.send_message(\"ack\", {});\n",
+ "}\n",
+ "\n",
+ "// A function to construct a web socket function for onmessage handling.\n",
+ "// Called in the figure constructor.\n",
+ "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
+ " return function socket_on_message(evt) {\n",
+ " if (evt.data instanceof Blob) {\n",
+ " /* FIXME: We get \"Resource interpreted as Image but\n",
+ " * transferred with MIME type text/plain:\" errors on\n",
+ " * Chrome. But how to set the MIME type? It doesn't seem\n",
+ " * to be part of the websocket stream */\n",
+ " evt.data.type = \"image/png\";\n",
+ "\n",
+ " /* Free the memory for the previous frames */\n",
+ " if (fig.imageObj.src) {\n",
+ " (window.URL || window.webkitURL).revokeObjectURL(\n",
+ " fig.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
+ " evt.data);\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
+ " fig.imageObj.src = evt.data;\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var msg = JSON.parse(evt.data);\n",
+ " var msg_type = msg['type'];\n",
+ "\n",
+ " // Call the \"handle_{type}\" callback, which takes\n",
+ " // the figure and JSON message as its only arguments.\n",
+ " try {\n",
+ " var callback = fig[\"handle_\" + msg_type];\n",
+ " } catch (e) {\n",
+ " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " if (callback) {\n",
+ " try {\n",
+ " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
+ " callback(fig, msg);\n",
+ " } catch (e) {\n",
+ " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
+ " }\n",
+ " }\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
+ "mpl.findpos = function(e) {\n",
+ " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
+ " var targ;\n",
+ " if (!e)\n",
+ " e = window.event;\n",
+ " if (e.target)\n",
+ " targ = e.target;\n",
+ " else if (e.srcElement)\n",
+ " targ = e.srcElement;\n",
+ " if (targ.nodeType == 3) // defeat Safari bug\n",
+ " targ = targ.parentNode;\n",
+ "\n",
+ " // jQuery normalizes the pageX and pageY\n",
+ " // pageX,Y are the mouse positions relative to the document\n",
+ " // offset() returns the position of the element relative to the document\n",
+ " var x = e.pageX - $(targ).offset().left;\n",
+ " var y = e.pageY - $(targ).offset().top;\n",
+ "\n",
+ " return {\"x\": x, \"y\": y};\n",
+ "};\n",
+ "\n",
+ "/*\n",
+ " * return a copy of an object with only non-object keys\n",
+ " * we need this to avoid circular references\n",
+ " * http://stackoverflow.com/a/24161582/3208463\n",
+ " */\n",
+ "function simpleKeys (original) {\n",
+ " return Object.keys(original).reduce(function (obj, key) {\n",
+ " if (typeof original[key] !== 'object')\n",
+ " obj[key] = original[key]\n",
+ " return obj;\n",
+ " }, {});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.mouse_event = function(event, name) {\n",
+ " var canvas_pos = mpl.findpos(event)\n",
+ "\n",
+ " if (name === 'button_press')\n",
+ " {\n",
+ " this.canvas.focus();\n",
+ " this.canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " var x = canvas_pos.x;\n",
+ " var y = canvas_pos.y;\n",
+ "\n",
+ " this.send_message(name, {x: x, y: y, button: event.button,\n",
+ " step: event.step,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ "\n",
+ " /* This prevents the web browser from automatically changing to\n",
+ " * the text insertion cursor when the button is pressed. We want\n",
+ " * to control all of the cursor setting manually through the\n",
+ " * 'cursor' event from matplotlib */\n",
+ " event.preventDefault();\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " // Handle any extra behaviour associated with a key event\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.key_event = function(event, name) {\n",
+ "\n",
+ " // Prevent repeat events\n",
+ " if (name == 'key_press')\n",
+ " {\n",
+ " if (event.which === this._key)\n",
+ " return;\n",
+ " else\n",
+ " this._key = event.which;\n",
+ " }\n",
+ " if (name == 'key_release')\n",
+ " this._key = null;\n",
+ "\n",
+ " var value = '';\n",
+ " if (event.ctrlKey && event.which != 17)\n",
+ " value += \"ctrl+\";\n",
+ " if (event.altKey && event.which != 18)\n",
+ " value += \"alt+\";\n",
+ " if (event.shiftKey && event.which != 16)\n",
+ " value += \"shift+\";\n",
+ "\n",
+ " value += 'k';\n",
+ " value += event.which.toString();\n",
+ "\n",
+ " this._key_event_extra(event, name);\n",
+ "\n",
+ " this.send_message(name, {key: value,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
+ " if (name == 'download') {\n",
+ " this.handle_save(this, null);\n",
+ " } else {\n",
+ " this.send_message(\"toolbar_button\", {name: name});\n",
+ " }\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
+ " this.message.textContent = tooltip;\n",
+ "};\n",
+ "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
+ "\n",
+ "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
+ "\n",
+ "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
+ " // Create a \"websocket\"-like object which calls the given IPython comm\n",
+ " // object with the appropriate methods. Currently this is a non binary\n",
+ " // socket, so there is still some room for performance tuning.\n",
+ " var ws = {};\n",
+ "\n",
+ " ws.close = function() {\n",
+ " comm.close()\n",
+ " };\n",
+ " ws.send = function(m) {\n",
+ " //console.log('sending', m);\n",
+ " comm.send(m);\n",
+ " };\n",
+ " // Register the callback with on_msg.\n",
+ " comm.on_msg(function(msg) {\n",
+ " //console.log('receiving', msg['content']['data'], msg);\n",
+ " // Pass the mpl event to the overriden (by mpl) onmessage function.\n",
+ " ws.onmessage(msg['content']['data'])\n",
+ " });\n",
+ " return ws;\n",
+ "}\n",
+ "\n",
+ "mpl.mpl_figure_comm = function(comm, msg) {\n",
+ " // This is the function which gets called when the mpl process\n",
+ " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
+ "\n",
+ " var id = msg.content.data.id;\n",
+ " // Get hold of the div created by the display call when the Comm\n",
+ " // socket was opened in Python.\n",
+ " var element = $(\"#\" + id);\n",
+ " var ws_proxy = comm_websocket_adapter(comm)\n",
+ "\n",
+ " function ondownload(figure, format) {\n",
+ " window.open(figure.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " var fig = new mpl.figure(id, ws_proxy,\n",
+ " ondownload,\n",
+ " element.get(0));\n",
+ "\n",
+ " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
+ " // web socket which is closed, not our websocket->open comm proxy.\n",
+ " ws_proxy.onopen();\n",
+ "\n",
+ " fig.parent_element = element.get(0);\n",
+ " fig.cell_info = mpl.find_output_cell(\"
\");\n",
+ " if (!fig.cell_info) {\n",
+ " console.error(\"Failed to find cell for figure\", id, fig);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var output_index = fig.cell_info[2]\n",
+ " var cell = fig.cell_info[0];\n",
+ "\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
+ " fig.root.unbind('remove')\n",
+ "\n",
+ " // Update the output cell to use the data from the current canvas.\n",
+ " fig.push_to_output();\n",
+ " var dataURL = fig.canvas.toDataURL();\n",
+ " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
+ " // the notebook keyboard shortcuts fail.\n",
+ " IPython.keyboard_manager.enable()\n",
+ " $(fig.parent_element).html(' ');\n",
+ " fig.close_ws(fig, msg);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.close_ws = function(fig, msg){\n",
+ " fig.send_message('closing', msg);\n",
+ " // fig.ws.close()\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
+ " // Turn the data on the canvas into data in the output cell.\n",
+ " var dataURL = this.canvas.toDataURL();\n",
+ " this.cell_info[1]['text/html'] = ' ';\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Tell IPython that the notebook contents must change.\n",
+ " IPython.notebook.set_dirty(true);\n",
+ " this.send_message(\"ack\", {});\n",
+ " var fig = this;\n",
+ " // Wait a second, then push the new image to the DOM so\n",
+ " // that it is saved nicely (might be nice to debounce this).\n",
+ " setTimeout(function () { fig.push_to_output() }, 1000);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items){\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) { continue; };\n",
+ "\n",
+ " var button = $(' ');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " // Add the status bar.\n",
+ " var status_bar = $(' ');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "\n",
+ " // Add the close button to the window.\n",
+ " var buttongrp = $('
');\n",
+ " var button = $(' ');\n",
+ " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
+ " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
+ " buttongrp.append(button);\n",
+ " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
+ " titlebar.prepend(buttongrp);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(el){\n",
+ " var fig = this\n",
+ " el.on(\"remove\", function(){\n",
+ "\tfig.close_ws(fig, {});\n",
+ " });\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(el){\n",
+ " // this is important to make the div 'focusable\n",
+ " el.attr('tabindex', 0)\n",
+ " // reach out to IPython and tell the keyboard manager to turn it's self\n",
+ " // off when our div gets focus\n",
+ "\n",
+ " // location in version 3\n",
+ " if (IPython.notebook.keyboard_manager) {\n",
+ " IPython.notebook.keyboard_manager.register_events(el);\n",
+ " }\n",
+ " else {\n",
+ " // location in version 2\n",
+ " IPython.keyboard_manager.register_events(el);\n",
+ " }\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " var manager = IPython.notebook.keyboard_manager;\n",
+ " if (!manager)\n",
+ " manager = IPython.keyboard_manager;\n",
+ "\n",
+ " // Check for shift+enter\n",
+ " if (event.shiftKey && event.which == 13) {\n",
+ " this.canvas_div.blur();\n",
+ " event.shiftKey = false;\n",
+ " // Send a \"J\" for go to next cell\n",
+ " event.which = 74;\n",
+ " event.keyCode = 74;\n",
+ " manager.command_mode();\n",
+ " manager.handle_keydown(event);\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " fig.ondownload(fig, null);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.find_output_cell = function(html_output) {\n",
+ " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
+ " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
+ " // IPython event is triggered only after the cells have been serialised, which for\n",
+ " // our purposes (turning an active figure into a static one), is too late.\n",
+ " var cells = IPython.notebook.get_cells();\n",
+ " var ncells = cells.length;\n",
+ " for (var i=0; i= 3 moved mimebundle to data attribute of output\n",
+ " data = data.data;\n",
+ " }\n",
+ " if (data['text/html'] == html_output) {\n",
+ " return [cell, data, j];\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "// Register the function which deals with the matplotlib target/channel.\n",
+ "// The kernel may be null if the page has been refreshed.\n",
+ "if (IPython.notebook.kernel != null) {\n",
+ " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
+ "}\n"
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ }
+ ],
+ "prompt_number": 10
+ },
+ {
+ "cell_type": "heading",
+ "level": 1,
+ "metadata": {},
+ "source": [
+ "analyze another run using previous alignment"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "rShot = xanes_analyzeRun.AnalyzeRun(192,initAlign=\"mecl3616_init_pars/run0190_transform.npy\",swapx=True,swapy=False)"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "Building paths list of HDF5 file(s)...done 0.02 s\n",
+ "Defining fee_spec.....(as general detector).....done 0.00 s\n",
+ "Defining opal2.....(as general detector).....done 0.00 s\n",
+ "Time stamp matching started ......done 0.00 s\n",
+ "init transform and ROIs from mecl3616_init_pars/run0190_transform.npy\n"
+ ]
+ }
+ ],
+ "prompt_number": 11
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "out = rShot.doShots(slice(0,5))\n",
+ "ratios = out[\"ratio\"]\n",
+ "plt.figure()\n",
+ "for i,r in enumerate(ratios):\n",
+ " plt.plot(r/ref,label=\"Shot %d\"%i)\n",
+ "trash = plt.ylim(0,1)\n",
+ "trash = plt.legend(loc=2)"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "FOM for best alignment 0.32\n"
+ ]
+ },
+ {
+ "javascript": [
+ "/* Put everything inside the global mpl namespace */\n",
+ "window.mpl = {};\n",
+ "\n",
+ "mpl.get_websocket_type = function() {\n",
+ " if (typeof(WebSocket) !== 'undefined') {\n",
+ " return WebSocket;\n",
+ " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
+ " return MozWebSocket;\n",
+ " } else {\n",
+ " alert('Your browser does not have WebSocket support.' +\n",
+ " 'Please try Chrome, Safari or Firefox \u2265 6. ' +\n",
+ " 'Firefox 4 and 5 are also supported but you ' +\n",
+ " 'have to enable WebSockets in about:config.');\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
+ " this.id = figure_id;\n",
+ "\n",
+ " this.ws = websocket;\n",
+ "\n",
+ " this.supports_binary = (this.ws.binaryType != undefined);\n",
+ "\n",
+ " if (!this.supports_binary) {\n",
+ " var warnings = document.getElementById(\"mpl-warnings\");\n",
+ " if (warnings) {\n",
+ " warnings.style.display = 'block';\n",
+ " warnings.textContent = (\n",
+ " \"This browser does not support binary websocket messages. \" +\n",
+ " \"Performance may be slow.\");\n",
+ " }\n",
+ " }\n",
+ "\n",
+ " this.imageObj = new Image();\n",
+ "\n",
+ " this.context = undefined;\n",
+ " this.message = undefined;\n",
+ " this.canvas = undefined;\n",
+ " this.rubberband_canvas = undefined;\n",
+ " this.rubberband_context = undefined;\n",
+ " this.format_dropdown = undefined;\n",
+ "\n",
+ " this.image_mode = 'full';\n",
+ "\n",
+ " this.root = $('
');\n",
+ " this._root_extra_style(this.root)\n",
+ " this.root.attr('style', 'display: inline-block');\n",
+ "\n",
+ " $(parent_element).append(this.root);\n",
+ "\n",
+ " this._init_header(this);\n",
+ " this._init_canvas(this);\n",
+ " this._init_toolbar(this);\n",
+ "\n",
+ " var fig = this;\n",
+ "\n",
+ " this.waiting = false;\n",
+ "\n",
+ " this.ws.onopen = function () {\n",
+ " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
+ " fig.send_message(\"send_image_mode\", {});\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " }\n",
+ "\n",
+ " this.imageObj.onload = function() {\n",
+ " if (fig.image_mode == 'full') {\n",
+ " // Full images could contain transparency (where diff images\n",
+ " // almost always do), so we need to clear the canvas so that\n",
+ " // there is no ghosting.\n",
+ " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
+ " }\n",
+ " fig.context.drawImage(fig.imageObj, 0, 0);\n",
+ " };\n",
+ "\n",
+ " this.imageObj.onunload = function() {\n",
+ " this.ws.close();\n",
+ " }\n",
+ "\n",
+ " this.ws.onmessage = this._make_on_message_function(this);\n",
+ "\n",
+ " this.ondownload = ondownload;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_header = function() {\n",
+ " var titlebar = $(\n",
+ " '
');\n",
+ " var titletext = $(\n",
+ " '
');\n",
+ " titlebar.append(titletext)\n",
+ " this.root.append(titlebar);\n",
+ " this.header = titletext[0];\n",
+ "}\n",
+ "\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_canvas = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var canvas_div = $('
');\n",
+ "\n",
+ " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
+ "\n",
+ " function canvas_keyboard_event(event) {\n",
+ " return fig.key_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
+ " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
+ " this.canvas_div = canvas_div\n",
+ " this._canvas_extra_style(canvas_div)\n",
+ " this.root.append(canvas_div);\n",
+ "\n",
+ " var canvas = $(' ');\n",
+ " canvas.addClass('mpl-canvas');\n",
+ " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
+ "\n",
+ " this.canvas = canvas[0];\n",
+ " this.context = canvas[0].getContext(\"2d\");\n",
+ "\n",
+ " var rubberband = $(' ');\n",
+ " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
+ "\n",
+ " var pass_mouse_events = true;\n",
+ "\n",
+ " canvas_div.resizable({\n",
+ " start: function(event, ui) {\n",
+ " pass_mouse_events = false;\n",
+ " },\n",
+ " resize: function(event, ui) {\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " stop: function(event, ui) {\n",
+ " pass_mouse_events = true;\n",
+ " fig.request_resize(ui.size.width, ui.size.height);\n",
+ " },\n",
+ " });\n",
+ "\n",
+ " function mouse_event_fn(event) {\n",
+ " if (pass_mouse_events)\n",
+ " return fig.mouse_event(event, event['data']);\n",
+ " }\n",
+ "\n",
+ " rubberband.mousedown('button_press', mouse_event_fn);\n",
+ " rubberband.mouseup('button_release', mouse_event_fn);\n",
+ " // Throttle sequential mouse events to 1 every 20ms.\n",
+ " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
+ "\n",
+ " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
+ " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
+ "\n",
+ " canvas_div.on(\"wheel\", function (event) {\n",
+ " event = event.originalEvent;\n",
+ " event['data'] = 'scroll'\n",
+ " if (event.deltaY < 0) {\n",
+ " event.step = 1;\n",
+ " } else {\n",
+ " event.step = -1;\n",
+ " }\n",
+ " mouse_event_fn(event);\n",
+ " });\n",
+ "\n",
+ " canvas_div.append(canvas);\n",
+ " canvas_div.append(rubberband);\n",
+ "\n",
+ " this.rubberband = rubberband;\n",
+ " this.rubberband_canvas = rubberband[0];\n",
+ " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
+ " this.rubberband_context.strokeStyle = \"#000000\";\n",
+ "\n",
+ " this._resize_canvas = function(width, height) {\n",
+ " // Keep the size of the canvas, canvas container, and rubber band\n",
+ " // canvas in synch.\n",
+ " canvas_div.css('width', width)\n",
+ " canvas_div.css('height', height)\n",
+ "\n",
+ " canvas.attr('width', width);\n",
+ " canvas.attr('height', height);\n",
+ "\n",
+ " rubberband.attr('width', width);\n",
+ " rubberband.attr('height', height);\n",
+ " }\n",
+ "\n",
+ " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
+ " // upon first draw.\n",
+ " this._resize_canvas(600, 600);\n",
+ "\n",
+ " // Disable right mouse context menu.\n",
+ " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
+ " return false;\n",
+ " });\n",
+ "\n",
+ " function set_focus () {\n",
+ " canvas.focus();\n",
+ " canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " window.setTimeout(set_focus, 100);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items) {\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) {\n",
+ " // put a spacer in here.\n",
+ " continue;\n",
+ " }\n",
+ " var button = $(' ');\n",
+ " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
+ " 'ui-button-icon-only');\n",
+ " button.attr('role', 'button');\n",
+ " button.attr('aria-disabled', 'false');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ "\n",
+ " var icon_img = $(' ');\n",
+ " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
+ " icon_img.addClass(image);\n",
+ " icon_img.addClass('ui-corner-all');\n",
+ "\n",
+ " var tooltip_span = $(' ');\n",
+ " tooltip_span.addClass('ui-button-text');\n",
+ " tooltip_span.html(tooltip);\n",
+ "\n",
+ " button.append(icon_img);\n",
+ " button.append(tooltip_span);\n",
+ "\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " var fmt_picker_span = $(' ');\n",
+ "\n",
+ " var fmt_picker = $(' ');\n",
+ " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
+ " fmt_picker_span.append(fmt_picker);\n",
+ " nav_element.append(fmt_picker_span);\n",
+ " this.format_dropdown = fmt_picker[0];\n",
+ "\n",
+ " for (var ind in mpl.extensions) {\n",
+ " var fmt = mpl.extensions[ind];\n",
+ " var option = $(\n",
+ " ' ', {selected: fmt === mpl.default_extension}).html(fmt);\n",
+ " fmt_picker.append(option)\n",
+ " }\n",
+ "\n",
+ " // Add hover states to the ui-buttons\n",
+ " $( \".ui-button\" ).hover(\n",
+ " function() { $(this).addClass(\"ui-state-hover\");},\n",
+ " function() { $(this).removeClass(\"ui-state-hover\");}\n",
+ " );\n",
+ "\n",
+ " var status_bar = $('');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
+ " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
+ " // which will in turn request a refresh of the image.\n",
+ " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_message = function(type, properties) {\n",
+ " properties['type'] = type;\n",
+ " properties['figure_id'] = this.id;\n",
+ " this.ws.send(JSON.stringify(properties));\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.send_draw_message = function() {\n",
+ " if (!this.waiting) {\n",
+ " this.waiting = true;\n",
+ " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " var format_dropdown = fig.format_dropdown;\n",
+ " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
+ " fig.ondownload(fig, format);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
+ " var size = msg['size'];\n",
+ " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
+ " fig._resize_canvas(size[0], size[1]);\n",
+ " fig.send_message(\"refresh\", {});\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
+ " var x0 = msg['x0'];\n",
+ " var y0 = fig.canvas.height - msg['y0'];\n",
+ " var x1 = msg['x1'];\n",
+ " var y1 = fig.canvas.height - msg['y1'];\n",
+ " x0 = Math.floor(x0) + 0.5;\n",
+ " y0 = Math.floor(y0) + 0.5;\n",
+ " x1 = Math.floor(x1) + 0.5;\n",
+ " y1 = Math.floor(y1) + 0.5;\n",
+ " var min_x = Math.min(x0, x1);\n",
+ " var min_y = Math.min(y0, y1);\n",
+ " var width = Math.abs(x1 - x0);\n",
+ " var height = Math.abs(y1 - y0);\n",
+ "\n",
+ " fig.rubberband_context.clearRect(\n",
+ " 0, 0, fig.canvas.width, fig.canvas.height);\n",
+ "\n",
+ " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
+ " // Updates the figure title.\n",
+ " fig.header.textContent = msg['label'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
+ " var cursor = msg['cursor'];\n",
+ " switch(cursor)\n",
+ " {\n",
+ " case 0:\n",
+ " cursor = 'pointer';\n",
+ " break;\n",
+ " case 1:\n",
+ " cursor = 'default';\n",
+ " break;\n",
+ " case 2:\n",
+ " cursor = 'crosshair';\n",
+ " break;\n",
+ " case 3:\n",
+ " cursor = 'move';\n",
+ " break;\n",
+ " }\n",
+ " fig.rubberband_canvas.style.cursor = cursor;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
+ " fig.message.textContent = msg['message'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
+ " // Request the server to send over a new figure.\n",
+ " fig.send_draw_message();\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
+ " fig.image_mode = msg['mode'];\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Called whenever the canvas gets updated.\n",
+ " this.send_message(\"ack\", {});\n",
+ "}\n",
+ "\n",
+ "// A function to construct a web socket function for onmessage handling.\n",
+ "// Called in the figure constructor.\n",
+ "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
+ " return function socket_on_message(evt) {\n",
+ " if (evt.data instanceof Blob) {\n",
+ " /* FIXME: We get \"Resource interpreted as Image but\n",
+ " * transferred with MIME type text/plain:\" errors on\n",
+ " * Chrome. But how to set the MIME type? It doesn't seem\n",
+ " * to be part of the websocket stream */\n",
+ " evt.data.type = \"image/png\";\n",
+ "\n",
+ " /* Free the memory for the previous frames */\n",
+ " if (fig.imageObj.src) {\n",
+ " (window.URL || window.webkitURL).revokeObjectURL(\n",
+ " fig.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
+ " evt.data);\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
+ " fig.imageObj.src = evt.data;\n",
+ " fig.updated_canvas_event();\n",
+ " fig.waiting = false;\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var msg = JSON.parse(evt.data);\n",
+ " var msg_type = msg['type'];\n",
+ "\n",
+ " // Call the \"handle_{type}\" callback, which takes\n",
+ " // the figure and JSON message as its only arguments.\n",
+ " try {\n",
+ " var callback = fig[\"handle_\" + msg_type];\n",
+ " } catch (e) {\n",
+ " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " if (callback) {\n",
+ " try {\n",
+ " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
+ " callback(fig, msg);\n",
+ " } catch (e) {\n",
+ " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
+ " }\n",
+ " }\n",
+ " };\n",
+ "}\n",
+ "\n",
+ "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
+ "mpl.findpos = function(e) {\n",
+ " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
+ " var targ;\n",
+ " if (!e)\n",
+ " e = window.event;\n",
+ " if (e.target)\n",
+ " targ = e.target;\n",
+ " else if (e.srcElement)\n",
+ " targ = e.srcElement;\n",
+ " if (targ.nodeType == 3) // defeat Safari bug\n",
+ " targ = targ.parentNode;\n",
+ "\n",
+ " // jQuery normalizes the pageX and pageY\n",
+ " // pageX,Y are the mouse positions relative to the document\n",
+ " // offset() returns the position of the element relative to the document\n",
+ " var x = e.pageX - $(targ).offset().left;\n",
+ " var y = e.pageY - $(targ).offset().top;\n",
+ "\n",
+ " return {\"x\": x, \"y\": y};\n",
+ "};\n",
+ "\n",
+ "/*\n",
+ " * return a copy of an object with only non-object keys\n",
+ " * we need this to avoid circular references\n",
+ " * http://stackoverflow.com/a/24161582/3208463\n",
+ " */\n",
+ "function simpleKeys (original) {\n",
+ " return Object.keys(original).reduce(function (obj, key) {\n",
+ " if (typeof original[key] !== 'object')\n",
+ " obj[key] = original[key]\n",
+ " return obj;\n",
+ " }, {});\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.mouse_event = function(event, name) {\n",
+ " var canvas_pos = mpl.findpos(event)\n",
+ "\n",
+ " if (name === 'button_press')\n",
+ " {\n",
+ " this.canvas.focus();\n",
+ " this.canvas_div.focus();\n",
+ " }\n",
+ "\n",
+ " var x = canvas_pos.x;\n",
+ " var y = canvas_pos.y;\n",
+ "\n",
+ " this.send_message(name, {x: x, y: y, button: event.button,\n",
+ " step: event.step,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ "\n",
+ " /* This prevents the web browser from automatically changing to\n",
+ " * the text insertion cursor when the button is pressed. We want\n",
+ " * to control all of the cursor setting manually through the\n",
+ " * 'cursor' event from matplotlib */\n",
+ " event.preventDefault();\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " // Handle any extra behaviour associated with a key event\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.key_event = function(event, name) {\n",
+ "\n",
+ " // Prevent repeat events\n",
+ " if (name == 'key_press')\n",
+ " {\n",
+ " if (event.which === this._key)\n",
+ " return;\n",
+ " else\n",
+ " this._key = event.which;\n",
+ " }\n",
+ " if (name == 'key_release')\n",
+ " this._key = null;\n",
+ "\n",
+ " var value = '';\n",
+ " if (event.ctrlKey && event.which != 17)\n",
+ " value += \"ctrl+\";\n",
+ " if (event.altKey && event.which != 18)\n",
+ " value += \"alt+\";\n",
+ " if (event.shiftKey && event.which != 16)\n",
+ " value += \"shift+\";\n",
+ "\n",
+ " value += 'k';\n",
+ " value += event.which.toString();\n",
+ "\n",
+ " this._key_event_extra(event, name);\n",
+ "\n",
+ " this.send_message(name, {key: value,\n",
+ " guiEvent: simpleKeys(event)});\n",
+ " return false;\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
+ " if (name == 'download') {\n",
+ " this.handle_save(this, null);\n",
+ " } else {\n",
+ " this.send_message(\"toolbar_button\", {name: name});\n",
+ " }\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
+ " this.message.textContent = tooltip;\n",
+ "};\n",
+ "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
+ "\n",
+ "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
+ "\n",
+ "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
+ " // Create a \"websocket\"-like object which calls the given IPython comm\n",
+ " // object with the appropriate methods. Currently this is a non binary\n",
+ " // socket, so there is still some room for performance tuning.\n",
+ " var ws = {};\n",
+ "\n",
+ " ws.close = function() {\n",
+ " comm.close()\n",
+ " };\n",
+ " ws.send = function(m) {\n",
+ " //console.log('sending', m);\n",
+ " comm.send(m);\n",
+ " };\n",
+ " // Register the callback with on_msg.\n",
+ " comm.on_msg(function(msg) {\n",
+ " //console.log('receiving', msg['content']['data'], msg);\n",
+ " // Pass the mpl event to the overriden (by mpl) onmessage function.\n",
+ " ws.onmessage(msg['content']['data'])\n",
+ " });\n",
+ " return ws;\n",
+ "}\n",
+ "\n",
+ "mpl.mpl_figure_comm = function(comm, msg) {\n",
+ " // This is the function which gets called when the mpl process\n",
+ " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
+ "\n",
+ " var id = msg.content.data.id;\n",
+ " // Get hold of the div created by the display call when the Comm\n",
+ " // socket was opened in Python.\n",
+ " var element = $(\"#\" + id);\n",
+ " var ws_proxy = comm_websocket_adapter(comm)\n",
+ "\n",
+ " function ondownload(figure, format) {\n",
+ " window.open(figure.imageObj.src);\n",
+ " }\n",
+ "\n",
+ " var fig = new mpl.figure(id, ws_proxy,\n",
+ " ondownload,\n",
+ " element.get(0));\n",
+ "\n",
+ " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
+ " // web socket which is closed, not our websocket->open comm proxy.\n",
+ " ws_proxy.onopen();\n",
+ "\n",
+ " fig.parent_element = element.get(0);\n",
+ " fig.cell_info = mpl.find_output_cell(\"
\");\n",
+ " if (!fig.cell_info) {\n",
+ " console.error(\"Failed to find cell for figure\", id, fig);\n",
+ " return;\n",
+ " }\n",
+ "\n",
+ " var output_index = fig.cell_info[2]\n",
+ " var cell = fig.cell_info[0];\n",
+ "\n",
+ "};\n",
+ "\n",
+ "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
+ " fig.root.unbind('remove')\n",
+ "\n",
+ " // Update the output cell to use the data from the current canvas.\n",
+ " fig.push_to_output();\n",
+ " var dataURL = fig.canvas.toDataURL();\n",
+ " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
+ " // the notebook keyboard shortcuts fail.\n",
+ " IPython.keyboard_manager.enable()\n",
+ " $(fig.parent_element).html(' ');\n",
+ " fig.close_ws(fig, msg);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.close_ws = function(fig, msg){\n",
+ " fig.send_message('closing', msg);\n",
+ " // fig.ws.close()\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
+ " // Turn the data on the canvas into data in the output cell.\n",
+ " var dataURL = this.canvas.toDataURL();\n",
+ " this.cell_info[1]['text/html'] = ' ';\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.updated_canvas_event = function() {\n",
+ " // Tell IPython that the notebook contents must change.\n",
+ " IPython.notebook.set_dirty(true);\n",
+ " this.send_message(\"ack\", {});\n",
+ " var fig = this;\n",
+ " // Wait a second, then push the new image to the DOM so\n",
+ " // that it is saved nicely (might be nice to debounce this).\n",
+ " setTimeout(function () { fig.push_to_output() }, 1000);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._init_toolbar = function() {\n",
+ " var fig = this;\n",
+ "\n",
+ " var nav_element = $('
')\n",
+ " nav_element.attr('style', 'width: 100%');\n",
+ " this.root.append(nav_element);\n",
+ "\n",
+ " // Define a callback function for later on.\n",
+ " function toolbar_event(event) {\n",
+ " return fig.toolbar_button_onclick(event['data']);\n",
+ " }\n",
+ " function toolbar_mouse_event(event) {\n",
+ " return fig.toolbar_button_onmouseover(event['data']);\n",
+ " }\n",
+ "\n",
+ " for(var toolbar_ind in mpl.toolbar_items){\n",
+ " var name = mpl.toolbar_items[toolbar_ind][0];\n",
+ " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
+ " var image = mpl.toolbar_items[toolbar_ind][2];\n",
+ " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
+ "\n",
+ " if (!name) { continue; };\n",
+ "\n",
+ " var button = $(' ');\n",
+ " button.click(method_name, toolbar_event);\n",
+ " button.mouseover(tooltip, toolbar_mouse_event);\n",
+ " nav_element.append(button);\n",
+ " }\n",
+ "\n",
+ " // Add the status bar.\n",
+ " var status_bar = $(' ');\n",
+ " nav_element.append(status_bar);\n",
+ " this.message = status_bar[0];\n",
+ "\n",
+ " // Add the close button to the window.\n",
+ " var buttongrp = $('
');\n",
+ " var button = $(' ');\n",
+ " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
+ " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
+ " buttongrp.append(button);\n",
+ " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
+ " titlebar.prepend(buttongrp);\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._root_extra_style = function(el){\n",
+ " var fig = this\n",
+ " el.on(\"remove\", function(){\n",
+ "\tfig.close_ws(fig, {});\n",
+ " });\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._canvas_extra_style = function(el){\n",
+ " // this is important to make the div 'focusable\n",
+ " el.attr('tabindex', 0)\n",
+ " // reach out to IPython and tell the keyboard manager to turn it's self\n",
+ " // off when our div gets focus\n",
+ "\n",
+ " // location in version 3\n",
+ " if (IPython.notebook.keyboard_manager) {\n",
+ " IPython.notebook.keyboard_manager.register_events(el);\n",
+ " }\n",
+ " else {\n",
+ " // location in version 2\n",
+ " IPython.keyboard_manager.register_events(el);\n",
+ " }\n",
+ "\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
+ " var manager = IPython.notebook.keyboard_manager;\n",
+ " if (!manager)\n",
+ " manager = IPython.keyboard_manager;\n",
+ "\n",
+ " // Check for shift+enter\n",
+ " if (event.shiftKey && event.which == 13) {\n",
+ " this.canvas_div.blur();\n",
+ " event.shiftKey = false;\n",
+ " // Send a \"J\" for go to next cell\n",
+ " event.which = 74;\n",
+ " event.keyCode = 74;\n",
+ " manager.command_mode();\n",
+ " manager.handle_keydown(event);\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
+ " fig.ondownload(fig, null);\n",
+ "}\n",
+ "\n",
+ "\n",
+ "mpl.find_output_cell = function(html_output) {\n",
+ " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
+ " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
+ " // IPython event is triggered only after the cells have been serialised, which for\n",
+ " // our purposes (turning an active figure into a static one), is too late.\n",
+ " var cells = IPython.notebook.get_cells();\n",
+ " var ncells = cells.length;\n",
+ " for (var i=0; i= 3 moved mimebundle to data attribute of output\n",
+ " data = data.data;\n",
+ " }\n",
+ " if (data['text/html'] == html_output) {\n",
+ " return [cell, data, j];\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "// Register the function which deals with the matplotlib target/channel.\n",
+ "// The kernel may be null if the page has been refreshed.\n",
+ "if (IPython.notebook.kernel != null) {\n",
+ " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
+ "}\n"
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ },
+ {
+ "html": [
+ " "
+ ],
+ "metadata": {},
+ "output_type": "display_data",
+ "text": [
+ ""
+ ]
+ }
+ ],
+ "prompt_number": 12
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "# save results in hdf file for Andy's happiness\n",
+ "rShot.save(overwrite=True)"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": [
+ "Saving results to mecl3616_output//run0192_analysis.h5\n"
+ ]
+ }
+ ],
+ "prompt_number": 13
+ }
+ ],
+ "metadata": {}
+ }
+ ]
+}
\ No newline at end of file
diff --git a/NOTES.txt b/NOTES.txt
new file mode 100644
index 0000000..387e4f6
--- /dev/null
+++ b/NOTES.txt
@@ -0,0 +1,6 @@
+run 13, fit on first shot, foms:
+{'fom': array([ 0.05494294, 0.06082832, 0.0530633 , 0.04097997, 0.04311072,
+ 0.04868919, 0.03658052, 0.05205008, 0.02965361, 0.0349829 ,
+ 0.05938427, 0.04889882, 0.04420127, 0.05612349, 0.05459789,
+ 0.04026893, 0.06067866, 0.04404101, 0.05147894, 0.06231822]),
+
diff --git a/alignment.py b/alignment.py
new file mode 100644
index 0000000..8f713da
--- /dev/null
+++ b/alignment.py
@@ -0,0 +1,589 @@
+from __future__ import print_function,division
+from skimage import transform as tf
+from scipy.ndimage import gaussian_filter1d as g1d
+import mcutils as mc
+import joblib
+import collections
+import numpy as np
+import matplotlib.pyplot as plt
+import time
+
+# /--------\
+# | |
+# | UTILS |
+# | |
+# \--------/
+
+#defaultE = np.arange(1024)*0.12+7060
+defaultE = (np.arange(1024)-512)*0.189+7123
+
+__i = np.arange(1024)
+__x = (__i-512)/512
+
+g_fit_default_kw = dict(
+ intensity = 1.,
+ error_intensity = 0.02,
+ transx = 0,
+ error_transx = 3,
+ limit_transx = ( -400,400 ),
+ transy = 0,
+ error_transy = 3,
+ limit_transy = ( -50,50 ),
+ rotation = 0.01,
+ error_rotation = 0.005,
+ limit_rotation = (-0.06,0.06),
+ scalex = 1,
+ limit_scalex = (0.4,1.2),
+ error_scalex = 0.05,
+ scaley = 1,
+ error_scaley = 0.05,
+ limit_scaley = (0.8,1.2),
+ shear = 0.01,
+ error_shear = 0.001,
+ limit_shear = (-0.2,0.2),
+ igauss1cen = 512,
+ error_igauss1cen = 2.,
+ fix_igauss1cen = True,
+ igauss1sig = 4000.,
+ error_igauss1sig = 2.,
+ fix_igauss1sig = True,
+ igauss2cen = 512,
+ error_igauss2cen = 2.,
+ fix_igauss2cen = True,
+ igauss2sig = 4000.,
+ error_igauss2sig = 2.,
+ fix_igauss2sig = True,
+ iblur1 = 0,
+ limit_iblur1 = (0,20),
+ error_iblur1 = 0.02,
+ fix_iblur1 = True
+)
+
+
+def rebin1D(a,shape):
+ n0 = a.shape[0]//shape
+ sh = shape,n0
+ return a[:n0*shape].reshape(sh).mean(1)
+
+
+kw_2dplot = dict(
+ interpolation = "none",
+ aspect = "auto",
+ cmap = plt.cm.viridis
+ )
+
+fit_ret = collections.namedtuple("fit_ret",["fit_result","init_pars","final_pars",\
+ "final_transform1","final_transform2","im1","im2","p1","p2","fom","ratio","tneeded"] )
+
+def calcFOM(p1,p2,ratio):
+ idx = ( p1>p1.max()/10 ) & (p2>p2.max()/10)
+ ratio = ratio[idx]
+ return ratio.std()/ratio.mean()
+
+def subtractBkg(imgs,nPix=100,bkg_type="line"):
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ if bkg_type == "line":
+ bkg = np.median(imgs[:,:nPix,:],axis=1)
+ imgs = imgs-bkg[:,np.newaxis,:]
+ elif bkg_type == "corner":
+ q1 = imgs[:,:nPix,:nPix].mean(-1).mean(-1)
+ imgs[:,:512,:512]-=q1[:,np.newaxis,np.newaxis]
+ q2 = imgs[:,:nPix,-nPix:].mean(-1).mean(-1)
+ imgs[:,:512,-512:]-=q2[:,np.newaxis,np.newaxis]
+ q3 = imgs[:,-nPix:,-nPix:].mean(-1).mean(-1)
+ imgs[:,-512:,-512:]-=q3[:,np.newaxis,np.newaxis]
+ q4 = imgs[:,-nPix:,:nPix].mean(-1).mean(-1)
+ imgs[:,-512:,:512]-=q4[:,np.newaxis,np.newaxis]
+ elif bkg_type is None:
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:].astype(np.float)
+ else:
+ print("Background subtraction '%s' Not impleted"%bkg_type)
+ return imgs
+
+def getCenterOfMax(img,axis=0,threshold=0.05):
+ img = img.copy()
+ img[imgp1.max()/10.) & (p2>p2.max()/10)
+ ax[5].plot(E[idx],pr[idx])
+ if res is not None:
+ ax[5].set_title("FOM: %.2f"%res.fom)
+ else:
+ ax[5].set_title("FOM: %.2f"% calcFOM(p1,p2,pr))
+ if (save is not None) and (save is not False): plt.savefig(save,transparent=True,dpi=500)
+ return fig
+
+def plotRatios(r,fig=None,E=defaultE,save=None):
+ if fig is None: fig = plt.subplots(2,1,sharex=True)[0]
+ ax = fig.axes
+ n = r.shape[0]
+ i = ax[0].imshow(r,**kw_2dplot,extent=(E[0],E[-1],0,n))
+ i.set_clim(0,1.2)
+ idx = np.random.random_integers(0,n-1)
+ ax[1].plot(E,r[idx],label="Shot n %d"%idx)
+ ax[1].plot(E,np.nanmedian(r[:10],axis=0),label="median 10 shots")
+ ax[1].plot(E,np.nanmedian(r,axis=0),label="all shots")
+ ax[1].legend()
+ ax[1].set_ylim(0,1.5)
+ ax[1].set_xlabel("Energy")
+ ax[1].set_ylabel("Transmission")
+ ax[0].set_ylabel("Shot num")
+ if (save is not None) and (save is not False): plt.savefig(save,transparent=True,dpi=500)
+
+def plotSingleShots(r,nShots=10,fig=None,E=defaultE,save=None,ErangeForStd=(7090,7150)):
+ if fig is None: fig = plt.subplots(2,1,sharex=True)[0]
+ ax = fig.axes
+ for i in range(nShots):
+ ax[0].plot(E,r[i]+i)
+ ax[0].set_ylim(0,nShots+0.5)
+ av = (1,3,10,30,100)
+ good = np.nanmedian(r,0)
+ for i,a in enumerate(av):
+ m = np.nanmedian(r[:a],0)
+ idx = (E>ErangeForStd[0]) & (E0): i = g1d(i,iblur[0],axis=1)
+ if (iblur[1] is not None) and (iblur[1]>0): i = g1d(i,iblur[1],axis=0)
+ if igauss is not None:
+ if isinstance(igauss,(int,float)):
+ igauss = (__i[-1]/2,igauss); # if one parameter only, assume it is centered on image
+ g = mc.gaussian(__i,x0=igauss[0],sig=igauss[1],normalize=False)
+ i *= g
+ if show: plotShot(img,i)
+ return i
+
+
+class SpecrometerTransformation(object):
+ def __init__(self,translation=(0,0),scale=(1,1),rotation=0,shear=0,
+ intensity=1,igauss=None,iblur=None):
+ self.affineTransform = getTransform(translation=translation,
+ scale = scale,rotation=rotation,shear=shear)
+ self.intensity=intensity
+ self.igauss = igauss
+ self.iblur = iblur
+
+ def update(self,**kw):
+ # current transformation, necessary because skimage transformation do not support
+ # setting of attributes
+ names = ["translation","scale","rotation","shear"]
+ trans_dict = dict( [(n,getattr(self.affineTransform,n)) for n in names] )
+ for k,v in kw.items():
+ if hasattr(self,k):
+ setattr(self,k,v)
+ elif k in names:
+ trans_dict[k] = v
+ self.affineTransform = getTransform(**trans_dict)
+
+ def transformImage(self,img,orderRotation=1,show=False):
+ return transformImage(img,self.affineTransform,iblur=self.iblur,\
+ intensity=self.intensity,igauss=self.igauss,orderRotation=orderRotation,\
+ show=show)
+
+def saveAlignment(fname,transform,roi1,roi2):
+ np.save(fname, dict( transform = transform, roi1=roi1, roi2 = roi2 ) )
+
+def loadAlignment(fname):
+ return np.load(fname).item()
+
+def unravel_results(res,getBest=False):
+ out = dict()
+ parnames = res[0].fit_result.parameters
+ out["parameters"] = dict()
+ for n in parnames:
+ out["parameters"][n] = np.asarray( [r.final_pars[n] for r in res])
+ out["ratio"] = np.asarray( [r.ratio for r in res])
+ out["p1"] = np.asarray( [r.p1 for r in res] )
+ out["p2"] = np.asarray( [r.p2 for r in res] )
+ out["fom"] = np.asarray( [r.fom for r in res] )
+ return out
+
+def getTransform(translation=(0,0),scale=(1,1),rotation=0,shear=0):
+ t= tf.AffineTransform(scale=scale,rotation=rotation,shear=shear,\
+ translation=translation)
+ return t
+
+def findTransform(p1,p2,ttype="affine"):
+ return tf.estimate_transform(ttype,p1,p2)
+
+
+#__i = np.arange(2**12)/2**11
+#def _transformToIntensitylDependence(transform):
+# c = 1.
+# if hasattr(transform,"i_a"):
+# c += transform.i_a*_i
+# return c
+
+
+
+# /--------\
+# | |
+# | FIT |
+# | |
+# \--------/
+
+
+def transformIminuit(im1,im2,init_transform=dict(),show=False,verbose=True,zeroThreshold=0.05,doFit=True):
+ import iminuit
+ assert im1.dtype == im2.dtype
+ t0 = time.time()
+ # create local copy we can mess up with
+ im1_toFit = im1.copy()
+ im2_toFit = im2.copy()
+
+ # set anything below the 5% of the max to zero (one of the two opal is noisy)
+ im1_toFit[im1_toFitnp.nanmax(p1)/10.
+ fom = calcFOM(p1,p2,r)
+ return fit_ret(
+ fit_result = imin,
+ init_pars = init_params,
+ final_pars = final_params,
+ final_transform1 = t1,
+ final_transform2 = t2,
+ im1 = i1,
+ im2 = i2,
+ p1 = p1,
+ p2 = p2,
+ ratio = r,
+ fom = fom,
+ tneeded = time.time()-t0
+ )
+
+
+# /--------\
+# | |
+# | MANUAL |
+# | ALIGN |
+# | |
+# \--------/
+class GuiAlignment(object):
+ def __init__(self,im1,im2,autostart=False):
+ self.im1 = im1
+ self.im2 = im2
+ self.f,self.ax=plt.subplots(1,2)
+ self.ax[0].imshow(im1,aspect="auto")
+ self.ax[1].imshow(im2,aspect="auto")
+ self.transform = None
+ if autostart:
+ return self.start()
+ else:
+ print("Zoom first then use the .start method")
+
+ def OnClick(self,event):
+ if event.button == 1:
+ if self._count % 2 == 0:
+ self.im1_p.append( (event.xdata,event.ydata) )
+ print("Added",event.xdata,event.ydata,"to im1")
+ else:
+ self.im2_p.append( (event.xdata,event.ydata) )
+ print("Added",event.xdata,event.ydata,"to im2")
+ self._count += 1
+ elif event.button == 2:
+ # neglect middle click
+ return
+ elif event.button == 3:
+ self.done = True
+ return
+ else:
+ return
+
+ def start(self):
+ self._nP = 0
+ self._count = 0
+ self.im1_p = []
+ self.im2_p = []
+ self.done = False
+ cid_up = self.f.canvas.mpl_connect('button_press_event', self.OnClick)
+ print("Press right button to finish")
+ while not self.done:
+ if self._count % 2 == 0:
+ print("Select point %d for left image"%self._nP)
+ else:
+ print("Select point %d for right image"%self._nP)
+ self._nP = self._count //2
+ plt.waitforbuttonpress()
+ self.im1_p = np.asarray(self.im1_p)
+ self.im2_p = np.asarray(self.im2_p)
+ self.transform = findTransform(self.im1_p,self.im2_p)
+ self.transform.intensity = 1.
+ return self.transform
+
+ def show(self):
+ if self.transform is None:
+ print("Do the alignment first (with .start()")
+ return
+ # just to save some tipying
+ im1 = self.im1; im2 = self.im2
+ im1_new = transformImage(im1,self.transform)
+ f,ax=plt.subplots(1,3)
+ ax[0].imshow(im1,aspect="auto")
+ ax[1].imshow(im1_new,aspect="auto")
+ ax[2].imshow(im2,aspect="auto")
+
+ def save(self,fname):
+ if self.transform is None:
+ print("Do the alignment first (with .start()")
+ return
+ else:
+ np.save(fname,self.transform)
+
+ def load(self,fname):
+ self.transform = np.load(fname).item()
+
+
+def getAverageTransformation(out):
+ res = unravel_results(out)
+ # get average parameters
+ tx = np.median(res["transx"])
+ ty = np.median(res["transy"])
+ sx = np.median(res["scalex"])
+ sy = np.median(res["scaley"])
+ r = np.median(res["rotation"])
+ sh = np.median(res["shear"])
+ inten = np.median(res["intensity"])
+ t = getTransform( (tx,ty),(sx,sy),r,sh,intensity=inten )
+ return t
+
+def checkAverageTransformation(out,imgs1):
+ t,inten = getAverageTransformation(out)
+ res["ratio_av"] = []
+ for shot,values in out.items():
+ i = transformImage(imgs1[shot],t)
+ p1 = np.nansum(i,axis=0)
+ r = p1/values.p2
+ res["ratio_av"].append( r )
+ res["ratio_av"] = np.asarray(res["ratio_av"])
+ return res
+
+
+g_lastpars = None
+
+def clearCache():
+ globals()["g_lastpars"]=None
+
+def doShot(i1,i2,init_pars,doFit=True,show=False):
+ #if g_lastpars is not None: init_pars = g_lastpars
+ r = transformIminuit(i1,i2,init_pars,show=show,verbose=False,doFit=doFit)
+ return r
+
+
+def doShots(imgs1,imgs2,initpars,nJobs=16,doFit=False,returnBestTransform=False):
+ clearCache()
+ N = imgs1.shape[0]
+ pool = joblib.Parallel(backend="threading",n_jobs=nJobs) \
+ (joblib.delayed(doShot)(imgs1[i],imgs2[i],initpars,doFit=doFit) for i in range(N))
+ if returnBestTransform:
+ idx = np.argmin( np.abs([p.fom for p in pool]) ); # abs because sometime fit screws up the give negative spectra...
+ print("FOM for best alignment %.2f"%pool[idx].fom)
+ return pool,pool[idx].final_transform1
+ else:
+ return pool
+# out = collections.OrderedDict( enumerate(pool) )
+# return out
+
+# /--------\
+# | |
+# | TEST |
+# | ALIGN |
+# | |
+# \--------/
+
+
+
+def testDiling(N=100,roi=slice(350,680),doGUIalignment=False,nJobs=4,useIminuit=True):
+ import xppll37_mc
+ globals()["g_lastpars"]=None
+ d = xppll37_mc.readDilingDataset()
+ im1 = xppll37_mc.subtractBkg(d.opal1[:N])[:,roi,:]
+ im2 = xppll37_mc.subtractBkg(d.opal2[:N])[:,roi,:]
+ N = im1.shape[0]; # redefie N in case it reads less than N
+ # to manual alignment
+ if doGUIalignment:
+ a = GuiAlignment(im1[0],im2[0])
+ input("Ok to start")
+ init_pars = a.start()
+ np.save("gui_align_transform.npy",init_pars)
+ else:
+ init_pars = np.load("gui_align_transform.npy").item()
+ pool = joblib.Parallel(backend="threading",n_jobs=nJobs,verbose=20) \
+ (joblib.delayed(doShot)(im1[i],im2[i],init_pars,useIminuit=useIminuit) for i in range(N))
+ out = collections.OrderedDict( enumerate(pool) )
+ return out
+
+if __name__ == '__main__':
+ pass
diff --git a/make_little_data.py b/make_little_data.py
new file mode 100644
index 0000000..bbefc67
--- /dev/null
+++ b/make_little_data.py
@@ -0,0 +1,16 @@
+import os
+import numpy as np
+import xppll37_mc
+import sys
+
+
+def do(run,N):
+ r = xppll37_mc.readDataset(run)
+ o1 = r.opal0[:N]
+ o2 = r.opal1[:N]
+ np.savez("littleData/run%04d.npz" % run, opal0 = o1, opal1 = o2 )
+
+if __name__ == "__main__":
+ run = int(sys.argv[1])
+ N=100
+ do(run,N)
diff --git a/mcutils.py b/mcutils.py
new file mode 100644
index 0000000..8ceaf4f
--- /dev/null
+++ b/mcutils.py
@@ -0,0 +1,1293 @@
+from __future__ import print_function,division
+#import sys
+#if (sys.version_info[0] < 3):
+import numpy as np
+from numpy import exp
+import re
+import codecs
+import string
+import scipy.signal
+import functools
+import types
+import os
+import pylab as plt
+from itertools import chain
+sqrt2=np.sqrt(2)
+
+
+### COLORS, ETC ###
+colors = None
+
+nice_colors = (
+# from http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
+ "#4D4D4D", # (gray)
+ "#5DA5DA", # (blue)
+ "#FAA43A", # (orange)
+ "#60BD68", # (green)
+ "#F17CB0", # (pink)
+ "#B2912F", # (brown)
+ "#B276B2", # (purple)
+ "#DECF3F", # (yellow)
+ "#F15854", # (red)
+)
+
+def colormap( list_of_colors ):
+ from matplotlib.colors import colorConverter,LinearSegmentedColormap
+ c = [ colorConverter.to_rgba(l) for l in list_of_colors ]
+ # make the colormaps
+ cmap = LinearSegmentedColormap.from_list('cmap',c,256)
+ return cmap
+
+def simpleaxis(ax=plt.gca()):
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.get_xaxis().tick_bottom()
+ ax.get_yaxis().tick_left()
+
+def noaxis(ax=plt.gca()):
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.spines['left'].set_visible(False)
+ ax.spines['bottom'].set_visible(False)
+
+def xrayAttLenght(*args,**kw):
+ from periodictable import xsf
+ n = xsf.index_of_refraction(*args,**kw)
+ if not "wavelength" in kw:
+ wavelength = 12.398/np.asarray(kw["energy"])
+ else:
+ wavelength = np.asarray(kw["wavelength"])
+ attenuation_length = np.abs( (wavelength*1e-10)/ (4*np.pi*np.imag(n)) )
+ return attenuation_length
+
+
+def xrayFluo(atom,density,energy=7.,length=30.,I0=1e10,\
+ det_radius=1.,det_dist=10.,det_material="Si",det_thick=300,verbose=True):
+ """ compound: anything periodictable would understand
+ density: in mM
+ length: sample length in um
+ energy: in keV, could be array
+ """
+ import periodictable
+ from periodictable import xsf
+ wavelength = 12.398/energy
+ atom = periodictable.__dict__[atom]
+ # 1e3 -> from mM to M
+ # 1e3 -> from L to cm3
+ # so 1 mM = 1e-3M/L = 1e-6 M/cm3
+ density_g_cm3 = density*1e-6*atom.mass
+ n = xsf.index_of_refraction(atom,density=density_g_cm3,wavelength=wavelength)
+ attenuation_length = xrayAttLenght( atom,density=density_g_cm3,energy=energy )
+ # um-> m: 1e-6
+ fraction_absorbed = 1.-np.exp(-length*1e-6/attenuation_length)
+ if verbose:
+ print("Fraction of x-ray photons absorbed by the sample:",fraction_absorbed)
+ ## detector ##
+ det_area = np.pi*det_radius**2
+ det_solid_angle = det_area/(4*np.pi*det_dist**2)
+ if verbose:
+ print("Detector fraction of solid angle:",det_solid_angle)
+ det_att_len = xrayAttLenght(det_material,wavelength=atom.K_alpha)
+ det_abs = 1-np.exp(-det_thick*1e-6/det_att_len)
+ if verbose:
+ print("Detector efficiency (assuming E fluo = E_K_alpha):",det_abs)
+ eff = fraction_absorbed*det_solid_angle*det_abs
+ if verbose:
+ print("Overall intensity (as ratio to incoming one):",eff)
+ return eff
+
+
+def pulseDuration(t0,L,GVD):
+ return t0*np.sqrt( 1.+(L/(t0**2/2/np.abs(GVD))))
+
+class MCError(Exception):
+ def __init__(self, value):
+ self.value = value
+ def __str__(self):
+ return repr(self.value)
+
+
+### VECTOR ... ETC. ###
+
+def vectorLenght(v):
+ """ assuming axis -1 as coord """
+ return np.sqrt(np.sum(v*v,axis=-1))
+
+def versor(v):
+ return v/vectorLenght(v)[:,np.newaxis]
+
+
+### LIST,INDEXING ... ETC. ###
+
+def smartIdx(idx,forceContigous=False):
+ """ Try to interpret an array of bool as slice;
+ this allows selecting a subarray alot more efficient
+ since array[slice] it returns a view and not a copy """
+ if (isinstance(idx,int)):
+ ret = slice(idx,idx+1)
+ elif (isinstance(idx,slice)):
+ ret = idx
+ else:
+ idx = np.asarray(idx)
+ if idx.dtype == np.bool:
+ i = np.where(idx)[0]
+ else:
+ i = idx
+ # in case there is only one
+ if (len(i) == 1):
+ ret = slice(i[0],i[0]+1)
+ return ret
+ if forceContigous:
+ ret = slice(i[0],i[-1])
+ else:
+ d = i[1:]-i[0:-1]
+ dmean = int(d.mean())
+ if np.all(d==dmean):
+ ret = slice(i[0],i[-1]+1,dmean)
+ else:
+ ret = idx
+ return ret
+
+
+### CONVOLUTION,INTERPOLATION,SMOOTHING ... ETC. ###
+
+def poly_approximant(x,y,order=10,allowExtrapolation=False,fill_value=0):
+ """ return a polinomial view """
+ poly = np.polyfit(x,y,order)
+ def f(xx):
+ res = np.polyval(poly,xx)
+ if allowExtrapolation:
+ return res
+ else:
+ if np.isscalar(xx) and ( ( xx>x.max()) or (xxx.max() )
+ res[idx] = fill_value
+ return res
+ return f
+
+
+def smoothing(x,y,err=None,k=5,s=None,newx=None,derivative_order=0):
+ idx = np.isnan(x)|np.isnan(y)
+ idx = ~ idx
+ if newx is None: newx=x
+ if idx.sum() > 0:
+ x=x[idx]
+ y=y[idx]
+ if idx.sum() < 3:
+ return np.ones(len(newx))
+ if err is None:
+ w=None
+ elif err == "auto":
+ n=len(x)
+ imin = max(0,n/2-20)
+ imax = min(n,n/2+20)
+ idx = range(imin,imax)
+ p = np.polyfit(x[idx],y[idx],4)
+ e = np.std( y[idx] - np.polyval(p,x[idx] ) )
+ w = np.ones_like(x)/e
+ else:
+ w=np.ones_like(x)/err
+ from scipy.interpolate import UnivariateSpline
+ if (s is not None):
+ s = len(x)*s
+ s = UnivariateSpline(x, y,w=w, k=k,s=s)
+ if (derivative_order==0):
+ return s(newx)
+ else:
+ try:
+ len(derivative_order)
+ return [s.derivative(d)(newx) for d in derivative_order]
+ except:
+ return s.derivative(derivative_order)(newx)
+
+
+def interpolator(x,y,kind='linear',axis=-1, copy=False, bounds_error=False, fill_value=np.nan):
+ from scipy import interpolate
+ if (kind != "linear"):
+ print("Warning interp1d can be VERY SLOW when using something that is not liear")
+ f = interpolate.interp1d(x,y,kind=kind,axis=axis,copy=copy,bounds_error=bounds_error,fill_value=fill_value)
+ return f
+
+def interpolator_spl(x,y,kind="cubic"):
+ from scipy import interpolate as itp
+ if kind == "linear": kind=1
+ if kind == "cubic" : kind=3
+ splinepars = itp.splrep(x,y,k=kind)
+ def f(x,der=0,):
+ """f(x) returns values for x[i]. f(x,order) return order-th derivative"""
+ return itp.splev(x,splinepars,der=der)
+ return f
+
+def interpolate_fast(x,y,newx,kind='cubic'):
+ f = interpolator_spl(x,y,kind=kind)
+ return f(newx)
+
+def interpolate(x,y,newx,kind='linear',axis=-1, copy=False, bounds_error=False, fill_value=np.nan):
+ f = interpolator(x,y,kind=kind,axis=axis,copy=copy,bounds_error=bounds_error,fill_value=fill_value)
+ return f(newx)
+
+def getElement(a,i,axis=-1):
+ nDim = a.ndim
+ if (axis<0): axis = nDim+axis
+ colon = (slice(None),)
+ return a[colon*axis+(i,)+colon*(nDim-axis-1)]
+
+def setElement(a,i,res,axis=-1):
+ temp = getElement(a,i,axis=axis)
+ np.copyto(temp,res)
+
+def invertedView(x):
+ return x[ slice(None,None,-1) ]
+
+def convolveQuad(x,y,xres,yres,useAutoCrop=True,
+ fill_value=0.,axis=-1):
+ print("NOT FINISHED")
+ return
+ from scipy import integrate
+ if (useAutoCrop):
+ idxRes = smartIdx( yres>(1e-4*yres.max()) )
+ #print("Autocropping",idxRes,xres.shape)
+ else:
+ idxRes = slice(None)
+ xresInv = -invertedView( xres[idxRes] )
+ yresInv = invertedView( yres[idxRes] )
+ area = integrate.simps(yres,x=xres)
+
+ f = interpolator(x,y)
+ r = interpolator(xres,yres)
+
+ if y.ndim < 2: y = y[np.newaxis,:]
+ nDim = y.ndim
+ if (axis<0): axis = nDim+axis
+
+ ## expand yres to allow broadcasting
+ sh = [1,]*y.ndim
+ sh[axis] = len(yres)
+ yres = yres.reshape(sh)
+
+ ## prepare output
+ out = np.empty_like(y)
+ nP = len(x)
+ for i in range(nP):
+ # interpolate x,y on xres+x[i]
+ x_integral = xresInv+x[i]
+ ytemp = interpolate(x,y,x_integral,fill_value=fill_value,axis=axis)/area
+ # do integration
+ res = integrate.simps(ytemp*yresInv,x=xresInv+x[i],axis=axis)
+ colon = (slice(None),)
+ setElement(out,i,res,axis=axis)
+ return out
+
+
+def convolve(x,y,xres,yres,useAutoCrop=True,approximantOrder=None,fill_value=0.,axis=-1):
+ """ if approximantOrder is not None, use interpolating polynomial of order
+ approximantOrder to perform integration """
+ from scipy import integrate
+ import copy
+ if (useAutoCrop):
+ idxRes = smartIdx( yres>(1e-4*yres.max()) )
+ #print("Autocropping",idxRes,xres.shape)
+ else:
+ idxRes = slice(None)
+ xresInv = -invertedView( xres[idxRes] )
+ yresInv = invertedView( yres[idxRes] )
+ area = integrate.simps(yres,x=xres)
+
+ if approximantOrder is not None:
+ #print("Using approximant!!",xresInv.shape)
+ approx = poly_approximant(xresInv,yresInv/area,approximantOrder,
+ allowExtrapolation=False,fill_value=0)
+ #return approx,xresInv,yresInv
+ return convolveFunc(x,y,approx,fill_value=fill_value,axis=axis,)
+
+ if y.ndim < 2: y = y[np.newaxis,:]
+ nDim = y.ndim
+ if (axis<0): axis = nDim+axis
+
+ ## expand yres to allow broadcasting
+ sh = [1,]*y.ndim
+ sh[axis] = len(yres)
+ yres = yres.reshape(sh)
+
+ ## prepare output
+ out = np.empty_like(y)
+ nP = len(x)
+ f = interpolator(x,y,fill_value=fill_value,axis=axis)
+ for i in range(nP):
+ # interpolate x,y on xres+x[i]
+ x_integral = xresInv+x[i]
+ ytemp = f(x_integral)/area
+ #ytemp = interpolate(x,y,x_integral,fill_value=fill_value,axis=axis)/area
+ #ytemp = f(x_integral)/area
+ # do integration
+ res = integrate.simps( np.transpose(ytemp.T*yresInv),x=xresInv+x[i],axis=axis)
+ colon = (slice(None),)
+ setElement(out,i,res,axis=axis)
+ return out
+
+
+def fftconvolve(x,y,yres,xres=None,normalize=False):
+ if (xres is not None):
+ yres = interpolate(xres,yres,x,fill_value=0)
+ fft = scipy.signal.fftconvolve(y,yres,"full")
+ _idx = np.argmin( np.abs(x) ); # find t=0
+ fft = fft[_idx:_idx+len(x)]
+ if normalize:
+ norm = fftconvolve_find_norm(x,yres,xres=None)
+ else:
+ norm = 1
+ return fft/norm
+
+def fftconvolve_find_norm(x,res,xres=None):
+ step = np.ones_like(x)
+ n = int( len(step)/2 )
+ step[:n] = 0
+ norm = fftconvolve(x,step,res,xres=xres,normalize=False).max()
+ return norm
+
+def convolveGaussian(x,y,sig=1.,nPointGaussian=51,fill_value=0.,axis=-1):
+ xG = np.linspace(-5*sig,5*sig,nPointGaussian)
+ G = gaussian(xG,x0=0,sig=sig)
+ return convolve(x,y,xG,G,fill_value=fill_value,axis=axis)
+
+
+def convolveFunc(x,y,func_res,fill_value=0.,axis=-1):
+ from scipy import integrate
+ if y.ndim < 2: y = y[np.newaxis,:]
+ nDim = y.ndim
+ if (axis<0): axis = nDim+axis
+
+ ## prepare output
+ out = np.empty_like(y)
+
+ nP = len(x)
+ for i in range(nP):
+ # calculate the values of the resolution function on x-x[i]
+ ytemp = func_res(x-x[i])
+ # do integration
+ res = integrate.simps(y*ytemp,x=x-x[i],axis=axis)
+ setElement(out,i,res,axis=axis)
+ return out
+
+def convolveFuncParams(x,y,func_res,func_res_pars,fill_value=0.,axis=-1):
+ def tempFunc(xx):
+ return func_res(xx,*func_res_pars)
+ return convolveFunc(x,y,tempFunc,fill_value=fill_value,axis=axis)
+
+def convolve_test(nG=51):
+ import time
+ x=np.arange(100)
+ y=(x>50).astype(np.float)
+ sig = 3
+ xG = np.linspace(-5*sig,5*sig,nG)
+ G = gaussian(xG,x0=0,sig=sig)
+ Gpoly = np.polyfit(xG,G,20)
+ t0 = time.time()
+ conv_num = convolve(x,y,xG,G,fill_value=0.)
+ print("Num:",time.time()-t0)
+ t0 = time.time()
+ conv_poly = convolve(x,y,xG,G,approximantOrder=10,fill_value=0.)
+ print("Num:",time.time()-t0)
+ t0 = time.time()
+ conv_fun = convolveFuncParams(x,y,gaussian,(0,sig),fill_value=0.)
+ print("Fun:",time.time()-t0)
+ import pylab as plt
+ plt.plot(conv_num.T,label="Numerical %d points" % nG)
+ plt.plot(conv_fun.T,"o",label="Gaussian F")
+ plt.plot(conv_poly.T,label="Gaussian (poly)")
+ plt.plot(conv_num.T-conv_fun.T)
+ return conv_num,conv_fun
+
+
+def conv_gauss_and_const(x,sig):
+ from scipy.special import erf
+ return 0.5*(1-erf(-x/sqrt2/sig))
+
+def conv_gauss_and_exp(x,sig,tau):
+ from scipy.special import erf
+ #from mpmath import erf
+ #http://www.numberempire.com/integralcalculator.php?function=exp%28-x%2Fl%29*exp%28-%28t-x%29**2%2F2%2Fs**2%29%2FSqrt%282%29%2FSqrt%28pi%29%2Fs&var=x&answers=
+ # actually calculated with sympy
+ #return -(erf(sqrt2*(sig**2 - x*tau)/(2*sig*tau)) - 1)*exp(sig**2/(2*tau**2) - x/tau)/2
+ return 0.5*np.exp(-(2*tau*x-sig**2)/2/tau**2)*(1-erf( (-tau*x+sig**2)/sqrt2/tau/sig))
+
+def gaussian(x,x0=0,sig=1,normalize=True):
+ g = np.exp(-(x-x0)**2/2/sig**2)
+ if normalize:
+ return 1/np.sqrt(2*np.pi)/sig*g
+ else:
+ return g
+
+
+## FFT filter ##
+class FFTfilter(object):
+ def __init__(self,s,dx=1,wins=((0.024,0.01),),wintype="gauss"):
+ f,ffts = fft(s,dx=dx)
+ filter = np.ones_like(f)
+ for win in wins:
+ if wintype == "gauss":
+ filter *= (1-gaussian(f,win[0],win[1],normalize=False))
+ filter *= (1-gaussian(f,-win[0],win[1],normalize=False))
+ else:
+ print("Not implemented")
+
+ self.filter=filter
+
+ def apply(self,s):
+ s = np.fft.fft(s)
+ return np.fft.ifft(s*self.filter)
+
+
+### PROMPT,PROCESS,TIME,DATE ... ETC. ###
+
+class procCom(object):
+ def __init__(self,cmd):
+ import pexpect
+ self.proc = pexpect.spawn(cmd)
+
+ def get(self,timeout=None,waitFor=None):
+ import pexpect
+ if (waitFor is not None):
+ s = ""
+ try:
+ while s.find(waitFor)<0:
+ s+=self.proc.read_nonblocking(timeout=timeout)
+ except (pexpect.TIMEOUT,pexpect.EOF):
+ pass
+ else:
+ s=""
+ try:
+ while 1:
+ s+=self.proc.read_nonblocking(timeout=timeout)
+ except (pexpect.TIMEOUT,pexpect.EOF):
+ pass
+ #print "got",s
+ return s
+
+ def send(self,what):
+ self.proc.write(what)
+ self.proc.flush()
+ #print "send",what
+
+ def query(self,what,timeout=None,waitFor=None):
+ self.send(what)
+ return self,get(timeout=timeout,waitFor=waitFor)
+
+def getCMD(cmd,strip=True):
+ import os
+ shell = os.popen(cmd)
+ ret = shell.readlines()
+ shell.close()
+ if (strip):
+ ret = [x.strip() for x in ret]
+ return ret
+
+def lsdir(path,withQuotes=False,recursive=False):
+ if recursive:
+ dirs = []
+ for (dir, _, file) in os.walk(path): dirs.append(dir)
+ else:
+ content = getCMD("ls -1 %s" % path)
+ content = ["%s/%s" % (path,x) for x in content]
+ dirs = [x for x in content if os.path.isdir(x)]
+ if (withQuotes):
+ dirs = [ "'%s'" % x for x in dirs ]
+ return dirs
+
+
+def lsfiles(path,withQuotes=False,recursive=False):
+ if recursive:
+ print("Not sure is working")
+ files = []
+ for (dir, _, file) in os.walk(path): files.append(file)
+ else:
+ content = getCMD("ls -1 %s" % path)
+ content = ["%s/%s" % (path,x) for x in content]
+ files = [x for x in content if os.path.isfile(x)]
+ if (withQuotes):
+ files = [ "'%s'" % x for x in files ]
+ return files
+
+def downloadPDB(pdbID,outFileName=None):
+ import urllib2
+ import os
+ address = "http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=%s" % pdbID
+ p = urllib2.urlopen(address)
+ lines = p.readlines()
+ if (outFileName is None):
+ outFileName = pdbID+".pdb"
+ folder = os.path.dirname(outFileName)
+ if (folder != '' and not os.path.exists(folder)):
+ os.makedirs(folder)
+ f=open(outFileName,"w")
+ f.write( "".join(lines) )
+ f.close()
+
+
+def dateStringToObj(s,format="%Y.%m.%d %H:%M:%S"):
+ import datetime
+ return datetime.datetime.strptime(s,format)
+
+def now():
+ import time
+ return time.strftime("%Y.%m.%d %H:%M:%S",time.localtime())
+
+def mytimer(func,args):
+ import time
+ t0=time.time()
+ ret=func(*args)
+ return time.time()-t0,ret
+
+### TXT I/O ###
+
+def lineToVals(line):
+ return map(eval,string.split(line))
+
+class DataFile(object):
+ filename=""
+ lines=[]
+ comments=[]
+ head={}
+ Data=[]
+ Ndata=0
+
+ def __init__(self,f):
+ self.filename=f
+ self.Read()
+
+ def Read(self):
+ f=open(self.filename,"r")
+ temp = f.readlines();
+ f.close();
+ r=re.compile('\s+');
+ c=re.compile('^\s*#');
+ for l in temp:
+ if (re.match(c,l)):
+ self.comments.append(l)
+ else:
+ self.lines.append(l)
+ # first of non commented line might be header
+ # try to understand it
+ keys = []
+ try:
+ v=lineToVals(self.lines[0])
+ for i in range(len(v)):
+ keys.append(i)
+ except:
+ keys=self.lines[0].split()
+ self.lines.remove( self.lines[0] )
+ datatemp = []
+ for l in self.lines:
+ datatemp.append( lineToVals(l) )
+ self.Data = np.asarray(datatemp)
+ for i in range(len(keys)):
+ self.head[keys[i]] = self.Data[:,i]
+ self.__dict__[keys[i]] = self.Data[:,i]
+ (self.Ndata,self.Ncol) = self.Data.shape
+
+ def clean(self):
+ del self.Data
+
+
+def writev(fname,x,Ys,form="%+.6g",sep=" ",header=None,headerv=None):
+ """ Write data to file 'fname' in text format.
+ Inputs:
+ x = x vector
+ Ys = vector(or array or list of vectors) for the Ys
+ form = format to use
+ sep = separator
+ header = text header (must be a string)
+ headerv = vector to be used as header, it is convienient when
+ the output must be of the form
+ Ncol 252 253 254
+ x1 y11 y12 y13
+ .......
+ In this case headerv should be [252,253,254]
+ """
+ if (type(x) != np.ndarray): x=np.array(x)
+ if (type(Ys) != np.ndarray): Ys=np.array(Ys)
+ if (len(Ys.shape)==1):
+ Ys=Ys.reshape(Ys.shape[0],1)
+ nx = len(x)
+ if (Ys.shape[0] == nx):
+ ny=Ys.shape[1]
+ elif (Ys.shape[1] == nx):
+ ny=Ys.shape[0]
+ Ys=np.transpose(Ys)
+ else:
+ raise MCError("dimension of x (%d) does not match any of the dimensions of Ys (%d,%d)" % (nx,Ys.shape[0],Ys.shape[1]))
+ f=codecs.open(fname,encoding='utf-8',mode="w")
+ if (header is not None):
+ f.write(header.strip()+"\n")
+ if (headerv is not None):
+ f.write("%d" % (ny+1))
+ for i in range(ny):
+ f.write(sep)
+ f.write(form % headerv[i])
+ f.write("\n")
+ for i in range(nx):
+ f.write(form % x[i])
+ f.write(sep)
+ for j in range(ny-1):
+ f.write(form % Ys[i,j])
+ f.write(sep)
+ f.write(form % Ys[i,-1])
+ f.write("\n")
+ f.close()
+
+
+def writev(fname,x,Ys,form="%+.6g",sep=" ",header=None,headerv=None):
+ """ Write data to file 'fname' in text format.
+ Inputs:
+ x = x vector
+ Ys = vector(or array or list of vectors) for the Ys
+ form = format to use
+ sep = separator
+ header = text header (must be a string)
+ headerv = vector to be used as header, it is convienient when
+ the output must be of the form
+ Ncol 252 253 254
+ x1 y11 y12 y13
+ .......
+ In this case headerv should be [252,253,254]
+ """
+ if (type(x) != np.ndarray): x=np.array(x)
+ if (type(Ys) != np.ndarray): Ys=np.array(Ys)
+ if (len(Ys.shape)==1):
+ Ys=Ys.reshape(Ys.shape[0],1)
+ nx = len(x)
+ if (Ys.shape[1] == nx):
+ ny=Ys.shape[0]
+ elif (Ys.shape[0] == nx):
+ ny=Ys.shape[1]
+ Ys=np.transpose(Ys)
+ else:
+ raise MCError("dimension of x (%d) does not match any of the dimensions of Ys (%d,%d)" % (nx,Ys.shape[0],Ys.shape[1]))
+ f=codecs.open(fname,encoding='utf-8',mode="w")
+ if (header is not None):
+ f.write(header.strip()+"\n")
+ if (headerv is not None):
+ f.write("%d" % (ny+1))
+ for i in range(ny):
+ f.write(sep)
+ f.write(form % headerv[i])
+ f.write("\n")
+ out = np.vstack( (x,Ys) )
+ np.savetxt(f,np.transpose(out),fmt=form,delimiter=sep)
+
+def loadtxt(fname,hasVectorHeader=True,asObj=False,isRecArray=False):
+ if (isRecArray):
+ return loadRecArray(fname,asObj=asObj)
+ a=np.loadtxt(fname)
+ if (not hasVectorHeader):
+ x = a[:,0]
+ y = a[:,1:].T
+ t = None
+ else:
+ x = a[1:,0]
+ y = a[1:,1:].T
+ t = a[0,1:]
+ if (asObj):
+ class txtFile(object):
+ def __init__(self,x,y,t):
+ self.x = x
+ self.y = y
+ self.t = t
+ return txtFile(x,y,t)
+ else:
+ return x,y,t
+
+def loadRecArray(fname,hasVectorHeader=True,asObj=False):
+ a=np.loadtxt(fname,skiprows=1)
+ # find header
+ f=open(fname,"r")
+ found = None
+ while found is None:
+ s=f.readline().strip()
+ if s[0] != "#":
+ found = s
+ names = found.split()
+ if (asObj):
+ class txtFile(object):
+ def __init__(self):
+ pass
+ ret = txtFile()
+ for i in range(len(names)):
+ ret.__dict__[names[i]] = a[:,i]
+ else:
+ ret = np.core.records.fromarrays(a.transpose(),names=",".join(names))
+ return ret
+
+
+def prepareRecArrayFromDict( mydict,n=1,leaveEmpty=True ):
+ names = mydict.keys()
+ formats = [ type(mydict[p]) for p in names ]
+ if leaveEmpty:
+ array_kind = np.empty
+ else:
+ array_kind = np.zeros
+ return array_kind(n, dtype={'names':names, 'formats':formats})
+
+def prepareRecArrayFromNamesAndArray( names,ar,n=1,leaveEmpty=True ):
+ formats = [ ar.dtype.type for p in names ]
+ if leaveEmpty:
+ array_kind = np.empty
+ else:
+ array_kind = np.zeros
+ return array_kind(n, dtype={'names':names, 'formats':formats})
+
+
+
+def writeMatrix(fout,M,x,y,form="%+.6g",sep=" ",header=None):
+ (nx,ny) = M.shape
+ if ( (nx == len(x)) and (ny==len(y)) ):
+ pass
+ elif ( (nx == len(y)) and (ny==len(x)) ):
+ M=M.transpose()
+ (nx,ny) = M.shape
+ else:
+ e = "Dimensions of matrix and the x or y vectors don't match"
+ e += "shapes of M, x, y: " + str(M.shape) + " " +str(len(x))+ " " +str(len(y))
+ raise MCError(e)
+ temp = np.zeros( (nx+1,ny) )
+ temp[1:,:] = M
+ temp[0,:] = y
+ writev(fout,np.hstack( (0,x) ),temp,form=form,sep=sep,header=header)
+
+
+### MATPLOTLIB ... ETC. ###
+
+def lt(i,style="-"):
+ colors="rkbgy"
+ i = i%len(colors)
+ color = colors[i]
+ if (style is not None): color += style
+ return color
+
+def displayFig(i,x=None,y=None,roi=None):
+ import pylab as plt
+ from matplotlib.widgets import Slider, Button, RadioButtons
+ fig=plt.figure()
+ n1,n2=i.shape
+ if x is None:
+ x = np.arange(n1)
+ if y is None:
+ y = np.arange(n2)
+
+ ax = fig.add_subplot(111)
+ if roi is not None:
+ (x1,x2,y1,y2) = roi
+ else:
+ x1,x2,y1,y2 = (0,n1,0,n2)
+ xm=x[x1]; xM=x[x2-1]
+ ym=y[y1]; yM=y[y2-1]
+ def _format_coord(x, y):
+ col = int(x+0.5)
+ row = int(y+0.5)
+ if col>=0 and col=0 and rownhalf):
+ vec = np.concatenate( (vec[at_idx-nhalf:],vec[:at_idx-nhalf] ))
+ else:
+ vec = np.concatenate( (vec[at_idx+nhalf:],vec[:at_idx+nhalf]))
+ return vec
+
+### REBIN, RUNNING AVG, ... ETC ###
+
+def rebinOLD(bins_edges,x,*Y):
+ """ rebins a list of Y based on x using bin_edges
+ returns
+ center of bins (vector)
+ rebinned Y (list of vectors)
+ Simga's (list of vectors), note: just std not std of average
+ N (list of vectors), number of occurrances
+ """
+ n=len(bins_edges)-1
+ outX = []
+ outY = []
+ outS = []
+ outN = []
+ for j in range(len(Y)):
+ outY.append(np.empty(n))
+ outS.append(np.empty(n))
+ outN.append(np.empty(n))
+ outX = np.empty(n)
+ for i in range(n):
+ idx = (x>=bins_edges[i]) & (x 0):
+ for j in range(len(Y)):
+ outN[j][i] = idx.sum()
+ outY[j][i] = Y[j][idx].mean()
+ outS[j][i] = Y[j][idx].std()
+ else:
+ for j in range(len(Y)):
+ outN[j][i] = 0
+ outY[j][i] = np.nan
+ outS[j][i] = np.nan
+ return outX,outY,outS,outN
+
+def rebin1D(a,shape):
+ sh = shape,a.shape[0]//shape
+ return a.reshape(sh).mean(1)
+
+def rebin1Dnew(a,shape):
+ n0 = a.shape[0]//shape
+ sh = shape,n0
+ return a[:n0*shape].reshape(sh).mean(1)
+
+def rebin2D(a, shape):
+ sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1]
+ return a.reshape(sh).mean(-1).mean(1)
+
+def rebin2Dnew(a, shape):
+ # // means floor
+ n0 = a.shape[0]//shape[0]
+ n1 = a.shape[1]//shape[1]
+ crop = shape[0]*n0,shape[1]*n1
+ sh = shape[0],n0,shape[1],n1
+ #print a[:n0*shape[0],:n1*shape[1]].reshape(sh)
+ return a[:crop[0],:crop[1]].reshape(sh).mean(-1).mean(1)
+
+def rebin3Dnew(a, shape):
+ # // means floor
+ n0 = a.shape[0]//shape[0]
+ n1 = a.shape[1]//shape[1]
+ n2 = a.shape[2]//shape[2]
+ sh = shape[0],n0,shape[1],n1,shape[2],n2
+ crop = n0*shape[0],n1*shape[1],n2*shape[2]
+ #print a[:n0*shape[0],:n1*shape[1]].reshape(sh)
+ return a[:crop[0],:crop[1],:crop[2]].reshape(sh).mean(-1).mean(-2).mean(-3)
+
+def rebin(a, shape):
+ a = np.asarray(a)
+ ndim = a.ndim
+ if (ndim == 1):
+ return rebin1Dnew(a,shape)
+ elif (ndim == 2):
+ return rebin2Dnew(a,shape)
+ elif (ndim == 3):
+ return rebin3Dnew(a,shape)
+ else:
+ print("Can't do rebin of",a)
+
+
+def rebinTODO(a, shape):
+ ndim = a.ndim
+ if (len(shape) != ndim):
+ print("Error, asked to rebin a %d dimensional array but provided shape with %d lengths" % (ndim,len(shape)))
+ return None
+ nout = []
+ for n in range(ndim):
+ nout.append( a.shape[n]%shape[n] )
+ print("Not implemented ...")
+
+### DISTRIBUTION, MEDIAN, SIGMA, ETC. ###
+
+def idx_within_std_from_center(vector,range):
+ (m,s) = MedianAndSigma(vector)
+ return np.abs(vector-m)<(range*s)
+
+def MedianAndSigma(a):
+ median = np.median(a)
+ MAD = np.median(np.abs(a-median))
+ sigma = 1.4826*MAD; # this assumes gauss distribution
+ return (median,sigma)
+
+def weigthed_average(y,e=None,axis=0):
+ if e is None:
+ e=np.ones_like(y)
+ if (axis != 0):
+ y = y.transpose()
+ e = e.transpose()
+ (n0,n1) = y.shape
+ yout = np.empty(n1)
+ eout = np.empty(n1)
+ for i in range(n1):
+ toav = y[:,i]
+ valid = np.isfinite(toav)
+ toav = toav[valid]
+ w = 1/e[valid,i]**2
+ yout[i] = np.sum(toav*w)/np.sum(w)
+ eout[i] = np.sqrt(1/np.sum(w))
+ return yout,eout
+
+### CONVERSION ###
+def convert(value=1,unit="eV",out="nm"):
+ if (unit == "eV") & (out =="nm"):
+ return 1239.8/value
+
+
+### IMINUIT RELATED ###
+
+def iminuitClass(modelFunc):
+ """ build a class to help fitting, first argumes of modelFunc should be x"""
+ import inspect
+ import iminuit
+ import iminuit.util
+ args = inspect.getargspec(modelFunc).args
+ defaults = inspect.getargspec(modelFunc).defaults
+ if defaults is not None:
+ nDef = len( defaults )
+ args = args[:-nDef]
+ args_str = ",".join(args[1:])
+
+
+ class iminuitFit(object):
+ def __init__(self,x,data,init_pars,err=1.):
+ self.x = x
+ self.data = data
+ self.err = err
+ self.init_pars=init_pars
+ self.func_code = iminuit.util.make_func_code(args[1:])#docking off independent variable
+ self.func_defaults = None #this keeps np.vectorize happy
+
+ def __call__(self,*arg):
+ return self.chi2(*arg)
+
+ def model(self,*arg):
+ return modelFunc(self.x,*arg)
+
+ def chi2(self,*arg):
+ c2 = (self.model(*arg)-self.data)/self.err
+ return np.sum(c2*c2)
+
+ def fit(self,showInit=True,showPlot=True,doFit=True,doMinos=False):
+ import pylab as plt
+ p = self.init_pars
+ if "errordef" not in p:
+ p["errordef"] = 1.
+ #m = iminuit.Minuit(self,print_level=0,pedantic=False,**p)
+ m = iminuit.Minuit(self,**p)
+ if showInit:
+ model = self.model(*m.args)
+ plt.figure("initial pars")
+ plt.grid()
+ plt.plot(self.x,self.data,"o")
+ plt.plot(self.x,model,'r-',linewidth=2)
+ raw_input()
+ if doFit:
+ m.migrad()
+ if doMinos:
+ m.minos()
+ for p in m.parameters:
+ err = m.get_merrors()[p]
+ err = "+ %.4f - %.4f" % (np.abs(err["upper"]),np.abs(err["lower"]))
+ print("%10s %.4f %s"%(p,m.values[p],err))
+ else:
+ for p in m.parameters:
+ err = m.errors[p]
+ err = "+/- %.4f" % (err)
+ print("%10s %.4f %s"%(p,m.values[p],err))
+
+ model = self.model(*m.args)
+ if (showPlot):
+ plt.figure("final fit")
+ plt.grid()
+ plt.plot(self.x,self.data,"o")
+ plt.plot(self.x,model,'r-',linewidth=2)
+ self.m = m
+ return m,self.x,self.data,model
+
+ return iminuitFit
+
+
+def iminuitParsToStr(iminuit,withErrs=True,withFixed=True):
+ values = iminuit.values
+ errs = iminuit.errors
+ pnames = values.keys()
+ lenParNames = max( [len(p) for p in pnames] )
+ fmt = "%%%ds" % lenParNames
+ pnames.sort()
+ res = []
+ for p in pnames:
+ v = values[p]
+ e = errs[p]
+ isf = iminuit.is_fixed(p)
+ if not withFixed and isf:
+ continue
+ v,e = approx_err(v,e,asstring=True)
+ if isf: e="fixed"
+ s = fmt % p
+ if withErrs:
+ s += " = %s +/- %s" % (v,e)
+ else:
+ s += " = %s" % (v)
+ res.append(s)
+ return res
+
+
+### VARIOUS ###
+
+def myProgressBar(N,title="Percentage"):
+ import progressbar as pb
+ widgets = [title, pb.Percentage(), ' ', pb.Bar(), ' ', pb.ETA()]
+ pbar = pb.ProgressBar(widgets=widgets, maxval=N)
+ return pbar
+
+def chunk(iterableOrNum, size):
+ temp = []
+ try:
+ n = len(iterableOrNum)
+ except TypeError:
+ n = iterableOrNum
+ nGroups = int(np.ceil(float(n)/size))
+ for i in range(nGroups):
+ m = i*size
+ M = (i+1)*size; M=min(M,n)
+ if (m>=n):
+ break
+ temp.append( slice(m,M) )
+ try:
+ ret = [iterableOrNum[x] for x in temp]
+ except TypeError:
+ ret = temp
+ return ret
+
+def timeres(*K):
+ """ return sqrt(a1**2+a2**2+...) """
+ s = 0
+ for k in K:
+ s += k**2
+ return np.sqrt(s)
+
+def approx_err(value,err,asstring=False):
+ if (not (np.isfinite(err))):
+ err = np.abs(value/1e3)
+ if (err != 0):
+ ndigerr = -int(np.floor(np.log10(err)))
+ if (ndigerr<1): ndigerr=2
+ e =round(err,ndigerr)
+ ndigerr = -int(np.floor(np.log10(err)))
+ v =round(value,ndigerr)
+ else:
+ v=value
+ e=err
+ if (asstring):
+ return "%s" % v,"%s" % e
+ else:
+ return v,e
+
+def linFitOld(A,B):
+ """ solve Ax = B, returning x """
+ temp = np.dot(A.T,B)
+ square = np.dot(A.T,A)
+ if (np.asarray(square).ndim==0):
+ inv = 1./square
+ else:
+ inv = np.linalg.inv(square)
+ x = np.dot(inv,temp)
+ return x
+
+
+
+def linFit(A,B,cond=None):
+ """ solve Ax = B, returning x """
+ from scipy import linalg
+ temp = np.dot(A.T,B)
+ square = np.dot(A.T,A)
+ if (np.asarray(square).ndim==0):
+ inv = 1./square
+ else:
+ inv = linalg.pinvh(square,cond=cond)
+ x = np.dot(inv,temp)
+ return x
+ #return np.linalg.lstsq(A,B)[0]
+
+def insertInSortedArray(a,v):
+ if v>a.max(): return a
+ idx = np.argmin(a1:
+ vvo = []
+ for i in range(len(vv)-1):
+ vvo.append(np.linspace(vv[i],vv[i+1],oversample+1)[:-1])
+ vvo.append(vv[-1])
+ vv = np.array(np.hstack(vvo))
+ return vv
+
+def subtractBkg(imgs,nPix=100,dKtype='corners'):
+ """ Opals tend to have different backgroud for every quadrant """
+ if dKtype is 'corners':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ q1 = imgs[:,:nPix,:nPix].mean(-1).mean(-1)
+ imgs[:,:512,:512]-=q1[:,np.newaxis,np.newaxis]
+ q2 = imgs[:,:nPix,-nPix:].mean(-1).mean(-1)
+ imgs[:,:512,-512:]-=q2[:,np.newaxis,np.newaxis]
+ q3 = imgs[:,-nPix:,-nPix:].mean(-1).mean(-1)
+ imgs[:,-512:,-512:]-=q3[:,np.newaxis,np.newaxis]
+ q4 = imgs[:,-nPix:,:nPix].mean(-1).mean(-1)
+ imgs[:,-512:,:512]-=q4[:,np.newaxis,np.newaxis]
+ elif dKtype is 'stripes':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ s1 = imgs[:,:nPix,:].mean(-2)
+
+
+
+
+ return np.squeeze(imgs)
+
+def getData():
+ t0 = time.time()
+ context = zmq.Context()
+ socket = context.socket(zmq.REQ)
+ socket.connect('tcp://daq-xpp-mon06:12322')
+ #socket.setsockopt(zmq.SUBSCRIBE, b'')
+ while True:
+ socket.send(b"Request")
+ ret = socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ print('received',ret.keys(),time.time()-t0)
+ t0 = time.time()
+
+if __name__ == "__main__":
+ getData()
+
+class SpecHandler(object):
+ def __init__(self,connectString='tcp://daq-xpp-mon06:12322',spec1name='opal0',spec2name='opal1',roi=[0,1024,0,1024]):
+ self.connectString = connectString
+ self.spec1name = spec1name
+ self.spec2name = spec2name
+ self.surveyplot = Surveyplot(spec1name=spec1name,spec2name=spec2name)
+ self.roi = roi
+ self.projsimple = ProjSimple(spec1name=spec1name,spec2name=spec2name)
+ self._rawContinuousTime = None
+ self.lastDat = None
+ self.openSocket()
+ self.dataCollector = []
+ self.runningPlot = RunningPlot(self.dataCollector)
+
+
+ def openSocket(self):
+ context = zmq.Context()
+ self.context = context
+ self.socket = context.socket(zmq.REQ)
+ self.socket.connect(self.connectString)
+ #self.socket.setsockopt(zmq.SUBSCRIBE, b'')
+
+ def closeSocket(self):
+ del self.context
+ del self.socket
+
+ def getData(self):
+ self.socket.send(b"Request")
+ ret = self.socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ for sn in [self.spec1name,self.spec2name]:
+ ret[sn] = np.squeeze(alignment.subtractBkg(ret[sn], nPix=100, bkg_type='line'))
+ self.lastDat = ret
+ return ret
+
+ def getRaw(self,repoenConnection=False,doAlign=False,show=False,doFit=False):
+ if doFit is True: doFit='iminuit'
+
+
+ if repoenConnection:
+ self.closeSocket()
+ self.openSocket()
+ dat = self.getData()
+ im1 = dat[self.spec1name]; im2 = dat[self.spec2name]
+ if doAlign:
+ #t = np.load("gui_align_transform_xppl3716.npy").item()
+ if hasattr(self,'transformer'):
+ algn = self.transformer
+ else:
+ algn = alignment.loadAlignment('last_trafo.npy')
+ t = algn['transform']
+ roi1 = algn['roi1']
+ roi2 = algn['roi2']
+
+ r = alignment.doShot( im1[roi1,:],im2[roi2,:],t, show=show, doFit=doFit)
+ self.transformer = dict(transform=r.final_transform,roi1=roi1,roi2=roi2)
+ alignment.saveAlignment('last_trafo.npy',r.final_transform,roi1,roi2)
+
+ im1 = r.im1; im2 = r.im2
+ showDiff = True
+ showRatio = True
+ else:
+ showDiff = False
+ showRatio = False
+ self.surveyplot.plotImages(im1,im2,showDiff=showDiff,showRatio=showRatio)
+ self.projsimple.plotProfiles(im1,im2)
+ if doAlign:
+ thres = 0.05
+ im1[im10:
+ times = np.asarray(([i['time'] for i in self.dataCollector]))
+ foms = np.asarray(([i['fom'] for i in self.dataCollector]))
+ im1Proj = np.asarray(([i['im1Proj'] for i in self.dataCollector]))
+ im2Proj = np.asarray(([i['im2Proj'] for i in self.dataCollector]))
+
+ if hasattr(self,'fomline'):
+ self.fomline.set_xdata(times)
+ self.fomline.set_ydata(foms)
+ #self.axs[0].autoscale(enable=True,axis='x')
+
+ else:
+ self.fomline = self.axs.plot(times,foms,'o-')[0]
+ #if hasattr(self,'ratioimg'):
+ #self.ratioimg.set_data()
+ #self.ratioimg.set_ydata(foms)
+ #else:
+ #self.axs[0].plot(times,foms,'o-')
+
+
+
+
+
+ #def plotOrUpdate(img1,img2):
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+
diff --git a/online/sMhelper_dev.py b/online/sMhelper_dev.py
new file mode 100644
index 0000000..b1b1e54
--- /dev/null
+++ b/online/sMhelper_dev.py
@@ -0,0 +1,297 @@
+import sys
+import zmq
+import numpy as np
+import time
+import pickle
+import alignment
+import matplotlib.pyplot as plt
+import threading
+import datetime
+import copy
+
+plt.rcParams['image.cmap'] = 'viridis'
+
+def histVec(v,oversample=1):
+ v = np.atleast_1d(v)
+ v = np.unique(v)
+ vd = np.diff(v)
+ vd = np.hstack([vd[0],vd])
+ #vv = np.hstack([v-vd/2,v[-1]+vd[-1]/2])
+ vv = np.hstack([v-vd/2.,v[-1]+vd[-1]/2.])
+ if oversample>1:
+ vvo = []
+ for i in range(len(vv)-1):
+ vvo.append(np.linspace(vv[i],vv[i+1],oversample+1)[:-1])
+ vvo.append(vv[-1])
+ vv = np.array(np.hstack(vvo))
+ return vv
+
+def subtractBkg(imgs,nPix=100,dKtype='corners'):
+ """ Opals tend to have different backgroud for every quadrant """
+ if dKtype is 'corners':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ q1 = imgs[:,:nPix,:nPix].mean(-1).mean(-1)
+ imgs[:,:512,:512]-=q1[:,np.newaxis,np.newaxis]
+ q2 = imgs[:,:nPix,-nPix:].mean(-1).mean(-1)
+ imgs[:,:512,-512:]-=q2[:,np.newaxis,np.newaxis]
+ q3 = imgs[:,-nPix:,-nPix:].mean(-1).mean(-1)
+ imgs[:,-512:,-512:]-=q3[:,np.newaxis,np.newaxis]
+ q4 = imgs[:,-nPix:,:nPix].mean(-1).mean(-1)
+ imgs[:,-512:,:512]-=q4[:,np.newaxis,np.newaxis]
+ elif dKtype is 'stripes':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ s1 = imgs[:,:nPix,:].mean(-2)
+
+
+
+
+ return np.squeeze(imgs)
+
+def getData():
+ t0 = time.time()
+ context = zmq.Context()
+ socket = context.socket(zmq.REQ)
+ socket.connect('tcp://daq-xpp-mon06:12322')
+ #socket.setsockopt(zmq.SUBSCRIBE, b'')
+ while True:
+ socket.send(b"Request")
+ ret = socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ print('received',ret.keys(),time.time()-t0)
+ t0 = time.time()
+
+if __name__ == "__main__":
+ getData()
+
+class SpecHandler(object):
+ def __init__(self,connectString='tcp://daq-xpp-mon06:12322',spec1name='opal0',spec2name='opal1',roi=[0,1024,0,1024]):
+ self.connectString = connectString
+ self.spec1name = spec1name
+ self.spec2name = spec2name
+ self.dataCollector = []
+ #self.surveyplot = Surveyplot(spec1name=spec1name,spec2name=spec2name)
+ self.roi = roi
+ self.projsimple = ProjSimple(spec1name=spec1name,spec2name=spec2name,dataCollector=self.dataCollector)
+ self._rawContinuousTime = None
+ self.lastDat = None
+ self.openSocket()
+ self.runningPlot = RunningPlot(self.dataCollector)
+
+
+ def openSocket(self):
+ context = zmq.Context()
+ self.context = context
+ self.socket = context.socket(zmq.REQ)
+ self.socket.connect(self.connectString)
+ #self.socket.setsockopt(zmq.SUBSCRIBE, b'')
+
+ def closeSocket(self):
+ del self.context
+ del self.socket
+
+ def getData(self):
+ self.socket.send(b"Request")
+ ret = self.socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ for sn in [self.spec1name,self.spec2name]:
+ ret[sn] = np.squeeze(alignment.subtractBkg(ret[sn], nPix=100, bkg_type='line'))
+ self.lastDat = ret
+ return ret
+
+ def getRaw(self,repoenConnection=False,doAlign=False,show=False,doFit=False,updateImg=True,updateProj=True,updateFom=True, ispaceCorr=False,flipit=False,xshift=None):
+ if doFit is True: doFit='iminuit'
+
+
+ if repoenConnection:
+ self.closeSocket()
+ self.openSocket()
+ dat = self.getData()
+ im1 = dat[self.spec1name]; im2 = dat[self.spec2name]
+ if doAlign:
+ #t = np.load("gui_align_transform_xppl3716.npy").item()
+ if hasattr(self,'transformer'):
+ algn = self.transformer
+ else:
+ algn = alignment.loadAlignment('last_trafo.npy')
+ t = algn['transform']
+ roi1 = algn['roi1']
+ roi2 = algn['roi2']
+ im1 = im1[roi1];
+ if flipit:
+ im1 = im1[::-1]
+ im2 = im2[roi2]
+ alignment.clearCache()
+ r = alignment.doShot( im1,im2, t, show=show, doFit=doFit, xshift=xshift)
+ self.transformer = dict(transform=r.final_transform,roi1=roi1,roi2=roi2)
+ alignment.saveAlignment('last_trafo.npy',r.final_transform,roi1,roi2)
+
+ im1 = r.im1; im2 = r.im2
+ showDiff = True
+ showRatio = True
+ else:
+ showDiff = False
+ showRatio = False
+ if doAlign:
+ thres = 0.05
+ #im1[im1 0 :
+ im1Proj = np.asarray([i['im1Proj'] for i in self.dataCollector])
+ im2Proj = np.asarray([i['im2Proj'] for i in self.dataCollector])
+ #print(im1Proj.shape,im2Proj.shape)
+ ratAv = np.median(im2Proj[-10:],0)/np.median(im1Proj[-10:],0)
+ if hasattr(self,'lratAv'):
+ self.lratAv.set_ydata(ratAv)
+ else:
+ self.lratAv = self.axs[1].plot(ratAv,'r',label='ratio Avg')[0]
+ self.axs[1].set_ylim(0,2)
+
+
+class RunningPlot(object):
+ def __init__(self,dataCollector):
+ self.dataCollector = dataCollector
+ self.fig,self.axs = plt.subplots(1,1)
+
+ def updatePlot(self):
+ if len(self.dataCollector)>0:
+ times = np.asarray(([i['time'] for i in self.dataCollector]))
+ foms = np.asarray(([i['fom'] for i in self.dataCollector]))
+ im1Proj = np.asarray(([i['im1Proj'] for i in self.dataCollector]))
+ im2Proj = np.asarray(([i['im2Proj'] for i in self.dataCollector]))
+
+ if hasattr(self,'fomline'):
+ self.fomline.set_ydata(foms)
+ self.fomline.set_xdata(times)
+ self.axs.set_xlim(np.min(times)-datetime.timedelta(0,10),np.max(times)+datetime.timedelta(0,10))
+
+ #self.axs[0].autoscale(enable=True,axis='x')
+
+ else:
+ self.fomline = self.axs.plot(times,foms,'o-')[0]
+ self.axs.autoscale(enable=True,axis='x')
+ #if hasattr(self,'ratioimg'):
+ #self.ratioimg.set_data()
+ #self.ratioimg.set_ydata(foms)
+ #else:
+ #self.axs[0].plot(times,foms,'o-')
+
+
+
+
+
+ #def plotOrUpdate(img1,img2):
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+
diff --git a/online/sMhelper_dev_pg.py b/online/sMhelper_dev_pg.py
new file mode 100644
index 0000000..3b0876f
--- /dev/null
+++ b/online/sMhelper_dev_pg.py
@@ -0,0 +1,345 @@
+import sys
+import zmq
+import numpy as np
+import time
+import pickle
+import alignment
+import matplotlib.pyplot as plt
+import threading
+import datetime
+import copy
+import pyqtgraph as pg
+
+plt.rcParams['image.cmap'] = 'viridis'
+
+def histVec(v,oversample=1):
+ v = np.atleast_1d(v)
+ v = np.unique(v)
+ vd = np.diff(v)
+ vd = np.hstack([vd[0],vd])
+ #vv = np.hstack([v-vd/2,v[-1]+vd[-1]/2])
+ vv = np.hstack([v-vd/2.,v[-1]+vd[-1]/2.])
+ if oversample>1:
+ vvo = []
+ for i in range(len(vv)-1):
+ vvo.append(np.linspace(vv[i],vv[i+1],oversample+1)[:-1])
+ vvo.append(vv[-1])
+ vv = np.array(np.hstack(vvo))
+ return vv
+
+def subtractBkg(imgs,nPix=100,dKtype='corners'):
+ """ Opals tend to have different backgroud for every quadrant """
+ if dKtype is 'corners':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ q1 = imgs[:,:nPix,:nPix].mean(-1).mean(-1)
+ imgs[:,:512,:512]-=q1[:,np.newaxis,np.newaxis]
+ q2 = imgs[:,:nPix,-nPix:].mean(-1).mean(-1)
+ imgs[:,:512,-512:]-=q2[:,np.newaxis,np.newaxis]
+ q3 = imgs[:,-nPix:,-nPix:].mean(-1).mean(-1)
+ imgs[:,-512:,-512:]-=q3[:,np.newaxis,np.newaxis]
+ q4 = imgs[:,-nPix:,:nPix].mean(-1).mean(-1)
+ imgs[:,-512:,:512]-=q4[:,np.newaxis,np.newaxis]
+ elif dKtype is 'stripes':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ s1 = imgs[:,:nPix,:].mean(-2)
+
+
+
+
+ return np.squeeze(imgs)
+
+def getData():
+ t0 = time.time()
+ context = zmq.Context()
+ socket = context.socket(zmq.REQ)
+ socket.connect('tcp://daq-xpp-mon06:12322')
+ #socket.setsockopt(zmq.SUBSCRIBE, b'')
+ while True:
+ socket.send(b"Request")
+ ret = socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ print('received',ret.keys(),time.time()-t0)
+ t0 = time.time()
+
+if __name__ == "__main__":
+ getData()
+
+class SpecHandler(object):
+ def __init__(self,connectString='tcp://daq-xpp-mon06:12322',spec1name='opal0',spec2name='opal1',roi=[0,1024,0,1024]):
+ self.connectString = connectString
+ self.spec1name = spec1name
+ self.spec2name = spec2name
+ self.dataCollector = []
+ #self.surveyplot = Surveyplot(spec1name=spec1name,spec2name=spec2name)
+ self.roi = roi
+ self.projsimple = ProjSimple(spec1name=spec1name,spec2name=spec2name,dataCollector=self.dataCollector)
+ self._rawContinuousTime = None
+ self.lastDat = None
+ self.openSocket()
+ #self.runningPlot = RunningPlot(self.dataCollector)
+
+
+ def openSocket(self):
+ context = zmq.Context()
+ self.context = context
+ self.socket = context.socket(zmq.REQ)
+ self.socket.connect(self.connectString)
+ #self.socket.setsockopt(zmq.SUBSCRIBE, b'')
+
+ def closeSocket(self):
+ del self.context
+ del self.socket
+
+ def getData(self):
+ self.socket.send(b"Request")
+ ret = self.socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ for sn in [self.spec1name,self.spec2name]:
+ ret[sn] = np.squeeze(alignment.subtractBkg(ret[sn], nPix=100, bkg_type='line'))
+ self.lastDat = ret
+ return ret
+
+ def getRaw(self,repoenConnection=False,doAlign=False,show=False,doFit=False,updateImg=True,updateProj=True,updateFom=True):
+ if doFit is True: doFit='iminuit'
+
+
+ if repoenConnection:
+ self.closeSocket()
+ self.openSocket()
+ dat = self.getData()
+ im1 = dat[self.spec1name]; im2 = dat[self.spec2name]
+ if doAlign:
+ #t = np.load("gui_align_transform_xppl3716.npy").item()
+ if hasattr(self,'transformer'):
+ algn = self.transformer
+ else:
+ algn = alignment.loadAlignment('last_trafo.npy')
+ t = algn['transform']
+ roi1 = algn['roi1']
+ roi2 = algn['roi2']
+
+ r = alignment.doShot( im1[roi1,:],im2[roi2,:],t, show=show, doFit=doFit)
+ self.transformer = dict(transform=r.final_transform,roi1=roi1,roi2=roi2)
+ alignment.saveAlignment('last_trafo.npy',r.final_transform,roi1,roi2)
+
+ im1 = r.im1; im2 = r.im2
+ showDiff = True
+ showRatio = True
+ else:
+ showDiff = False
+ showRatio = False
+ if doAlign:
+ thres = 0.05
+ #im1[im1 0 :
+ im1Proj = np.asarray([i['im1Proj'] for i in self.dataCollector])
+ im2Proj = np.asarray([i['im2Proj'] for i in self.dataCollector])
+ #print(im1Proj.shape,im2Proj.shape)
+ ratAv = np.median(im2Proj,0)/np.median(im1Proj,0)
+ if hasattr(self,'lratAv'):
+ self.lratAv.set_ydata(ratAv)
+ else:
+ self.lratAv = self.axs[1].plot(ratAv,'r',label='ratio Avg')[0]
+ self.axs[1].set_ylim(0,2)
+
+class ProjSimplePG(object):
+ def __init__(self,spec1name='sp ec1',spec2name='spec2',roi1=[0,1024,0,1024],roi2=[0,1024,0,1024],dataCollector=[]):
+ from pyqtgraph.Qt import QtGui, QtCore
+ import numpy as np
+ import pyqtgraph as pg
+ self.app = QtGui.Qapplication([])
+ self.win = pg.GraphicsWindow(title='Single shot XANES')
+ pg.setConfigOptions(antialias=True)
+ self.sp1 = win.addPlot(title='spectrometer spectra')
+ self.sp2 = win.addPlot(title='Ratio')
+
+
+ self.fig,self.axs = plt.subplots(2,1,sharex=True)
+
+ self.roi1 = roi1
+ self.roi2 = roi2
+ self.spec1name=spec1name
+ self.spec2name=spec2name
+ self.dataCollector = dataCollector
+
+ #def getROI(self,specNo):
+ def _roiit(self,img,roi):
+ return img[roi[0]:roi[1],roi[2]:roi[3]]
+
+ def plotProfiles(self,img1,img2):
+ prof1 = np.nansum(self._roiit(img1,self.roi1),0)
+ prof2 = np.nansum(self._roiit(img2,self.roi2),0)
+ if hasattr(self,'l1'):
+ self.l1.set_ydata(prof1)
+ else:
+ self.l1 = self.axs[0].plot(prof1,label=self.spec1name)[0]
+ if hasattr(self,'l2'):
+ self.l2.set_ydata(prof2)
+ else:
+ self.l2 = self.axs[0].plot(prof2,label=self.spec2name)[0]
+ plt.legend()
+
+ if hasattr(self,'lrat'):
+ self.lrat.set_ydata(prof2/prof1)
+ else:
+ self.lrat = self.axs[1].plot(prof2/prof1,'k',label='ratio')[0]
+ self.axs[1].set_ylim(0,2)
+ if len(self.dataCollector) > 0 :
+ im1Proj = np.asarray([i['im1Proj'] for i in self.dataCollector])
+ im2Proj = np.asarray([i['im2Proj'] for i in self.dataCollector])
+ #print(im1Proj.shape,im2Proj.shape)
+ ratAv = np.median(im2Proj,0)/np.median(im1Proj,0)
+ if hasattr(self,'lratAv'):
+ self.lratAv.set_ydata(ratAv)
+ else:
+ self.lratAv = self.axs[1].plot(ratAv,'r',label='ratio Avg')[0]
+ self.axs[1].set_ylim(0,2)
+
+class RunningPlot(object):
+ def __init__(self,dataCollector):
+ self.dataCollector = dataCollector
+ self.fig,self.axs = plt.subplots(1,1)
+
+ def updatePlot(self):
+ if len(self.dataCollector)>0:
+ times = np.asarray(([i['time'] for i in self.dataCollector]))
+ foms = np.asarray(([i['fom'] for i in self.dataCollector]))
+ im1Proj = np.asarray(([i['im1Proj'] for i in self.dataCollector]))
+ im2Proj = np.asarray(([i['im2Proj'] for i in self.dataCollector]))
+
+ if hasattr(self,'fomline'):
+ self.fomline.set_ydata(foms)
+ self.fomline.set_xdata(times)
+ self.axs.set_xlim(np.min(times)-datetime.timedelta(0,10),np.max(times)+datetime.timedelta(0,10))
+
+ #self.axs[0].autoscale(enable=True,axis='x')
+
+ else:
+ self.fomline = self.axs.plot(times,foms,'o-')[0]
+ self.axs.autoscale(enable=True,axis='x')
+ #if hasattr(self,'ratioimg'):
+ #self.ratioimg.set_data()
+ #self.ratioimg.set_ydata(foms)
+ #else:
+ #self.axs[0].plot(times,foms,'o-')
+
+
+
+
+
+ #def plotOrUpdate(img1,img2):
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+
diff --git a/online/sMhelper_upd.py b/online/sMhelper_upd.py
new file mode 100644
index 0000000..c076bde
--- /dev/null
+++ b/online/sMhelper_upd.py
@@ -0,0 +1,296 @@
+import sys
+import zmq
+import numpy as np
+import time
+import pickle
+import alignment
+import matplotlib.pyplot as plt
+import threading
+import datetime
+import copy
+
+plt.rcParams['image.cmap'] = 'viridis'
+
+def histVec(v,oversample=1):
+ v = np.atleast_1d(v)
+ v = np.unique(v)
+ vd = np.diff(v)
+ vd = np.hstack([vd[0],vd])
+ #vv = np.hstack([v-vd/2,v[-1]+vd[-1]/2])
+ vv = np.hstack([v-vd/2.,v[-1]+vd[-1]/2.])
+ if oversample>1:
+ vvo = []
+ for i in range(len(vv)-1):
+ vvo.append(np.linspace(vv[i],vv[i+1],oversample+1)[:-1])
+ vvo.append(vv[-1])
+ vv = np.array(np.hstack(vvo))
+ return vv
+
+def subtractBkg(imgs,nPix=100,dKtype='corners'):
+ """ Opals tend to have different backgroud for every quadrant """
+ if dKtype is 'corners':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ q1 = imgs[:,:nPix,:nPix].mean(-1).mean(-1)
+ imgs[:,:512,:512]-=q1[:,np.newaxis,np.newaxis]
+ q2 = imgs[:,:nPix,-nPix:].mean(-1).mean(-1)
+ imgs[:,:512,-512:]-=q2[:,np.newaxis,np.newaxis]
+ q3 = imgs[:,-nPix:,-nPix:].mean(-1).mean(-1)
+ imgs[:,-512:,-512:]-=q3[:,np.newaxis,np.newaxis]
+ q4 = imgs[:,-nPix:,:nPix].mean(-1).mean(-1)
+ imgs[:,-512:,:512]-=q4[:,np.newaxis,np.newaxis]
+ elif dKtype is 'stripes':
+ if imgs.ndim == 2: imgs = imgs[np.newaxis,:]
+ imgs = imgs.astype(np.float)
+ s1 = imgs[:,:nPix,:].mean(-2)
+
+
+
+
+ return np.squeeze(imgs)
+
+def getData():
+ t0 = time.time()
+ context = zmq.Context()
+ socket = context.socket(zmq.REQ)
+ socket.connect('tcp://daq-xpp-mon06:12322')
+ #socket.setsockopt(zmq.SUBSCRIBE, b'')
+ while True:
+ socket.send(b"Request")
+ ret = socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ print('received',ret.keys(),time.time()-t0)
+ t0 = time.time()
+
+if __name__ == "__main__":
+ getData()
+
+class SpecHandler(object):
+ def __init__(self,connectString='tcp://daq-xpp-mon06:12322',spec1name='opal0',spec2name='opal1',roi=[0,1024,0,1024]):
+ self.connectString = connectString
+ self.spec1name = spec1name
+ self.spec2name = spec2name
+ self.dataCollector = []
+ #self.surveyplot = Surveyplot(spec1name=spec1name,spec2name=spec2name)
+ self.roi = roi
+ self.projsimple = ProjSimple(spec1name=spec1name,spec2name=spec2name,dataCollector=self.dataCollector)
+ self._rawContinuousTime = None
+ self.lastDat = None
+ self.openSocket()
+ #self.runningPlot = RunningPlot(self.dataCollector)
+
+
+ def openSocket(self):
+ context = zmq.Context()
+ self.context = context
+ self.socket = context.socket(zmq.REQ)
+ self.socket.connect(self.connectString)
+ #self.socket.setsockopt(zmq.SUBSCRIBE, b'')
+
+ def closeSocket(self):
+ del self.context
+ del self.socket
+
+ def getData(self):
+ self.socket.send(b"Request")
+ ret = self.socket.recv()
+ ret = pickle.loads(ret, encoding='latin1')
+ for sn in [self.spec1name,self.spec2name]:
+ ret[sn] = np.squeeze(alignment.subtractBkg(ret[sn], nPix=100, bkg_type='line'))
+ self.lastDat = ret
+ return ret
+
+ def getRaw(self,repoenConnection=False,doAlign=False,show=False,doFit=False,updateImg=True,updateProj=True,updateFom=True,flipit=False):
+ if doFit is True: doFit='iminuit'
+
+
+ if repoenConnection:
+ self.closeSocket()
+ self.openSocket()
+ dat = self.getData()
+ im1 = dat[self.spec1name]; im2 = dat[self.spec2name]
+ if doAlign:
+ #t = np.load("gui_align_transform_xppl3716.npy").item()
+ #if hasattr(self,'transformer'):
+ #algn = self.transformer
+ #else:
+ algn = alignment.loadAlignment('last_trafo.npy')
+ t = algn['transform']
+ roi1 = algn['roi1']
+ roi2 = algn['roi2']
+ im1 = im1[roi1];
+ if flipit:
+ im1 = im1[::-1]
+ im2 = im2[roi2]
+
+ r = alignment.doShot( im1,im2, t, show=show, doFit=doFit)
+ self.transformer = dict(transform=r.final_transform,roi1=roi1,roi2=roi2)
+ alignment.saveAlignment('last_trafo.npy',r.final_transform,roi1,roi2)
+
+ im1 = r.im1; im2 = r.im2
+ showDiff = True
+ showRatio = True
+ else:
+ showDiff = False
+ showRatio = False
+ if doAlign:
+ thres = 0.05
+ #im1[im1 0 :
+ im1Proj = np.asarray([i['im1Proj'] for i in self.dataCollector])
+ im2Proj = np.asarray([i['im2Proj'] for i in self.dataCollector])
+ #print(im1Proj.shape,im2Proj.shape)
+ ratAv = np.median(im2Proj[-10:,:],0)/np.median(im1Proj[-10:,:],0)
+ if hasattr(self,'lratAv'):
+ self.lratAv.set_ydata(ratAv)
+ else:
+ self.lratAv = self.axs[1].plot(ratAv,'r',label='ratio Avg')[0]
+ self.axs[1].set_ylim(0,2)
+
+
+class RunningPlot(object):
+ def __init__(self,dataCollector):
+ self.dataCollector = dataCollector
+ self.fig,self.axs = plt.subplots(1,1)
+
+ def updatePlot(self):
+ if len(self.dataCollector)>0:
+ times = np.asarray(([i['time'] for i in self.dataCollector]))
+ foms = np.asarray(([i['fom'] for i in self.dataCollector]))
+ im1Proj = np.asarray(([i['im1Proj'] for i in self.dataCollector]))
+ im2Proj = np.asarray(([i['im2Proj'] for i in self.dataCollector]))
+
+ if hasattr(self,'fomline'):
+ self.fomline.set_ydata(foms)
+ self.fomline.set_xdata(times)
+ self.axs.set_xlim(np.min(times)-datetime.timedelta(0,10),np.max(times)+datetime.timedelta(0,10))
+
+ #self.axs[0].autoscale(enable=True,axis='x')
+
+ else:
+ self.fomline = self.axs.plot(times,foms,'o-')[0]
+ self.axs.autoscale(enable=True,axis='x')
+ #if hasattr(self,'ratioimg'):
+ #self.ratioimg.set_data()
+ #self.ratioimg.set_ydata(foms)
+ #else:
+ #self.axs[0].plot(times,foms,'o-')
+
+
+
+
+
+ #def plotOrUpdate(img1,img2):
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+ #if hasattr(self,i1):
+ #self.i1.set_data(img1)
+ #else:
+ #self.i1 = self.axs.imshow(img1,interpolate='none',origin='bottom')
+
diff --git a/online/server.py b/online/server.py
new file mode 100644
index 0000000..928c841
--- /dev/null
+++ b/online/server.py
@@ -0,0 +1,41 @@
+import zmq
+import time
+import psana
+import numpy as np
+
+context = zmq.Context()
+socket = context.socket(zmq.REP)
+socket.bind("tcp://*:12322")
+poller = zmq.Poller()
+poller.register(socket, zmq.POLLIN)
+
+#run = 8
+#ds = psana.DataSource('exp=xppl3816:run=%d:smd' %run)
+ds = psana.DataSource('shmem=XPP.0:stop=no')
+epics = ds.env().epicsStore()
+opal_0_detector = psana.Detector('opal_0')
+opal_1_detector = psana.Detector('opal_1')
+#ipm3_src = psana.Source('BldInfo(XppSb3_Ipm)')
+
+t0 = time.time()
+for i, evt in enumerate(ds.events()):
+ events = dict(poller.poll(0))
+ if socket in events and events[socket] == zmq.POLLIN:
+ opal_0 = opal_0_detector.raw(evt)
+ opal_1 = opal_1_detector.raw(evt)
+ cntr = ds.env().configStore().get(psana.ControlData.ConfigV3, psana.Source()).pvControls()
+ if len(cntr) > 0:
+ cpvName = cntr[0].name()
+ cpvValue = cntr[0].value()
+ else:
+ cpvName = None
+ cpvValue = None
+
+ if opal_0 is None or opal_1 is None:
+ print 'missing opal'
+ continue
+ message = socket.recv()
+ socket.send_pyobj( dict( opal0 = opal_0, opal1 = opal_1, cPv = dict(name=cpvName,value=cpvValue)) )
+ print 'Shot',i, 'sent; time since starting:', time.time()-t0
+
+
diff --git a/online/server_pub.py b/online/server_pub.py
new file mode 100644
index 0000000..f38e7ec
--- /dev/null
+++ b/online/server_pub.py
@@ -0,0 +1,41 @@
+import zmq
+import time
+import psana
+import numpy as np
+
+context = zmq.Context()
+socket = context.socket(zmq.PUB)
+socket.bind("tcp://*:12322")
+
+#run = 8
+#ds = psana.DataSource('exp=xppl3816:run=%d:smd' %run)
+ds = psana.DataSource('shmem=XPP.0:stop=no')
+epics = ds.env().epicsStore()
+opal_0_detector = psana.Detector('opal_0')
+opal_1_detector = psana.Detector('opal_1')
+opal_1_detector = psana.Detector('opal_1')
+#ipm3_src = psana.Source('BldInfo(XppSb3_Ipm)')
+
+t0 = time.time()
+for i, evt in enumerate(ds.events()):
+ #if i % 20 != 0:
+ # continue
+ opal_0 = opal_0_detector.raw(evt)
+# opal_2 = np.random.random((1024, 1024))#opal_2_detector.raw(evt)
+ opal_1 = opal_1_detector.raw(evt)
+ cntr = ds.env().configStore().get(psana.ControlData.ConfigV3, psana.Source()).pvControls()
+ if len(cntr) > 0:
+ cpvName = cntr.pvControlsu()[0].name()
+ cpvValue = cntr.pvControls()[0].value()
+ else:
+ cpvName = None
+ cpvValue = None
+
+ if opal_0 is None or opal_1 is None:
+ print 'missing opal'
+ continue
+ socket.send_pyobj( dict( opal0 = opal_0, opal1 = opal_1, cPv = dict(name=cpvName,value=cpvValue)) )
+ print 'Shot',i, 'sent; time since starting:', time.time()-t0
+ time.sleep(1.0)
+
+
diff --git a/x3py_config b/x3py_config
new file mode 100644
index 0000000..71e46a5
--- /dev/null
+++ b/x3py_config
@@ -0,0 +1 @@
+#cachepath = "/reg/d/psdm/xpp/xppl3716/scratch/mc/cache"
diff --git a/xanes_analyzeRun.py b/xanes_analyzeRun.py
new file mode 100644
index 0000000..77f8e4a
--- /dev/null
+++ b/xanes_analyzeRun.py
@@ -0,0 +1,291 @@
+import os
+import sys
+import numpy as np
+np.warnings.simplefilter('ignore')
+import time
+import matplotlib.pyplot as plt
+import h5py
+import re
+
+from x3py import x3py
+import alignment
+import mcutils as mc
+
+kw_2dplot = dict(
+ interpolation = "none",
+ aspect = "auto",
+ cmap = plt.cm.viridis
+ )
+
+
+g_exp = "mecl3616"
+g_exp = "xppl3716"
+g_bml = g_exp[:3]
+
+x3py.config.updateBeamline(g_bml)
+
+g_folder_init = g_exp+"_init_pars/"
+g_folder_out = g_exp+"_output/"
+g_folder_data = "/reg/d/psdm/"+g_bml+"/"+ g_exp +"/hdf5/"
+import socket
+hostname = socket.gethostname()
+if hostname == "x1":
+ g_folder_data = "/home/marco/temp"
+
+# set defaults based on experiment
+if g_bml == "xpp":
+ g_roi_height = 200
+ g_swapx = False
+ g_swapy = False
+else:
+ g_roi_height = 100
+ g_swapx = True
+ g_swapy = False
+
+print("Working on experiment",g_exp,"(beamline %s)"%g_bml)
+print(" folder data →",g_folder_data)
+print(" folder init_pars →",g_folder_init)
+print(" folder outout →",g_folder_out)
+
+#g_folder = "/reg/d/psdm/xpp/xppl3716/ftc/hdf5/"
+
+def readDataset(fnameOrRun=7,
+ force=False,
+ doBkgSub=False):
+ if isinstance(fnameOrRun,str) and (fnameOrRun[-3:]=="npz"):
+ d = x3py.toolsVarious.DropObject()
+ temp = np.load(fnameOrRun)
+ spec1 = temp["spec1"]
+ spec2 = temp["spec2"]
+ nS = spec1.shape[0]
+ d.spec1 = x3py.toolsDetectors.wrapArray("spec1",spec1,time=np.arange(nS))
+ d.spec2 = x3py.toolsDetectors.wrapArray("spec2",spec2,time=np.arange(nS))
+ else:
+ if isinstance(fnameOrRun,int):
+ fnameOrRun=g_folder_data+"/"+g_exp+"-r%04d.h5" % fnameOrRun
+ d = x3py.Dataset(fnameOrRun,detectors=["opal0","opal1","fee_spec","opal2"])
+ if g_bml == "xpp":
+ d.spec1 = d.opal0
+ d.spec2 = d.opal1
+ else:
+ d.spec1 = d.fee_spec
+ d.spec2 = d.opal2
+ if not hasattr(d,"scan"):
+ d.scan = x3py.toolsVarious.DropObject()
+ d.scan.scanmotor0_values = [0,]
+ return d
+
+
+def getCenter(img,axis=0,threshold=0.05):
+ img = img.copy()
+ img[img %.3f aligned (best FOM: %.2f)" % (i,self.d.scan.scanmotor0_values[i],res.fom))
+ ret = alignment.doShots(s1,s2,initpars=initpars,doFit=doFit)
+ res = alignment.unravel_results(ret)
+ self.results[i] = res
+ return self.results.values()
+
+ def doShot(self,shot=0,calib=None,initpars=None,im1=None,im2=None,doFit=True,show=False,showInit=False,save=False,savePlot="auto"):
+ if initpars is None: initpars= self.initAlign
+ if (im1 is None) or (im2 is None):
+ im1,im2 = self.getShot(shot,calib=calib); im1=im1[0]; im2=im2[0]
+ r = alignment.doShot(im1,im2,initpars,doFit=doFit,show=showInit)
+ im1 = r.im1
+ im2 = r.im2
+ self.initAlign = r.final_pars
+ if show:
+ if savePlot == "auto":
+ savePlot = g_folder_out+"/run%04d_calib%s_shot%04d_fit.png" % (self.run,calib,shot)
+ alignment.plotShot(im1,im2,res=r,save=savePlot)
+ if save: self.saveTransform()
+ return r
+
+ def doShots(self,shots=slice(0,50),calib=None,initpars=None,doFit=False,returnBestTransform=False,unravel=True):
+ if initpars is None: initpars= self.initAlign
+ d = self.d
+ s1,s2 = self.getShot(shots,calib=calib)
+ ret,t = alignment.doShots(s1,s2,initpars=initpars,doFit=doFit,\
+ returnBestTransform=True)
+ if doFit:
+ self.initAlign = t
+ ret_unravel = alignment.unravel_results(ret)
+ # keep it for later !
+ self.results[calib] = ret_unravel
+ if unravel: ret = ret_unravel
+ if returnBestTransform:
+ return ret,t
+ else:
+ return ret
+
+ def save(self,fname="auto",overwrite=False):
+ if fname == "auto":
+ fname = g_folder_out+"/run%04d_analysis.h5" % self.run
+ if os.path.exists(fname) and not overwrite:
+ print("File %s exists, **NOT** saving, use overwrite=True is you want ..."%fname)
+ return
+ if os.path.exists(fname) and overwrite:
+ os.unlink(fname)
+ print("Saving results to %s"%fname)
+ h = h5py.File(fname)
+ h["roi1"] = (self.roi1.start,self.roi1.stop)
+ h["roi2"] = (self.roi2.start,self.roi2.stop)
+ #h["transform"] = self.initAlign
+ for (c,v) in self.results.items():
+ cname = "calib%04d/" % c if isinstance(c,int) else "calib%s/" % c
+ for p,vv in v.items():
+ if p == "parameters":
+ for pname,parray in vv.items():
+ name = cname + p + "/" + pname
+ h[name] = parray
+ else:
+ h[cname + p] = vv
+ h.close()
+
+
+ def saveTransform(self,fname="auto",transform=None):
+ if transform is None: transform = self.initAlign
+ if fname == "auto":
+ fname = g_folder_init+"/run%04d_transform.npy" % self.run
+ print("Saving roi and transformation parameter to %s"%fname)
+ alignment.saveAlignment(fname,self.initAlign,self.roi1,self.roi2)
+
+ def loadTransform(self,fname="auto"):
+ if fname == "auto":
+ fname = g_folder_init+"/run%04d_transform.npy" % self.run
+ elif isinstance(fname,int):
+ fname = g_folder_init+"/run%04d_transform.npy" % fname
+ temp = np.load(fname).item()
+ self.initAlign = temp["transform"]
+ self.roi1 = temp["roi1"]
+ self.roi2 = temp["roi2"]
+ print("init transform and ROIs from %s"%fname)
+
+
+ def clearCache(self):
+ del self.roi1
+ del self.roi2
+ alignment.clearCache(); # nedded for multiprocessing can leave bad parameters in the cache
+
+ def setDefaultTransform( self ):
+ t = dict( scalex=0.65,rotation=0.0,transx=90, iblur1=4.3,fix_iblur1=False )
+ self.initAlign = t
+ return t
+
+def quick_mec(run,ref=236,divideByRef=False,returnRes=False):
+ """ useful to analyze the runs around 140 (done with the focusing """
+ ref_run = 236
+ h=h5py.File("mecl3616_output/run%04d_analysis.h5" %ref,"r")
+ ref = np.nanmean(h["calibNone"]["ratio"][...],axis=0)
+ r = AnalyzeRun(run,initAlign=ref,swapx=True,swapy=False)
+ res=r.doShots(slice(5),doFit=False)
+ ret = res["ratio"]/ref if divideByRef else res["ratio"]
+ if returnRes:
+ return ret,res
+ else:
+ return ret
+
+def quickAndDirty(run,nShots=300,returnAll=True,doFit=False):
+ """ useful to analyze the runs around 140 (done with the focusing """
+ r = AnalyzeRun(run,swap=True,initAlign=g_folder_init+"/run0144_transform.npy")
+ res=r.doShots(slice(nShots),doFit=doFit)
+ o = alignment.unravel_results(res)
+ ref = np.nanmedian(o["ratio"][:40],0)
+ sam = np.nanmedian(o["ratio"][50:],0)
+ if returnAll:
+ return sam/ref,o["ratio"]/ref
+ else:
+ return sam/ref
diff --git a/xppl3716_init_pars/run0013_transform.npy b/xppl3716_init_pars/run0013_transform.npy
new file mode 100644
index 0000000..246238f
Binary files /dev/null and b/xppl3716_init_pars/run0013_transform.npy differ
diff --git a/xppl3716_init_pars/run0023_gui_align.npy b/xppl3716_init_pars/run0023_gui_align.npy
new file mode 100644
index 0000000..5d19866
Binary files /dev/null and b/xppl3716_init_pars/run0023_gui_align.npy differ
diff --git a/xppl3716_init_pars/run0023_transform.npy b/xppl3716_init_pars/run0023_transform.npy
new file mode 100644
index 0000000..db2ee6b
Binary files /dev/null and b/xppl3716_init_pars/run0023_transform.npy differ
diff --git a/xppl3716_init_pars/run0024_transform.npy b/xppl3716_init_pars/run0024_transform.npy
new file mode 100644
index 0000000..8eb135d
Binary files /dev/null and b/xppl3716_init_pars/run0024_transform.npy differ
diff --git a/xppl3716_init_pars/run0025_transform.npy b/xppl3716_init_pars/run0025_transform.npy
new file mode 100644
index 0000000..65b1390
Binary files /dev/null and b/xppl3716_init_pars/run0025_transform.npy differ
diff --git a/xppl3716_init_pars/run0028_transform.npy b/xppl3716_init_pars/run0028_transform.npy
new file mode 100644
index 0000000..5ecd0b1
Binary files /dev/null and b/xppl3716_init_pars/run0028_transform.npy differ
diff --git a/xppl3716_init_pars/run0029_transform.npy b/xppl3716_init_pars/run0029_transform.npy
new file mode 100644
index 0000000..f0ba1d6
Binary files /dev/null and b/xppl3716_init_pars/run0029_transform.npy differ
diff --git a/xppl3716_init_pars/run0043_transform.npy b/xppl3716_init_pars/run0043_transform.npy
new file mode 100644
index 0000000..b0597be
Binary files /dev/null and b/xppl3716_init_pars/run0043_transform.npy differ
diff --git a/xppl3716_init_pars/run0044_transform.npy b/xppl3716_init_pars/run0044_transform.npy
new file mode 100644
index 0000000..66be7dd
Binary files /dev/null and b/xppl3716_init_pars/run0044_transform.npy differ
diff --git a/xppl3716_init_pars/run0045_transform.npy b/xppl3716_init_pars/run0045_transform.npy
new file mode 100644
index 0000000..66be7dd
Binary files /dev/null and b/xppl3716_init_pars/run0045_transform.npy differ
diff --git a/xppl3716_init_pars/run0054_gui_align.npy b/xppl3716_init_pars/run0054_gui_align.npy
new file mode 100644
index 0000000..b32ef6b
Binary files /dev/null and b/xppl3716_init_pars/run0054_gui_align.npy differ
diff --git a/xppl3716_init_pars/run0054_transform.npy b/xppl3716_init_pars/run0054_transform.npy
new file mode 100644
index 0000000..3506b15
Binary files /dev/null and b/xppl3716_init_pars/run0054_transform.npy differ
diff --git a/xppl3716_init_pars/run0079_gui_align.npy b/xppl3716_init_pars/run0079_gui_align.npy
new file mode 100644
index 0000000..97e3023
Binary files /dev/null and b/xppl3716_init_pars/run0079_gui_align.npy differ
diff --git a/xppl3716_init_pars/run0080_transform.npy b/xppl3716_init_pars/run0080_transform.npy
new file mode 100644
index 0000000..bd9eea0
Binary files /dev/null and b/xppl3716_init_pars/run0080_transform.npy differ
diff --git a/xppl3716_init_pars/run0082_transform.npy b/xppl3716_init_pars/run0082_transform.npy
new file mode 100644
index 0000000..69e2eb1
Binary files /dev/null and b/xppl3716_init_pars/run0082_transform.npy differ
diff --git a/xppl3716_init_pars/run0084_transform.npy b/xppl3716_init_pars/run0084_transform.npy
new file mode 100644
index 0000000..e235f15
Binary files /dev/null and b/xppl3716_init_pars/run0084_transform.npy differ
diff --git a/xppl3716_init_pars/run0095_transform.npy b/xppl3716_init_pars/run0095_transform.npy
new file mode 100644
index 0000000..b1cb08f
Binary files /dev/null and b/xppl3716_init_pars/run0095_transform.npy differ
diff --git a/xppl3716_init_pars/run0097_transform.npy b/xppl3716_init_pars/run0097_transform.npy
new file mode 100644
index 0000000..149a6c5
Binary files /dev/null and b/xppl3716_init_pars/run0097_transform.npy differ
diff --git a/xppl3716_init_pars/run0104_transform.npy b/xppl3716_init_pars/run0104_transform.npy
new file mode 100644
index 0000000..e87d02a
Binary files /dev/null and b/xppl3716_init_pars/run0104_transform.npy differ
diff --git a/xppl3716_init_pars/run0113_gui_align.npy b/xppl3716_init_pars/run0113_gui_align.npy
new file mode 100644
index 0000000..b4d1623
Binary files /dev/null and b/xppl3716_init_pars/run0113_gui_align.npy differ
diff --git a/xppl3716_init_pars/run0113_transform.npy b/xppl3716_init_pars/run0113_transform.npy
new file mode 100644
index 0000000..65b849b
Binary files /dev/null and b/xppl3716_init_pars/run0113_transform.npy differ
diff --git a/xppl3716_init_pars/run0117_transform.npy b/xppl3716_init_pars/run0117_transform.npy
new file mode 100644
index 0000000..d41a1e6
Binary files /dev/null and b/xppl3716_init_pars/run0117_transform.npy differ
diff --git a/xppl3716_init_pars/run0118_gui_align.npy b/xppl3716_init_pars/run0118_gui_align.npy
new file mode 100644
index 0000000..59ffdef
Binary files /dev/null and b/xppl3716_init_pars/run0118_gui_align.npy differ
diff --git a/xppl3716_init_pars/run0118_transform.npy b/xppl3716_init_pars/run0118_transform.npy
new file mode 100644
index 0000000..70e01dd
Binary files /dev/null and b/xppl3716_init_pars/run0118_transform.npy differ
diff --git a/xppl3716_init_pars/run0124_transform.npy b/xppl3716_init_pars/run0124_transform.npy
new file mode 100644
index 0000000..1f8fb02
Binary files /dev/null and b/xppl3716_init_pars/run0124_transform.npy differ
diff --git a/xppl3716_init_pars/run0128_transform.npy b/xppl3716_init_pars/run0128_transform.npy
new file mode 100644
index 0000000..7f51649
Binary files /dev/null and b/xppl3716_init_pars/run0128_transform.npy differ
diff --git a/xppl3716_init_pars/run0144_transform.npy b/xppl3716_init_pars/run0144_transform.npy
new file mode 100644
index 0000000..ead16bd
Binary files /dev/null and b/xppl3716_init_pars/run0144_transform.npy differ
diff --git a/xppl3716_init_pars/run0152_transform.npy b/xppl3716_init_pars/run0152_transform.npy
new file mode 100644
index 0000000..17b06e9
Binary files /dev/null and b/xppl3716_init_pars/run0152_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0013_transform.npy b/xppl3716_init_pars_old/run0013_transform.npy
new file mode 100644
index 0000000..246238f
Binary files /dev/null and b/xppl3716_init_pars_old/run0013_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0023_gui_align.npy b/xppl3716_init_pars_old/run0023_gui_align.npy
new file mode 100644
index 0000000..5d19866
Binary files /dev/null and b/xppl3716_init_pars_old/run0023_gui_align.npy differ
diff --git a/xppl3716_init_pars_old/run0023_transform.npy b/xppl3716_init_pars_old/run0023_transform.npy
new file mode 100644
index 0000000..db2ee6b
Binary files /dev/null and b/xppl3716_init_pars_old/run0023_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0024_transform.npy b/xppl3716_init_pars_old/run0024_transform.npy
new file mode 100644
index 0000000..8eb135d
Binary files /dev/null and b/xppl3716_init_pars_old/run0024_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0025_transform.npy b/xppl3716_init_pars_old/run0025_transform.npy
new file mode 100644
index 0000000..65b1390
Binary files /dev/null and b/xppl3716_init_pars_old/run0025_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0028_transform.npy b/xppl3716_init_pars_old/run0028_transform.npy
new file mode 100644
index 0000000..5ecd0b1
Binary files /dev/null and b/xppl3716_init_pars_old/run0028_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0029_transform.npy b/xppl3716_init_pars_old/run0029_transform.npy
new file mode 100644
index 0000000..f0ba1d6
Binary files /dev/null and b/xppl3716_init_pars_old/run0029_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0043_transform.npy b/xppl3716_init_pars_old/run0043_transform.npy
new file mode 100644
index 0000000..b0597be
Binary files /dev/null and b/xppl3716_init_pars_old/run0043_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0044_transform.npy b/xppl3716_init_pars_old/run0044_transform.npy
new file mode 100644
index 0000000..66be7dd
Binary files /dev/null and b/xppl3716_init_pars_old/run0044_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0045_transform.npy b/xppl3716_init_pars_old/run0045_transform.npy
new file mode 100644
index 0000000..66be7dd
Binary files /dev/null and b/xppl3716_init_pars_old/run0045_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0054_gui_align.npy b/xppl3716_init_pars_old/run0054_gui_align.npy
new file mode 100644
index 0000000..b32ef6b
Binary files /dev/null and b/xppl3716_init_pars_old/run0054_gui_align.npy differ
diff --git a/xppl3716_init_pars_old/run0054_transform.npy b/xppl3716_init_pars_old/run0054_transform.npy
new file mode 100644
index 0000000..3506b15
Binary files /dev/null and b/xppl3716_init_pars_old/run0054_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0079_gui_align.npy b/xppl3716_init_pars_old/run0079_gui_align.npy
new file mode 100644
index 0000000..97e3023
Binary files /dev/null and b/xppl3716_init_pars_old/run0079_gui_align.npy differ
diff --git a/xppl3716_init_pars_old/run0080_transform.npy b/xppl3716_init_pars_old/run0080_transform.npy
new file mode 100644
index 0000000..bd9eea0
Binary files /dev/null and b/xppl3716_init_pars_old/run0080_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0082_transform.npy b/xppl3716_init_pars_old/run0082_transform.npy
new file mode 100644
index 0000000..69e2eb1
Binary files /dev/null and b/xppl3716_init_pars_old/run0082_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0084_transform.npy b/xppl3716_init_pars_old/run0084_transform.npy
new file mode 100644
index 0000000..e235f15
Binary files /dev/null and b/xppl3716_init_pars_old/run0084_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0095_transform.npy b/xppl3716_init_pars_old/run0095_transform.npy
new file mode 100644
index 0000000..b1cb08f
Binary files /dev/null and b/xppl3716_init_pars_old/run0095_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0097_transform.npy b/xppl3716_init_pars_old/run0097_transform.npy
new file mode 100644
index 0000000..d6bf9c1
Binary files /dev/null and b/xppl3716_init_pars_old/run0097_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0104_transform.npy b/xppl3716_init_pars_old/run0104_transform.npy
new file mode 100644
index 0000000..e87d02a
Binary files /dev/null and b/xppl3716_init_pars_old/run0104_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0113_gui_align.npy b/xppl3716_init_pars_old/run0113_gui_align.npy
new file mode 100644
index 0000000..b4d1623
Binary files /dev/null and b/xppl3716_init_pars_old/run0113_gui_align.npy differ
diff --git a/xppl3716_init_pars_old/run0113_transform.npy b/xppl3716_init_pars_old/run0113_transform.npy
new file mode 100644
index 0000000..65b849b
Binary files /dev/null and b/xppl3716_init_pars_old/run0113_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0117_transform.npy b/xppl3716_init_pars_old/run0117_transform.npy
new file mode 100644
index 0000000..d41a1e6
Binary files /dev/null and b/xppl3716_init_pars_old/run0117_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0118_gui_align.npy b/xppl3716_init_pars_old/run0118_gui_align.npy
new file mode 100644
index 0000000..59ffdef
Binary files /dev/null and b/xppl3716_init_pars_old/run0118_gui_align.npy differ
diff --git a/xppl3716_init_pars_old/run0118_transform.npy b/xppl3716_init_pars_old/run0118_transform.npy
new file mode 100644
index 0000000..70e01dd
Binary files /dev/null and b/xppl3716_init_pars_old/run0118_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0124_transform.npy b/xppl3716_init_pars_old/run0124_transform.npy
new file mode 100644
index 0000000..1f8fb02
Binary files /dev/null and b/xppl3716_init_pars_old/run0124_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0128_transform.npy b/xppl3716_init_pars_old/run0128_transform.npy
new file mode 100644
index 0000000..7f51649
Binary files /dev/null and b/xppl3716_init_pars_old/run0128_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0144_transform.npy b/xppl3716_init_pars_old/run0144_transform.npy
new file mode 100644
index 0000000..ead16bd
Binary files /dev/null and b/xppl3716_init_pars_old/run0144_transform.npy differ
diff --git a/xppl3716_init_pars_old/run0152_transform.npy b/xppl3716_init_pars_old/run0152_transform.npy
new file mode 100644
index 0000000..17b06e9
Binary files /dev/null and b/xppl3716_init_pars_old/run0152_transform.npy differ