Beispiel #1
0
 def update_plot(timeRangeStart, timeRangeEnd, timeRangeStartFrame,
                 timeRangeEndFrame):
     # This funtion updates the plot after a change in the time selector widget
     #
     # @param: timeRangeStart Begin of time range in seconds
     # @param: timeRangeEnd End of time range in seconds
     # @param: timeRangeStartFrame Begin of time range in frames
     # @param: timeRangeEndFrame End of time range in frames
     #
     timeRangeStartLine.data_source.data['x'] = [
         timeRangeStart, timeRangeStart
     ]
     timeRangeEndLine.data_source.data['x'] = [timeRangeEnd, timeRangeEnd]
     timeRangeStartFill.data_source.data['x'] = [
         0, timeRangeStart, timeRangeStart, 0
     ]
     timeRangeEndFill.data_source.data['x'] = [
         timeRangeEnd, dt_snd[-1], dt_snd[-1], timeRangeEnd
     ]
     formantScatterPlot.data_source.data = {
         'x': F2[timeRangeStartFrame:timeRangeEndFrame],
         'y': F1[timeRangeStartFrame:timeRangeEndFrame]
     }
     if lineSwitch:
         formantLinePlot.data_source.data = {
             'x': F2[timeRangeStartFrame:timeRangeEndFrame],
             'y': F1[timeRangeStartFrame:timeRangeEndFrame]
         }
     push_notebook()
Beispiel #2
0
    def distribution_visualizer(data: dict,
                                title: str = None,
                                x_axis: str = None,
                                y_axis: str = None):
        """

        :param data:
        :param title:
        :param x_axis:
        :param y_axis:
        """
        entities = list(data.keys())
        value = list(data.values())

        hover = HoverTool(tooltips=[
            ("Entities", "@entities"),
            ("Counts", "$value"),
        ])

        p = figure(x_range=entities,
                   plot_height=300,
                   title=title,
                   toolbar_location='above',
                   tools=[hover])

        p.vbar(x=entities, top=value, width=0.9)

        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None

        t = show(p, notebook_handle=True)

        push_notebook(t)
Beispiel #3
0
    def update_in(x_min=x_min_df, x_interval=default_interval):
        nonlocal df1

        if df1.index[0] > x_min or df1.index[-1] < x_min + x_interval:
            if isinstance(df, pd.DataFrame):
                df1 = df[((x_min - max_time / 2) < df.index)
                         & (df.index < (x_min + max_time / 2))]
            else:
                df1 = load_continuous_tsd(
                    df,
                    t_min=tu.format_timestamps(x_min - max_time / 2,
                                               units=units),
                    t_max=tu.format_timestamps(x_min + max_time / 2,
                                               units=units),
                    downsample=downsample).as_units(units)
            t = df1.index
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                for ix, x in enumerate(df1.columns):
                    lines[ix].data_source.data['t'] = t
                    lines[ix].data_source.data[x] = df1[x] + spread_vec[ix]
            push_notebook()
        plot.x_range.start = x_min
        plot.x_range.end = x_min + x_interval
        push_notebook()
Beispiel #4
0
Datei: ui.py Projekt: andyhyh/ray
        def update_plot(abs_earliest, abs_latest, abs_num_tasks, tasks):
            num_buckets = 100
            left, right, top = compute_utilizations(abs_earliest, abs_latest,
                                                    abs_num_tasks, tasks,
                                                    num_buckets)

            time_series_source.data = {
                "left": left,
                "right": right,
                "top": top
            }

            x_range = (max(0, min(left)) if len(left) else 0,
                       max(right) if len(right) else 1)
            y_range = (0, max(top) + 1 if len(top) else 1)

            # Define the axis ranges
            x_range = helpers._get_range(x_range)
            time_series_fig.x_range.start = x_range.start
            time_series_fig.x_range.end = x_range.end

            y_range = helpers._get_range(y_range)
            time_series_fig.y_range.start = y_range.start
            time_series_fig.y_range.end = num_cpus

            # Push the updated data to the notebook
            push_notebook(handle=handle)
Beispiel #5
0
   def drawToPlot(self):
      fi = self.detector.parameters['freqrange'][0]
      ff = self.detector.parameters['freqrange'][1]
      self.scorecalculator.SetFreqRange(fi, ff)
      x, y, names = self.scorecalculator.GetNoiseCurves()
      for i, yi in enumerate(y):
         # TODO: fix this, adf 14.02.2018
         # the following is a workaround for a Bokeh bug which
         # causes lines to not be clipped at the X/Y limits
         # See: https://github.com/bokeh/bokeh/issues/6787
         yi=np.array(yi)
         x=np.array(x)
         idxs = np.nonzero((yi<=self.yHi) & (yi>=self.yLo))[0]

         if names[i] not in self.names:
            self.colours[names[i]] = palettelight[i]
            self.lines[names[i]] = self.plot.line(x[idxs], yi[idxs], color=palettelight[i], \
                                                  line_width=10)
            label = Label(x=x[int(len(x)/2)], y=yi[int(len(yi)/2)],
                          text=names[i], x_offset=7, y_offset=3, level='glyph', \
                          render_mode='canvas', text_color=palettelight[i], \
                          text_font_size='8pt')
            self.plot.add_layout(label)
         else:
            self.lines[names[i]].data_source.data['x'] = x[idxs]
            self.lines[names[i]].data_source.data['y'] = yi[idxs]
      for nm in self.names:
         if nm not in names:
            self.lines[nm].data_source.data['x'] = x
            self.lines[nm].data_source.data['y'] = [0] * len(x)

      self.budget.value = self.budgetMsg()
      push_notebook()
Beispiel #6
0
        def run_clustering(*args):
            method = self.w.clu_method.value
            stats, trans = run_dr_2()

            if method == 'dbscan':
                labels = run_dbscan(trans, self.w.clu_dbscan_eps.value)
            else:
                lg.warning('Not implemented cluster method: {}'.format(method))
                return

            self.thelenota._CLUSTER_LABELS[self.dr_name()] = labels
            colv = labels
            color_mapper = CategoricalColorMapper(
                palette=bokeh.palettes.Category20[20],
                factors=list(colv.value_counts().index))
            colorbar_mapper = LinearColorMapper(palette='Inferno256',
                                                low=0,
                                                high=0)
            bcolorbar.color_mapper = colorbar_mapper
            if not bfigure.legend[0].items:
                bfigure.legend[0].items.append(blegend)
            bplot.data_source.data['score'] = colv
            bplot.glyph.fill_color['transform'] = color_mapper
            bplot.glyph.line_width = 0
            bplot.glyph.line_alpha = 0
            bokeh_io.push_notebook(handle=bhandle)
Beispiel #7
0
def plot_line_separate(genfn, source, handle):
    "Time a generator while plotting result, using a separate generator for each point"
    # Generate first 1000 primes to warm up the code first
    list(islice(genfn(approx_nth(1000)), 999, 1000))[0]
    for r in range(_repeats):
        for n, i in enumerate(iterations()):
            def timed():
                return list(islice(genfn(approx_nth(i)), i - 1, i))[0]
            t = timeit(timed, number=1, globals=globals()) - _overhead
            if r == 0:
                # First time, stream every measurememt to the plot
                source.stream(dict(x=[i], y=[t]))
            else:
                # Then patch in any lower measurements
                if t < source.data['y'][n]:
                    source.patch(dict(x=[(n, i)], y=[(n, t)]))
            if handle:
                push_notebook(handle=handle)
            if r == 0:
                # First time through keep going until just over 1 second elapsed
                # with a slight buffer in case following measurements bring it down
                if t >= 1.2:
                    break
            else:
                # On following passes remeasure each existing point
                if n >= len(source.data['x']) - 1:
                    break
Beispiel #8
0
    def task_completion_time_update(abs_earliest,
                                    abs_latest,
                                    abs_num_tasks,
                                    tasks):
        if len(tasks) == 0:
            return

        # Create the distribution to plot
        distr = []
        for task_id, data in tasks.items():
            distr.append(data["store_outputs_end"] -
                         data["get_arguments_start"])

        # Create a histogram from the distribution
        top, bin_edges = np.histogram(distr, bins="auto")
        left = bin_edges[:-1]
        right = bin_edges[1:]

        source.data = {"top": top, "left": left, "right": right}

        # Set the x and y ranges
        x_range = (min(left) if len(left) else 0,
                   max(right) if len(right) else 1)
        y_range = (0, max(top) + 1 if len(top) else 1)

        x_range = helpers._get_range(x_range)
        p.x_range.start = x_range.start
        p.x_range.end = x_range.end

        y_range = helpers._get_range(y_range)
        p.y_range.start = y_range.start
        p.y_range.end = y_range.end

        # Push updates to the plot
        push_notebook(handle=handle)
Beispiel #9
0
        def _create_scatter_plot(only_color=False):
            if (self.w.drfilter_lower_perc_switch.value) or (
                    self.w.drfilter_log_switch.value):
                self.counts = filter_counts()
            else:
                self.counts = self.thelenota.counttable

            self.warn("count table: {}".format(str(self.counts.shape)))

            if not only_color:
                meta, trans = run_dr_2()
                self.thelenota.dr = trans

                self.thelenota._dr_meta = meta
                self.thelenota._dr_trans = trans
                col1, col2 = trans.columns[:2]
                d1 = trans[col1]
                d2 = trans[col2]
                title = self.dr_name().replace('_', ' ')

                m = max(d2.max() - d2.min(), d1.max() - d1.min())
                bplot.data_source.data['size'] = [0.008 * m] * nosamples
                bplot.data_source.data['x'] = d1
                bplot.data_source.data['y'] = d2

            bfigure.title.text = _create_title()
            set_color_scale()
            bokeh_io.push_notebook(handle=bhandle)
Beispiel #10
0
 def _update_plot(self):
     self.ds.data['x'] = self.data_frame['iteration']
     self.ds.data['y'] = self.data_frame['fitness']
     self.ds.data['fill_color'] = self.data_frame['color']
     self.ds.data['line_color'] = self.data_frame['color']
     self.ds._dirty = True
     push_notebook()
    def _update(self, ispec=None):
        '''Update the data and plots for target number ispec

        If ispec is None, use self.ispec; otherwise set self.ispec = ispec
        '''
        if ispec is not None:
            self.ispec = ispec

        self._update_data()
        if not self._plotted:
            return

        self._update_xylim()
        self._update_lines()

        zb = self.zbest[self.izbest]
        try:
            title = '{0} z={1:.4f} zwarn={2}'.format(zb['SPECTYPE'].strip(),
                                                     zb['Z'], zb['ZWARN'])
        except KeyError:
            title = '{0} ({1}) z={2:.4f} zwarn={3}'.format(
                zb['CLASS'].strip(), zb['SUBCLASS'].strip(), zb['Z'],
                zb['ZWARNING'])
        self.specplot.title.text = title

        self._update_info_div()
        self._update_cutout()

        push_notebook(handle=self.plot_handle)
Beispiel #12
0
def notebook_plot(x_key, y_keys, **kwargs):
    r"""Live plot log entries in the current notebook.

    Parameters
    ----------
    x_key : str
        The key in the serialized JSON object that contains the x-axis
        value.
    y_key : list of str
        See `x_key`.
    \*\*kwargs
        Connection parameters passed to the `connect` function.

    """
    subscriber, sequence, x, y = get_socket(x_key, y_keys, **kwargs)
    output_notebook()

    fig = figure()
    plot = fig.line(x, y)

    handle = show(fig, notebook_handle=True)
    push_notebook(handle=handle)

    while True:
        update(x_key, y_keys, sequence, subscriber, plot)
        push_notebook(handle=handle)
Beispiel #13
0
    def update_spct(channel=DEFAULT_TICKERS[0], f=10, numbins=20):
        channel = int(channel.split('_')[1])
        plot_chan = int(channel)
        plot_freq = np.where(sc.f_axis == f)[0][0]
        y, x = np.histogram(abs(sc.spg[plot_chan, plot_freq, :])**2,
                            bins=numbins,
                            density=True)

        # create a column data source for the plots to share
        data_source = {
            'freq_vals': sc.f_axis[1:],
            'psd_vals': sc.psd[plot_chan].T[1:],
            'scv_vals': sc.scv[plot_chan].T[1:]
        }
        source.data = data_source
        vline_psd.location = f
        vline_scv.location = f
        # update histogram with data from frequency f
        hist_plot.data_source.data['left'] = x[:-1]
        hist_plot.data_source.data['right'] = x[1:]
        hist_plot.data_source.data['top'] = y
        # update fitted
        rv = expon(scale=sp.stats.expon.fit(abs(sc.spg[plot_chan,
                                                       plot_freq, :])**2,
                                            floc=0)[1])
        fit_plot.data_source.data['x'] = x
        fit_plot.data_source.data['y'] = rv.pdf(x)

        # update complex data
        complex_source.data['real_vals'] = sc.spg.real[plot_chan][f]
        complex_source.data['imag_vals'] = sc.spg.imag[plot_chan][f]

        hist_fig.title.text = 'Freq = %.1fHz, p-value = %.4f' % (
            f, sc.ks_pvals[int(plot_chan), f])
        push_notebook()
Beispiel #14
0
def show_manhattan_plot(df, group_by, x_axis, y_axis):
    chroms = df[group_by].unique().to_array()

    manhattan_fig = figure()

    start_position = -0.5
    for chrom in chroms:
        query = '%s == %s' % (group_by, chrom)
        cdf = df.query(query)

        x_array = cupy.fromDlpack(cdf[x_axis].to_dlpack()) + start_position
        y_array = cupy.fromDlpack(cdf[y_axis].to_dlpack())

        manhattan_fig.circle(x_array.get(),
                             y_array.get(),
                             size=2,
                             color='orange' if
                             (start_position - 0.5) % 2 == 0 else 'gray',
                             alpha=0.5)

        start_position += 1

    manhattan_handle = show(manhattan_fig, notebook_handle=True)
    push_notebook(handle=manhattan_handle)
    return manhattan_fig
Beispiel #15
0
def image_update(Qdata, fig, Nrep, Nplot, stop_flag):
    renderer = fig.select(dict(name='echos', type=GlyphRenderer))
    source = renderer[0].data_source
    img = source.data['image'][0]

    while (not stop_flag.is_set()):
        new_line = Qdata.get()
        #new_line = np.uint8(new_line/np.max(new_line)*255)

        if new_line is "EOT":
            break

        #print(np.percentile(new_line,99))
        #print(np.max(new_line))
        # Normalize to some percentile instead of max, prevent divide by 0 and apply gamma to help see dim peaks
        new_line = np.minimum(
            new_line / np.maximum(np.percentile(new_line, 97), 1e-5),
            1)**(1 / 1.8)
        img = np.roll(img, 1, 0)
        view = img.view(dtype=np.uint8).reshape((Nrep, Nplot, 4))
        view[0, :, :] = cm.jet(new_line) * 255

        source.data['image'] = [img]
        push_notebook()
        Qdata.queue.clear()
def plot_ssl_wrapper_at_idx(idx):
    ssl_wrapper_plotter.plot_ssl_wrapper(wrapper_proto_log[idx])

    field_length = wrapper_proto_log[idx].geometry.field.field_length / MM_PER_M
    field_width = wrapper_proto_log[idx].geometry.field.field_width / MM_PER_M

    the_world = world.World(wrapper_proto_log[idx].SerializeToString(),
                            dict(friendly_color_yellow=True))

    pass_dict = {
        "receiver_point": world.Point(-3, 2.5),
        "pass_speed": 3,
    }

    def ratePassEnemyRiskCost(x, y):
        pass_dict["passer_point"] = world.Point(x, y)
        return passing.ratePassEnemyRisk(the_world, pass_dict, config)

    def keepAwayCost(x, y):
        pass_dict["passer_point"] = world.Point(x, y)
        return keep_away.ratePasserPointForKeepAway(the_world, pass_dict)

    enemy_risk_heatmap.plot_heatmap(ratePassEnemyRiskCost)
    keep_away_heatmap.plot_heatmap(keepAwayCost)

    plotter.plot_points(
        [keep_away.findKeepAwayTargetPosition(the_world, pass_dict)])

    push_notebook()
Beispiel #17
0
 def _update_plot(self):
     self.ds.data['x'] = self.data_frame['iteration']
     self.ds.data['y'] = self.data_frame['fitness']
     self.ds.data['fill_color'] = self.data_frame['color']
     self.ds.data['line_color'] = self.data_frame['color']
     self.ds._dirty = True
     push_notebook(handle=self.handle)
Beispiel #18
0
def show_candlestick(df, title=None, save=False, width=None, height=None):
    is_notebook = in_ipynb()
    if is_notebook:
        output_notebook()
    if width is None:
        width = 700 if is_notebook else 1000
    if height is None:
        height = 350 if is_notebook else 500

    inc = df.close > df.open
    dec = df.open > df.close
    w = 12 * 60 * 60 * 1000  # half day in ms
    graph_title = title + ' Chart' if title is not None else 'Chart'

    p = figure(x_axis_type="datetime", tools=TOOLS, title=graph_title, plot_width=width, plot_height=height)
    p.xaxis.major_label_orientation = pi / 4
    p.grid.grid_line_alpha = 0.3
    p.xaxis.axis_label = 'Date'
    p.yaxis.axis_label = 'Price'

    p.segment(df.index, df.high, df.index, df.low, color="black")
    p.vbar(df.index[inc], w, df.open[inc], df.close[inc], fill_color='#B2DF8A', line_color="green")
    p.vbar(df.index[dec], w, df.open[dec], df.close[dec], fill_color="#FA8072", line_color="red")

    if save and not is_notebook:
        # Store as a HTML file
        output_file("stock_information.html", title="candlestick.py")
    # Display
    show(p)
    if is_notebook:
        push_notebook()
Beispiel #19
0
 def _update_cv_score_std_src(self, cv_score_std):
     patches = dict()
     for key in cv_score_std.keys():
         patches[key] = [(slice(NoteBookVisualizer.stream_rollover * 2),
                          cv_score_std[key])]
     self.cv_score_std_src.patch(patches)
     push_notebook(handle=self.bokeh_handle)
Beispiel #20
0
 def updateInteractive(self, b):
     for hisTitle, projectionList in zip(*[iter(self.selectionList)] * 2):
         for iDim in range(
                 self.histArray.FindObject(hisTitle).GetNdimensions() - 1,
                 -1, -1):
             iSlider = self.sliderNames.index(
                 self.histArray.FindObject(hisTitle).GetAxis(
                     iDim).GetTitle())
             value = self.sliderList[iSlider].value
             self.histArray.FindObject(hisTitle).GetAxis(iDim).SetRangeUser(
                 value[0], value[1])
     iterator = 0
     for hisTitle, projectionList in zip(*[iter(self.selectionList)] * 2):
         dimList = list(map(int, projectionList))
         nDim = len(dimList)
         if nDim > 1:
             raise NotImplementedError(
                 "Sorry!!.. Multidimensional projections have not been implemented, yet"
             )
         histogram = self.histArray.FindObject(hisTitle).Projection(
             dimList[0])
         cds = makeCDS(histogram)
         self.source[iterator].data = cds.data
         iterator = iterator + 1
     push_notebook(self.handle)
Beispiel #21
0
 def viewCameraStreamJupyterBokeh(self):
     try:
         # Live view in a Jupyter Notebook
         # Flickering occurs
         output_notebook()
         frame = self.getImage(saveImage=False, saveNumpy=False)
         frame = cv2.cvtColor(
             frame,
             cv2.COLOR_BGR2RGBA)  # because Bokeh expects a RGBA image
         frame = cv2.flip(frame, -1)  # because Bokeh flips vertically
         width = frame.shape[1]
         height = frame.shape[0]
         p = figure(x_range=(0, width),
                    y_range=(0, height),
                    width=width,
                    height=height)
         myImage = p.image_rgba(image=[frame],
                                x=0,
                                y=0,
                                dw=width,
                                dh=height)
         show(p, notebook_handle=True)
         while True:
             frame = self.getImage(saveImage=False, saveNumpy=False)
             frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
             frame = cv2.flip(frame, -1)
             myImage.data_source.data['image'] = [frame]
             push_notebook()
             time.sleep(2)
     except KeyboardInterrupt:
         self.quit_and_open()
Beispiel #22
0
Datei: ui.py Projekt: andyhyh/ray
    def task_completion_time_update(abs_earliest, abs_latest, abs_num_tasks,
                                    tasks):
        if len(tasks) == 0:
            return

        # Create the distribution to plot
        distr = []
        for task_id, data in tasks.items():
            distr.append(data["store_outputs_end"] -
                         data["get_arguments_start"])

        # Create a histogram from the distribution
        top, bin_edges = np.histogram(distr, bins="auto")
        left = bin_edges[:-1]
        right = bin_edges[1:]

        source.data = {"top": top, "left": left, "right": right}

        # Set the x and y ranges
        x_range = (min(left) if len(left) else 0,
                   max(right) if len(right) else 1)
        y_range = (0, max(top) + 1 if len(top) else 1)

        x_range = helpers._get_range(x_range)
        p.x_range.start = x_range.start
        p.x_range.end = x_range.end

        y_range = helpers._get_range(y_range)
        p.y_range.start = y_range.start
        p.y_range.end = y_range.end

        # Push updates to the plot
        push_notebook(handle=handle)
Beispiel #23
0
def update(f, w=1, A=1, phi=0):
    """update"""
    if f == 'sin': func = np.sin
    elif f == 'cos': func = np.cos
    elif f == 'tan': func = np.tan
    r.data_source.data['y'] = A * func(w * x + phi)
    push_notebook()
Beispiel #24
0
 def on_sort_change(*args):
     order = get_sort_order()
     d = bplot.data_source.data
     d['x'].index = order
     d['y'] = d['y'].loc[order]
     d['score'] = d['score'].loc[order]
     bokeh_io.push_notebook(handle=bhandle)
Beispiel #25
0
 def update(bits=3):
     # Round to the nearest level based on bits used
     levels = 2 ** bits
     base = sig.max() / (levels-1)
     rounded = base * np.round(sig.y()/base)
     digital_signal.update({'y': rounded})
     push_notebook(handle=handle)
Beispiel #26
0
 def update(level):
     print("level {}".format(level))
     data, title = self[level].plot_data_title(**kwargs)
     canvas.title.text = title
     source.data = data
     push_notebook()
     pass
Beispiel #27
0
def update(m):
    #data = dict(lat=df_bokeh.loc[month_year].latitude,
    #        lon=df_bokeh.loc[month_year].longitude,
    #        trap=df_bokeh.loc[month_year].trap,
    #        species=df_bokeh.loc[month_year].species)
    #data1.data = data
    r.data_source.data['longitude'] = df_bokeh[df_bokeh.month_year ==
                                               m]['longitude']
    r.data_source.data['latitude'] = df_bokeh[df_bokeh.month_year ==
                                              m]['latitude']
    r.data_source.data['wnvpresent'] = df_bokeh[df_bokeh.month_year ==
                                                m]['wnvpresent']
    r.update
    T1 = str(df_bokeh[df_bokeh.month_year == m].month.unique()).replace(
        '[', '').replace(']', '')
    T2 = str(df_bokeh[df_bokeh.month_year == m].year.unique()).replace(
        '[', '').replace(']', '')
    p.title.text = "Chicago - West Nile Outbreak - {}/{}".format(T1, T2)
    hover = HoverTool(tooltips=[
        ("Trap", '@trap'),
        ("Species", '@species'),
        ("Coordinates", "(@latitude{0.0000}, @longitude{0.0000})"),
    ])
    #p.add_tools(hover)

    #hover.update
    #print(m)
    #p.title.text="Chicago - West Nile Outbreak {}".format
    push_notebook()
Beispiel #28
0
def display_partial_party_network(plot_data, slice_range_type, slice_range,
                                  slice_changed_callback):

    nodes, edges = slice_network_datasource(plot_data.edges, plot_data.nodes,
                                            slice_range, slice_range_type)

    plot_data.edges_source.data.update(edges)
    plot_data.nodes_source.data.update(nodes)

    plot_data.slice_range_type = slice_range_type
    plot_data.slice_range = slice_range

    sign_dates = plot_data.edges_source.data['signed']

    if len(sign_dates) == 0:
        return

    min_year, max_year = min(sign_dates).year, max(sign_dates).year

    slice_changed_callback(min_year, max_year)

    print('Slice range by {}: {}-{}, edge count: {} ({})'.format(
        'id' if slice_range_type == 1 else 'Year', slice_range[0],
        slice_range[1], len(plot_data.edges_source.data['signed']),
        len(plot_data.edges['signed'])))

    push_notebook(handle=plot_data.handle)
Beispiel #29
0
 def update(y):
     news.set_order_qty(y)
     new_sources, new_glyphs = calc_func(news)
     for field in sources.keys():
         sources[field].data = dict(new_sources[field].data)
     if handle is not None:
         push_notebook(handle=handle)
Beispiel #30
0
def update(f, w=1, A=1, phi=0):
    """update"""
    if f == 'sin': func = np.sin
    elif f == 'cos': func = np.cos
    elif f == 'tan': func = np.tan
    r.data_source.data['y'] = A * func(w * x + phi)
    push_notebook()
Beispiel #31
0
        def update_plot(abs_earliest, abs_latest, abs_num_tasks, tasks):
            num_buckets = 100
            left, right, top = compute_utilizations(abs_earliest,
                                                    abs_latest,
                                                    abs_num_tasks,
                                                    tasks,
                                                    num_buckets)

            time_series_source.data = {"left": left,
                                       "right": right,
                                       "top": top}

            x_range = (max(0, min(left))
                       if len(left) else 0,
                       max(right) if len(right) else 1)
            y_range = (0, max(top) + 1 if len(top) else 1)

            # Define the axis ranges
            x_range = helpers._get_range(x_range)
            time_series_fig.x_range.start = x_range.start
            time_series_fig.x_range.end = x_range.end

            y_range = helpers._get_range(y_range)
            time_series_fig.y_range.start = y_range.start
            time_series_fig.y_range.end = num_cpus

            # Push the updated data to the notebook
            push_notebook(handle=handle)
Beispiel #32
0
def plot_prices(df,
                template_name='stock',
                notebook=False,
                x='Date',
                y='Adj. Close',
                title="Stock prices",
                xlabel="Date",
                ylabel="Price"):
    """
    Bokeh Plot for stock prices with a custom title and meaningful axis labels.
    template_name: output file name of plot
    notebook: boolean for showing plot on jupyter notebook
    """
    source = ColumnDataSource(df)
    # create a new plot with a title and axis labels
    p = Figure(
        title=title,
        x_axis_label=xlabel,
        y_axis_label=ylabel,
        x_axis_type='datetime',
        plot_height=500,
        plot_width=950,
        tools=['pan', 'wheel_zoom'],
        toolbar_location='below',
    )

    # configure so that Bokeh chooses what (if any) scroll tool is active
    p.toolbar.active_scroll = "auto"

    # add a line renderer with legend and line thickness
    p.line(x=x, y=y, line_width=2, legend='Adj Close', source=source)
    p.legend.location = "top_left"
    p.legend.click_policy = "hide"
    hover = HoverTool(
        tooltips=[
            ('Date', '@Date{%F}'),
            ('Close',
             '$@{Adj. Close}{%0.2f}'),  # use @{ } for field names with spaces
            ('Volume', '@Volume{0.00 a}'),
        ],
        formatters={
            'Date': 'datetime',  # use 'datetime' formatter for 'date' field
            'Adj. Close':
            'printf',  # use 'printf' formatter for 'adj close' field
            # use default 'numeral' formatter for other fields
        },

        # display a tooltip whenever the cursor is vertically in line with a glyph
        mode='vline')
    p.add_tools(hover)

    if notebook:
        # show the results
        show(p, notebook_handle=True)
        push_notebook()
    else:
        # output the results
        output_file('%s.html' % template_name)
        save(p)
Beispiel #33
0
 def push_data(self):
     """A function to push the content of the source DataFrame
     to a specific plot source
     """
     self.bokeh_source.data = dict([(x, self.source[x].values) for x in self.source.columns])
     self.plot.xaxis.axis_label = self.x_label
     self.plot.yaxis.axis_label = self.y_label
     push_notebook()
Beispiel #34
0
 def update(self):
     new_data = dict(x=[self.__counter])
     for i in range(0, self.__num_lines):
         new_data["t00%d" % (i)] = np.array([self.data[i]])
     self.__source.stream(new_data, self.resolution)
     push_notebook(handle=self.__handle)
     self.__counter += 1
     self.__line_counter = 0
 def slider_value_changed(change):
     for cnt1 in range(nimgs):
         renderer = fig_t.select(
             dict(name='img3d%d' % cnt1, type=GlyphRenderer))
         img_t[cnt1].data_source.data['image'] = [
             imgs2[cnt1][:, :, sld.value]
         ]
     push_notebook(handle=bk_t)
Beispiel #36
0
    def generate_table(self, fun):
        """
        Generate a table displaying the functions called by fun and their
        respective running times. This is done using Bokeh's DataTable widget,
        which is based on SlickGrid.
        """
        if fun is None:
            # Generate summary page
            calls = self.cprofile_tree.keys()
        else:
            calls = [function for function in self.cprofile_tree[fun]['calls']]

        self.n_table_elements = len(calls)

        names = [call if type(call) == str else call.co_name for call in calls]

        # List of tuples containing:
        # (id number, name, totaltime, inlinetime, cprofile_key)
        calls = list(zip(range(len(calls)), names,
                         (self.cprofile_tree[x]['totaltime'] for x in calls),
                         (self.cprofile_tree[x]['inlinetime'] for x in calls),
                         calls))

        self.id_dict = {"function" + str(id): cprofile_key for
                        (id, name, time, inlinetime, cprofile_key) in calls}

        # Sort by total time (descending)
        calls.sort(key=lambda x: x[2])
        calls.reverse()

        # Generate bokeh table
        try:
            ids, names, times, inlinetimes = list(zip(*calls))[:-1]
        except ValueError:
            return

        time_plot_multiplier = 100 / max(times)
        plot_inline_times = [time_plot_multiplier * time for time in
                             inlinetimes]
        plot_extra_times = [time_plot_multiplier * (totaltime - inlinetime)
                            for totaltime, inlinetime in zip(times,
                                                             inlinetimes)]

        self.table_data.data = dict(ids=ids, names=names, times=times,
                                    inlinetimes=inlinetimes,
                                    plot_inline_times=plot_inline_times,
                                    plot_extra_times=plot_extra_times)

        if self.bokeh_table_div == "":
            # First run
            self.init_bokeh_table()
        else:
            if fun is None:
                self.bokeh_table.height = 27 + 25 * 20
            else:
                self.bokeh_table.height = 27 + 25 * min(10, len(calls))
            push_notebook()
Beispiel #37
0
 def push_data(self):
     """A function to push the content of the source DataFrame
     to a specific plot source
     """
     self.bk_node_source.data = dict([(x, self.node_source[x].values)\
                                      for x in self.node_source.columns])
     self.bk_edge_source.data = dict([(x, self.edge_source[x].values)\
                                      for x in self.edge_source.columns])
     push_notebook()
Beispiel #38
0
    def push_data(self):
        """A function to push the content of the source DataFrame
        to a specific plot source
        """
        self.bokeh_source.data = dict([(x, self.output[x].values) for x in self.output.columns])
        self.plot.xaxis.axis_label = self.mapper.x.data_slicer.description
        self.plot.yaxis.axis_label = self.mapper.y.data_slicer.description

        push_notebook()
Beispiel #39
0
    def heat_map_update(abs_earliest, abs_latest, abs_num_tasks, tasks):
        if len(tasks) == 0:
            return

        earliest = time.time()
        latest = 0

        node_to_tasks = dict()
        # Determine which task has the earlest start time out of the ones
        # passed into the update function
        for task_id, data in tasks.items():
            if data["score"] > latest:
                latest = data["score"]
            if data["score"] < earliest:
                earliest = data["score"]
            worker_id = data["worker_id"]
            node_ip = workers[worker_id]["node_ip_address"]
            if node_ip not in node_to_tasks:
                node_to_tasks[node_ip] = {}
            node_to_tasks[node_ip][task_id] = data

        nodes = []
        times = []
        lengths = []
        num_tasks = []

        for node_ip, task_dict in node_to_tasks.items():
            left, right, top = compute_utilizations(earliest,
                                                    latest,
                                                    abs_num_tasks,
                                                    task_dict,
                                                    100,
                                                    True)
            for (l, r, t) in zip(left, right, top):
                nodes.append(node_ip)
                times.append((l + r) / 2)
                lengths.append(r - l)
                num_tasks.append(t)

        # Set the y range of the plot to be the node IP addresses
        p.y_range.factors = list(set(nodes))

        mapper.low = min(min(num_tasks), 0)
        mapper.high = max(max(num_tasks), 1)

        # Update plot with new data based on slider and text box values
        source.data = {"node_ip_address": nodes,
                       "time": times,
                       "num_tasks": num_tasks,
                       "length": lengths}

        push_notebook(handle=handle)
    def update(self, addr, interval):
        """ Query the Scheduler, update the figure

        This opens a connection to the scheduler, sends it a function to run
        periodically, streams the results back and uses those results to update
        the bokeh figure
        """
        self.stream = yield connect(*addr)

        def func(scheduler):
            """ Get tasks running or waiting on each worker """
            workers = [k for k, v in sorted(scheduler.ncores.items(),
                                            key=lambda x: x[0], reverse=True)]
            processing = [list(map(key_split, scheduler.processing[w]))
                          for w in workers]
            nprocessing = list(map(len, processing))
            nstacks = [len(scheduler.stacks[w]) for w in workers]

            return {'host': [w.split(':')[0] for w in workers],
                    'processing': processing,
                    'nprocessing': nprocessing,
                    'waiting': nstacks}

        yield write(self.stream, {'op': 'feed',
                                  'function': dumps(func),
                                  'interval': interval})
        while True:
            try:
                response = yield read(self.stream)
            except Exception:
                break

            self.cds.data.update(response)

            n = len(response['host'])

            self.figure.y_range.end = max(self.figure.y_range.end,
                                          *response['nprocessing'])
            self.figure.extra_y_ranges['waiting'].end = \
                    max(self.figure.extra_y_ranges['waiting'].end,
                        *response['waiting'])

            self.cds.data['zero'] = [0] * n
            self.cds.data['left'] = [i + 0.00 for i in range(n)]
            self.cds.data['mid'] = [i + 0.50 for i in range(n)]
            self.cds.data['right'] = [i + 1.00 for i in range(n)]

            if self.display_notebook:
                push_notebook()
    def doRender(self, handlerId):
        clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true"
        if not clientHasBokeh:
            output_notebook(hide_banner=True)
        data = self.entity.getNextData()
        if data is None:
            return

        x = None
        y = None

        if isinstance(data, (list,np.ndarray)):
            x = list(range(self.windowSize)) if self.glyphRenderer is None else self.glyphRenderer.data_source.data['x']
            y = data if self.glyphRenderer is None else self._concatArrays(self.glyphRenderer.data_source.data['y'],data)
            if len(y) < self.windowSize:
                y = [0]*(self.windowSize-len(y)) + y
            elif len(y) > self.windowSize:
                y = self._delWindowElements(y)
        elif isinstance(data, pandas.core.frame.DataFrame):
            pd = pd.drop(pd.index[[0]])
            #pd.index = list(range(len(pd.index)))
            pd['x'] = list(range(len(pd.index)))
        else:
            x = data[0]
            y = data[1]

        if self.glyphRenderer is None:
            self.glyphRenderer = self.createGlyphRenderer( self.figure, x, y )
        else:
            self.updateGlyphRenderer( self.figure, self.glyphRenderer)

        if self.glyphRenderer is None:
            print("Error: no glyphRenderer found")
            return

        self.glyphRenderer.data_source.data['x'] = x
        self.glyphRenderer.data_source.data['y'] = y

        if not self.comms_handle:
            state = curstate()
            doc = state.document
            if self.figure not in doc.roots:
               doc.add_root(self.figure)
            self.comms_handle = show_doc(self.figure, state, notebook_handle=True)
        else:
            push_notebook(handle = self.comms_handle)
Beispiel #42
0
    def update(**kwargs):
        lti.update(**kwargs)
        g_impulse.data_source.data['x'], g_impulse.data_source.data['y'] = (
            impulse(lti.sys, T=t))

        g_step.data_source.data['x'], g_step.data_source.data['y'] = (
            step(lti.sys, T=t))

        g_poles.data_source.data['x'] = lti.sys.poles.real
        g_poles.data_source.data['y'] = lti.sys.poles.imag

        w, mag, phase, = bode(lti.sys)
        g_bode_mag.data_source.data['x'] = w
        g_bode_mag.data_source.data['y'] = mag
        g_bode_phase.data_source.data['x'] = w
        g_bode_phase.data_source.data['y'] = phase

        push_notebook()
Beispiel #43
0
    def push_notebook(self):
        """ Update a data source for a plot in a Jupyter notebook.

        This function can be be used to update data in plot data sources
        in the Jupyter notebook, without having to use the Bokeh server.

        .. warning::
            This function has been deprecated. Please use
            ``bokeh.io.push_notebook()`` which will push all changes
            (not just data sources) to the last shown plot in a Jupyter
            notebook.

        Returns:
            None

        """
        from bokeh.io import push_notebook
        push_notebook()
    def update(self, addr, interval):
        """ Query the Scheduler, update the figure

        This opens a connection to the scheduler, sends it a function to run
        periodically, streams the results back and uses those results to update
        the bokeh figure
        """
        self.stream = yield connect(*addr)

        def func(scheduler):
            """ Get CPU and Memory usage on each worker """
            workers = [k for k, v in sorted(scheduler.ncores.items(),
                                            key=lambda x: x[0], reverse=True)]
            nannies = [(ip, scheduler.nannies[(ip, port)])
                       for ip, port in workers]
            dicts = [get(-1, scheduler.resource_logs[w], dict())
                     for w in nannies]

            return {'workers': workers,
                    'cpu': [d.get('cpu_percent', -1) for d in dicts],
                    'memory': [d.get('memory_percent', -1) for d in dicts]}

        yield write(self.stream, {'op': 'feed',
                                  'function': func,
                                  'interval': interval})
        while True:
            try:
                response = yield read(self.stream)
            except Exception:
                break

            self.cds.data['host'] = [host for host, port in response['workers']]
            self.cds.data['cpu'] = response['cpu']
            self.cds.data['memory'] = response['memory']

            n = len(response['workers'])

            self.cds.data['zero'] = [0] * n
            self.cds.data['left'] = [i + 0.00 for i in range(n)]
            self.cds.data['mid'] = [i + 0.50 for i in range(n)]
            self.cds.data['right'] = [i + 1.00 for i in range(n)]

            if self.display_notebook:
                push_notebook()
Beispiel #45
0
    def update_image(self):
        self.logger.debug("redraw surface")
        if self.figure is None:
            return

        # Grab the RGB array for the current image and place it in the
        # Bokeh image
        data = self.getwin_array(order=self.rgb_order)
        ht, wd = data.shape[:2]

        # Casting as a 32-bit uint array type hopefully to get more
        # efficient JSON encoding en route to the browser
        data = data.view(dtype=np.uint32).reshape((ht, wd))

        dst_x = dst_y = 0

        try:
            # Create an Image_RGBA object in the plot
            if self.bkimage is None:
                self.d_src = ColumnDataSource({'image': [data]})
                self.bkimage = self.figure.image_rgba(image='image',
                                                      x=dst_x, y=dst_y,
                                                      dw=wd, dh=ht,
                                                      source=self.d_src)
                self._setup_handlers(self.d_src)

            else:
                # note: get the data source (a ColumnDataSource) and update
                # the values
                self.logger.info("Updating image")
                update = dict(image=[data], x=[dst_x], y=[dst_y],
                              dw=[wd], dh=[ht])
                self.d_src.data = update

                if self._push_handle is not None:
                    self.logger.info("pushing to notebook...")
                    #self.d_src.push_notebook(self._push_handle)
                    push_notebook(self._push_handle)
                self.logger.info("Image updated")

        except Exception as e:
            self.logger.error("Error updating image: %s" % (str(e)))
            return
Beispiel #46
0
    def update(self):
        """ Query the Scheduler, update the figure

        This opens a connection to the scheduler, sends it a function to run
        periodically, streams the results back and uses those results to update
        the bokeh figure
        """
        with log_errors():
            tasks, workers = yield [
                    self.client.fetch('http://%s:%d/tasks.json' % self.addr),
                    self.client.fetch('http://%s:%d/workers.json' % self.addr)]

            tasks = json.loads(tasks.body.decode())
            workers = json.loads(workers.body.decode())

            task_table_update(self.task_source, tasks)
            worker_table_update(self.worker_source, workers)

            if self.display_notebook:
                push_notebook()
Beispiel #47
0
    def update_image(self):
        if self.figure is None:
            return

        wd, ht = self.get_window_size()

        # Get surface as a numpy array
        data = self.renderer.get_surface_as_array(order='RGBA')

        # Casting as a 32-bit uint array type hopefully to get more
        # efficient JSON encoding en route to the browser
        data = data.view(dtype=np.uint32).reshape((ht, wd))

        data = np.flipud(data)

        dst_x = dst_y = 0

        # Create an Image_RGBA object in the plot
        if self.bkimage is None:
            self.d_src = ColumnDataSource({'image': [data]})
            self.bkimage = self.figure.image_rgba(image='image',
                                                  x=dst_x, y=dst_y,
                                                  dw=wd, dh=ht,
                                                  source=self.d_src)
            self._setup_handlers(self.d_src)

        else:
            # note: get the data source (a ColumnDataSource) and update
            # the values
            self.logger.info("Updating image")
            update = dict(image=[data], x=[dst_x], y=[dst_y],
                          dw=[wd], dh=[ht])
            self.d_src.data = update

            if self._push_handle is not None:
                self.logger.info("pushing to notebook...")
                #self.d_src.push_notebook(self._push_handle)
                push_notebook(self._push_handle)
            self.logger.info("Image updated")
Beispiel #48
0
    def _throw(self, velocity, v_angle):
        assert not self._hit

        try:
            if self._escaped:
                raise UserWarning('%s is not a valid target!' % (self,))

            self._update_ball_trajectory(velocity, v_angle)
            self._move_target()

            distances = cdist(self._ball_path, [[self._mon_x, self._mon_y]])
            closest = distances.min()
            if closest < self._max_dist:
                self._hit = True
                impact_point = distances.argmin()
                x = self._ball_path[impact_point,0]
                y = self._ball_path[impact_point,1]
                self._ball_path = self._ball_path[:impact_point]
                print('Hit at %0.2f×%0.2f with a distance of %f' % (x, y, closest))
                self._interact.widget.set_trait('visible', False)

            self._source.data['ball_x'] = self._ball_path[:, 0]
            self._source.data['ball_y'] = self._ball_path[:, 1]

            # this seems like a filthy hack...
            # Bokeh seems to want every data item to have the same len
            n = self._source.data['ball_x'].shape[0]
            self._source.data['mon_x'] = [self._mon_x]*n
            self._source.data['mon_y'] = [self._mon_y]*n
            self._source.data['mon_h'] = [self._mon_h]*n
            self._source.data['mon_w'] = [self._mon_w]*n
            self._source.data['mon_u'] = [self._mon_url]*n
            
            push_notebook()

        except UserWarning as e:
            print(e)
Beispiel #49
0
 def push(self):
     push_notebook()
Beispiel #50
0
 def vizpoints(self, x, y):
     print(x)
     self.p.circle(y, self.dh - np.array(x), fill_color="yellow", size=10)
     push_notebook(handle=self.t)
Beispiel #51
0
 def update(self):
     from bokeh.io import push_notebook
     self.set_sources()
     push_notebook()
Beispiel #52
0
def update_notebook_source(source: ColumnDataSource):
    if source:
        push_notebook()
Beispiel #53
0
 def notebook_update():
     update(x_key, y_key, sequence, subscriber, plot)
     push_notebook()
Beispiel #54
0
 def _update(self):
     self.ds.data['x'] = [e[self.x] for e in self.fitness]
     self.ds.data['y'] = [e[self.y] for e in self.fitness]
     push_notebook(handle=self.handle)
Beispiel #55
0
 def _update(self):
     self.ds.data['x'] = self.iterations[-self.window_size:]
     self.ds.data['y'] = self.fitness[-self.window_size:]
     push_notebook(handle=self.handle)