Commit c7baea82 authored by Theresa Pollinger's avatar Theresa Pollinger
Browse files

playing around with html and matplotlib contents

parent 3473cb6f
#!/usr/bin/env python3
import sys
from ipykernel.kernelbase import Kernel
from ipykernel.comm import CommManager
from metakernel import MetaKernel from metakernel import MetaKernel
from IPython.display import HTML, Javascript
from metakernel import IPythonKernel
# #
# for directly converting Latex commands to unicode # for directly converting Latex commands to unicode
from pylatexenc.latex2text import LatexNodes2Text from pylatexenc.latex2text import LatexNodes2Text
import getpass import getpass
from pde_state_machine import * from pde_state_machine import *
import matplotlib.pyplot as plt
...@@ -47,11 +43,13 @@ class Interview(MetaKernel): ...@@ -47,11 +43,13 @@ class Interview(MetaKernel):
# call superclass constructor # call superclass constructor
super(Interview, self).__init__(**kwargs) super(Interview, self).__init__(**kwargs)
# cf.
# self.comm_manager = CommManager(parent=self, kernel=self)
from IPython import get_ipython self.do_execute("%matplotlib nbagg")
from metakernel import register_ipython_magics plt.ion()
# To make custom magics happen, cf.
# from IPython import get_ipython
# from metakernel import register_ipython_magics
# register_ipython_magics() # register_ipython_magics()
self.update_prompt() self.update_prompt()
...@@ -68,6 +66,7 @@ class Interview(MetaKernel): ...@@ -68,6 +66,7 @@ class Interview(MetaKernel):
# allow_stdin=False): # allow_stdin=False):
def do_execute_direct(self, code, silent=False): def do_execute_direct(self, code, silent=False):
"""This is where the user input enters our code""" """This is where the user input enters our code"""
arg = LatexNodes2Text().latex_to_text(code) arg = LatexNodes2Text().latex_to_text(code)
if not self.keyword_handling(arg): if not self.keyword_handling(arg):
...@@ -132,6 +131,12 @@ class Interview(MetaKernel): ...@@ -132,6 +131,12 @@ class Interview(MetaKernel):
if arg.startswith("recap"): if arg.startswith("recap"):
self.state_machine.recap(arg) self.state_machine.recap(arg)
return True return True
if arg.startswith("html"):
return True
if arg.startswith("plt"):
return True
return False return False
# called when user types 'explain [expression]' # called when user types 'explain [expression]'
...@@ -151,7 +156,7 @@ class Interview(MetaKernel): ...@@ -151,7 +156,7 @@ class Interview(MetaKernel):
# called when user types 'undo' # called when user types 'undo'
def do_undo(self, expression): def do_undo(self, expression):
"Go back to the last question" "Go back to the last question"
self.trigger('last_state') self.state_machine.trigger('last_state')
def help_undo(self): def help_undo(self):
self.poutput('\n'.join(['undo', self.poutput('\n'.join(['undo',
...@@ -161,6 +166,11 @@ class Interview(MetaKernel): ...@@ -161,6 +166,11 @@ class Interview(MetaKernel):
def update_prompt(self): def update_prompt(self):
self.prompt = "(" + self.state_machine.state + ")" #TODO self.prompt = "(" + self.state_machine.state + ")" #TODO
def do_shutdown(self, restart):
return super(Interview, self).do_shutdown(restart)
# tab completion for empty lines # tab completion for empty lines
def completenames(self, text, line, begidx, endidx): def completenames(self, text, line, begidx, endidx):
"""Override of cmd2 method which completes command names both for command completion and help.""" """Override of cmd2 method which completes command names both for command completion and help."""
...@@ -188,6 +198,37 @@ class Interview(MetaKernel): ...@@ -188,6 +198,37 @@ class Interview(MetaKernel):
cmd_completion[0] += ' ' cmd_completion[0] += ' '
return cmd_completion return cmd_completion
def display_html(self):
<style type="text/css">
.styled-background { background-color: #ff7; }
if (typeof markedText !== 'undefined') {
var cell = IPython.notebook.get_selected_cell();
markedText = cell.code_mirror.markText({line: %s, col: %s},
{line: %s, col: %s},
{className: "styled-background"});
""" % (1, 0, 3, 0)))
othercode = """
### have tgview here
def display_plt(self):
# plt.ion()
# matplotlib.use('nbagg')
self.Display(plt.plot([3, 8, 2, 5, 1]))
# #TODO find out why there is no comm and interactive shell - and if it should be there
if __name__ == '__main__': if __name__ == '__main__':
# from ipykernel.kernelapp import IPKernelApp # from ipykernel.kernelapp import IPKernelApp
...@@ -796,64 +796,12 @@ class PDE_States: ...@@ -796,64 +796,12 @@ class PDE_States:
self.poutput("Generated ExaStencils input.") self.poutput("Generated ExaStencils input.")
# TODO generate and run simulation # TODO generate and run simulation
# display solution using matplotlib # display solution using matplotlib
# cf.
import matplotlib import matplotlib
matplotlib.use('nbagg') # matplotlib.use('nbagg')
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
#from ipykernel.core import InteractiveShell
plt.ion() plt.ion()
# gui, backend ="nbagg")
#except Exception as e:
# raise InterviewError("Unable to use matplotlib for display, sorry! \n" + e.args[0])
plt.plot([1, 2, 3]) plt.plot([1, 2, 3])
def enable_matplotlib(self, gui=None):
"""Enable interactive matplotlib and inline figure support.
stolen from .
This takes the following steps:
1. select the appropriate eventloop and matplotlib backend
2. set up matplotlib for interactive use with that backend
3. configure formatters for inline figure display
4. enable the selected gui eventloop
gui : optional, string
If given, dictates the choice of matplotlib GUI backend to use
(should be one of IPython's supported backends, 'qt', 'osx', 'tk',
'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
matplotlib (as dictated by the matplotlib build-time options plus the
user's matplotlibrc configuration file). Note that not all backends
make sense in all contexts, for example a terminal ipython can't
display figures inline.
from IPython.core import pylabtools as pt
gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
if gui != 'inline':
# If we have our first gui selection, store it
if self.pylab_gui_select is None:
self.pylab_gui_select = gui
# Otherwise if they are different
elif gui != self.pylab_gui_select:
print('Warning: Cannot change to a different GUI toolkit: %s.'
' Using %s instead.' % (gui, self.pylab_gui_select))
gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
pt.configure_inline_support(self, backend)
# Now we must activate the gui pylab wants to use, and fix %run to take
# plot updates into account
self.magics_manager.registry['ExecutionMagics'].default_runner = \
return gui, backend
def sim_ok_fd(self): def sim_ok_fd(self):
self.simdata["sim"]["type"] = "FiniteDifferences" self.simdata["sim"]["type"] = "FiniteDifferences"
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment