def test_heatmap_recipe(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })
        plot = figure(plot_width=600, plot_height=400, title="Test Title")
        plot.square('A', 'B', source=source)

        plot2 = ar_downsample.heatmap(plot,
                                      palette="Reds9",
                                      reserve_val=0,
                                      points=True,
                                      client_color=True,
                                      title="Test Title 2")
        source2 = self._find_source(plot2)

        self.assertEquals("Test Title 2", plot2.title)
        self.assertEquals(type(source2), ServerDataSource)

        transform = source2.transform
        self.assertEquals(type(transform['info']), ar_downsample.Const)
        self.assertEquals(type(transform['agg']), ar_downsample.Count)
        self.assertEquals(type(transform['shader']), ar_downsample.Seq)
        self.assertEquals(transform['shader'].out, "image")
def animated():

    from numpy import pi, cos, sin, linspace, zeros_like

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8",
              "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5

    cx = cy = zeros_like(rmin)

    output_server("animated_reveal")

    figure(title="Animations")

    hold()

    annular_wedge(
        cx, cy, rmin, rmax, theta[:-1], theta[1:],
        x_range=[-11, 11],
        y_range=[-11, 11],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
        tools="pan,wheel_zoom,box_zoom,reset,previewsave"
    )

    return curplot(), cursession()
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2

    output_server("distribution_reveal")

    hold()

    figure(title="Interactive plots",
           tools="pan, wheel_zoom, box_zoom, reset, previewsave",
           background_fill="#E5E5E5")
    quad(top=hist, bottom=np.zeros(len(hist)), left=edges[:-1], right=edges[1:],
         fill_color="#333333", line_color="#E5E5E5", line_width=3)

    # Use `line` renderers to display the PDF and CDF
    line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    xgrid().grid_line_color = "white"
    xgrid().grid_line_width = 3
    ygrid().grid_line_color = "white"
    ygrid().grid_line_width = 3

    legend().orientation = "top_left"

    return curplot(), cursession()
    def test_source(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })

        plot = figure()
        plot.square('A', 'B', source=source)

        agg = ar_downsample.CountCategories()
        info = ar_downsample.Const(val=1)
        shader = ar_downsample.InterpolateColor()

        new_source = ar_downsample.source(plot,
                                          agg=agg,
                                          info=info,
                                          shader=shader)
        self.assertIsNotNone(new_source.transform)
        trans = new_source.transform

        self.assertEquals(trans['resample'], 'abstract rendering')
        self.assertEquals(trans['agg'], agg)
        self.assertEquals(trans['info'], info)
        self.assertEquals(trans['shader'], shader)
        self.assertEquals(trans['glyphspec'],
                          plot.select({'type': GlyphRenderer})[0].glyph)
        self.assertEquals(trans['points'], False)
    def test_replot_result_type(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )
        plot = figure()
        plot.square('A', 'B', source=source)

        expected = {"image": "Image", "image_rgb": "ImageRGBA", "multi_line": "MultiLine"}

        shaders = dict()

        for name in dir(ar_downsample):
            item = getattr(ar_downsample, name)
            if isinstance(item, ar_downsample.Shader):
                shaders[item] = item.out

        for shader_class in shaders:
            shader = shader_class()
            rslt = ar_downsample.replot(plot, shader=shader)
            self.assertEquals(expected[shader.out], self._glyphspec(rslt)['type'],
                              "Error with {0}. Expected {1}, recieved {2}"
                              .format(str(shader_class), expected[shader.out], self._glyphspec(rslt)))
    def test_replot_result_type(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })
        plot = figure()
        plot.square('A', 'B', source=source)

        expected = {
            "image": "Image",
            "image_rgb": "ImageRGBA",
            "multi_line": "MultiLine"
        }

        shaders = dict()

        for name in dir(ar_downsample):
            item = getattr(ar_downsample, name)
            if isinstance(item, ar_downsample.Shader):
                shaders[item] = item.out

        for shader_class in shaders:
            shader = shader_class()
            rslt = ar_downsample.replot(plot, shader=shader)
            self.assertEquals(
                expected[shader.out],
                self._glyphspec(rslt)['type'],
                "Error with {0}. Expected {1}, recieved {2}".format(
                    str(shader_class), expected[shader.out],
                    self._glyphspec(rslt)))
Exemple #7
0
def init_plot(crawl_name):
    session = Session()
    document = Document()
    session.use_doc(crawl_name)
    session.load_document(document)

    if document.context.children:
        plot = document.context.children[0]
    else:
        output_server(crawl_name)
        # TODO: Remove these when Bokeh is upgraded
        # placeholders or Bokeh can't inject properly
        current = np.datetime64(datetime.now())
        xdr = Range1d(current, current + 1)
        ydr = ["urls"]

        # styling suggested by Bryan
        plot = figure(title="Crawler Monitor", tools="hover",
                      x_axis_type="datetime", y_axis_location="right", x_range=xdr, y_range=ydr,
                      width=1200, height=600)
        plot.toolbar_location = None
        plot.xgrid.grid_line_color = None

    document.add(plot)
    session.store_document(document)
    script = autoload_server(plot, session)

    #TODO: Looks like a Bokeh bug, probably not repeatable with current code
    script = script.replace("'modelid': u'", "'modelid': '")
    return script
Exemple #8
0
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2

    output_server("distribution_reveal")

    p = figure(title="Interactive plots",
               background_fill="#E5E5E5")
    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#333333", line_color="#E5E5E5", line_width=3)

    # Use `line` renderers to display the PDF and CDF
    p.line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    p.line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    p.legend.orientation = "top_left"

    p.xaxis.axis_label = 'x'
    p.xgrid[0].grid_line_color = "white"
    p.xgrid[0].grid_line_width = 3

    p.yaxis.axis_label = 'Pr(x)'
    p.ygrid[0].grid_line_color = "white"
    p.ygrid[0].grid_line_width = 3

    push()

    return p, cursession()
Exemple #9
0
    def __init__(self,
                 document,
                 channels,
                 open_browser=False,
                 start_server=False,
                 **kwargs):
        if not BOKEH_AVAILABLE:
            raise ImportError
        self.plots = {}
        self.start_server = start_server
        self._startserver()
        output_server(document)

        # Create figures for each group of channels
        self.p = []
        self.p_indices = {}
        for i, channel_set in enumerate(channels):
            self.p.append(figure(title='{} #{}'.format(document, i + 1)))
            for channel in channel_set:
                self.p_indices[channel] = i
        if open_browser:
            show()

        kwargs.setdefault('after_every_epoch', True)
        kwargs.setdefault("before_first_epoch", True)
        super(Plot, self).__init__(**kwargs)
 def __init__(self, predit_funct=None):
     Callback.__init__(self)
     # output_notebook()
     self.loss = np.array([])
     self.psnrs = np.array([])
     output_server("line")
     self.imagew = 512
     self.min_loss = 10000
     self.predit_funct = predit_funct
     self.p = figure()
     self.p2 = figure()
     self.x = np.array([])
     self.y = np.array([])
     self.bx = np.array([])
     self.by = np.array([])
     self.cx = np.array([])
     self.epochNo = 0
     self.p.line(self.x, self.y, name='line', color="tomato", line_width=2)
     self.p.line(self.bx, self.by, name='batch_line', color="blue", line_width=2)
     self.p2.line(self.cx, self.psnrs, name='psnr', color="green", line_width=2)
     show(self.p)
     # show(self.p2)
     # self.p2 = figure(x_range=[0, self.imagew], y_range=[0, self.imagew])
     # self.p2.image_rgba(name='image', image=[np.array((self.imagew, self.imagew), dtype='uint32')], x=0, y=0, dw=self.imagew, dh=self.imagew)
     # show(self.p2)
     self.psnr = 0
Exemple #11
0
def draw_plot(all_freqs, all_segm_dict, uniq_id="no-id"):
    #zbior nazw wszystkich komorek podczas symulacji
    cells_types = set()

    for i in range(len(all_freqs)):
        for e in all_freqs[i].keys():
            cells_types.add(e)

    #dla kazdego typu komorek przypisywany jest inny kolor
    col_dict = {}
    from bokeh.palettes import brewer
    colors_palette = brewer["Spectral"][11]
    color = lambda: random.randint(0, 255)
    for i, element in enumerate(cells_types):
        if i < 11:
            col_dict[element] = colors_palette[i]
        else:
            #losowy kolor
            col_dict[element] = ('#%02X%02X%02X' % (color(), color(), color()))

    #dodanie klucza od wartosci ktorych nie ma po pierwszej iteracji
    for element in cells_types:
        for i in range(len(all_freqs)):
            if element not in all_freqs[i]:
                all_freqs[i][element] = [0, 0, 0, 0]

    output_server("stops3" + uniq_id)

    bar, geny = plot_segments(all_freqs[0], col_dict)
    plot = plot_environment(all_segm_dict[0])

    push()

    return bar, plot, cursession(), geny
    def __init__(self, document, channels, server, **kwargs):
        kwargs.setdefault('after_epoch', True)
        kwargs.setdefault('after_training', True)
        super(Plot, self).__init__(**kwargs)
        self.plots = {}
        self.document = document
        self.server = server

        output_server(self.document, url=self.server)

        self.p = []
        self.p_indx = {}
        self.color_indx = {}
        for i, channel_set in enumerate(channels):
            channel_set_opts = {}
            if isinstance(channel_set, dict):
                channel_set_opts = channel_set
                channel_set = channel_set_opts.pop('channels')
            channel_set_opts.setdefault('title',
                                        '{} #{}'.format(document, i + 1))
            channel_set_opts.setdefault('x_axis_label', 'epochs')
            channel_set_opts.setdefault('y_axis_label', 'value')
            self.p.append(figure(**channel_set_opts))
            for j, channel in enumerate(channel_set):
                self.p_indx[channel] = i
                self.color_indx[channel] = j
Exemple #13
0
def init_plot(crawl_name):
    session = Session()
    document = Document()
    session.use_doc(crawl_name)
    session.load_document(document)

    if document.context.children:
        plot = document.context.children[0]
    else:
        output_server(crawl_name)
        # TODO: Remove these when Bokeh is upgraded
        # placeholders or Bokeh can't inject properly
        current = np.datetime64(datetime.now())
        xdr = Range1d(current, current + 1)
        ydr = ["urls"]

        # styling suggested by Bryan
        plot = figure(title="Crawler Monitor",
                      tools="hover",
                      x_axis_type="datetime",
                      y_axis_location="right",
                      x_range=xdr,
                      y_range=ydr,
                      width=1200,
                      height=600)
        plot.toolbar_location = None
        plot.xgrid.grid_line_color = None

    document.add(plot)
    session.store_document(document)
    script = autoload_server(plot, session)

    #TODO: Looks like a Bokeh bug, probably not repeatable with current code
    script = script.replace("'modelid': u'", "'modelid': '")
    return script
Exemple #14
0
def animated():

    from numpy import pi, cos, sin, linspace

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8",
              "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5

    output_server("animated_reveal")

    p = figure(title="Animations", x_range=[-11, 11], y_range=[-11, 11])

    p.annular_wedge(
        0, 0, rmin, rmax, theta[:-1], theta[1:],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
    )

    push()

    return p, cursession()
Exemple #15
0
 def create_plot(self):
     output_server('animation')
     source = ColumnDataSource(data=dict(x=[], y=[]))
     p = figure(plot_width=800, plot_height=400)
     p.line(x='x', y='y', source=source, name='line')
     push()
     return p, cursession()
    def test_source(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )

        plot = figure()
        plot.square('A', 'B', source=source)

        agg = ar_downsample.CountCategories()
        info = ar_downsample.Const(val=1)
        shader = ar_downsample.InterpolateColor()

        new_source = ar_downsample.source(plot, agg=agg, info=info, shader=shader)
        self.assertIsNotNone(new_source.transform)
        trans = new_source.transform

        self.assertEquals(trans['resample'], 'abstract rendering')
        self.assertEquals(trans['agg'], agg)
        self.assertEquals(trans['info'], info)
        self.assertEquals(trans['shader'], shader)
        self.assertEquals(trans['glyphspec'],
                          plot.select({'type' : GlyphRenderer})[0].glyph)
        self.assertEquals(trans['points'], False)
Exemple #17
0
    def start_server(self, start_server_flag):
        """
        Starts a bokeh-server at the default URL location.

        Parameters
        ----------
        start_server_flag : bool
            Whether to start the bokeh server.
        """
        if BOKEH_AVAILABLE:
            if start_server_flag:

                def preexec_fn():
                    """Prevents the server from dying on training interrupt."""
                    signal.signal(signal.SIGINT, signal.SIG_IGN)

                # Only memory works with subprocess, need to wait for it to start
                log.info('Starting plotting server on %s', self.server_url)
                self.sub = Popen('bokeh-server --ip 0.0.0.0 '
                                 '--backend memory'.split(),
                                 stdout=PIPE,
                                 stderr=PIPE,
                                 preexec_fn=preexec_fn)
                time.sleep(2)
                log.info('Plotting server PID: {}'.format(self.sub.pid))
            else:
                self.sub = None
            output_server(self.bokeh_doc_name, url=self.server_url)
Exemple #18
0
    def test_replot_property_transfer(self):
        self.assertIsNotNone(self.bokeh_server, "Server failed to start, cannot tests")
        ar_downsample._loadAR()
        output_server("Census")
        source = ServerDataSource(data_url="fn://bivariate", owner_username="******")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"

        plot = figure(lot_width=plot_width, plot_height=plot_height, title=plot_title)
        plot.square('A', 'B', source=source)
        ar_plot = ar_downsample.replot(plot)

        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width not transfered")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height not transfered")
        self.assertEquals(ar_plot.title, plot_title, "Plot title not transfered")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"
        ar_plot = ar_downsample.replot(plot, title=plot_title, plot_width=plot_width, plot_height=plot_height)
        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width override failed")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height override failed")
        self.assertEquals(ar_plot.title, plot_title, "Plot title override failed")
Exemple #19
0
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2

    output_server("distribution_reveal")

    p = figure(title="Interactive plots",
               background_fill="#E5E5E5")
    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#333333", line_color="#E5E5E5", line_width=3)

    # Use `line` renderers to display the PDF and CDF
    p.line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    p.line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    p.legend.orientation = "top_left"

    p.xaxis.axis_label = 'x'
    p.xgrid[0].grid_line_color = "white"
    p.xgrid[0].grid_line_width = 3

    p.yaxis.axis_label = 'Pr(x)'
    p.ygrid[0].grid_line_color = "white"
    p.ygrid[0].grid_line_width = 3

    push()

    return p, cursession()
Exemple #20
0
def animated():

    from numpy import pi, cos, sin, linspace

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = ["FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8",
              "#253494", "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"] * 5

    output_server("animated_reveal")

    p = figure(title="Animations", x_range=[-11, 11], y_range=[-11, 11])

    p.annular_wedge(
        0, 0, rmin, rmax, theta[:-1], theta[1:],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
    )

    push()

    return p, cursession()
Exemple #21
0
 def __init__(self, predit_funct=None):
     Callback.__init__(self)
     # output_notebook()
     self.loss = np.array([])
     self.psnrs = np.array([])
     output_server("line")
     self.imagew = 512
     self.min_loss = 10000
     self.predit_funct = predit_funct
     self.p = figure()
     self.p2 = figure()
     self.x = np.array([])
     self.y = np.array([])
     self.bx = np.array([])
     self.by = np.array([])
     self.cx = np.array([])
     self.epochNo = 0
     self.p.line(self.x, self.y, name='line', color="tomato", line_width=2)
     self.p.line(self.bx,
                 self.by,
                 name='batch_line',
                 color="blue",
                 line_width=2)
     self.p2.line(self.cx,
                  self.psnrs,
                  name='psnr',
                  color="green",
                  line_width=2)
     show(self.p)
     # show(self.p2)
     # self.p2 = figure(x_range=[0, self.imagew], y_range=[0, self.imagew])
     # self.p2.image_rgba(name='image', image=[np.array((self.imagew, self.imagew), dtype='uint32')], x=0, y=0, dw=self.imagew, dh=self.imagew)
     # show(self.p2)
     self.psnr = 0
    def test_replot_property_transfer(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"

        plot = figure(plot_width=plot_width, plot_height=plot_height, title=plot_title)
        plot.square('A', 'B', source=source)
        ar_plot = ar_downsample.replot(plot)

        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width not transfered")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height not transfered")
        self.assertEquals(ar_plot.title, plot_title, "Plot title not transfered")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"
        ar_plot = ar_downsample.replot(plot, title=plot_title, plot_width=plot_width, plot_height=plot_height)
        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width override failed")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height override failed")
        self.assertEquals(ar_plot.title, plot_title, "Plot title override failed")
    def __init__(self,
                 linenames,
                 sessionname=None,
                 colors=None,
                 xaxis='iterations',
                 callevery=1):
        """
        :type linenames: list or tuple
        :param linenames: Names of the time series for the Bokeh server to plot. The call method must have the names
                          in the list as keyword arguments.

        :type sessionname: str
        :param sessionname: Name of the Bokeh session

        :type xaxis: str
        :param xaxis: What goes in the x axis ('iterations' or 'epochs')
        """
        super(plotter, self).__init__(callevery=callevery)

        # Meta
        self.linenames = list(linenames)
        self.sessionname = "PlotterID-{}".format(
            id(self)) if sessionname is None else sessionname
        self.colors = colors if colors is not None else [
            None,
        ] * len(self.linenames)
        self.xaxis = xaxis

        # Init plot server
        bplt.output_server(self.sessionname)

        # Build figure
        self.figure = bplt.figure()
        self.figure.xaxis.axis_label = self.xaxis

        # Make lines in figure
        for name, color in zip(self.linenames, self.colors):
            if color is not None:
                self.figure.line(x=[],
                                 y=[],
                                 name=name,
                                 color=color,
                                 legend=name)
            else:
                self.figure.line(x=[], y=[], name=name, legend=name)

        bplt.show(self.figure)

        # Make list of renderers and datasources
        self.renderers = {
            name: self.figure.select(dict(name=name))
            for name in self.linenames
        }
        self.datasources = {
            name: self.renderers[name][0].data_source
            for name in self.linenames
        }
Exemple #24
0
 def wrapper(*args, **kwargs):
     docname = prefix + str(uuid.uuid4())
     output_server(docname, url=url)
     app = func(*args, **kwargs)
     session().add(app)
     session().plotcontext.children=[app]
     session().plotcontext._dirty = True
     logger.debug("stored: %s", str(session().store_all()))
     app.docname = docname
     return app
Exemple #25
0
 def _init_plotsession(self,url):
     docname = self.trainer.model.name
     try:
         output_server(docname,url=url)
     except:
         return False
     d = curdoc()
     self.plot_address = '%s/bokeh/doc/%s/%s'%(url,d.docid,d.ref['id'])
     print('plots available at: %s'%(self.plot_address))
     return True
Exemple #26
0
 def wrapper(*args, **kwargs):
     docname = prefix + str(uuid.uuid4())
     output_server(docname, url=url)
     curdoc().autoadd(False)
     app = func(*args, **kwargs)
     curdoc()._plotcontext.children = [app]
     curdoc().add_all()
     changed = push()
     logger.debug("stored: %s", str(changed))
     app.docname = docname
     return app
Exemple #27
0
def draw_bokeh_plot(pop_mat,
                    grid_shape,
                    color_dict,
                    width=800,
                    uniq_id="no-id"):
    #wykres na siatce heksagonalnej
    output_server("stops2" + uniq_id)
    p = figure(plot_width=width, title="STOPS")

    p.ygrid.grid_line_color = "white"
    p.xgrid.grid_line_color = "white"

    m, n = grid_shape
    beta = 0.5
    alpha = beta / math.sqrt(3)
    h = beta / math.sqrt(3)

    points_x = []
    points_y = []
    y = 0
    for i in range(n):
        if i % 2 == 1:
            x = -0.5
        else:
            x = -1
        for j in range(m):
            if i % 2 == 1:
                x += 1
            else:
                x += 1
            points = hexagon_points(x, y, alpha, beta)
            points_x.append(points[0])
            points_y.append(points[1])
        y += 3 * h

    colors, wektor = value_color(pop_mat, color_dict)

    source = ColumnDataSource(data=dict(
        points_x=points_x, points_y=points_y, wektor=wektor, colors=colors))

    p.patches(xs="points_x",
              ys="points_y",
              source=source,
              line_color="blue",
              color="colors",
              line_width=2,
              fill_alpha=0.8)
    hover = HoverTool(plot=p, tooltips=dict(wektor="@wektor"))
    p.tools.append(hover)

    push()

    return p, cursession()
Exemple #28
0
    def xy_scatter_bokeh(self):
        from bokeh.plotting import output_server, figure, scatter, show
        ux, uy, pos_mean, pos_sem, neg_mean, neg_sem, colors, size = \
            self.xy_plot_info()
        output_server("scatter.html")
        figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave,select")

        scatter(ux, uy, color="#FF00FF", nonselection_fill_color="#FFFF00", nonselection_fill_alpha=1)
        scatter(ux, uy, color="red")
        scatter(ux, uy, marker="square", color="green")
        scatter(ux, uy, marker="square", color="blue", name="scatter_example")

        show()
Exemple #29
0
def make_test_plot():
    import numpy as np
    from bokeh.plotting import output_server, line

    N = 8000

    x = np.linspace(0, 4 * np.pi, N)
    y = np.sin(x)

    output_server("line.py example")

    l = line(x, y, color="#0000FF", plot_height=300, plot_width=300, tools="pan,resize")
    return l
Exemple #30
0
def main():
    setup_logging()
    logging.getLogger("requests").setLevel(logging.WARNING)

    output_server("Temp Chart")

    window = 200
    width = 800
    height = 200

    now = datetime.now()
    start = now - timedelta(hours=window)
    r_start = time.mktime(start.timetuple()) * 1000 - 20000000
    r_end = time.mktime(now.timetuple()) * 1000 - 20000000
    ran = Range1d(r_start, r_end)

    # line chart
    line_fig = figure(plot_width=width, plot_height=height) #, x_range=ran)
    line = line_fig.line(x=[], y=[])

    # circle chart
    c_fig = figure(plot_width=width, plot_height=height)
    circle = c_fig.circle(x=[], y=[], size=1)

    # format axes
    line_fig.xaxis[0].formatter = DatetimeTickFormatter(formats=dict(days=["%T"]))
    line_fig.xaxis.major_label_orientation = pi/4
    c_fig.xaxis[0].formatter = DatetimeTickFormatter(formats=dict(days=["%T"]))
    c_fig.xaxis.major_label_orientation = pi/4

    p = vplot(line_fig, c_fig)
    show(p)

    line_ds = line.select(dict(type=GlyphRenderer))[0].data_source
    circle_ds = circle.select(dict(type=GlyphRenderer))[0].data_source

    lines = tail_generator(exit_after=0)
    if True:
        for line in lines:
            line = decimate(lines, skip=300)
            temp, date = parse_line(line)
            if temp is None:
                continue
            update_series(line_ds, date, temp)
            update_range(line_ds, line_fig, 60)
            update_series(circle_ds, date, temp)
            update_range(circle_ds, c_fig, 12)
            time.sleep(0.01)

    return c_fig, circle
Exemple #31
0
 def _startserver(self):
     if self.start_server:
         def preexec_fn():
             """Prevents the server from dying on training interrupt."""
             signal.signal(signal.SIGINT, signal.SIG_IGN)
         # Only memory works with subprocess, need to wait for it to start
         logger.info('Starting plotting server on localhost:5006')
         self.sub = Popen('bokeh-server --ip 0.0.0.0 '
                          '--backend memory'.split(),
                          stdout=PIPE, stderr=PIPE, preexec_fn=preexec_fn)
         time.sleep(2)
         logger.info('Plotting server PID: {}'.format(self.sub.pid))
     else:
         self.sub = None
     output_server(self.document, url=self.server_url)
    def __init__(self, title, legends, n_images_train=0, n_images_test=0, n_cols_images=3, axisx="Epochs",
                 axisy="Values", line_width=4, alpha=0.8, line_dash=[4, 4], plot_width=800, plot_height=400):

        # Save some parameters
        self.n_lines_plot = len(legends)
        self.n_images_train = n_images_train
        self.n_images_test = n_images_test

        # prepare output to server
        output_server(title)
        cursession().publish()

        # Create the figure plot
        if self.n_lines_plot > 0:
            p_plot, self.data_plot = self.create_figure_plot(title, legends, axisx=axisx, axisy=axisy,
                                                             line_width=line_width, alpha=alpha, line_dash=line_dash,
                                                             plot_width=plot_width, plot_height=plot_height)

        if n_images_train > 0:
            # Create black images as initialization
            img = np.zeros((64, 256, 3))
            img_batch = []
            for i in xrange(n_images_train):
                img_batch.append(img)

            # Create the training image grid
            p_images_train, self.data_img_train = self.create_grid_images(img_batch, name='img_train', n_cols=n_cols_images)

        if n_images_test > 0:
            # Create black images as initialization
            img = np.zeros((64, 256, 3))
            img_batch = []
            for i in xrange(n_images_test):
                img_batch.append(img)

            # Create the testing image grid
            p_images_test, self.data_img_test = self.create_grid_images(img_batch, name='img_test', n_cols=n_cols_images)

        # Create a vertical grid with the plot and the train and test images
        if self.n_lines_plot > 0 and n_images_train > 0 and n_images_test > 0:
            p = vplot(p_plot, p_images_train, p_images_test)
        elif self.n_lines_plot > 0 and n_images_train > 0 and n_images_test <= 0:
            p = vplot(p_plot, p_images_train)
        else:
            print 'ERROR: Not implemented combination. Please, do it!'

        # Show the plot
        show(p)
Exemple #33
0
def main(document, server_url):
    plots = {}

    output_server(document, url=server_url)

    # Create figures for each group of channels
    p = []
    p_indices = {}
    for i, channel_set in enumerate(channels):
        channel_set_opts = {}
        if isinstance(channel_set, dict):
            channel_set_opts = channel_set
            channel_set = channel_set_opts.pop("channels")
        channel_set_opts.setdefault("title", "{} #{}".format(document, i + 1))
        p.append(figure(**channel_set_opts))
        for channel in channel_set:
            p_indices[channel] = i

    files = [f for f in listdir(document) if isfile(join(document, f)) and "_log_" in f]

    for file_name in sorted(files, key=lambda s: int(re.findall(r"\d+", s)[1])):
        with open(join(document, file_name), "rb") as f:
            log = pickle.load(f)

        iteration = log.status["iterations_done"]
        i = 0
        for key, value in log.current_row.items():
            if key in p_indices:
                if key not in plots:
                    fig = p[p_indices[key]]
                    fig.line(
                        [iteration],
                        [value],
                        legend=key,
                        x_axis_label="iterations",
                        y_axis_label="value",
                        name=key,
                        line_color=colors[i % len(colors)],
                    )
                    i += 1
                    renderer = fig.select(dict(name=key))
                    plots[key] = renderer[0].data_source
                else:
                    plots[key].data["x"].append(iteration)
                    plots[key].data["y"].append(value)

                    cursession().store_objects(plots[key])
        push()
Exemple #34
0
    def test_replot_remove(self):
        self.assertIsNotNone(self.bokeh_server, "Server failed to start, cannot tests")
        ar_downsample._loadAR()
        output_server("Census")
        source = ServerDataSource(data_url="fn://bivariate", owner_username="******")
        plot = square('A', 'B', source=source)
        ar_downsample.replot(plot, remove_original=False)

        self.assertTrue(plot in curdoc().context.children, "Not retained")
        ar_downsample.replot(plot, remove_original=True)
        self.assertTrue(plot not in curdoc().context.children, "Not removed")

        try:
            ar_downsample.replot(plot, remove_original=True)
        except:
            self.assertTrue(False, "Error reploting plot not in curdoc")
Exemple #35
0
def make_test_plot():
    import numpy as np
    from bokeh.plotting import output_server, line

    N = 8000

    x = np.linspace(0, 4*np.pi, N)
    y = np.sin(x)

    output_server("line.py example")

    l = line(
        x,y, color="#0000FF",
        plot_height=300, plot_width=300,
        tools="pan,resize")
    return l
Exemple #36
0
    def test_replot_remove(self):
        self.assertIsNotNone(self.bokeh_server, "Server failed to start, cannot tests")
        ar_downsample._loadAR()
        output_server("Census")
        source = ServerDataSource(data_url="fn://bivariate", owner_username="******")
        plot = figure()
        plot.square('A', 'B', source=source)
        ar_downsample.replot(plot, remove_original=False)

        self.assertTrue(plot in curdoc().context.children, "Not retained")
        ar_downsample.replot(plot, remove_original=True)
        self.assertTrue(plot not in curdoc().context.children, "Not removed")

        try:
            ar_downsample.replot(plot, remove_original=True)
        except:
            self.assertTrue(False, "Error reploting plot not in curdoc")
Exemple #37
0
    def __init__(self, name, fig_title, url):
        """
        fig_title: Figure Title
        url : str, optional
            Url of the bokeh-server. Ex: when starting the bokeh-server with
            ``bokeh-server --ip 0.0.0.0`` at ``alice``, server_url should be
            ``http://alice:5006``. When not specified the default configured
            by ``bokeh_server`` in ``.blocksrc`` will be used. Defaults to
            ``http://localhost:5006/``.

        Reference: mila-udem/blocks-extras
        """
        Callback.__init__(self)
        self.name = name
        self.fig_title = fig_title
        self.plots = []
        output_server(name, url=url)
        cursession().publish()
def bokeh_animated_colours(data_source):
    """
    Creates a coloured map of London tube stations by zone where the size of the tube station changes
    according to the number of people on the station
    :param data_source:
    :return:
    """
    #create the map
    data_file="/home/winterflower/programming_projects/python-londontube/src/data/londontubes.txt"
    map=simulation_utils.Map(data_file)
    map.initialise_map()
    graph_object=map.graph_object
    map=sim.initialise_commuters(map)
    print "Please make sure the bokeh-server is running before you run the script"
    output_server("bokeh_tube_stations")
    TOOLS="resize,hover,save"
    animated_figure=figure(title="London Underground", tools=TOOLS)
    animated_figure.plot_height=1000
    animated_figure.plot_width=1000
    length=len(data_source.data["longitudes"])
    ########################################
    #Get the sizes
    #######################################
    commuters=get_commuter_numbers(data_source.data["station_names"], map)
    # scale the commuters
    color=map_to_colours(commuters)
    data_source.data["color"]=color
    size=[10 for i in range(length)]
    animated_figure.circle(data_source.data["longitudes"], data_source.data["latitudes"], size=data_source.data["size"], color=data_source.data["color"], alpha=0.8, name="circle")
    show(animated_figure)

    #obtain the glyph renderer
    glyph_renderer=animated_figure.select((dict(name="circle")))
    print glyph_renderer
    figure_data_source=glyph_renderer[0].data_source
    while True:
        map=sim.simulate_one_cycle(map)
        commuters=get_commuter_numbers(data_source.data["station_names"],map)
        color=map_to_colours(commuters)
        size=map_to_comuters(commuters)
        figure_data_source.data["color"]=color
        figure_data_source.data["size"]=size
        cursession().store_objects(figure_data_source)
        time.sleep(0.05)
    def test_replot_remove(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )
        plot = figure()
        plot.square('A', 'B', source=source)
        ar_downsample.replot(plot, remove_original=False)

        self.assertTrue(plot in curdoc().context.children, "Not retained")
        ar_downsample.replot(plot, remove_original=True)
        self.assertTrue(plot not in curdoc().context.children, "Not removed")

        try:
            ar_downsample.replot(plot, remove_original=True)
        except:
            self.assertTrue(False, "Error reploting plot not in curdoc")
Exemple #40
0
def animated():

    from numpy import pi, cos, sin, linspace, zeros_like

    N = 50 + 1
    r_base = 8
    theta = linspace(0, 2 * pi, N)
    r_x = linspace(0, 6 * pi, N - 1)
    rmin = r_base - cos(r_x) - 1
    rmax = r_base + sin(r_x) + 1

    colors = [
        "FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#2C7FB8", "#253494",
        "#2C7FB8", "#41B6C4", "#7FCDBB", "#C7E9B4"
    ] * 5

    cx = cy = zeros_like(rmin)

    output_server("animated_reveal")

    figure(title="Animations",
           x_range=[-11, 11],
           y_range=[-11, 11],
           tools="pan,wheel_zoom,box_zoom,reset,previewsave")

    hold()

    annular_wedge(
        cx,
        cy,
        rmin,
        rmax,
        theta[:-1],
        theta[1:],
        inner_radius_units="data",
        outer_radius_units="data",
        fill_color=colors,
        line_color="black",
    )

    return curplot(), cursession()
    def test_replot_remove(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })
        plot = figure()
        plot.square('A', 'B', source=source)
        ar_downsample.replot(plot, remove_original=False)

        self.assertTrue(plot in curdoc().context.children, "Not retained")
        ar_downsample.replot(plot, remove_original=True)
        self.assertTrue(plot not in curdoc().context.children, "Not removed")

        try:
            ar_downsample.replot(plot, remove_original=True)
        except:
            self.assertTrue(False, "Error reploting plot not in curdoc")
 def __init__(self):
     rospy.loginfo("Setting up plot")
     self.MAX_DATA = 1000000 #* 10 # this was one message
     self.x_data = [0]
     self.y_data = [0]
     output_server("audio_plot")
     self.p1 = figure(title="Audio plot")
     self.p1.line(self.x_data, self.y_data,
         color="#0000FF",
         tools="pan,resize,wheel_zoom", 
         width=1200,
         height=300,
         legend='value of thing')
     show()
     self.renderer = self.p1.select(dict(type=GlyphRenderer))
     self.ds = self.renderer[0].data_source
     
     self.audio_data_buffer = []
     rospy.loginfo("Setting up sub")
     self.sub = rospy.Subscriber(NAOQI_AUDIO_TOPIC, AudioBuffer, self.audio_cb)
     rospy.loginfo("Done!")
Exemple #43
0
def distribution():

    mu, sigma = 0, 0.5

    measured = np.random.normal(mu, sigma, 1000)
    hist, edges = np.histogram(measured, density=True, bins=20)

    x = np.linspace(-2, 2, 1000)
    pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                    (2 * sigma**2))
    cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma**2))) / 2

    output_server("distribution_reveal")

    hold()

    figure(title="Interactive plots",
           tools="pan, wheel_zoom, box_zoom, reset, previewsave",
           background_fill="#E5E5E5")
    quad(top=hist,
         bottom=np.zeros(len(hist)),
         left=edges[:-1],
         right=edges[1:],
         fill_color="#333333",
         line_color="#E5E5E5",
         line_width=3)

    # Use `line` renderers to display the PDF and CDF
    line(x, pdf, line_color="#348abd", line_width=8, alpha=0.7, legend="PDF")
    line(x, cdf, line_color="#7a68a6", line_width=8, alpha=0.7, legend="CDF")

    xgrid().grid_line_color = "white"
    xgrid().grid_line_width = 3
    ygrid().grid_line_color = "white"
    ygrid().grid_line_width = 3

    legend().orientation = "top_left"

    return curplot(), cursession()
    def test_replot_property_transfer(self):
        ar_downsample._loadAR()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"

        plot = figure(plot_width=plot_width,
                      plot_height=plot_height,
                      title=plot_title)
        plot.square('A', 'B', source=source)
        ar_plot = ar_downsample.replot(plot)

        self.assertEquals(ar_plot.plot_width, plot_width,
                          "Plot width not transfered")
        self.assertEquals(ar_plot.plot_height, plot_height,
                          "Plot height not transfered")
        self.assertEquals(ar_plot.title, plot_title,
                          "Plot title not transfered")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"
        ar_plot = ar_downsample.replot(plot,
                                       title=plot_title,
                                       plot_width=plot_width,
                                       plot_height=plot_height)
        self.assertEquals(ar_plot.plot_width, plot_width,
                          "Plot width override failed")
        self.assertEquals(ar_plot.plot_height, plot_height,
                          "Plot height override failed")
        self.assertEquals(ar_plot.title, plot_title,
                          "Plot title override failed")
    def test_contour_recipe(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(expr={
            'op': 'Field',
            'args': [':leaf', 'bivariate']
        })
        plot = figure(plot_width=600, plot_height=400, title="Test Title")
        plot.square('A', 'B', source=source)

        plot2 = ar_downsample.contours(plot, title="Contour")
        source2 = self._find_source(plot2)

        self.assertEquals("Contour", plot2.title)
        self.assertEquals(type(source2), ServerDataSource)

        transform = source2.transform
        self.assertEquals(type(transform['info']), ar_downsample.Const)
        self.assertEquals(type(transform['agg']), ar_downsample.Count)
        self.assertEquals(type(transform['shader']), ar_downsample.Seq)
        self.assertEquals(transform['shader'].out, "multi_line")
Exemple #46
0
    def start_server(self, start_server_flag):
        """
        Starts a bokeh-server at the default URL location.

        Parameters
        ----------
        start_server_flag : bool
            Whether to start the bokeh server.
        """
        if BOKEH_AVAILABLE:
            if start_server_flag:
                def preexec_fn():
                    """Prevents the server from dying on training interrupt."""
                    signal.signal(signal.SIGINT, signal.SIG_IGN)
                # Only memory works with subprocess, need to wait for it to start
                log.info('Starting plotting server on %s', self.server_url)
                self.sub = Popen('bokeh-server --ip 0.0.0.0 '
                                 '--backend memory'.split(),
                                 stdout=PIPE, stderr=PIPE, preexec_fn=preexec_fn)
                time.sleep(2)
                log.info('Plotting server PID: {}'.format(self.sub.pid))
            else:
                self.sub = None
            output_server(self.bokeh_doc_name, url=self.server_url)
    def test_heatmap_recipe(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )
        plot = figure(plot_width=600,
                      plot_height=400,
                      title="Test Title")
        plot.square('A', 'B', source=source)

        plot2 = ar_downsample.heatmap(plot, palette="Reds9", reserve_val=0, points=True, client_color=True, title="Test Title 2")
        source2 = self._find_source(plot2)

        self.assertEquals("Test Title 2", plot2.title)
        self.assertEquals(type(source2), ServerDataSource)

        transform = source2.transform
        self.assertEquals(type(transform['info']), ar_downsample.Const)
        self.assertEquals(type(transform['agg']), ar_downsample.Count)
        self.assertEquals(type(transform['shader']), ar_downsample.Seq)
        self.assertEquals(transform['shader'].out, "image")
Exemple #48
0
    def test_replot_property_transfer(self):
        self.assertIsNotNone(self.bokeh_server, "Server failed to start, cannot tests")
        ar_downsample._loadAR()
        output_server("Census")
        source = ServerDataSource(data_url="fn://bivariate", owner_username="******")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"

        plot = square('A', 'B', source=source, plot_width=plot_width, plot_height=plot_height, title=plot_title)
        ar_plot = ar_downsample.replot(plot)

        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width not transfered")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height not transfered")
        self.assertEquals(ar_plot.title, plot_title, "Plot title not transfered")

        plot_width = 612
        plot_height = 408
        plot_title = "Test title"
        ar_plot = ar_downsample.replot(plot, title=plot_title, plot_width=plot_width, plot_height=plot_height)
        self.assertEquals(ar_plot.plot_width, plot_width, "Plot width override failed")
        self.assertEquals(ar_plot.plot_height, plot_height, "Plot height override failed")
        self.assertEquals(ar_plot.title, plot_title, "Plot title override failed")
    def test_contour_recipe(self):
        ar_downsample._loadAR()
        reset_output()
        sess = Session(client=app.test_client())
        output_server('Census', session=sess)
        source = ServerDataSource(
            expr={'op': 'Field', 'args': [':leaf', 'bivariate']}
        )
        plot = figure(plot_width=600,
                      plot_height=400,
                      title="Test Title")
        plot.square('A', 'B', source=source)

        plot2 = ar_downsample.contours(plot, title="Contour")
        source2 = self._find_source(plot2)

        self.assertEquals("Contour", plot2.title)
        self.assertEquals(type(source2), ServerDataSource)

        transform = source2.transform
        self.assertEquals(type(transform['info']), ar_downsample.Const)
        self.assertEquals(type(transform['agg']), ar_downsample.Count)
        self.assertEquals(type(transform['shader']), ar_downsample.Seq)
        self.assertEquals(transform['shader'].out, "multi_line")
    def __init__(self, reporting_freq=False, plot_title='Neural Network Learning Curves', bokeh_output='server'):
        super(Callback, self).__init__()
        self.latest_epoch = -1
        self.latest_batch = -1
        self.batches = []
        self.train_losses = []
        self.approx_train_acc_in_latest_epoch = 0.
        self.val_losses = []
        self.latest_val_acc = None
        self.min_val_loss = inf
        self.best_model = None
        self.best_model_epoch = None
        self.best_model_train_acc = None
        self.best_model_val_acc = None
        self.reporting_freq = reporting_freq

        printflush('\nConnecting to Bokeh Server for live Learning Curves plotting...\n')
        try:
            output_server('')
            self.bokeh_session = cursession()
            self.fig = figure(title=plot_title,
                              x_axis_label='# of Training Data Batches', y_axis_label='Loss',
                              plot_height=680, plot_width=880)
            self.fig.line((), (), name='TrainLoss', legend='Training Loss')
            self.fig.circle((), (), name='ValidLoss', legend='Validation Loss', color='red')
            show(self.fig)
            self.train_losses_curve_data_source = self.fig.select(dict(name='TrainLoss'))[0].data_source
            self.valid_losses_curve_data_source = self.fig.select(dict(name='ValidLoss'))[0].data_source
            printflush('\nConnecting to Bokeh Server for live Learning Curves plotting... done!\n')
        except:
            printflush('\nBokeh Server Connection *FAILED!*')
            printflush('Please make sure Bokeh package is already installed in Python, and')
            printflush('please open a new Command-Line Terminal window\n   (separate from this Terminal window)')
            printflush('   and run the following command firs to launch Bokeh Server:')
            printflush('       bokeh-server --backend=memory\n')
            _exit(0)
Exemple #51
0
Generates synthetic pressure vs. time data and streams data to a plot
in a bokeh server. You should start bokeh-server on the local machine.

TODO: Replace synthetic data with data streaming from a .csv file from different sensors.
"""

import numpy as np
import bokeh.plotting as bk
from bokeh.objects import Glyph
import time

t = 0
time_x = np.array([0])
pres_y = np.array([20])

bk.output_server('Pressure')

bk.line(time_x, pres_y, color='#0000FF',
        tools='pan,wheel_zoom,box_zoom,reset,resize,crosshair,select,previewsave,embed',
        width=1200,height=300)
bk.xaxis()[0].axis_label = 'Time'
bk.yaxis()[0].axis_label = 'Pressure'

renderer = [r for r in bk.curplot().renderers if isinstance(r, Glyph)][0]
ds = renderer.data_source

while True:
    ds.data["x"] = time_x
    ds.data["y"] = pres_y
    ds._dirty = True
    bk.session().store_obj(ds)
Exemple #52
0
# The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
import numpy as np

from bokeh.plotting import figure, show, output_server

# Define Bollinger Bands.
upperband = np.random.random_integers(100, 150, size=100)
lowerband = upperband - 100
x_data = np.arange(1, 101)

# Bollinger shading glyph:
band_x = np.append(x_data, x_data[::-1])
band_y = np.append(lowerband, upperband[::-1])

output_server('bollinger')

p = figure(x_axis_type='datetime')
p.patch(band_x, band_y, color='#7570B3', fill_alpha=0.2)

p.title = 'Bollinger Bands'
p.plot_height = 600
p.plot_width = 800
p.grid.grid_line_alpha = 0.4

show(p)
Exemple #53
0
                   "XOM"]  # "KO", "GE","PG" , "VZ"]

datacoords = ColumnDataSource(data=dict(
    x=[], y1=[], y2=[], y3=[], names=['15 DAYS', '45 DAYS', '60 DAYS']))
polyline = ColumnDataSource(
    data=dict(a_x=[], b_x=[], a_y=[], b_y=[], m_x=[], m_y=[]))
stocksource = ColumnDataSource(data=dict(s_x=[], s_y=[]))
global New_Stock
global good_Stock
New_Stock = True
good_Stock = True
window_size = [30, 7]
step_size = [30, 3]
days = [100, 180]
# Start the output server session
output_server("Stock & Yield")
ticker1 = TextInput(value="IBM", title="Test Stock:", width=200)
ticker2 = TextInput(value="None", title="Current Yield:", width=5)
# set up plots
tools = 'pan,wheel_zoom,xbox_select,reset,click'
p1 = figure(plot_width=1200,
            plot_height=400,
            title="Yield vs Time in Days:",
            x_axis_label="Time in Days",
            y_axis_label="Yield",
            toolbar_location="above")
p1.xaxis.formatter = DatetimeTickFormatter(
    hours=["%d %B %Y"],
    days=["%d %B %Y"],
    months=["%d %B %Y"],
    years=["%d %B %Y"],
Exemple #54
0
def vbox(*children, **kwargs):
    """ Generate a plot that arranges several subplots vertically. """
    layout = VBox(children=list(children), **kwargs)
    _deduplicate_plots(layout, children)
    _push_or_save()
    return layout


N = 5000

x = np.random.normal(size=N) * 100
y = np.random.normal(size=N) * 100
all_inds = np.arange(len(x))

output_server("selection_histogram")

TOOLS = "pan,wheel_zoom,box_select,lasso_select"

# create the scatter plot
p = figure(tools=TOOLS,
           plot_width=600,
           plot_height=600,
           title=None,
           min_border=10,
           min_border_left=50)
p.scatter(x, y, size=3, color="#3A5785", alpha=0.6, name="scatter")

renderer = p.select(dict(name="scatter"))
scatter_ds = renderer[0].data_source
Exemple #55
0
# Go to http://localhost:5006/bokeh to view this plot

import numpy as np
from bokeh.plotting import figure, show, output_server
from bokeh.transforms import image_downsample
from blaze.server.client import Client
from blaze import Data

N = 1000

x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx) * np.cos(yy)

output_server("remote_image")

c = Client('http://localhost:5006')
d = Data(c)
source = image_downsample.source()
source.from_blaze(d.array, local=True)

plot = figure(
    x_range=[0, 10],
    y_range=[0, 10],
)
plot.image(source=source,
           image="image",
           x="x",
           y="y",
           dw="dw",