Exemple #1
0
    def modify_document(self, doc):
        '''

        '''
        if self.failed:
            return

        module = self._runner.new_module()

        # One reason modules are stored is to prevent the module
        # from being gc'd before the document is. A symptom of a
        # gc'd module is that its globals become None. Additionally
        # stored modules are used to provide correct paths to
        # custom models resolver.
        sys.modules[module.__name__] = module
        doc._modules.append(module)

        old_doc = curdoc()
        set_curdoc(doc)
        old_io = self._monkeypatch_io()

        try:
            def post_check():
                newdoc = curdoc()
                # script is supposed to edit the doc not replace it
                if newdoc is not doc:
                    raise RuntimeError("%s at '%s' replaced the output document" % (self._origin, self._runner.path))
            self._runner.run(module, post_check)
        finally:
            self._unmonkeypatch_io(old_io)
            set_curdoc(old_doc)
    def test__trigger_event_wraps_curdoc(self):
        # This test is pretty clunky by assures that callbacks triggered by
        # events use the correct value of curdoc()
        from bokeh.io.doc import set_curdoc
        from bokeh.io import curdoc
        oldcd = curdoc()
        d1 = Document()
        d2 = Document()
        set_curdoc(d1)
        out = {}
        def cb():
            out['curdoc'] = curdoc()
        m = cbm.EventCallbackManager()
        m.subscribed_events = []
        m.on_event('foo', cb)
        m.id = 10
        m._document = d2

        assert len(m._event_callbacks) == 1
        assert m._event_callbacks['foo'] == [cb]

        class ev(object):
            _model_id = 10
            event_name = "foo"

        m._trigger_event(ev())
        assert out['curdoc'] is d2

        set_curdoc(oldcd)
    def test__trigger_event_wraps_curdoc(self):
        # This test is pretty clunky by assures that callbacks triggered by
        # events use the correct value of curdoc()
        from bokeh.io.doc import set_curdoc
        from bokeh.io import curdoc
        oldcd = curdoc()
        d1 = Document()
        d2 = Document()
        set_curdoc(d1)
        out = {}
        def cb():
            out['curdoc'] = curdoc()
        m = cbm.EventCallbackManager()
        m.subscribed_events = []
        m.on_event('foo', cb)
        m.id = 10
        m._document = d2

        assert len(m._event_callbacks) == 1
        assert m._event_callbacks['foo'] == [cb]

        class ev(object):
            _model_id = 10
            event_name = "foo"

        m._trigger_event(ev())
        assert out['curdoc'] is d2

        set_curdoc(oldcd)
Exemple #4
0
    def modify_document(self, doc):
        '''

        '''
        if self.failed:
            return

        module = self._runner.new_module()

        # One reason modules are stored is to prevent the module
        # from being gc'd before the document is. A symptom of a
        # gc'd module is that its globals become None. Additionally
        # stored modules are used to provide correct paths to
        # custom models resolver.
        sys.modules[module.__name__] = module
        doc._modules.append(module)

        old_doc = curdoc()
        set_curdoc(doc)
        old_io = self._monkeypatch_io()

        try:

            def post_check():
                newdoc = curdoc()
                # script is supposed to edit the doc not replace it
                if newdoc is not doc:
                    raise RuntimeError(
                        "%s at '%s' replaced the output document" %
                        (self._origin, self._runner.path))

            self._runner.run(module, post_check)
        finally:
            self._unmonkeypatch_io(old_io)
            set_curdoc(old_doc)
Exemple #5
0
    def dispatch(doc):
        files = find_files(filenames)
        html = []
        sep = ""
        for i, file in enumerate(files):
            html.append(
                f'''{sep}<a style="color:purple;text-decoration:none;" href="?app={file}">{file}</a>'''
            )
            next_ = files[i + 1:]
            sep = "<br/>" if next_ and os.path.dirname(
                next_[0]) != os.path.dirname(file) else " | "
        doc.add_root(
            Div(text="".join(html),
                style=dict(color="black", overflowY="scroll",
                           maxHeight="10vh")))

        _args = doc.session_context.request.arguments
        args = {k: v[0].decode("utf-8") for k, v in _args.items()}
        app = args.get("app", None)
        if app is not None:
            app = os.path.normpath(app)
        if app is not None and not (app.startswith("..")
                                    or os.path.isabs(app)):
            with open(app, "r") as file:
                source = file.read()
            set_curdoc(doc)
            module_name = app[:-3].replace("/", ".")
            module = ModuleType(module_name)
            sys.modules[module_name] = module
            module.__file__ = app
            exec(source, module.__dict__)
            del sys.modules[module_name]
 def test_point_stream_callback_clip(self):
     dmap = DynamicMap(lambda x, y: Points([(x, y)]), kdims=[], streams=[PointerXY()])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     plot.callbacks[0].on_msg({"x": -0.3, "y": 1.2})
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.array([0]))
     self.assertEqual(data['y'], np.array([1]))
Exemple #7
0
 def test_stream_callback_on_clone(self):
     points = Points([])
     stream = PointerXY(source=points)
     plot = bokeh_server_renderer.get_plot(points.clone())
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     plot.callbacks[0].on_msg({"x": 0.8, "y": 0.3})
     self.assertEqual(stream.x, 0.8)
     self.assertEqual(stream.y, 0.3)
Exemple #8
0
 def test_stream_callback_on_clone(self):
     points = Points([])
     stream = PointerXY(source=points)
     plot = bokeh_server_renderer.get_plot(points.clone())
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     plot.callbacks[0].on_msg({"x": 0.8, "y": 0.3})
     self.assertEqual(stream.x, 0.8)
     self.assertEqual(stream.y, 0.3)
Exemple #9
0
 def test_point_stream_callback_clip(self):
     dmap = DynamicMap(lambda x, y: Points([(x, y)]), kdims=[], streams=[PointerXY()])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     plot.callbacks[0].on_msg({"x": -0.3, "y": 1.2})
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.array([0]))
     self.assertEqual(data['y'], np.array([1]))
 def setUp(self):
     self.previous_backend = Store.current_backend
     if not bokeh_renderer:
         raise SkipTest("Bokeh required to test plot instantiation")
     Store.current_backend = 'bokeh'
     self.doc = curdoc()
     set_curdoc(Document())
     self.nbcontext = Renderer.notebook_context
     with param.logging_level('ERROR'):
         Renderer.notebook_context = False
 def tearDown(self):
     Store.current_backend = self.previous_backend
     bokeh_renderer.last_plot = None
     Callback._callbacks = {}
     with param.logging_level('ERROR'):
         Renderer.notebook_context = self.nbcontext
     state.curdoc = None
     curdoc().clear()
     set_curdoc(self.doc)
     time.sleep(1)
Exemple #12
0
 def test_stream_callback_with_ids(self):
     dmap = DynamicMap(lambda x, y: Points([(x, y)]), kdims=[], streams=[PointerXY()])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     model = plot.state
     plot.callbacks[0].on_msg({"x": {'id': model.ref['id'], 'value': 0.5},
                               "y": {'id': model.ref['id'], 'value': 0.4}})
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.array([0.5]))
     self.assertEqual(data['y'], np.array([0.4]))
 def test_stream_callback_with_ids(self):
     dmap = DynamicMap(lambda x, y: Points([(x, y)]), kdims=[], streams=[PointerXY()])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     model = plot.state
     plot.callbacks[0].on_msg({"x": {'id': model.ref['id'], 'value': 0.5},
                               "y": {'id': model.ref['id'], 'value': 0.4}})
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.array([0.5]))
     self.assertEqual(data['y'], np.array([0.4]))
 def test_tap_datetime_out_of_bounds(self):
     points = Points([(dt.datetime(2017, 1, 1), 1), (dt.datetime(2017, 1, 3), 3)])
     SingleTap(source=points)
     plot = bokeh_server_renderer.get_plot(points)
     set_curdoc(plot.document)
     callback = plot.callbacks[0]
     self.assertIsInstance(callback, TapCallback)
     msg = callback._process_msg({'x': 1000, 'y': 2})
     self.assertEqual(msg, {})
     msg = callback._process_msg({'x': 10000000000000, 'y': 1})
     self.assertEqual(msg, {})
 def test_pointer_x_datetime_out_of_bounds(self):
     points = Points([(dt.datetime(2017, 1, 1), 1), (dt.datetime(2017, 1, 3), 3)])
     PointerX(source=points)
     plot = bokeh_server_renderer.get_plot(points)
     set_curdoc(plot.document)
     callback = plot.callbacks[0]
     self.assertIsInstance(callback, PointerXCallback)
     msg = callback._process_msg({'x': 1000})
     self.assertEqual(msg['x'], np.datetime64(dt.datetime(2017, 1, 1)))
     msg = callback._process_msg({'x': 10000000000000})
     self.assertEqual(msg['x'], np.datetime64(dt.datetime(2017, 1, 3)))
Exemple #16
0
 def test_pointer_x_datetime_out_of_bounds(self):
     points = Points([(dt.datetime(2017, 1, 1), 1), (dt.datetime(2017, 1, 3), 3)])
     PointerX(source=points)
     plot = bokeh_server_renderer.get_plot(points)
     set_curdoc(plot.document)
     callback = plot.callbacks[0]
     self.assertIsInstance(callback, PointerXCallback)
     msg = callback._process_msg({'x': 1000})
     self.assertEqual(msg['x'], np.datetime64(dt.datetime(2017, 1, 1)))
     msg = callback._process_msg({'x': 10000000000000})
     self.assertEqual(msg['x'], np.datetime64(dt.datetime(2017, 1, 3)))
Exemple #17
0
 def test_tap_datetime_out_of_bounds(self):
     points = Points([(dt.datetime(2017, 1, 1), 1), (dt.datetime(2017, 1, 3), 3)])
     SingleTap(source=points)
     plot = bokeh_server_renderer.get_plot(points)
     set_curdoc(plot.document)
     callback = plot.callbacks[0]
     self.assertIsInstance(callback, TapCallback)
     msg = callback._process_msg({'x': 1000, 'y': 2})
     self.assertEqual(msg, {})
     msg = callback._process_msg({'x': 10000000000000, 'y': 1})
     self.assertEqual(msg, {})
 def test_stream_callback_single_call(self):
     def history_callback(x, history=deque(maxlen=10)):
         history.append(x)
         return Curve(list(history))
     stream = PointerX(x=0)
     dmap = DynamicMap(history_callback, kdims=[], streams=[stream])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     for i in range(20):
         stream.event(x=i)
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.arange(10))
     self.assertEqual(data['y'], np.arange(10, 20))
Exemple #19
0
 def test_stream_callback_single_call(self):
     def history_callback(x, history=deque(maxlen=10)):
         history.append(x)
         return Curve(list(history))
     stream = PointerX(x=0)
     dmap = DynamicMap(history_callback, kdims=[], streams=[stream])
     plot = bokeh_server_renderer.get_plot(dmap)
     bokeh_server_renderer(plot)
     set_curdoc(plot.document)
     for i in range(20):
         stream.event(x=i)
     data = plot.handles['source'].data
     self.assertEqual(data['x'], np.arange(10))
     self.assertEqual(data['y'], np.arange(10, 20))
 def test_scatter(self):
     from bokeh.io.doc import set_curdoc
     from bokeh.plotting import figure
     import numpy as np
     d = document.Document()
     set_curdoc(d)
     assert not d.roots
     assert len(d._all_models) == 0
     p1 = figure(tools=[])
     N = 10
     x = np.linspace(0, 4 * np.pi, N)
     y = np.sin(x)
     p1.scatter(x, y, color="#FF00FF", nonselection_fill_color="#FFFF00", nonselection_fill_alpha=1)
     # figure does not automatically add itself to the document
     d.add_root(p1)
     assert len(d.roots) == 1
    def modify_document(self, doc: Document) -> None:
        if self.failed:
            return

        module = self._runner.new_module()

        doc.modules.add(module)

        orig_curdoc = curdoc()
        set_curdoc(doc)

        old_io, old_doc = self._monkeypatch()

        try:
            self._runner.run(module, lambda: None)
        finally:
            self._unmonkeypatch(old_io, old_doc)
            set_curdoc(orig_curdoc)
    def modify_document(self, doc):
        if self.failed:
            return

        module = self._runner.new_module()

        sys.modules[module.__name__] = module
        doc._modules.append(module)

        orig_curdoc = curdoc()
        set_curdoc(doc)

        old_io, old_doc = self._monkeypatch()

        try:
            self._runner.run(module, lambda: None)
        finally:
            self._unmonkeypatch(old_io, old_doc)
            set_curdoc(orig_curdoc)
Exemple #23
0
    def _with_self_as_curdoc(self, f):
        '''

        '''
        from bokeh.io.doc import set_curdoc, curdoc
        old_doc = curdoc()
        try:
            if getattr(f, "nolock", False):
                set_curdoc(UnlockedDocumentProxy(self))
            else:
                set_curdoc(self)
            return f()
        finally:
            set_curdoc(old_doc)
Exemple #24
0
    def _with_self_as_curdoc(self, f):
        '''

        '''
        from bokeh.io.doc import set_curdoc, curdoc
        old_doc = curdoc()
        try:
            if getattr(f, "nolock", False):
                set_curdoc(UnlockedDocumentProxy(self))
            else:
                set_curdoc(self)
            return f()
        finally:
            set_curdoc(old_doc)
Exemple #25
0
def test_set_curdoc_sets_curstate():
    d = Document()
    bid.set_curdoc(d)
    assert curstate().document is d
Exemple #26
0
def test_set_curdoc_sets_curstate():
    d = Document()
    bid.set_curdoc(d)
    assert curstate().document is d
x_kde = np.linspace(-3.9, 3.9, 400)  # should load from file...
dbw = 0.002  # this too
bws = np.arange(
    0.01, 2.0 + dbw,
    dbw)  # and this stuff. too make sure the LUT and slider match up
kdes = np.loadtxt('lut_kde.csv', delimiter=',')

x_hist_all = np.loadtxt('hist_bincenters.txt', delimiter=',')

hist_counts_all = np.loadtxt('hist_counts.txt', delimiter=',')

#%% bokeh prepare data

doc = Document()  # create fresh Document
set_curdoc(doc)

#> initial data
bw0 = 0.07
ibw0 = 30  # 0.01 + 30*0.002

#counts_hist, x_hist = calcHist(bw0)
#source_hist = ColumnDataSource({'x': x_hist, 'counts': counts_hist, 'bw': bw0*np.ones(x_hist.shape)})

x_hist_lut_dict = {}  # could be combined with the next one
hist_counts_lut_dict = {}
kde_dict = {'x': x_kde}
for i, bw in enumerate(bws):
    k = '{:.3f}'.format(bw)

    kde_dict[k] = kdes[i, :]