Last active
October 29, 2015 22:48
-
-
Save rossant/5183de4c179cc750ce42 to your computer and use it in GitHub Desktop.
plot_kernel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from IPython.kernel.zmq.kernelbase import Kernel | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from io import BytesIO | |
import urllib, base64 | |
def _to_png(fig): | |
"""Return a base64-encoded PNG from a | |
matplotlib figure.""" | |
imgdata = BytesIO() | |
fig.savefig(imgdata, format='png') | |
imgdata.seek(0) | |
return urllib.parse.quote( | |
base64.b64encode(imgdata.getvalue())) | |
_numpy_namespace = {n: getattr(np, n) | |
for n in dir(np)} | |
def _parse_function(code): | |
"""Return a NumPy function from a string 'y=f(x)'.""" | |
return lambda x: eval(code.split('=')[1].strip(), | |
_numpy_namespace, {'x': x}) | |
class PlotKernel(Kernel): | |
implementation = 'Plot' | |
implementation_version = '1.0' | |
language = 'no-op' | |
language_version = '0.1' | |
banner = "Simple plotting" | |
def do_execute(self, code, silent, | |
store_history=True, | |
user_expressions=None, | |
allow_stdin=False): | |
if not silent: | |
fig = plt.figure(figsize=(6,4), dpi=100) | |
x = np.linspace(-5., 5., 200) | |
for line in code.split('\n'): | |
f = _parse_function(line) | |
y = f(x) | |
plt.plot(x, y) | |
plt.xlim(-5, 5) | |
png = _to_png(fig) | |
content = { | |
'source': 'kernel', | |
'data': { | |
'image/png': png, | |
'text/plain': str(len(png)) | |
}, | |
'metadata' : { | |
'image/png' : { | |
'width': 600, | |
'height': 400 | |
} | |
} | |
} | |
self.send_response(self.iopub_socket, | |
'stream', {'name': 'stdout', 'data': ''}) | |
self.send_response(self.iopub_socket, | |
'display_data', content) | |
return {'status': 'ok', | |
'execution_count': self.execution_count, | |
'payload': [], | |
'user_expressions': {}, | |
} | |
def do_complete(self, code, cursor_pos): | |
return {'status': 'ok', | |
'cursor_start': 0, | |
'cursor_end': 0, | |
'matches': []} | |
if __name__ == '__main__': | |
from IPython.kernel.zmq.kernelapp import IPKernelApp | |
IPKernelApp.launch_instance(kernel_class=PlotKernel) | |
# ipython notebook --KernelManager.kernel_cmd="['python','-m','echokernel', '-f', '{connection_file}']" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment