Beispiel #1
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()
Beispiel #2
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()
Beispiel #3
0
 def _make_figures(self,ep,trainerr,metvals):
     self._datasources = []
     figures = []
     fig = figure(title='Total Training Cost',x_axis_label='Epoch',y_axis_label='Cost')
     fig.line([ep],[trainerr],name='plot')
     ds = fig.select(dict(name='plot'))[0].data_source
     self._datasources.append(ds)
     if self._plotmetricmean:
         figures.append(fig)
         fig = figure(title='Metric Mean',x_axis_label='Epoch',y_axis_label='Mean')
         fig.line([ep],[np.nanmean(metvals)],name='plot')
         ds = fig.select(dict(name='plot'))[0].data_source
         self._datasources.append(ds)
         figures.append(fig)
     for mv,(mk,m) in zip(metvals,self.metrics):
         if m.metric in xnn.metrics.metric_names:
             name = xnn.metrics.metric_names[m.metric]
         else:
             name = m.metric.__name__
         fig = figure(title=mk,x_axis_label='Epoch',y_axis_label=name)
         fig.line([ep],[mv],name='plot')
         ds = fig.select(dict(name='plot'))[0].data_source
         self._datasources.append(ds)
         figures.append(fig)
     allfigs = vplot(*figures)
     push()
Beispiel #4
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()
Beispiel #5
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
Beispiel #6
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()
Beispiel #7
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()
Beispiel #8
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()
Beispiel #9
0
 def run(self):
     while True:
         priority, obj = self.queue.get()
         if priority == PushThread.PUT:
             cursession().store_objects(obj)
         elif priority == PushThread.PUSH:
             push()
             # delete queued objects when training has finished
             if obj == "after_training":
                 with self.queue.mutex:
                     del self.queue.queue[:]
                 break
         self.queue.task_done()
Beispiel #10
0
 def run(self):
     while True:
         priority, obj = self.queue.get()
         if priority == PushThread.PUT:
             cursession().store_objects(obj)
         elif priority == PushThread.PUSH:
             push()
             # delete queued objects when training has finished
             if obj == "after_training":
                 with self.queue.mutex:
                     del self.queue.queue[:]
                 break
         self.queue.task_done()
Beispiel #11
0
 def on_epoch_end(self, epoch, logs={}):
     I = self.get_image()
     if not hasattr(self, 'fig'):
         self.fig = figure(title=self.fig_title,
                           x_range=[0, 1], y_range=[0, 1])
         self.fig.image(image=[I], x=[0], y=[0], dw=[1], dh=[1],
                        name='weight')
         renderer = self.fig.select({'name': 'weight'})
         self.plots.append(renderer[0].data_source)
         show(self.fig)
     else:
         self.plots[0].data['image'] = [I]
     cursession().store_objects(self.plots[0])
     push()
Beispiel #12
0
    def update_plots(self, epoch, monitors):
        """
        Given the calculated monitors (collapsed name and value tuple), add its datapoint to the appropriate figure
        and update the figure in bokeh-server.

        Parameters
        ----------
        epoch : int
            The epoch (x-axis value in the figure).
        monitors : dict
            The dictionary of monitors calculated at this epoch. The dictionary is of the form
            {collapsed_monitor_name: value}. The name is the same that was used in the creation of the
            figures in the plot, so it is used as the key to finding the appropriate figure to add the
            data.
        """
        if BOKEH_AVAILABLE:
            for key, value in monitors.items():
                if key in self.figure_indices:
                    if key not in self.plots:
                        # grab the correct figure by its index for the key (same with the color)
                        fig = self.figures[self.figure_indices[key]]
                        color_idx = self.figure_color_indices[
                            self.figure_indices[key]]
                        # split the channel from the monitor name
                        name = key.split(COLLAPSE_SEPARATOR, 1)
                        if len(name) > 1:
                            name = name[1]
                        else:
                            name = name[0]
                        # create a new line
                        fig.line([epoch], [value],
                                 legend=name,
                                 x_axis_label='iterations',
                                 y_axis_label='value',
                                 name=name,
                                 line_color=self.colors[color_idx %
                                                        len(self.colors)])
                        color_idx += 1
                        # set the color index back in the figure list
                        self.figure_color_indices[
                            self.figure_indices[key]] = color_idx
                        # grab the render object and put it in the plots dictionary
                        renderer = fig.select(dict(name=name))
                        self.plots[key] = renderer[0].data_source
                    else:
                        self.plots[key].data['x'].append(epoch)
                        self.plots[key].data['y'].append(value)
                        cursession().store_objects(self.plots[key])
            push()
Beispiel #13
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()
Beispiel #14
0
    def do(self, which_callback, *args):
        log = self.main_loop.log
        iteration = log.status["iterations_done"]
        i = 0
        for key, value in log.current_row.items():
            if key in self.p_indices:
                if key not in self.plots:
                    fig = self.p[self.p_indices[key]]
                    fig.line([iteration], [value], legend=key, name=key, line_color=self.colors[i % len(self.colors)])
                    i += 1
                    renderer = fig.select(dict(name=key))
                    self.plots[key] = renderer[0].data_source
                else:
                    self.plots[key].data["x"].append(iteration)
                    self.plots[key].data["y"].append(value)

                    cursession().store_objects(self.plots[key])
        push()
Beispiel #15
0
    def update_plots(self, epoch, monitors):
        """
        Given the calculated monitors (collapsed name and value tuple), add its datapoint to the appropriate figure
        and update the figure in bokeh-server.

        Parameters
        ----------
        epoch : int
            The epoch (x-axis value in the figure).
        monitors : dict
            The dictionary of monitors calculated at this epoch. The dictionary is of the form
            {collapsed_monitor_name: value}. The name is the same that was used in the creation of the
            figures in the plot, so it is used as the key to finding the appropriate figure to add the
            data.
        """
        if BOKEH_AVAILABLE:
            for key, value in monitors.items():
                if key in self.figure_indices:
                    if key not in self.plots:
                        # grab the correct figure by its index for the key (same with the color)
                        fig = self.figures[self.figure_indices[key]]
                        color_idx = self.figure_color_indices[self.figure_indices[key]]
                        # split the channel from the monitor name
                        name = key.split(COLLAPSE_SEPARATOR, 1)
                        if len(name) > 1:
                            name = name[1]
                        else:
                            name = name[0]
                        # create a new line
                        fig.line([epoch], [value], legend=name,
                                 x_axis_label='iterations',
                                 y_axis_label='value', name=name,
                                 line_color=self.colors[color_idx % len(self.colors)])
                        color_idx += 1
                        # set the color index back in the figure list
                        self.figure_color_indices[self.figure_indices[key]] = color_idx
                        # grab the render object and put it in the plots dictionary
                        renderer = fig.select(dict(name=name))
                        self.plots[key] = renderer[0].data_source
                    else:
                        self.plots[key].data['x'].append(epoch)
                        self.plots[key].data['y'].append(value)
                        cursession().store_objects(self.plots[key])
            push()
Beispiel #16
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
Beispiel #17
0
    def do(self, which_callback, *args):
        log = self.main_loop.log
        iteration = log.status['iterations_done']
        i = 0
        for key, value in log.current_row.items():
            if key in self.p_indices:
                if key not in self.plots:
                    fig = self.p[self.p_indices[key]]
                    fig.line([iteration], [value], legend=key,
                             x_axis_label='iterations',
                             y_axis_label='value', name=key,
                             line_color=self.colors[i % len(self.colors)])
                    i += 1
                    renderer = fig.select(dict(name=key))
                    self.plots[key] = renderer[0].data_source
                else:
                    self.plots[key].data['x'].append(iteration)
                    self.plots[key].data['y'].append(value)

                    cursession().store_objects(self.plots[key])
        push()
Beispiel #18
0
 def on_epoch_end(self, epoch, logs={}):
     if not hasattr(self, 'fig'):
         self.fig = figure(title=self.fig_title)
         for i, v in enumerate(['loss', 'val_loss']):
             if v == 'loss':
                 L = self.totals[v] / self.seen
             else:
                 L = logs.get(v)
             self.fig.line([epoch], [L], legend=v,
                           name=v, line_width=2,
                           line_color=self.colors[i % len(self.colors)])
             renderer = self.fig.select({'name': v})
             self.plots.append(renderer[0].data_source)
         show(self.fig)
     else:
         for i, v in enumerate(['loss', 'val_loss']):
             if v == 'loss':
                 L = self.totals[v] / self.seen
             else:
                 L = logs.get(v)
             self.plots[i].data['y'].append(L)
             self.plots[i].data['x'].append(epoch)
     cursession().store_objects(self.plots[i])
     push()
Beispiel #19
0
 #risale alla id univoca del graph
 idkey = name + " (" + gtype + ")"
 
 if idkey in gobjs: #se il graph già esiste
     #recupera graph e lo aggiorna con data
     g = gobjs[idkey]
     g.update(data)
     #aggiorna documento relativo a graph, passandone le info a bokeh-server
     s.use_doc("%s" %idkey) 
     s.store_document(gdocs["%s" %idkey])
     #salva graph aggiornato in dizionario
     gobjs[idkey] = g
     
 else:  #se il graph non esiste     
     #crea un nuovo graph
     g = gtypes[gtype](idkey)
     g.update(data)
     #crea un nuovo documento
     d = Document()
     gdocs["%s" %idkey] = d
     d.add(g.get_plot())
     #passa le info del documento a bokeh-server
     s.use_doc("%s" %idkey) 
     s.load_document(d)
     push(s, d)
     show(g.get_plot()) 
     #crea nuovi ingressi in dizionari in dizionari
     gobjs[idkey] = g
     gurls.set(idkey, s.object_link(g.get_plot()))
     
 #qui metti controllo su properties
Beispiel #20
0
def run_chart(exchange, asset, limit):
    client = pymongo.MongoClient()
    db = client['bitpredict_' + exchange]
    collection = db[asset_ + '_predictions']

    def get_data():
        cursor = collection.find().limit(limit).sort('_id', pymongo.DESCENDING)
        data = pd.DataFrame(list(cursor))
        data = data.set_index('_id')
        data = data.sort_index(ascending=True)
        timestamps = pd.to_datetime(data.index, unit='s').to_series()
        prices = data.price
        predictions = data.prediction * 10000
        returns = (data.position * data.change).cumsum() * 10000
        return timestamps, prices, predictions, returns

    timestamps, prices, predictions, returns = get_data()
    output_server('bitpredict_' + exchange + '_extended')

    background = '#f2f2f2'
    ylabel_standoff = 0
    xformatter = DatetimeTickFormatter(formats=dict(hours=["%H:%M"]))
    yformatter = PrintfTickFormatter(format="%8.1f")
    p1 = figure(title=None,
                plot_width=750,
                plot_height=300,
                x_axis_type='datetime',
                min_border_top=10,
                min_border_bottom=33,
                background_fill=background,
                tools='',
                toolbar_location=None)
    p1.line(x=timestamps,
            y=prices,
            name='prices',
            color='#4271ae',
            line_width=1,
            legend='Bitcoin Bid/Ask Midpoint',
            line_cap='round',
            line_join='round')
    p1.legend.orientation = 'top_left'
    p1.legend.border_line_color = background
    p1.outline_line_color = None
    p1.xgrid.grid_line_color = 'white'
    p1.ygrid.grid_line_color = 'white'
    p1.axis.axis_line_color = None
    p1.axis.major_tick_line_color = None
    p1.axis.minor_tick_line_color = None
    p1.yaxis.axis_label = 'Price'
    p1.yaxis.axis_label_standoff = ylabel_standoff
    p1.xaxis.formatter = xformatter
    p1.yaxis.formatter = PrintfTickFormatter(format='%8.2f')
    p1.yaxis.major_label_text_font = 'courier'
    p1.xaxis.major_label_text_font = 'courier'

    p2 = figure(title=None,
                plot_width=750,
                plot_height=295,
                x_axis_type='datetime',
                min_border_top=5,
                min_border_bottom=33,
                background_fill=background,
                tools='',
                toolbar_location=None)
    p2.line(x=timestamps,
            y=predictions,
            name='predictions',
            color='#c82829',
            line_width=1,
            legend='30 Second Prediction',
            line_cap='round',
            line_join='round')
    p2.legend.orientation = 'top_left'
    p2.legend.border_line_color = background
    p2.outline_line_color = None
    p2.xgrid.grid_line_color = 'white'
    p2.ygrid.grid_line_color = 'white'
    p2.axis.axis_line_color = None
    p2.axis.major_tick_line_color = None
    p2.axis.minor_tick_line_color = None
    p2.yaxis.axis_label = 'Basis Points'
    p2.yaxis.axis_label_standoff = ylabel_standoff
    p2.xaxis.formatter = xformatter
    p2.yaxis.formatter = yformatter
    p2.yaxis.major_label_text_font = 'courier'
    p2.xaxis.major_label_text_font = 'courier'
    p2.x_range = p1.x_range

    p3 = figure(title=None,
                plot_width=750,
                plot_height=320,
                x_axis_type='datetime',
                min_border_top=5,
                min_border_bottom=10,
                background_fill=background,
                x_axis_label='Greenwich Mean Time',
                tools='',
                toolbar_location=None)
    p3.line(x=timestamps,
            y=returns,
            name='returns',
            color='#8959a8',
            line_width=1,
            legend='Cumulative Return',
            line_cap='round',
            line_join='round')
    p3.legend.orientation = 'top_left'
    p3.legend.border_line_color = background
    p3.outline_line_color = None
    p3.xgrid.grid_line_color = 'white'
    p3.ygrid.grid_line_color = 'white'
    p3.axis.axis_line_color = None
    p3.axis.major_tick_line_color = None
    p3.axis.minor_tick_line_color = None
    p3.yaxis.axis_label = 'Basis Points'
    p3.yaxis.axis_label_standoff = ylabel_standoff
    p3.xaxis.formatter = xformatter
    p3.yaxis.formatter = yformatter
    p3.xaxis.axis_label_standoff = 12
    p3.yaxis.major_label_text_font = 'courier'
    p3.xaxis.major_label_text_font = 'courier'
    p3.x_range = p1.x_range

    vp = vplot(p1, p2, p3)
    push()
    ip = load(urlopen('http://jsonip.com'))['ip']
    ssn = cursession()
    ssn.publish()
    embed.autoload_server(vp, ssn, public=True)

    renderer = p1.select(dict(name='prices'))
    ds_prices = renderer[0].data_source
    renderer = p2.select(dict(name='predictions'))
    ds_predictions = renderer[0].data_source
    renderer = p3.select(dict(name='returns'))
    ds_returns = renderer[0].data_source

    while True:
        timestamps, prices, predictions, returns = get_data(exchange, limit)
        ds_prices.data['x'] = timestamps
        ds_predictions.data['x'] = timestamps
        ds_returns.data['x'] = timestamps
        ds_prices.data['y'] = prices
        ds_predictions.data['y'] = predictions
        ds_returns.data['y'] = returns
        ssn.store_objects(ds_prices)
        ssn.store_objects(ds_predictions)
        ssn.store_objects(ds_returns)
        time.sleep(60)
Beispiel #21
0
    def do(self, which_callback, *args):
        for plotter in self.plotters:
            plotter.call()

        push()
Beispiel #22
0
    def do(self, which_callback, *args):
        for plotter in self.plotters:
            plotter.call()

        push()
def run_chart(exchange, asset, limit):
    client = pymongo.MongoClient()
    db = client['bitpredict_'+exchange]
    collection = db[asset_+'_predictions']

    def get_data():
        if (limit)
            cursor = collection.find()
        else
            cursor = collection.find().limit(limit)
        data = pd.DataFrame(list(cursor))
        data = data.set_index('_id')
        data = data.sort_index(ascending=True)
        timestamps = pd.to_datetime(data.index, unit='s').to_series()
        returns = data.returns.cumsum()*100
        return timestamps, returns

    timestamps, returns = get_data()
    output_server('bitpredict_'+exchange+'_performance')

    background = '#f2f2f2'
    ylabel_standoff = 0
    xformatter = DatetimeTickFormatter(formats=dict(hours=["%H:%M"]))
    yformatter = PrintfTickFormatter(format="%8.1f")
    p = figure(title=None,
                plot_width=750,
                plot_height=500,
                x_axis_type='datetime',
                min_border_top=5,
                min_border_bottom=10,
                background_fill=background,
                x_axis_label='Date',
                tools='',
                toolbar_location=None)
    p.line(x=timestamps,
            y=returns,
            name='returns',
            color='#8959a8',
            line_width=1,
            legend='Cumulative Return',
            line_cap='round',
            line_join='round')
    p.legend.orientation = 'top_left'
    p.legend.border_line_color = background
    p.outline_line_color = None
    p.xgrid.grid_line_color = 'white'
    p.ygrid.grid_line_color = 'white'
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.minor_tick_line_color = None
    p.yaxis.axis_label = 'Percent'
    p.yaxis.axis_label_standoff = ylabel_standoff
    p.xaxis.formatter = xformatter
    p.yaxis.formatter = yformatter
    p.xaxis.axis_label_standoff = 12
    p.yaxis.major_label_text_font = 'courier'
    p.xaxis.major_label_text_font = 'courier'

    push()
    ip = load(urlopen('http://jsonip.com'))['ip']
    ssn = cursession()
    ssn.publish()
    tag = embed.autoload_server(p, ssn, public=True)
    renderer = p.select(dict(name='returns'))
    ds_returns = renderer[0].data_source

    while True:
        timestamps, returns = get_data()
        ds_returns.data['x'] = timestamps
        ds_returns.data['y'] = returns
        ssn.store_objects(ds_returns)
        time.sleep(300)
Beispiel #24
0
p.legend.border_line_color = background
p.outline_line_color = None
p.xgrid.grid_line_color = 'white'
p.ygrid.grid_line_color = 'white'
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.minor_tick_line_color = None
p.yaxis.axis_label = 'Percent'
p.yaxis.axis_label_standoff = ylabel_standoff
p.xaxis.formatter = xformatter
p.yaxis.formatter = yformatter
p.xaxis.axis_label_standoff = 12
p.yaxis.major_label_text_font = 'courier'
p.xaxis.major_label_text_font = 'courier'

push()
ip = load(urlopen('http://jsonip.com'))['ip']
ssn = cursession()
ssn.publish()
tag = embed.autoload_server(p, ssn, public=True).replace('localhost', ip)
html = """
{%% extends "layout.html" %%}
{%% block bokeh %%}
%s
{%% endblock %%}
""" % tag

with open('templates/performance.html', 'w+') as f:
    f.write(html)

renderer = p.select(dict(name='returns'))
Beispiel #25
0
def plot_bokeh(symulacja, normalized_types = False, types_to_plot = None, type_labels = None, ligand_labels = None,uniq_id="no-id"):
    from bokeh.plotting import figure, VBox, output_server, cursession, push, Session
    from bokeh.models import Range1d
    from bokeh.document import Document

    pops = symulacja[0]
    ligands = symulacja[1]
    types = symulacja[2]

    if types_to_plot == None:
        types_to_plot = types.keys()

    if type_labels == None:
        type_labels = dict([])
        for k in types.keys():
           type_labels[k] = k

    if ligand_labels == None:
        ligand_labels = dict([])
        for k in ligands.keys():
            ligand_labels[k] = k

    output_server("stops1"+uniq_id)

    len_pops = len(pops)
    step_axis = range(len_pops)

    TOOLS="resize,pan,wheel_zoom,box_zoom,reset,previewsave,poly_select"

    xrange1 = Range1d(start=0, end=len_pops-1)

    if normalized_types:
        #dwa wykresy - rozmiar populacji i procent komorek
        fig1 = figure(title="Population size",width=800, height=332,tools=TOOLS,x_range=xrange1)
        fig1.line(step_axis,pops,line_color = "blue",line_width=2,line_alpha=0.9)

        fig2 = figure(title="% of cells of specific types in the population",width=724,height=300,tools=TOOLS,x_range=xrange1)

        for k, v in types.items():
            if k in types_to_plot:
                norm_sizes = [(float(v[i]) / pops[i] * 100) for i in range(len(pops))]
                color = lambda: random.randint(0,255)
                rcolor = ('#%02X%02X%02X' % (color(),color(),color()))
                fig2.line(step_axis, norm_sizes, line_width=2, line_color = rcolor, legend=type_labels[k])

        fig2.legend.orientation = "top_right"
    else:
        fig1 = figure(title="Population / type size",width=724,height=300,tools=TOOLS,x_range=xrange1)

        for k, v in types.items():
            if k in types_to_plot:
                color = lambda: random.randint(0,255)
                rcolor = ('#%02X%02X%02X' % (color(),color(),color()))
                fig1.line(step_axis, v, line_width = 2, line_color=rcolor, legend = type_labels[k])

        fig1.legend.orientation = "top_right"

        fig1.line(step_axis, pops, line_width = 2.0, line_color = "blue", legend = "population size")

    fig3 = figure(title="Ligands",width=724,height=300,tools=TOOLS,x_range=xrange1)

    for k, v in ligands.items():
        color = lambda: random.randint(0,255)
        rcolor = ('#%02X%02X%02X' % (color(),color(),color()))
        fig3.line(step_axis, v, line_width = 3, line_color = rcolor, legend = ligand_labels[k])

    fig3.legend.orientation = "top_right"

    push()

    if normalized_types:
        p = VBox(fig1,fig2,fig3)
    else:
        p = VBox(fig1,fig3)

    session=cursession()
    return p,session