Exemple #1
0
 def _finish_request(self, kind):
     print '\n\n' + '=' * 80
     print 'New %s request' % kind
     print '=' * 80 + '\n'
     data_id = int(self.request.uri.strip('/DataFrame'))
     print 'get data for data id %d' % data_id
     data = get_data(data_id)
     if kind == 'get':
         print 'create figure for "get" request with args:'
         fig = create_figure(data, None, ['A'], [])
     elif kind == 'post':
         args = self.request.arguments
         print 'create figure for "post" request with args:'
         print args
         x = args.get('x', None)
         left_y = args.get('left_y', [])
         right_y = args.get('right_y', [])
         fig = create_figure(data, x, left_y, right_y)
         print id(fig)
     else:
         raise TypeError('kind must be "get" or "post"')
     fignum = id(fig)
     manager = new_figure_manager_given_figure(fignum, fig)
     self.application.figures[fignum] = (fig, manager)
     print 'created figure %d and %s' % (fignum, repr(manager))
     ws_uri = "ws://{req.host}/".format(req=self.request)
     y_cols = list(data.columns)
     x_cols = y_cols[:]
     x_cols.insert(0, 'index')
     self.render('plot.html', ws_uri=ws_uri, fig_id=manager.num,
                 y_cols=y_cols, x_cols=x_cols)
    def __init__(self, figure):
        self.figure = figure
        self.manager = new_figure_manager_given_figure(id(figure), figure)

        super().__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)', tornado.web.StaticFileHandler, {
                'path': FigureManagerWebAgg.get_static_file_path()
            }),

            # Static images for the toolbar
            (r'/_images/(.*)', tornado.web.StaticFileHandler, {
                'path': Path(mpl.get_data_path(), 'images')
            }),

            # The page that contains all of the pieces
            ('/', self.MainPage),
            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ])
Exemple #3
0
    def _get_or_create_figure_manager(self) -> Optional[FigureManagerWebAgg]:
        workspace = self.workspace
        figure_id = self.figure_id

        figure = workspace.resource_cache.get_value_by_id(figure_id)
        if isinstance(figure, Figure):
            figure_managers = workspace.user_data.get('figure_managers')
            figure_manager = figure_managers and figure_managers.get(figure_id)
            if figure_manager:
                if figure_manager.canvas.figure is figure:
                    # we have a figure_manager and it already manages our figure
                    return figure_manager
                # forget this manager, we have a new figure
                figure_manager.remove_web_socket(self)
            # create a new figure_manager for our figure
            figure_manager = new_figure_manager_given_figure(figure_id, figure)
            figure_manager.add_web_socket(self)
            if not figure_managers:
                # store a new mapping of figure_id to figure_manager
                figure_managers = dict()
                workspace.user_data['figure_managers'] = figure_managers
            # register our figure_manager
            figure_managers[figure_id] = figure_manager
            return figure_manager
        return None
Exemple #4
0
    def __init__(self, stop_callback=None):
        super(MyApplication, self).__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)', tornado.web.StaticFileHandler, {
                'path': FigureManagerWebAgg.get_static_file_path()
            }),

            # The page that contains all of the pieces
            ('/', self.MainPage),
            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ])

        figure = Figure()

        self.manager = new_figure_manager_given_figure(id(figure), figure)

        ax = figure.add_subplot(1, 1, 1)

        def callback(event):
            '''Sends event to front end'''
            event.info.pop(
                'caller',
                None)  # HACK: popping caller b/c it's not JSONizable.
            self.manager._send_event(event.type, **event.info)

        self.fc_manager = fc_widget.FCGateManager(ax, callback_list=callback)
        self.stop_callback = stop_callback
Exemple #5
0
    def _get_or_create_figure_manager(self) -> Optional[FigureManagerWebAgg]:
        workspace = self.workspace
        figure_id = self.figure_id

        figure = workspace.resource_cache.get_value_by_id(figure_id)
        if isinstance(figure, Figure):
            figure_managers = workspace.user_data.get('figure_managers')
            figure_manager = figure_managers and figure_managers.get(figure_id)
            if figure_manager:
                if figure_manager.canvas.figure is figure:
                    # we have a figure_manager and it already manages our figure
                    return figure_manager
                # forget this manager, we have a new figure
                figure_manager.remove_web_socket(self)
            # create a new figure_manager for our figure
            figure_manager = new_figure_manager_given_figure(figure_id, figure)
            figure_manager.add_web_socket(self)
            if not figure_managers:
                # store a new mapping of figure_id to figure_manager
                figure_managers = dict()
                workspace.user_data['figure_managers'] = figure_managers
            # register our figure_manager
            figure_managers[figure_id] = figure_manager
            return figure_manager
        return None
Exemple #6
0
    def __init__(self, stop_callback=None):
        super(MyApplication, self).__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)',
             tornado.web.StaticFileHandler,
             {'path': FigureManagerWebAgg.get_static_file_path()}),

            # The page that contains all of the pieces
            ('/', self.MainPage),

            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ])

        figure = Figure()

        self.manager = new_figure_manager_given_figure(
            id(figure), figure)

        ax = figure.add_subplot(1, 1, 1)

        def callback(event):
            '''Sends event to front end'''
            event.info.pop('caller', None)  # HACK: popping caller b/c it's not JSONizable.
            self.manager._send_event(event.type, **event.info)

        self.fc_manager = fc_widget.FCGateManager(ax, callback_list=callback)
        self.stop_callback = stop_callback
Exemple #7
0
 def register_new_figure(self, size):
   fig = Figure(figsize=size, facecolor='none', edgecolor='none',
                frameon=False, tight_layout=True, dpi=80)
   fignum = id(fig)
   manager = new_figure_manager_given_figure(fignum, fig)
   self.figure_data[fignum] = FigData(fig, manager)
   return fignum
Exemple #8
0
    def add_figure(self, key, figure=None, *args, **kwargs):
        if figure is None:
            figure = Figure(*args, **kwargs)

        self._figures[key] = figure
        self._managers[key] = new_figure_manager_given_figure(
            id(figure), figure)

        if len(figure.axes) == 0:
            # at least 1 axis per figure
            figure.add_subplot(111)
Exemple #9
0
  def post(self):
    #Gets the userid for the user running the program

    uid = self.get_argument('uid')
    # collect arguments for this section - Changes based on section
    # Each section has a hidden variable in ui.html that holdds the value to be passed in the section variable
    # When the submit button is clicked - the input tags in html are sent to the server
    # These values can be received in python using the below line.
    section = self.get_argument('section')
    state = self.application.prog_states[uid]
    
    kwargs = self._collect_kwargs(ignored_keys=('uid', 'section'))
    if 'lcp' in kwargs:
        cpfile = kwargs.pop('lcp', None)
        if cpfile:
            #Load state from checkpoint and not from the current uid and replace the prog state.
            state = pickle.load(cpfile)
            if state:
                self.application.prog_states[uid] = state

        # run the section method    
    logging.info('Running %s: %r', section, kwargs)
    try:
      #Calling each function at run time
      message, dl_param, figures = getattr(state, section)(**kwargs)
    except EnvironmentError as e:
      logging.exception('Section %s failed.', section)
      self.set_status(400)
      self.write(e.strerror)
      return
    except Exception as e:
      logging.exception('Section %s failed.', section)
      self.set_status(400)
      self.write(e.message)
      return
    # start returning html to the frontend
    self.write('<div>')
    self.write('<input type="hidden" id="uid_val" value="%s" />' % uid);
    if message:
      self.write(message)
    if dl_param:
      self.write('<a href="/?dl=1&uid=%s&p=%s" target="_blank">Download</a>' %
                 (uid, dl_param))
      self.write('<a href="/?cp=1&uid=%s" target="_blank">Download Checkpoint</a>' %
                 (uid))
    self.write('</div>')
    # initialize the figure managers
    fig_managers = self.application.fig_managers
    for fig in figures:
      # take care to prevent a fignum of zero, which is special to us
      fignum = id(fig) * 10 + 1
      fig_managers[str(fignum)] = new_figure_manager_given_figure(fignum, fig)
      self.write('<div id="fig%s" class="figure"></div>' % fignum)
Exemple #10
0
    def __init__(self, figure):
        self.figure = figure
        self.manager = new_figure_manager_given_figure(id(figure), figure)

        handlers = [(r'/_static/(.*)', tornado.web.StaticFileHandler, {
            'path': FigureManagerWebAgg.get_static_file_path()
        }), (r"/sin", self.MainHandler), (r"/ws", self.SocketHandler),
                    (r'/download.([a-z0-9.]+)', self.Download),
                    ('/mpl.js', self.MplJs), (r'/lines', self.LinesHandler)]
        settings = dict(
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=False,
        )
        super(Application, self).__init__(handlers, **settings)
Exemple #11
0
    def refresh_figures(self, figures=None):
        if figures is None:
            self.figures = create_default_figures()
        else:
            self.figures = figures

        for k, f in self.figures.items():
            if k not in self.managers:
                fignum = id(f)
                self.managers[k] = new_figure_manager_given_figure(fignum, f)
                self.fig_id_map[fignum] = self.managers[k]
            else:
                canvas = FigureCanvasWebAggCore(f)
                self.managers[k].canvas = canvas
                self.managers[k].canvas.manager = self.managers[k]
                self.managers[k]._get_toolbar(canvas)
                self.managers[k]._send_event("refresh")
                self.managers[k].canvas.draw()
    def __init__(self, figure):
        self.figure = figure
        self.manager = new_figure_manager_given_figure(id(figure), figure)

        super().__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)',
             tornado.web.StaticFileHandler,
             {'path': FigureManagerWebAgg.get_static_file_path()}),

            # The page that contains all of the pieces
            ('/', self.MainPage),

            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ])
Exemple #13
0
 def __init__(self, figure):
     self.figure = figure
     self.manager = new_figure_manager_given_figure(id(figure), figure)
     self.comm = CommSocket(self.manager)
     self.comm.open()
Exemple #14
0

def create_figure():
    """
    Creates a simple example figure.
    """
    fig = Figure()
    a = fig.add_subplot(111)
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2 * np.pi * t)
    a.plot(t, s)
    return fig


figure = create_figure()
Manager = new_figure_manager_given_figure(id(figure), figure)


class WebSocket_App(WebSocketApplication):
    """
    A websocket for interactive communication between the plot in
    the browser and the server.
    In addition to the methods required by tornado, it is required to
    have two callback methods:
        - ``send_json(json_content)`` is called by matplotlib when
          it needs to send json to the browser.  `json_content` is
          a JSON tree (Python dictionary), and it is the responsibility
          of this implementation to encode it as a string to send over
          the socket.
        - ``send_binary(blob)`` is called to send binary image data
          to the browser.
Exemple #15
0
 def add_figure(self, fig):
     # take care to prevent a fignum of zero, which is special to us
     fignum = id(fig) * 10 + 1
     manager = new_figure_manager_given_figure(fignum, fig)
     self.fig_managers[str(fignum)] = manager
     return fignum
Exemple #16
0
 def __init__(self, figure):
     self.figure = figure
     self.manager = new_figure_manager_given_figure(id(figure), figure)
     self.comm = CommSocket(self.manager)
     self.comm.open()