Script that analyzes the results from kinetic simulations

``````

In [1]:

# General libraries
import os
import pickle
import numpy as np

# Plot, in nb, only when .show() is called
import matplotlib.pyplot as plt
%matplotlib notebook
plt.ioff()

# Personal libraries
import tools.evaluation as ev
import tools.plot as pt

``````

Before evaluating the simulaion results, we scan the folders and create the variables where we will store the overlaps. Note that each type of simulations has a six letters heading. For example, for Kinetic Capacity simulation the heading is `KinCap`

``````

In [2]:

path = '/home/sartori/Data/memexp'
# path = '/Users/pablo/Data/memexp'
dir_list = [ path + '/' + x for x in os.listdir(path) if x[0:9]=='KinSeqLen']
dir_list.sort()

``````

We can now read the files and store the overlaps over time. We store them in a dictionary which assigns to the tuple `(k,p)` a list with all the overlaps over time (this implicitly assumes that all other parameters, such as network size or temperature, were kept fixed equal)

``````

In [26]:

data = {}
for d in dir_list:
net = pickle.load( open(d + '/net.pkl','rb') )
# Create the key to store data
key = (net.k, net.p)
data.setdefault(key,[]).append(overlaps)
print d

# Generate plot
#pt.plot_overlaps(overlaps, show = False, name = os.path.basename(d) )

``````

We can look at the values of (p,k) that we have loaded

``````

In [24]:

data.keys()

``````
``````

Out[24]:

[(5, 10),
(5, 11),
(5, 6),
(5, 12),
(5, 18),
(5, 13),
(5, 24),
(5, 14),
(5, 15),
(5, 8)]

``````

We can plot the overlaps for one example

``````

In [22]:

key = (5,15)
test_overlaps = data[key][0]
pt.plot_overlaps(test_overlaps[:,:])

``````
``````

var element = \$('#ddff045f-8970-448f-be7e-e9b8d1ed96c9');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

Out[22]:

0

``````

We can also check the score of the retrieved pattern

``````

In [23]:

ev.my_score(key, data[key], cutoff = 0.5, time_retrieved = 10)

``````
``````

(5, 4)

Out[23]:

0.0

``````

Analyze the data

Analysis

``````

In [44]:

xyz = []
for key in data.iterkeys():
wowo = ev.my_score(key, data[key], cutoff = 0.75, time_retrieved = 15)
xyz.append( (key[0], key[1], wowo) )

XYZ = np.asarray(xyz)
XY = XYZ[:,1:]

``````
``````

(5, 4)
(5, 4)
(5, 4)
(15, 29)

Out[44]:

array([[  5.        ,   0.        ],
[  6.        ,   1.        ],
[ 15.        ,   1.        ],
[ 15.        ,   1.        ],
[ 20.        ,   0.24137931]])

``````
``````

In [12]:

N_600_k_6 = np.array([[  6.        ,   0.95369048],
[  7.        ,   0.94718831],
[  8.        ,   0.95378571],
[  9.        ,   0.94807143],
[ 10.        ,   0.93169264],
[ 11.        ,   0.95302381],
[ 12.        ,   0.95964286],
[ 13.        ,   0.95659524],
[ 14.        ,   0.9325873 ],
[ 15.        ,   0.93683117],
[ 16.        ,   0.92232305],
[ 17.        ,   0.92747619],
[ 18.        ,   0.93204978],
[ 19.        ,   0.92041486],
[ 20.        ,   0.91522746],
[ 21.        ,   0.90003422],
[ 22.        ,   0.92825216],
[ 23.        ,   0.95593074],
[ 24.        ,   0.95315476],
[ 25.        ,   0.87068209],
[ 26.        ,   0.92831513],
[ 27.        ,   0.91080292],
[ 28.        ,   0.88504762],
[ 29.        ,   0.90925216],
[ 30.        ,   0.87813409],
[ 31.        ,   0.87394481],
[ 32.        ,   0.85943898],
[ 33.        ,   0.87564141],
[ 34.        ,   0.8303058 ],
[ 35.        ,   0.82828851],
[ 36.        ,   0.79966836],
[ 37.        ,   0.82360065],
[ 38.        ,   0.85686888],
[ 39.        ,   0.84079942],
[ 40.        ,   0.8664228 ],
[ 41.        ,   0.84274459],
[ 42.        ,   0.7854203 ],
[ 43.        ,   0.7805369 ],
[ 44.        ,   0.80515279],
[ 45.        ,   0.79861724]])

N_300_k_5 = np.array([[  5.        ,   0.95088889],
[  6.        ,   0.97050794],
[  7.        ,   0.91151587],
[  8.        ,   0.9357619 ],
[  9.        ,   0.96209127],
[ 10.        ,   0.9257619 ],
[ 11.        ,   0.9114127 ],
[ 12.        ,   0.9205119 ],
[ 13.        ,   0.91901462],
[ 14.        ,   0.88436383],
[ 15.        ,   0.91598016],
[ 16.        ,   0.90003719],
[ 17.        ,   0.86954906],
[ 18.        ,   0.87684491],
[ 19.        ,   0.83830397],
[ 20.        ,   0.83805614],
[ 21.        ,   0.84352797],
[ 22.        ,   0.84136762],
[ 23.        ,   0.81173737],
[ 24.        ,   0.82705898],
[ 25.        ,   0.79449098],
[ 26.        ,   0.73145088],
[ 27.        ,   0.7906142 ],
[ 28.        ,   0.74260462],
[ 29.        ,   0.7401806 ],
[ 30.        ,   0.71375386],
[ 31.        ,   0.69474206],
[ 32.        ,   0.66053139],
[ 33.        ,   0.67109002],
[ 34.        ,   0.62481405]])

N_300_k_7 = np.array([[  7.        ,   0.82206571],
[  8.        ,   0.81966461],
[  9.        ,   0.80958555],
[ 10.        ,   0.83364291],
[ 11.        ,   0.82373521],
[ 12.        ,   0.82612116],
[ 13.        ,   0.79994331],
[ 14.        ,   0.79163858],
[ 15.        ,   0.79444012],
[ 16.        ,   0.79028216],
[ 17.        ,   0.81237318],
[ 18.        ,   0.7482349 ],
[ 19.        ,   0.7502307 ],
[ 20.        ,   0.75578011],
[ 21.        ,   0.73713936],
[ 22.        ,   0.73331323],
[ 23.        ,   0.76652548],
[ 24.        ,   0.72488869],
[ 25.        ,   0.67307359],
[ 26.        ,   0.6778688 ],
[ 27.        ,   0.68594744],
[ 28.        ,   0.68337721],
[ 29.        ,   0.59460317],
[ 30.        ,   0.58188119],
[ 31.        ,   0.54068741],
[ 32.        ,   0.58741868],
[ 33.        ,   0.5091241 ],
[ 34.        ,   0.60376277],
[ 35.        ,   0.45519889],
[ 36.        ,   0.43525042]])

``````

We now generate a plot

``````

In [14]:

fig = plt.figure()

ax1.scatter(N_300_k_5[:,0], N_300_k_5[:,1], s=35, c='g', marker="o", label='\$N=300,\;k=5\$')
ax1.scatter(N_300_k_7[:,0], N_300_k_7[:,1], s=35, c='b', marker="o", label='\$N=300,\;k=7\$')

ax1.scatter(N_600_k_6[:,0], N_600_k_6[:,1], s=35, c='r', marker="s", label='\$N=600,\;k=6\$')

plt.xlabel('stored patterns, \$p\$',fontdict={'fontsize':20})
plt.ylabel('sequence retrieval score',fontdict={'fontsize':20})
plt.axis([0, 50, 0, 1])

plt.legend(loc='upper right');
plt.show()

``````
``````

var element = \$('#9fe2f735-e961-4174-81a8-e1400af692e4');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

``````

Analyze the results from energetic simulations

``````

In [1]:

# General libraries
import os
import pickle
import numpy as np

# Plot, in nb, only when .show() is called
import matplotlib.pyplot as plt
%matplotlib notebook
plt.ioff()

# Personal libraries
import tools.evaluation as ev
import tools.plot as pt

``````

Before evaluating the simulaion results, we scan the folders and create the variables where we will store the overlaps. Note that each type of simulations has a six letters heading. For example, for Kinetic Capacity simulation the heading is `EnCapCorr`

``````

In [ ]:

path = '/home/sartori/Data/memexp'
# path = '/Users/pablo/Data/memexp'
dir_list = [ path + '/' + x for x in os.listdir(path) if x[0:9]=='EnCapCorr']
dir_list.sort()

``````

We can now read the files and store the overlaps over time. We store them in a dictionary which assigns to the tuple `(k,p)` a list with all the overlaps over time (this implicitly assumes that all other parameters, such as network size or temperature, were kept fixed equal)

``````

In [26]:

data = {}
for d in dir_list:
# Create the key to store data
p = int(d.split("_")[1][1:])
c = int(d.split("_")[3][1:])
key = (c, p)
# Store the data
data.setdefault(key,[]).append(overlaps)
print d

# Generate plot
#pt.plot_overlaps(overlaps, show = False, name = os.path.basename(d) )

``````

Analyze data

Analysis for the case of correlated patterns

``````

In [ ]:

xyz = []
for key in data.iterkeys():
k = 15
p = key[1]
wowo = ev.my_score((k, p), data[key], cutoff = 0.75, time_retrieved = 15)
xyz.append( (k, c, wowo) )

XYZ = np.asarray(xyz)
XY = XYZ[:,1:]

``````

Collect the data form the simulations tun in the cluster

``````

In [4]:

Ec30k7 = np.array([[  7.00000000e+00,   8.45969336e-01],
[  8.00000000e+00,   8.17170274e-01],
[  9.00000000e+00,   7.35082126e-01],
[  1.00000000e+01,   6.38407703e-01],
[  1.10000000e+01,   5.99932900e-01],
[  1.20000000e+01,   4.64281205e-01],
[  1.30000000e+01,   4.01477273e-01],
[  1.40000000e+01,   2.31383690e-01],
[  1.50000000e+01,   1.87150794e-01],
[  1.60000000e+01,   6.57251082e-02],
[  1.70000000e+01,   4.19706960e-02],
[  1.80000000e+01,   6.39527417e-02],
[  1.90000000e+01,   2.32622655e-02],
[  2.00000000e+01,   3.22499722e-02],
[  2.10000000e+01,   2.22720842e-02],
[  2.20000000e+01,   1.72702020e-02],
[  2.30000000e+01,   1.31997863e-02],
[  2.40000000e+01,   1.10049020e-02],
[  2.50000000e+01,   1.88658009e-02],
[  2.60000000e+01,   2.11847874e-02],
[  2.70000000e+01,   1.30555556e-02],
[  2.80000000e+01,   1.26439394e-02],
[  2.90000000e+01,   9.88442113e-03]]) # cutoff = 0.75, dt = 15

Ec20k7 = np.array([[  7.        ,   0.725     ],
[  8.        ,   0.77942063],
[  9.        ,   0.71456349],
[ 10.        ,   0.74063492],
[ 11.        ,   0.73959921],
[ 12.        ,   0.67109127],
[ 13.        ,   0.71756349],
[ 14.        ,   0.69521429],
[ 15.        ,   0.64073413],
[ 16.        ,   0.63285714],
[ 17.        ,   0.60983766],
[ 18.        ,   0.54068987],
[ 19.        ,   0.49763492],
[ 20.        ,   0.4125    ],
[ 21.        ,   0.37652778],
[ 22.        ,   0.38134921],
[ 23.        ,   0.26017857],
[ 24.        ,   0.22642857],
[ 25.        ,   0.15038961],
[ 26.        ,   0.10321429],
[ 27.        ,   0.1325    ],
[ 28.        ,   0.05535714],
[ 29.        ,   0.03160714]])

Ec15k7 = np.array([[  7.        ,   0.60678571],
[  8.        ,   0.59357143],
[  9.        ,   0.59956349],
[ 10.        ,   0.62821429],
[ 11.        ,   0.56107143],
[ 12.        ,   0.64053571],
[ 13.        ,   0.58785714],
[ 14.        ,   0.53742063],
[ 15.        ,   0.58339286],
[ 16.        ,   0.57498016],
[ 17.        ,   0.58402778],
[ 18.        ,   0.55321429],
[ 19.        ,   0.607     ],
[ 20.        ,   0.58910714],
[ 21.        ,   0.56714286],
[ 22.        ,   0.49535714],
[ 23.        ,   0.53660714],
[ 24.        ,   0.47593254],
[ 25.        ,   0.41259921],
[ 26.        ,   0.44303571],
[ 27.        ,   0.35325397],
[ 28.        ,   0.41321429],
[ 29.        ,   0.28053571]])

Ec10k7 = np.array([[  7.        ,   0.3875    ],
[  8.        ,   0.45321429],
[  9.        ,   0.48089286],
[ 10.        ,   0.48535714],
[ 11.        ,   0.46732143],
[ 12.        ,   0.4575    ],
[ 13.        ,   0.46589286],
[ 14.        ,   0.51777778],
[ 15.        ,   0.49517857],
[ 16.        ,   0.47160714],
[ 17.        ,   0.40428571],
[ 18.        ,   0.4975    ],
[ 19.        ,   0.44160714],
[ 20.        ,   0.46607143],
[ 21.        ,   0.555     ],
[ 22.        ,   0.48785714],
[ 23.        ,   0.48160714],
[ 24.        ,   0.43142857],
[ 25.        ,   0.47910714],
[ 26.        ,   0.51089286],
[ 27.        ,   0.48589286],
[ 28.        ,   0.45714286],
[ 29.        ,   0.41      ]])

Ec5k7 = np.array([[  7.        ,   0.36142857],
[  8.        ,   0.38      ],
[  9.        ,   0.35285714],
[ 10.        ,   0.38      ],
[ 11.        ,   0.34875   ],
[ 12.        ,   0.4       ],
[ 13.        ,   0.34321429],
[ 14.        ,   0.34920635],
[ 15.        ,   0.35732143],
[ 16.        ,   0.36857143],
[ 17.        ,   0.33428571],
[ 18.        ,   0.37      ],
[ 19.        ,   0.35428571],
[ 20.        ,   0.39206349],
[ 21.        ,   0.36464286],
[ 22.        ,   0.35428571],
[ 23.        ,   0.37142857],
[ 24.        ,   0.35142857],
[ 25.        ,   0.40303571],
[ 26.        ,   0.39732143],
[ 27.        ,   0.33589286],
[ 28.        ,   0.35321429],
[ 29.        ,   0.31857143]])

Ec0k7 = np.array([[  7.        ,   0.24571429],
[  8.        ,   0.28571429],
[  9.        ,   0.30607143],
[ 10.        ,   0.27285714],
[ 11.        ,   0.29571429],
[ 12.        ,   0.29428571],
[ 13.        ,   0.26428571],
[ 14.        ,   0.28285714],
[ 15.        ,   0.27714286],
[ 16.        ,   0.28285714],
[ 17.        ,   0.28142857],
[ 18.        ,   0.28857143],
[ 19.        ,   0.26714286],
[ 20.        ,   0.28285714],
[ 21.        ,   0.27285714],
[ 22.        ,   0.28142857],
[ 23.        ,   0.26035714],
[ 24.        ,   0.28142857],
[ 25.        ,   0.29571429],
[ 26.        ,   0.25      ],
[ 27.        ,   0.28285714],
[ 28.        ,   0.25142857],
[ 29.        ,   0.28571429]])

Ec0k14 = np.array([[ 14.        ,   0.14857143],
[ 15.        ,   0.13571429],
[ 16.        ,   0.15      ],
[ 17.        ,   0.12785714],
[ 18.        ,   0.14785714],
[ 19.        ,   0.13785714],
[ 20.        ,   0.13071429],
[ 21.        ,   0.14285714],
[ 22.        ,   0.15357143],
[ 23.        ,   0.135     ],
[ 24.        ,   0.13642857],
[ 25.        ,   0.16642857],
[ 26.        ,   0.13714286],
[ 27.        ,   0.13714286],
[ 28.        ,   0.14571429],
[ 29.        ,   0.12571429],
[ 30.        ,   0.13785714],
[ 31.        ,   0.145     ],
[ 32.        ,   0.135     ],
[ 33.        ,   0.135     ],
[ 34.        ,   0.14071429],
[ 35.        ,   0.135     ],
[ 36.        ,   0.135     ]])

Kc30k7 = np.array([[  7.00000000e+00,   3.21269841e-01],
[  8.00000000e+00,   2.62678571e-01],
[  9.00000000e+00,   2.38571429e-01],
[  1.00000000e+01,   1.68571429e-01],
[  1.10000000e+01,   1.26300366e-01],
[  1.20000000e+01,   9.28571429e-02],
[  1.30000000e+01,   7.71428571e-02],
[  1.40000000e+01,   5.00000000e-02],
[  1.50000000e+01,   2.85714286e-02],
[  1.60000000e+01,   1.10714286e-02],
[  1.70000000e+01,   7.38095238e-03],
[  1.80000000e+01,   2.19780220e-03],
[  1.90000000e+01,   0.00000000e+00],
[  2.00000000e+01,   2.33766234e-03],
[  2.10000000e+01,   0.00000000e+00],
[  2.20000000e+01,   0.00000000e+00],
[  2.30000000e+01,   1.25000000e-03],
[  2.40000000e+01,   0.00000000e+00],
[  2.50000000e+01,   0.00000000e+00],
[  2.60000000e+01,   0.00000000e+00],
[  2.70000000e+01,   0.00000000e+00],
[  2.80000000e+01,   0.00000000e+00],
[  2.90000000e+01,   0.00000000e+00]]) # cutoff = 0.75, dt = 15

``````
``````

In [5]:

fig = plt.figure()

ax1.scatter(Ec30k7[:,0], Ec30k7[:,1], s=35, c='k', marker="o", label='Energetic, \$c=30,\;k=7\$')
ax1.scatter(Ec20k7[:,0], Ec20k7[:,1], s=35, c='0.6', marker="o", label='Energetic, \$c=20,\;k=7\$')
ax1.scatter(Ec15k7[:,0], Ec15k7[:,1], s=35, c='r', marker="o", label='Energetic, \$c=15,\;k=7\$')
ax1.scatter(Ec10k7[:,0], Ec10k7[:,1], s=35, c='g', marker="o", label='Energetic, \$c=10,\;k=7\$')
ax1.scatter(Ec5k7[:,0], Ec5k7[:,1], s=35, c='y', marker="o", label='Energetic, \$c=5,\;k=7\$')
ax1.scatter(Ec0k7[:,0], Ec0k7[:,1], s=35, c='b', marker="o", label='Energetic, \$c=0,\;k=7\$')
ax1.scatter(Ec0k14[:,0], Ec0k14[:,1], s=35, c='w',marker="o", label='Energetic, \$c=0,\;k=14\$')
ax1.scatter(Kc30k7[:,0], Kc30k7[:,1], s=35, c='b', marker="s", label='Kinetic, \$c=30,\;k=7\$')

plt.xlabel('stored patterns, \$p\$',fontdict={'fontsize':20})
plt.ylabel('sequence retrieval score',fontdict={'fontsize':20})
plt.axis([0, 50, 0, 1])

plt.legend(loc='upper right');
plt.show()

``````
``````

var element = \$('#702b261d-2078-4a12-918a-6b11a7b240a3');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

``````
``````

In [2]:

``````
``````

In [15]:

key = (5,15)
test_overlaps = data[key][54]
pt.plot_overlaps(test_overlaps[:,:])

``````
``````

var element = \$('#1cb3a25e-25ed-46ec-b104-ea9e4b8371e6');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

Out[15]:

0

``````
``````

In [16]:

ev.my_score(key, [data[key][54]], cutoff = 0.75, time_retrieved = 15)

``````
``````

(5, 4)

Out[16]:

0.80000000000000004

``````

Analysze kinetic+energetic simulations, core size

``````

In [1]:

# General libraries
import os
import pickle
import numpy as np

# Plot, in nb, only when .show() is called
import matplotlib.pyplot as plt
%matplotlib notebook
plt.ioff()

# Personal libraries
import tools.evaluation as ev
import tools.plot as pt

``````
``````

In [ ]:

path = '/home/sartori/Data/memexp'
# path = '/Users/pablo/Data/memexp'
dir_list = [ path + '/' + x for x in os.listdir(path) if x[0:10]=='KinCapCorr']
dir_list.sort()

``````
``````

In [ ]:

data = {}
for d in dir_list:
# Create the key to store data
p = 16
c = int(d.split("_")[1][1:])
key = (c, p)
# Store the data
data.setdefault(key,[]).append(overlaps)
print d

``````
``````

In [ ]:

xyz = []
for key in data.iterkeys():
k = 15
p = key[1]
wowo = ev.my_score((k, p), data[key], cutoff = 0.75, time_retrieved = 15)
xyz.append( (k, key[0], wowo) )

XYZ = np.asarray(xyz)
XY = XYZ[:,1:]
XY[np.argsort(XY[:,0]),:]

``````
``````

In [4]:

Ek15 = np.array([[  0.00000000e+00,   1.55333333e-01],
[  1.00000000e+00,   6.66666667e-02],
[  2.00000000e+00,   1.52666667e-01],
[  3.00000000e+00,   1.64000000e-01],
[  4.00000000e+00,   1.60000000e-01],
[  5.00000000e+00,   1.76666667e-01],
[  6.00000000e+00,   1.86666667e-01],
[  7.00000000e+00,   1.85333333e-01],
[  8.00000000e+00,   2.06000000e-01],
[  9.00000000e+00,   2.34666667e-01],
[  1.00000000e+01,   2.42000000e-01],
[  1.10000000e+01,   2.57333333e-01],
[  1.20000000e+01,   3.11333333e-01],
[  1.30000000e+01,   3.15333333e-01],
[  1.40000000e+01,   3.01333333e-01],
[  1.50000000e+01,   3.48000000e-01],
[  1.60000000e+01,   3.32000000e-01],
[  1.70000000e+01,   3.24000000e-01],
[  1.80000000e+01,   4.00000000e-01],
[  1.90000000e+01,   4.26000000e-01],
[  2.00000000e+01,   3.96000000e-01],
[  2.10000000e+01,   3.52666667e-01],
[  2.20000000e+01,   3.90666667e-01],
[  2.30000000e+01,   4.13541667e-01],
[  2.40000000e+01,   3.05333333e-01],
[  2.50000000e+01,   2.25372549e-01],
[  2.60000000e+01,   2.56588235e-01],
[  2.70000000e+01,   1.68666667e-01],
[  2.80000000e+01,   6.20000000e-02],
[  2.90000000e+01,   4.54166667e-02],
[  3.00000000e+01,   5.20000000e-02],
[  3.10000000e+01,   3.58596491e-02],
[  3.20000000e+01,   6.00000000e-03],
[  3.30000000e+01,   2.33333333e-02],
[  3.40000000e+01,   1.40000000e-02],
[  3.50000000e+01,   1.05138889e-02],
[  3.60000000e+01,   4.47619048e-03],
[  3.70000000e+01,   6.66666667e-03],
[  3.80000000e+01,   4.66666667e-03],
[  3.90000000e+01,   3.11111111e-03]])

Ek7 = np.array([[  0.00000000e+00,   2.68571429e-01],
[  1.00000000e+00,   1.42857143e-01],
[  2.00000000e+00,   3.04285714e-01],
[  3.00000000e+00,   3.02857143e-01],
[  4.00000000e+00,   3.61428571e-01],
[  5.00000000e+00,   3.35714286e-01],
[  6.00000000e+00,   3.31607143e-01],
[  7.00000000e+00,   4.04285714e-01],
[  8.00000000e+00,   4.05714286e-01],
[  9.00000000e+00,   4.21607143e-01],
[  1.00000000e+01,   4.82964286e-01],
[  1.10000000e+01,   5.36964286e-01],
[  1.20000000e+01,   5.48928571e-01],
[  1.30000000e+01,   5.17142857e-01],
[  1.40000000e+01,   5.23392857e-01],
[  1.50000000e+01,   5.62777778e-01],
[  1.60000000e+01,   5.96785714e-01],
[  1.70000000e+01,   6.42500000e-01],
[  1.80000000e+01,   6.36428571e-01],
[  1.90000000e+01,   6.26785714e-01],
[  2.00000000e+01,   6.23928571e-01],
[  2.10000000e+01,   6.12039683e-01],
[  2.20000000e+01,   4.96304945e-01],
[  2.30000000e+01,   5.57634921e-01],
[  2.40000000e+01,   4.75813492e-01],
[  2.50000000e+01,   3.79519841e-01],
[  2.60000000e+01,   3.07884921e-01],
[  2.70000000e+01,   2.33285104e-01],
[  2.80000000e+01,   1.86357143e-01],
[  2.90000000e+01,   1.28000111e-01],
[  3.00000000e+01,   1.36276718e-01],
[  3.10000000e+01,   1.21539322e-01],
[  3.20000000e+01,   5.11714674e-02],
[  3.30000000e+01,   4.05880231e-02],
[  3.40000000e+01,   3.30740093e-02],
[  3.50000000e+01,   5.33261034e-02],
[  3.60000000e+01,   6.31888061e-02],
[  3.70000000e+01,   6.10113449e-02],
[  3.80000000e+01,   3.93618355e-02],
[  3.90000000e+01,   4.30572930e-02]])

Kk7 = np.array([[  0.00000000e+00,   8.61299839e-01],
[  1.00000000e+00,   1.42857143e-01],
[  2.00000000e+00,   8.52142857e-01],
[  3.00000000e+00,   7.95597763e-01],
[  4.00000000e+00,   7.79185673e-01],
[  5.00000000e+00,   7.71347403e-01],
[  6.00000000e+00,   6.92350289e-01],
[  7.00000000e+00,   6.85451673e-01],
[  8.00000000e+00,   6.38240886e-01],
[  9.00000000e+00,   6.32092768e-01],
[  1.00000000e+01,   6.16261724e-01],
[  1.10000000e+01,   6.00443307e-01],
[  1.20000000e+01,   5.68620130e-01],
[  1.30000000e+01,   5.65396825e-01],
[  1.40000000e+01,   5.03704545e-01],
[  1.50000000e+01,   5.00259740e-01],
[  1.60000000e+01,   4.17658730e-01],
[  1.70000000e+01,   4.05702381e-01],
[  1.80000000e+01,   3.49523810e-01],
[  1.90000000e+01,   3.37893218e-01],
[  2.00000000e+01,   3.11447670e-01],
[  2.10000000e+01,   2.43791209e-01],
[  2.20000000e+01,   2.13593074e-01],
[  2.30000000e+01,   1.64444444e-01],
[  2.40000000e+01,   1.21648352e-01],
[  2.50000000e+01,   1.05714286e-01],
[  2.60000000e+01,   6.57142857e-02],
[  2.70000000e+01,   5.15873016e-02],
[  2.80000000e+01,   3.28571429e-02],
[  2.90000000e+01,   1.57142857e-02],
[  3.00000000e+01,   8.57142857e-03],
[  3.10000000e+01,   1.00000000e-02],
[  3.20000000e+01,   2.85714286e-03],
[  3.30000000e+01,   1.42857143e-03],
[  3.40000000e+01,   1.42857143e-03],
[  3.50000000e+01,   9.09090909e-04],
[  3.60000000e+01,   0.00000000e+00],
[  3.70000000e+01,   0.00000000e+00],
[  3.80000000e+01,   0.00000000e+00],
[  3.90000000e+01,   0.00000000e+00]])

Kk15 = np.array([[  0.00000000e+00,   4.44000000e-01],
[  1.00000000e+00,   6.66666667e-02],
[  2.00000000e+00,   3.95333333e-01],
[  3.00000000e+00,   3.64666667e-01],
[  4.00000000e+00,   3.33333333e-01],
[  5.00000000e+00,   3.16000000e-01],
[  6.00000000e+00,   3.03333333e-01],
[  7.00000000e+00,   2.84666667e-01],
[  8.00000000e+00,   2.65333333e-01],
[  9.00000000e+00,   2.49333333e-01],
[  1.00000000e+01,   2.24000000e-01],
[  1.10000000e+01,   2.06666667e-01],
[  1.20000000e+01,   2.16666667e-01],
[  1.30000000e+01,   2.00000000e-01],
[  1.40000000e+01,   1.76666667e-01],
[  1.50000000e+01,   1.66000000e-01],
[  1.60000000e+01,   1.34666667e-01],
[  1.70000000e+01,   1.24000000e-01],
[  1.80000000e+01,   1.00000000e-01],
[  1.90000000e+01,   8.40000000e-02],
[  2.00000000e+01,   7.73333333e-02],
[  2.10000000e+01,   5.53333333e-02],
[  2.20000000e+01,   4.93333333e-02],
[  2.30000000e+01,   4.26666667e-02],
[  2.40000000e+01,   2.73333333e-02],
[  2.50000000e+01,   2.20000000e-02],
[  2.60000000e+01,   1.80000000e-02],
[  2.70000000e+01,   1.73333333e-02],
[  2.80000000e+01,   8.00000000e-03],
[  2.90000000e+01,   6.66666667e-03],
[  3.00000000e+01,   1.33333333e-03],
[  3.10000000e+01,   6.66666667e-04],
[  3.20000000e+01,   6.66666667e-04],
[  3.30000000e+01,   6.66666667e-04],
[  3.40000000e+01,   0.00000000e+00],
[  3.50000000e+01,   0.00000000e+00],
[  3.60000000e+01,   0.00000000e+00],
[  3.70000000e+01,   0.00000000e+00],
[  3.80000000e+01,   0.00000000e+00],
[  3.90000000e+01,   0.00000000e+00]])

``````
``````

In [5]:

fig = plt.figure()

ax1.scatter(Ek15[:,0], Ek15[:,1], s=35, c='b', marker="o", label='Cubic-interactions \$p=16,\;k=15\$')
ax1.scatter(Ek7[:,0], Ek7[:,1], s=35, c='g', marker="o", label='Cubic-interactions \$p=16,\;k=7\$')

ax1.scatter(Kk15[:,0], Kk15[:,1], s=35, c='lightblue', marker="o", label='Kanter-Sompolinsky \$p=16,\;k=15\$')
ax1.scatter(Kk7[:,0], Kk7[:,1], s=35, c='lightgreen', marker="o", label='Kanter-Sompolinsky \$p=16,\;k=7\$')

plt.xlabel('core size, \$c\$',fontdict={'fontsize':20})
plt.ylabel('sequence retrieval score',fontdict={'fontsize':20})
plt.axis([0, 50, 0, 1])

plt.legend(loc='upper right');
plt.show()

``````
``````

var element = \$('#45264405-512f-4199-a281-61cd4f6407f5');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

``````

Analyze kinetic+energetic simulations, sequence length

``````

In [1]:

# General libraries
import os
import pickle
import numpy as np

# Plot, in nb, only when .show() is called
import matplotlib.pyplot as plt
%matplotlib notebook
plt.ioff()

# Personal libraries
import tools.evaluation as ev
import tools.plot as pt

``````
``````

In [ ]:

path = '/home/sartori/Data/memexp_sequence_length/En_p16_c20'
# path = '/Users/pablo/Data/memexp'
dir_list = [ path + '/' + x for x in os.listdir(path) if x[0:8]=='EnSeqLen']
dir_list.sort()

``````
``````

In [ ]:

data = {}
for d in dir_list:
# Create the key to store data
p = 20
k = int(d.split("_")[5][1:])
key = (k, p)
# Store the data
data.setdefault(key,[]).append(overlaps)
print d

``````
``````

In [ ]:

with open(path+'/data.npy', 'wb') as f: np.save(f, data)

``````
``````

In [ ]:

xyz = []
for key in data.iterkeys():
k = key[0]
p = key[1]
wowo = ev.my_score((k, p), data[key], cutoff = 0.75, time_retrieved = 15)
xyz.append( (key[1], key[0], wowo) )

XYZ = np.asarray(xyz)
XY = XYZ[:,1:]
XY[np.argsort(XY[:,0]),:]

``````
``````

In [12]:

Kp16c0 = np.array([[  1.        ,   1.        ],
[  2.        ,   0.98666667],
[  3.        ,   0.971     ],
[  4.        ,   0.971     ],
[  5.        ,   0.91410281],
[  6.        ,   0.88489569],
[  7.        ,   0.83180519],
[  8.        ,   0.7965348 ],
[  9.        ,   0.71244444],
[ 10.        ,   0.66614286],
[ 11.        ,   0.57727273],
[ 12.        ,   0.56262821],
[ 13.        ,   0.50923077],
[ 14.        ,   0.47285714],
[ 15.        ,   0.41466667],
[ 16.        ,   0.39125   ],
[ 17.        ,   0.37529412],
[ 18.        ,   0.32166667]])

En16c0 = np.array([[  1.        ,   0.985     ],
[  2.        ,   0.715     ],
[  3.        ,   0.58416667],
[  4.        ,   0.4605    ],
[  5.        ,   0.38833333],
[  6.        ,   0.3052381 ],
[  7.        ,   0.28285714],
[  8.        ,   0.2825    ],
[  9.        ,   0.22666667],
[ 10.        ,   0.216     ],
[ 11.        ,   0.18916667],
[ 12.        ,   0.1725    ],
[ 13.        ,   0.19538462],
[ 14.        ,   0.13428571],
[ 15.        ,   0.13466667],
[ 16.        ,   0.115     ],
[ 17.        ,   0.10764706],
[ 18.        ,   0.10722222]])

Kp16c20 = np.array([[  1.        ,   0.91688095],
[  2.        ,   0.81619048],
[  3.        ,   0.7350487 ],
[  4.        ,   0.56019391],
[  5.        ,   0.48214835],
[  6.        ,   0.32807113],
[  7.        ,   0.2952381 ],
[  8.        ,   0.26375   ],
[  9.        ,   0.21444444],
[ 10.        ,   0.157     ],
[ 11.        ,   0.13181818],
[ 12.        ,   0.105     ],
[ 13.        ,   0.08923077],
[ 14.        ,   0.07071429]])

En16c20 = np.array([[  1.        ,   0.91      ],
[  2.        ,   0.77      ],
[  3.        ,   0.81316667],
[  4.        ,   0.7385    ],
[  5.        ,   0.72269841],
[  6.        ,   0.68404762],
[  7.        ,   0.64701984],
[  8.        ,   0.55072222],
[  9.        ,   0.51480808],
[ 10.        ,   0.56598485],
[ 11.        ,   0.57325758],
[ 12.        ,   0.44965201],
[ 13.        ,   0.41461538],
[ 14.        ,   0.46438095]])

``````
``````

In [18]:

fig = plt.figure()

ax1.scatter(Kp16c0[:,0], Kp16c0[:,1], s=35, c='b', marker="o", label='Kanter-Sampolinsky \$p=20,\;c=0\$')
ax1.scatter(Kp16c20[:,0], Kp16c20[:,1], s=35, c='lightblue', marker="o", label='Kanter-Sampolinsky \$p=16,\;c=20\$')

ax1.scatter(En16c0[:,0], En16c0[:,1], s=35, c='g', marker="o", label='Cubic-interactions \$p=20,\;c=0\$')
ax1.scatter(En16c20[:,0], En16c20[:,1], s=35, c='lightgreen', marker="o", label='Cubic-interactions \$p=16,\;c=20\$')

plt.xlabel('sequence length, \$k\$',fontdict={'fontsize':20})
plt.ylabel('sequence retrieval score',fontdict={'fontsize':20})
plt.axis([0, 20, 0, 1])

plt.legend(loc='upper right');
plt.show()

``````
``````

var element = \$('#d298564f-84d0-4425-9b07-0c7ba8eec3da');
/* Put everything inside the global mpl namespace */
window.mpl = {};

mpl.get_websocket_type = function() {
if (typeof(WebSocket) !== 'undefined') {
return WebSocket;
} else if (typeof(MozWebSocket) !== 'undefined') {
return MozWebSocket;
} else {
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.');
};
}

this.id = figure_id;

this.ws = websocket;

this.supports_binary = (this.ws.binaryType != undefined);

if (!this.supports_binary) {
var warnings = document.getElementById("mpl-warnings");
if (warnings) {
warnings.style.display = 'block';
warnings.textContent = (
"This browser does not support binary websocket messages. " +
"Performance may be slow.");
}
}

this.imageObj = new Image();

this.context = undefined;
this.message = undefined;
this.canvas = undefined;
this.rubberband_canvas = undefined;
this.rubberband_context = undefined;
this.format_dropdown = undefined;

this.image_mode = 'full';

this.root = \$('<div/>');
this._root_extra_style(this.root)
this.root.attr('style', 'display: inline-block');

\$(parent_element).append(this.root);

this._init_canvas(this);
this._init_toolbar(this);

var fig = this;

this.waiting = false;

this.ws.onopen =  function () {
fig.send_message("supports_binary", {value: fig.supports_binary});
fig.send_message("send_image_mode", {});
fig.send_message("refresh", {});
}

if (fig.image_mode == 'full') {
// Full images could contain transparency (where diff images
// almost always do), so we need to clear the canvas so that
// there is no ghosting.
fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
}
fig.context.drawImage(fig.imageObj, 0, 0);
};

this.ws.close();
}

this.ws.onmessage = this._make_on_message_function(this);

}

var titlebar = \$(
'<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ' +
'ui-helper-clearfix"/>');
var titletext = \$(
'<div class="ui-dialog-title" style="width: 100%; ' +
titlebar.append(titletext)
this.root.append(titlebar);
}

mpl.figure.prototype._canvas_extra_style = function(canvas_div) {

}

mpl.figure.prototype._root_extra_style = function(canvas_div) {

}

mpl.figure.prototype._init_canvas = function() {
var fig = this;

var canvas_div = \$('<div/>');

canvas_div.attr('style', 'position: relative; clear: both; outline: 0');

function canvas_keyboard_event(event) {
return fig.key_event(event, event['data']);
}

canvas_div.keydown('key_press', canvas_keyboard_event);
canvas_div.keyup('key_release', canvas_keyboard_event);
this.canvas_div = canvas_div
this._canvas_extra_style(canvas_div)
this.root.append(canvas_div);

var canvas = \$('<canvas/>');
canvas.attr('style', "left: 0; top: 0; z-index: 0; outline: 0")

this.canvas = canvas[0];
this.context = canvas[0].getContext("2d");

var rubberband = \$('<canvas/>');
rubberband.attr('style', "position: absolute; left: 0; top: 0; z-index: 1;")

var pass_mouse_events = true;

canvas_div.resizable({
start: function(event, ui) {
pass_mouse_events = false;
},
resize: function(event, ui) {
fig.request_resize(ui.size.width, ui.size.height);
},
stop: function(event, ui) {
pass_mouse_events = true;
fig.request_resize(ui.size.width, ui.size.height);
},
});

function mouse_event_fn(event) {
if (pass_mouse_events)
return fig.mouse_event(event, event['data']);
}

rubberband.mousedown('button_press', mouse_event_fn);
rubberband.mouseup('button_release', mouse_event_fn);
// Throttle sequential mouse events to 1 every 20ms.
rubberband.mousemove('motion_notify', mouse_event_fn);

rubberband.mouseenter('figure_enter', mouse_event_fn);
rubberband.mouseleave('figure_leave', mouse_event_fn);

canvas_div.on("wheel", function (event) {
event = event.originalEvent;
event['data'] = 'scroll'
if (event.deltaY < 0) {
event.step = 1;
} else {
event.step = -1;
}
mouse_event_fn(event);
});

canvas_div.append(canvas);
canvas_div.append(rubberband);

this.rubberband = rubberband;
this.rubberband_canvas = rubberband[0];
this.rubberband_context = rubberband[0].getContext("2d");
this.rubberband_context.strokeStyle = "#000000";

this._resize_canvas = function(width, height) {
// Keep the size of the canvas, canvas container, and rubber band
// canvas in synch.
canvas_div.css('width', width)
canvas_div.css('height', height)

canvas.attr('width', width);
canvas.attr('height', height);

rubberband.attr('width', width);
rubberband.attr('height', height);
}

// Set the figure to an initial 600x600px, this will subsequently be updated
// upon first draw.
this._resize_canvas(600, 600);

// Disable right mouse context menu.
return false;
});

function set_focus () {
canvas.focus();
canvas_div.focus();
}

window.setTimeout(set_focus, 100);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items) {
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) {
// put a spacer in here.
continue;
}
var button = \$('<button/>');
button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +
'ui-button-icon-only');
button.attr('role', 'button');
button.attr('aria-disabled', 'false');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);

var icon_img = \$('<span/>');

var tooltip_span = \$('<span/>');
tooltip_span.html(tooltip);

button.append(icon_img);
button.append(tooltip_span);

nav_element.append(button);
}

var fmt_picker_span = \$('<span/>');

var fmt_picker = \$('<select/>');
fmt_picker_span.append(fmt_picker);
nav_element.append(fmt_picker_span);
this.format_dropdown = fmt_picker[0];

for (var ind in mpl.extensions) {
var fmt = mpl.extensions[ind];
var option = \$(
'<option/>', {selected: fmt === mpl.default_extension}).html(fmt);
fmt_picker.append(option)
}

// Add hover states to the ui-buttons
\$( ".ui-button" ).hover(
function() { \$(this).removeClass("ui-state-hover");}
);

var status_bar = \$('<span class="mpl-message"/>');
nav_element.append(status_bar);
this.message = status_bar[0];
}

mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {
// Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
// which will in turn request a refresh of the image.
this.send_message('resize', {'width': x_pixels, 'height': y_pixels});
}

mpl.figure.prototype.send_message = function(type, properties) {
properties['type'] = type;
properties['figure_id'] = this.id;
this.ws.send(JSON.stringify(properties));
}

mpl.figure.prototype.send_draw_message = function() {
if (!this.waiting) {
this.waiting = true;
this.ws.send(JSON.stringify({type: "draw", figure_id: this.id}));
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
var format_dropdown = fig.format_dropdown;
var format = format_dropdown.options[format_dropdown.selectedIndex].value;
}

mpl.figure.prototype.handle_resize = function(fig, msg) {
var size = msg['size'];
if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {
fig._resize_canvas(size[0], size[1]);
fig.send_message("refresh", {});
};
}

mpl.figure.prototype.handle_rubberband = function(fig, msg) {
var x0 = msg['x0'];
var y0 = fig.canvas.height - msg['y0'];
var x1 = msg['x1'];
var y1 = fig.canvas.height - msg['y1'];
x0 = Math.floor(x0) + 0.5;
y0 = Math.floor(y0) + 0.5;
x1 = Math.floor(x1) + 0.5;
y1 = Math.floor(y1) + 0.5;
var min_x = Math.min(x0, x1);
var min_y = Math.min(y0, y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);

fig.rubberband_context.clearRect(
0, 0, fig.canvas.width, fig.canvas.height);

fig.rubberband_context.strokeRect(min_x, min_y, width, height);
}

mpl.figure.prototype.handle_figure_label = function(fig, msg) {
}

mpl.figure.prototype.handle_cursor = function(fig, msg) {
var cursor = msg['cursor'];
switch(cursor)
{
case 0:
cursor = 'pointer';
break;
case 1:
cursor = 'default';
break;
case 2:
cursor = 'crosshair';
break;
case 3:
cursor = 'move';
break;
}
fig.rubberband_canvas.style.cursor = cursor;
}

mpl.figure.prototype.handle_message = function(fig, msg) {
fig.message.textContent = msg['message'];
}

mpl.figure.prototype.handle_draw = function(fig, msg) {
// Request the server to send over a new figure.
fig.send_draw_message();
}

mpl.figure.prototype.handle_image_mode = function(fig, msg) {
fig.image_mode = msg['mode'];
}

mpl.figure.prototype.updated_canvas_event = function() {
// Called whenever the canvas gets updated.
this.send_message("ack", {});
}

// A function to construct a web socket function for onmessage handling.
// Called in the figure constructor.
mpl.figure.prototype._make_on_message_function = function(fig) {
return function socket_on_message(evt) {
if (evt.data instanceof Blob) {
/* FIXME: We get "Resource interpreted as Image but
* transferred with MIME type text/plain:" errors on
* Chrome.  But how to set the MIME type?  It doesn't seem
* to be part of the websocket stream */
evt.data.type = "image/png";

/* Free the memory for the previous frames */
if (fig.imageObj.src) {
(window.URL || window.webkitURL).revokeObjectURL(
fig.imageObj.src);
}

fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
evt.data);
fig.updated_canvas_event();
fig.waiting = false;
return;
}
else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == "data:image/png;base64") {
fig.imageObj.src = evt.data;
fig.updated_canvas_event();
fig.waiting = false;
return;
}

var msg = JSON.parse(evt.data);
var msg_type = msg['type'];

// Call the  "handle_{type}" callback, which takes
// the figure and JSON message as its only arguments.
try {
var callback = fig["handle_" + msg_type];
} catch (e) {
console.log("No handler for the '" + msg_type + "' message type: ", msg);
return;
}

if (callback) {
try {
// console.log("Handling '" + msg_type + "' message: ", msg);
callback(fig, msg);
} catch (e) {
console.log("Exception inside the 'handler_" + msg_type + "' callback:", e, e.stack, msg);
}
}
};
}

// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas
mpl.findpos = function(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - \$(targ).offset().left;
var y = e.pageY - \$(targ).offset().top;

return {"x": x, "y": y};
};

/*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
* http://stackoverflow.com/a/24161582/3208463
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
if (typeof original[key] !== 'object')
obj[key] = original[key]
return obj;
}, {});
}

mpl.figure.prototype.mouse_event = function(event, name) {
var canvas_pos = mpl.findpos(event)

if (name === 'button_press')
{
this.canvas.focus();
this.canvas_div.focus();
}

var x = canvas_pos.x;
var y = canvas_pos.y;

this.send_message(name, {x: x, y: y, button: event.button,
step: event.step,
guiEvent: simpleKeys(event)});

/* This prevents the web browser from automatically changing to
* the text insertion cursor when the button is pressed.  We want
* to control all of the cursor setting manually through the
* 'cursor' event from matplotlib */
event.preventDefault();
return false;
}

mpl.figure.prototype._key_event_extra = function(event, name) {
// Handle any extra behaviour associated with a key event
}

mpl.figure.prototype.key_event = function(event, name) {

// Prevent repeat events
if (name == 'key_press')
{
if (event.which === this._key)
return;
else
this._key = event.which;
}
if (name == 'key_release')
this._key = null;

var value = '';
if (event.ctrlKey && event.which != 17)
value += "ctrl+";
if (event.altKey && event.which != 18)
value += "alt+";
if (event.shiftKey && event.which != 16)
value += "shift+";

value += 'k';
value += event.which.toString();

this._key_event_extra(event, name);

this.send_message(name, {key: value,
guiEvent: simpleKeys(event)});
return false;
}

mpl.figure.prototype.toolbar_button_onclick = function(name) {
this.handle_save(this, null);
} else {
this.send_message("toolbar_button", {name: name});
}
};

mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {
this.message.textContent = tooltip;
};
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"]];

mpl.extensions = ["eps", "jpeg", "pdf", "png", "ps", "raw", "svg", "tif"];

mpl.default_extension = "png";var comm_websocket_adapter = function(comm) {
// Create a "websocket"-like object which calls the given IPython comm
// object with the appropriate methods. Currently this is a non binary
// socket, so there is still some room for performance tuning.
var ws = {};

ws.close = function() {
comm.close()
};
ws.send = function(m) {
//console.log('sending', m);
comm.send(m);
};
// Register the callback with on_msg.
comm.on_msg(function(msg) {
//console.log('receiving', msg['content']['data'], msg);
// Pass the mpl event to the overriden (by mpl) onmessage function.
ws.onmessage(msg['content']['data'])
});
return ws;
}

mpl.mpl_figure_comm = function(comm, msg) {
// This is the function which gets called when the mpl process
// starts-up an IPython Comm through the "matplotlib" channel.

var id = msg.content.data.id;
// Get hold of the div created by the display call when the Comm
// socket was opened in Python.
var element = \$("#" + id);

window.open(figure.imageObj.src);
}

var fig = new mpl.figure(id, ws_proxy,
element.get(0));

// Call onopen now - mpl needs it, as it is assuming we've passed it a real
// web socket which is closed, not our websocket->open comm proxy.
ws_proxy.onopen();

fig.parent_element = element.get(0);
fig.cell_info = mpl.find_output_cell("<div id='" + id + "'></div>");
if (!fig.cell_info) {
console.error("Failed to find cell for figure", id, fig);
return;
}

var output_index = fig.cell_info[2]
var cell = fig.cell_info[0];

};

mpl.figure.prototype.handle_close = function(fig, msg) {
fig.root.unbind('remove')

// Update the output cell to use the data from the current canvas.
fig.push_to_output();
var dataURL = fig.canvas.toDataURL();
// Re-enable the keyboard manager in IPython - without this line, in FF,
// the notebook keyboard shortcuts fail.
IPython.keyboard_manager.enable()
\$(fig.parent_element).html('<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">');
fig.close_ws(fig, msg);
}

mpl.figure.prototype.close_ws = function(fig, msg){
fig.send_message('closing', msg);
// fig.ws.close()
}

mpl.figure.prototype.push_to_output = function(remove_interactive) {
// Turn the data on the canvas into data in the output cell.
var dataURL = this.canvas.toDataURL();
this.cell_info[1]['text/html'] = '<amp-img layout="responsive" width="500" height="300" src="' + dataURL + '">';
}

mpl.figure.prototype.updated_canvas_event = function() {
// Tell IPython that the notebook contents must change.
IPython.notebook.set_dirty(true);
this.send_message("ack", {});
var fig = this;
// Wait a second, then push the new image to the DOM so
// that it is saved nicely (might be nice to debounce this).
setTimeout(function () { fig.push_to_output() }, 1000);
}

mpl.figure.prototype._init_toolbar = function() {
var fig = this;

var nav_element = \$('<div/>')
nav_element.attr('style', 'width: 100%');
this.root.append(nav_element);

// Define a callback function for later on.
function toolbar_event(event) {
return fig.toolbar_button_onclick(event['data']);
}
function toolbar_mouse_event(event) {
return fig.toolbar_button_onmouseover(event['data']);
}

for(var toolbar_ind in mpl.toolbar_items){
var name = mpl.toolbar_items[toolbar_ind][0];
var tooltip = mpl.toolbar_items[toolbar_ind][1];
var image = mpl.toolbar_items[toolbar_ind][2];
var method_name = mpl.toolbar_items[toolbar_ind][3];

if (!name) { continue; };

var button = \$('<button class="btn btn-default" href="#" title="' + name + '"><i class="fa ' + image + ' fa-lg"></i></button>');
button.click(method_name, toolbar_event);
button.mouseover(tooltip, toolbar_mouse_event);
nav_element.append(button);
}

var status_bar = \$('<span class="mpl-message" style="text-align:right; float: right;"/>');
nav_element.append(status_bar);
this.message = status_bar[0];

// Add the close button to the window.
var buttongrp = \$('<div class="btn-group inline pull-right"></div>');
var button = \$('<button class="btn btn-mini btn-primary" href="#" title="Stop Interaction"><i class="fa fa-power-off icon-remove icon-large"></i></button>');
button.click(function (evt) { fig.handle_close(fig, {}); } );
button.mouseover('Stop Interaction', toolbar_mouse_event);
buttongrp.append(button);
var titlebar = this.root.find(\$('.ui-dialog-titlebar'));
titlebar.prepend(buttongrp);
}

mpl.figure.prototype._root_extra_style = function(el){
var fig = this
el.on("remove", function(){
fig.close_ws(fig, {});
});
}

mpl.figure.prototype._canvas_extra_style = function(el){
// this is important to make the div 'focusable
el.attr('tabindex', 0)
// reach out to IPython and tell the keyboard manager to turn it's self
// off when our div gets focus

// location in version 3
if (IPython.notebook.keyboard_manager) {
IPython.notebook.keyboard_manager.register_events(el);
}
else {
// location in version 2
IPython.keyboard_manager.register_events(el);
}

}

mpl.figure.prototype._key_event_extra = function(event, name) {
var manager = IPython.notebook.keyboard_manager;
if (!manager)
manager = IPython.keyboard_manager;

// Check for shift+enter
if (event.shiftKey && event.which == 13) {
this.canvas_div.blur();
// select the cell after this one
var index = IPython.notebook.find_cell_index(this.cell_info[0]);
IPython.notebook.select(index + 1);
}
}

mpl.figure.prototype.handle_save = function(fig, msg) {
}

mpl.find_output_cell = function(html_output) {
// Return the cell and output element which can be found *uniquely* in the notebook.
// Note - this is a bit hacky, but it is done because the "notebook_saving.Notebook"
// IPython event is triggered only after the cells have been serialised, which for
// our purposes (turning an active figure into a static one), is too late.
var cells = IPython.notebook.get_cells();
var ncells = cells.length;
for (var i=0; i<ncells; i++) {
var cell = cells[i];
if (cell.cell_type === 'code'){
for (var j=0; j<cell.output_area.outputs.length; j++) {
var data = cell.output_area.outputs[j];
if (data.data) {
// IPython >= 3 moved mimebundle to data attribute of output
data = data.data;
}
if (data['text/html'] == html_output) {
return [cell, data, j];
}
}
}
}
}

// Register the function which deals with the matplotlib target/channel.
// The kernel may be null if the page has been refreshed.
if (IPython.notebook.kernel != null) {
IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);
}

``````
``````

In [ ]:

``````