コード例 #1
0
    def _init_plots_views(self, mdtraj_trajectories, plotx_label, ploty_label):
        colvars = self.colvars
        stride = self.stride
        plotx = self.plotx
        plotys = self.ploty
        p = self.figure

        n = len(colvars)
        if n >= 3:
            palette = colorblind['Colorblind'][n]
        else:
            palette = colorblind['Colorblind'][3]
        palette = palette[::-1]

        view_layout = widgets.Layout(**self.def_view_layout)
        if len(mdtraj_trajectories) == 1:
            view_layout.width='500px'
            view_layout.height='600px'

        sources = []
        views = []

        for n,(colvar, traj, ploty) in enumerate(zip_longest(colvars, mdtraj_trajectories, plotys)):
            if traj is not None:
                working_traj = traj

            times = working_traj.time[::stride]
            
            if len(colvar) != len(working_traj):
                raise ValueError("Colvar and trajectory should have same number of frames")
            
            if isinstance(colvar, np.ndarray):
                x = colvar[::stride, plotx]
                y = colvar[::stride, ploty]
            else:
                x = colvar[plotx][::stride]
                y = colvar[ploty][::stride]

            if isinstance(ploty, str):
                this_ploty_label = ploty
            elif ploty_label is not None:
                this_ploty_label = ploty_label
            else:
                this_ploty_label = str(ploty)
            ploty_label_list = [this_ploty_label] * len(y)

            source = ColumnDataSource(data={
                'run': [n]*len(x),
                'plotx_label': [plotx_label]*len(x),
                'ploty_label': ploty_label_list,
                'time': times/1000,
                'x': x,
                'y': y,
                'alphas': [(t)/(times[-1]) for t in times]
            })
            sources.append(source)
            
            colour = palette[n-1]
            
            if traj is not None:
                view = show_mdtraj(traj[::stride], gui=False)
                view.observe(self._update_frame, names=['frame']), 
                view._colour = colour
                if len(traj.top.select('protein')):
                    view.clear_representations()
                    view.add_cartoon(selection='polymer', color=colour)
                # view.frame_stride = stride
                view.layout = view_layout
                view._set_sync_camera()
                views.append(view)
                vline = Span(
                    location=view.frame * traj.timestep * stride + traj.time[0],
                    dimension='height',
                    line_color=colour
                )
                self._vlines[view] = vline
                p.add_layout(vline)

            view.link_to_bokeh_ds(source)
            
            p.scatter(x='x', y='y', 
                      source=source, 
                      color=colour, 
                      fill_alpha='alphas',
                      legend=this_ploty_label)

        return sources, views
コード例 #2
0
ファイル: plot_TA.py プロジェクト: izdiharzuhdi/gitlearn
def plot_chart_bokeh(processed, dataCollection, keys, outputfilename):
    stock = processed['data']

    # Define constants
    W_PLOT = 1000
    H_PLOT = 360
    TOOLS = 'pan,wheel_zoom,reset'

    VBAR_WIDTH = 1 * 12 * 60 * 60 * 1000  # one day in ms
    RED = Category20[7][6]
    GREEN = Category20[5][4]

    BLUE = Category20[3][0]
    BLUE_LIGHT = Category20[3][1]

    ORANGE = Category20[3][2]
    PURPLE = Category20[9][8]
    BROWN = Category20[11][10]

    # ==========================================================================
    # ===================       PLOT CANDLE STICK GRAPH     ====================
    # ==========================================================================
    p1 = figure(plot_width=W_PLOT,
                plot_height=H_PLOT,
                tools=TOOLS,
                toolbar_location='right')

    inc = stock.data['Close'] >= stock.data['Open']
    dec = stock.data['Open'] > stock.data['Close']
    # limit = stock.data['ZC_d2/dt2'] > 10
    # limit = stock.data['ZC_d/dt'] > 0

    # view_inc = CDSView(source=stock, filters=[BooleanFilter(inc), BooleanFilter(limit)])
    # view_dec = CDSView(source=stock, filters=[BooleanFilter(dec), BooleanFilter(limit)])
    view_inc = CDSView(source=stock, filters=[BooleanFilter(inc)])
    view_dec = CDSView(source=stock, filters=[BooleanFilter(dec)])

    # # map dataframe indices to date strings and use as label overrides
    p1.y_range.start = 0.9 * min(stock.data['Low'])
    p1.y_range.end = 1.1 * max(stock.data['High'])
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=GREEN,
               source=stock,
               view=view_inc)
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=RED,
               source=stock,
               view=view_dec)

    vb1 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='forestgreen',
                  fill_alpha=1,
                  line_color='forestgreen',
                  source=stock,
                  view=view_inc,
                  name="price")
    vb2 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='orangered',
                  fill_alpha=1,
                  line_color='orangered',
                  source=stock,
                  view=view_dec,
                  name="price")

    # Bollinger band plot
    patch1 = p1.varea(x='Date',
                      y1='lowerband',
                      y2='upperband',
                      source=stock,
                      fill_alpha=0.05,
                      fill_color='dodgerblue')
    patch_line1 = p1.line(x='Date',
                          y='lowerband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)
    patch_line2 = p1.line(x='Date',
                          y='middleband',
                          source=stock,
                          line_color='grey',
                          line_alpha=0.8,
                          line_dash='dotdash')
    patch_line3 = p1.line(x='Date',
                          y='upperband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)

    # ZC Line plot
    zc_7 = p1.line(x='Date',
                   y='ma7',
                   source=stock,
                   line_color='crimson',
                   line_alpha=0.4)
    zc_26 = p1.line(x='Date',
                    y='ma26',
                    source=stock,
                    line_color='darkslateblue',
                    line_alpha=0.4)

    # # Resistance plots
    # r1 = p1.line(x='Date', y='r1', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.6)
    # r2 = p1.line(x='Date', y='r2', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.8)
    # r3 = p1.line(x='Date', y='r3', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=1.0)

    # # Support plots
    # s1 = p1.line(x='Date', y='s1', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.6)
    # s2 = p1.line(x='Date', y='s2', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.8)
    # s3 = p1.line(x='Date', y='s3', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=1.0)

    # Extrema plots
    # minima = p1.inverted_triangle(x='Date', y='minima', source=stock, size=5, color="goldenrod", alpha=0.5)
    # maxima = p1.triangle(x='Date', y='maxima', source=stock, size=5, color="teal", alpha=0.5)
    # minima = p1.circle(
    #     x='Date', y='minima', source=stock, size=10,
    #     fill_color="grey", hover_fill_color="firebrick",
    #     fill_alpha=0.2, hover_alpha=0.8, hover_line_color="white")
    # maxima = p1.triangle(
    #     x='Date', y='maxima', source=stock,
    #     size=10, fill_color="grey", fill_alpha=0.2,
    #     hover_fill_color="firebrick", hover_alpha=0.8, hover_line_color="white")

    # Volume plot
    # Setting the second y axis range name and range
    p1.extra_y_ranges = {
        "vol_axis": Range1d(start=0, end=max(stock.data['Volume']) * 4)
    }
    # Adding the second axis to the plot.
    p1.add_layout(LinearAxis(y_range_name="vol_axis", visible=False), 'right')
    vol_inc = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=GREEN,
                      fill_alpha=0.1,
                      line_color=GREEN,
                      line_alpha=0.2,
                      source=stock,
                      view=view_inc,
                      y_range_name="vol_axis")
    vol_dec = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=RED,
                      fill_alpha=0.1,
                      line_color=RED,
                      line_alpha=0.2,
                      source=stock,
                      view=view_dec,
                      y_range_name="vol_axis")

    legend = Legend(items=[
        LegendItem(
            label="All",
            renderers=[
                patch1,
                patch_line1,
                patch_line2,
                patch_line3,
                vol_inc,
                vol_dec,
                zc_7,
                zc_26,
                #    s1, s2, s3,r1, r2, r3,
                #    minima, maxima
            ],
            index=0),
        LegendItem(label="BB",
                   renderers=[patch1, patch_line1, patch_line2, patch_line3],
                   index=1),
        LegendItem(label="Volume", renderers=[vol_inc, vol_dec], index=2),
        LegendItem(label="ZC", renderers=[zc_7, zc_26], index=3),
        LegendItem(label="MA7", renderers=[zc_7], index=4),
        LegendItem(label="MA26", renderers=[zc_26], index=5),
        # LegendItem(label="Support", renderers=[s1, s2, s3], index=6),
        # LegendItem(label="Resistance", renderers=[r1, r2, r3], index=7),
        # LegendItem(label="Extrema", renderers=[minima, maxima], index=8)
    ])
    p1.add_layout(legend)
    p1.legend.location = "top_left"
    p1.legend.border_line_alpha = 0
    p1.legend.background_fill_alpha = 0
    p1.legend.click_policy = "hide"
    p1.legend.orientation = "horizontal"
    # p1.add_layout(Title(text="Stock price", align="left"), "left")

    p1.yaxis.axis_label = 'Stock price'
    p1.yaxis.formatter = NumeralTickFormatter(format='0.00')
    p1.x_range.range_padding = 0.05
    p1.xaxis.ticker.desired_num_ticks = 40
    p1.xaxis.major_label_orientation = 3.14 / 4
    p1.xaxis.visible = False
    p1.xgrid.grid_line_color = None
    p1.ygrid.grid_line_color = None

    # Select specific tool for the plot
    p1.add_tools(
        HoverTool(
            tooltips=[("Datetime", "@Date{%Y-%m-%d}"),
                      ("Open", "@Open{0,0.00}"), ("Close", "@Close{0,0.00}"),
                      ("Volume", "@Volume{(0.00 a)}")],
            formatters={"@Date": 'datetime'},

            # display a tooltip whenever the cursor is vertically in line with a glyph
            mode='vline',
            renderers=[vb1, vb2]))

    # ==========================================================================
    # ===================      PLOT STOCH / RSI GRAPH          =================
    # ==========================================================================
    p2 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 4),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime')  # , y_range=(-20, 120)

    stoch_k = p2.line(x='Date',
                      y='slowk',
                      source=stock,
                      line_color='royalblue',
                      alpha=0.8,
                      muted_alpha=0.2)
    stoch_d = p2.line(x='Date',
                      y='slowd',
                      source=stock,
                      line_color='tomato',
                      alpha=0.8,
                      muted_alpha=0.2)
    rsi = p2.line(x='Date',
                  y='rsi',
                  source=stock,
                  line_color='gray',
                  alpha=0.8,
                  muted_alpha=0.2)
    mid_box = BoxAnnotation(bottom=20,
                            top=80,
                            fill_alpha=0.2,
                            fill_color='palegreen',
                            line_color='lightcoral',
                            line_alpha=0.4,
                            line_dash='dashed')
    # candle = p2.line(x='Date', y='candle', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # mid_box = BoxAnnotation(bottom=-300, top=300, fill_alpha=0.2, fill_color='palegreen', line_color='lightcoral', line_alpha=0.4, line_dash='dashed')
    legend = Legend(items=[
        LegendItem(label="Stoch", renderers=[stoch_k, stoch_d], index=0),
        LegendItem(label="RSI", renderers=[rsi], index=1)
        # LegendItem(label="Candle", renderers=[candle], index=1)
    ])
    p2.add_layout(legend)
    p2.add_layout(mid_box)
    # p2.add_layout(lower)
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p2.add_layout(zero)
    p2.yaxis.axis_label = 'Stochastic / RSI'
    p2.x_range.range_padding = 0.05
    # p2.toolbar.autohide = True
    p2.xaxis.visible = False
    p2.legend.location = "top_left"
    p2.legend.border_line_alpha = 0
    p2.legend.background_fill_alpha = 0
    p2.legend.click_policy = "mute"
    p2.xgrid.grid_line_color = None
    p2.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================                 Plot MACD         ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['macd_hist'], key=abs))
    y2_limit = abs(max(stock.data['macd_d/dt'], key=abs))
    p3 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 2.5),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))
    mapper = LinearColorMapper(palette=Viridis256)
    macd_line = p3.line(x='Date',
                        y='macd_hist',
                        source=stock,
                        line_color='darkgreen',
                        alpha=0.8,
                        muted_alpha=0.2)
    # macd_hist = p3.vbar_stack(['macd'], x='Date', source=stock, width=int(VBAR_WIDTH * 2), fill_color={'field':'macd', 'transform': mapper})

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p3.add_layout(zero)
    p3.add_layout(mid_box)

    # Setting the second y axis range name and range
    p3.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p3.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')
    macd_v = p3.line(x='Date',
                     y='macd_d/dt',
                     source=stock,
                     line_color='dodgerblue',
                     line_dash='solid',
                     alpha=0.8,
                     muted_alpha=0.2,
                     y_range_name="extra_y_axis")
    macd_acc = p3.line(x='Date',
                       y='macd_d2/dt2',
                       source=stock,
                       line_color='tomato',
                       line_dash='dotdash',
                       alpha=0.8,
                       muted_alpha=0.2,
                       y_range_name="extra_y_axis")

    legend = Legend(items=[
        LegendItem(label="MACD", renderers=[macd_line], index=0),
        LegendItem(label="MACD-v", renderers=[macd_v], index=1),
        LegendItem(label="MACD-a", renderers=[macd_acc], index=2)
    ])
    p3.add_layout(legend)
    p3.legend.location = "top_left"
    p3.legend.border_line_alpha = 0
    p3.legend.background_fill_alpha = 0
    p3.legend.click_policy = "mute"
    p3.legend.orientation = "horizontal"
    # p3.add_layout(Title(text="MACD", align="center"), "left")
    p3.yaxis.axis_label = 'MACD'
    p3.x_range.range_padding = 0.05
    p3.xaxis.visible = False
    p3.xaxis.ticker.desired_num_ticks = 40
    p3.xaxis.major_label_orientation = 3.14 / 4
    p3.toolbar.autohide = True
    p3.xgrid.grid_line_color = None
    p3.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================         Plot ZC        ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['ZC'], key=abs))
    y2_limit = abs(max(stock.data['ZC_d/dt'], key=abs))
    # y_limit = abs(max(stock.data['slowk'], key=abs))
    # y2_limit = abs(max(stock.data['slowk_d/dt'], key=abs))
    p4 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 3),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))

    p4.xaxis.formatter = DatetimeTickFormatter(
        hours=["%d.%m.%y"],
        days=["%d.%m.%y"],
        months=["%d.%m.%y"],
        years=["%d.%m.%y"],
    )
    # macd_v = p4.line(x='Date', y='macd_d/dt', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # macd_acc = p4.line(x='Date', y='macd_d2/dt2', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # ad = p4.line(x='Date', y='ck_AD', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # adosc = p4.line(x='Date', y='ck_ADOSC', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # obv = p4.line(x='Date', y='OBV', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)

    # Setting the second y axis range name and range
    p4.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p4.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')

    zc = p4.line(x='Date',
                 y='ZC',
                 source=stock,
                 line_color='darkgreen',
                 alpha=0.8,
                 muted_alpha=0.2)
    zc_v = p4.line(x='Date',
                   y='ZC_d/dt',
                   source=stock,
                   line_color='dodgerblue',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    zc_a = p4.line(x='Date',
                   y='ZC_d2/dt2',
                   source=stock,
                   line_color='tomato',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    # slowk = p4.line(x='Date', y='slowk', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)
    # slowk_v = p4.line(x='Date', y='slowk_d/dt', source=stock, line_color='dodgerblue', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")
    # slowk_a = p4.line(x='Date', y='slowk_d2/dt2', source=stock, line_color='tomato', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p4.add_layout(zero)
    p4.add_layout(mid_box)
    # p4.yaxis.axis_label = 'MACD v/acc'
    legend = Legend(items=[
        LegendItem(label="ZC", renderers=[zc], index=0),
        LegendItem(label="ZC-v", renderers=[zc_v], index=1),
        LegendItem(label="ZC-a", renderers=[zc_a], index=2),
        # LegendItem(label="slowk", renderers=[slowk], index=0),
        # LegendItem(label="slowk-v", renderers=[slowk_v], index=1),
        # LegendItem(label="slowk-a", renderers=[slowk_a], index=2)
    ])
    p4.add_layout(legend)
    p4.legend.location = "top_left"
    p4.legend.border_line_alpha = 0
    p4.legend.background_fill_alpha = 0
    p4.legend.click_policy = "mute"
    p4.legend.orientation = "horizontal"
    p4.x_range.range_padding = 0.05
    p4.xaxis.ticker.desired_num_ticks = 40
    p4.xaxis.major_label_orientation = 3.14 / 4
    p4.toolbar.autohide = True
    p4.xgrid.grid_line_color = None
    p4.ygrid.grid_line_color = None

    addSpans([p1, p2, p3, p4])

    columns = [
        TableColumn(field="Date",
                    title="Date",
                    formatter=DateFormatter(format='%d.%b')),
        # TableColumn(field="Open", title="Open", formatter=NumberFormatter(format='0.00')),
        # TableColumn(field="Close", title="Close", formatter=NumberFormatter(format='0.00')),
        TableColumn(field="ZC",
                    title="ZC",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="ZC_d/dt",
                    title="ZC-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_hist",
                    title="MACD",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_d/dt",
                    title="MACD-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        # TableColumn(field="macd_d2/dt2", title="MACD-a", formatter=NumberFormatter(format='0.000')),
        TableColumn(field="stoch",
                    title="STOCH",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        TableColumn(field="stoch-v",
                    title="STOCH-v",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        # TableColumn(field="slowk_d/dt", title="slowk-v", formatter=NumberFormatter(format='0.000')),
        # TableColumn(field="slowk_d2/dt2", title="slowk-a", formatter=NumberFormatter(format='0.000')),
    ]
    data_table = DataTable(source=stock,
                           columns=columns,
                           width=int(W_PLOT / 3),
                           height=int(H_PLOT * 2.2),
                           index_position=None,
                           width_policy='min')

    # ==========================================================================
    # ===================            SELECT WIDGET          ====================
    # ==========================================================================

    callback_select_main = """
        var d0 = s0.data;
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;

        /// Iterate over keys in new data and reassign old data with new data
        for (const key of Object.keys(data)) {
            d0[key] = []
            d0[key] = data[key]
        }
        s0.change.emit()

        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = 0.9 * Math.min(...data['Low'])
        plot.y_range.end = 1.1 * Math.max(...data['High'])
        plot.extra_y_ranges['vol_axis'].have_updated_interactively = true
        plot.extra_y_ranges['vol_axis'].start  = 0
        plot.extra_y_ranges['vol_axis'].end  = Math.max(...data['Volume']) * 4
        """

    callback_select_va = """
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;
        var y_limit = Math.max.apply(null, data[param_main].map(Math.abs));
        var y_extra_limit = Math.max.apply(null, data[param_extra].map(Math.abs));
        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = -y_limit
        plot.y_range.end = y_limit
        plot.extra_y_ranges['extra_y_axis'].have_updated_interactively = true
        plot.extra_y_ranges['extra_y_axis'].start  = -y_extra_limit
        plot.extra_y_ranges['extra_y_axis'].end  = y_extra_limit
        """
    selecthandler_main = CustomJS(args={
        's0': stock,
        'dataCollection': dataCollection,
        'plot': p1
    },
                                  code=callback_select_main)
    selecthandler_p3 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p3,
        'param_main': 'macd_hist',
        'param_extra': 'macd_d/dt'
    },
                                code=callback_select_va)
    selecthandler_p4 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p4,
        'param_main': 'ZC',
        'param_extra': 'ZC_d/dt'
    },
                                code=callback_select_va)
    # selecthandler_p4 = CustomJS(args={'dataCollection':dataCollection, 'plot':p4, 'param_main': 'slowk', 'param_extra': 'slowk_d/dt'}, code = callback_select_va)
    select = Select(title="Select:", value=keys[0], options=keys)
    select.js_on_change('value', selecthandler_main)
    select.js_on_change('value', selecthandler_p3)
    select.js_on_change('value', selecthandler_p4)

    # [cleanDate(x, stock.data) for x in [p1, p2, p3, p4]]
    # show the results
    gp1 = gridplot([select, data_table],
                   ncols=1,
                   plot_width=150,
                   toolbar_options=dict(autohide=True))
    gp2 = gridplot([p1, p2, p3, p4],
                   ncols=1,
                   sizing_mode='scale_width',
                   toolbar_location='right')

    output_file(outputfilename + '.html')
    show(row(gp1, gp2))
    # show(gp2)
    return True
コード例 #3
0
ファイル: dos.py プロジェクト: zhuruijie16/qmpy
    def bokeh_plot(self):
        if self._bokeh_plot is None:
            spinflag = False
            if len(self.dos) == 2:
                spinflag = True

            if spinflag:
                source = bkp.ColumnDataSource(data=dict(
                    en=self.energy,
                    up=self.dos[0],
                    down=-self.dos[1],
                ))
            else:
                source = bkp.ColumnDataSource(data=dict(
                    en=self.energy,
                    dos=self.dos[0],
                ))

            p = bkp.figure(
                width=500,
                height=300,
                x_range=(-10, 10),
                tools=['pan', 'box_zoom', 'hover', 'reset', 'save', 'help'])

            p.title.text = 'Density of States'
            p.title.align = 'center'
            p.title.text_font_size = "15pt"

            p.xaxis.axis_label = u'E \u2212 E_Fermi (eV)'
            p.xaxis.axis_label_text_font_size = '14pt'
            p.xaxis.major_label_text_font_size = '12pt'

            p.yaxis.axis_label = '# of states (arb. units)'
            p.yaxis.axis_label_text_font_size = '14pt'
            p.yaxis.major_label_text_font_size = '12pt'

            vline = Span(location=0,
                         dimension='height',
                         line_color='gray',
                         line_width=1.5,
                         line_dash='dashed')
            p.renderers.extend([vline])

            if spinflag:
                p.line('en',
                       'up',
                       line_width=2,
                       line_color='blue',
                       legend="Spin Up",
                       source=source)
                p.line('en',
                       'down',
                       line_width=2,
                       line_color='orange',
                       legend="Spin Down",
                       source=source)
            else:
                p.line('en',
                       'dos',
                       line_width=2,
                       line_color='blue',
                       legend='total',
                       source=source)

            p.legend.click_policy = "hide"
            self._bokeh_plot = p

        return self._bokeh_plot
コード例 #4
0
    def plot_bokeh(self,
                   plot_name=None,
                   show_plot=False,
                   barplot=True,
                   chng=True):
        """
        Plot OOB-scores as bar- or linechart in bokeh.

        Parameters
        ----------
        plot_name: str
            path where to store the plot, None to not save it
        show_plot: bool
            whether or not to open plot in standard browser
        barplot: bool
            plot OOB as barchart
        chng: bool
            plot OOB as linechart

        Returns
        -------
        layout: bokeh.models.Row
            bokeh plot (can be used in notebook or comparted with components)
        """
        # Get all relevant data-points
        params = list(self.evaluated_parameter_importance.keys())
        p_names_short = shorten_unique(params)
        errors = list(self.evaluated_parameter_importance.values())
        max_to_plot = min(len(errors), self.MAX_PARAMS_TO_PLOT)
        plot_indices = sorted(range(len(errors)),
                              key=lambda x: errors[x],
                              reverse=True)[:max_to_plot]

        # Customizing plot-style
        bar_width = 25

        # Create ColumnDataSource for both plots
        source = ColumnDataSource(data=dict(
            parameter_names_short=p_names_short,
            parameter_names=params,
            parameter_importance=errors,
        ))
        plots = []

        view = CDSView(source=source, filters=[IndexFilter(plot_indices)])
        tooltips = [
            ("Parameter", "@parameter_names"),
            ("Importance", "@parameter_importance"),
        ]
        if barplot:
            p = figure(x_range=p_names_short,
                       plot_height=350,
                       plot_width=100 + max_to_plot * bar_width,
                       toolbar_location=None,
                       tools="hover",
                       tooltips=tooltips)

            p.vbar(x='parameter_names_short',
                   top='parameter_importance',
                   width=0.9,
                   source=source,
                   view=view)
            for value in [
                    self.IMPORTANCE_THRESHOLD, -self.IMPORTANCE_THRESHOLD
            ]:
                p.add_layout(
                    Span(location=value,
                         dimension='width',
                         line_color='red',
                         line_dash='dashed'))

            plots.append(p)

        if chng:
            p = figure(x_range=p_names_short,
                       plot_height=350,
                       plot_width=100 + max_to_plot * bar_width,
                       toolbar_location=None,
                       tools="hover",
                       tooltips=tooltips)

            p.line(x='parameter_names_short',
                   y='parameter_importance',
                   source=source,
                   view=view)

            plots.append(p)

        # Common styling:
        for p in plots:
            p.xaxis.major_label_orientation = 1.3
            p.xaxis.major_label_text_font_size = "14pt"
            p.yaxis.formatter = BasicTickFormatter(use_scientific=False)
            p.yaxis.axis_label = 'CV-RMSE' if self.cv else 'OOB'

        layout = Row(*plots)

        # Save and show...
        save_and_show(plot_name, show_plot, layout)

        return layout
コード例 #5
0
    def mode_shape(self, mode):
        """Evaluates the mode shapes for the rotor.

        This analysis presents the vibration mode for each critical speed.
        The importance is to locate the critical node, where the displacement
        is the greatest, then apply loads for unbalance response (stability
        level 1)

        Parameters
        ----------
        mode : int
            the n'th vibration mode

        Returns
        -------
        node_min, node_max : list
            List with nodes where the largest absolute displacements occur

        Example
        -------
        >>> rotor = rotor_example()
        >>> report = Report(rotor=rotor,
        ...                 minspeed=400,
        ...                 maxspeed=1000,
        ...                 speed_units="rad/s")
        >>> report.mode_shape(mode=0)
        ([], array([3.]))
        """
        nodes_pos = self.rotor.nodes_pos
        df_bearings = self.rotor.df_bearings
        df_disks = self.rotor.df_disks

        modal = self.rotor.run_modal(speed=self.maxspeed)
        xn, yn, zn, xc, yc, zc_pos, nn = modal.calc_mode_shape(mode=mode)

        # reduce 3D view to 2D view
        vn = np.zeros(len(zn))
        for i in range(len(zn)):
            theta = np.arctan(xn[i] / yn[i])
            vn[i] = xn[i] * np.sin(theta) + yn[i] * np.cos(theta)

        # remove repetitive values from zn and vn
        idx_remove = []
        for i in range(1, len(zn)):
            if zn[i] == zn[i - 1]:
                idx_remove.append(i)
        zn = np.delete(zn, idx_remove)
        vn = np.delete(vn, idx_remove)

        node_min = []
        node_max = []

        if self.rotor_type == "between_bearings":

            aux_idx_max = argrelextrema(vn, np.greater)[0].tolist()
            aux_idx_min = argrelextrema(vn, np.less)[0].tolist()

            # verification of rigid modes
            if len(aux_idx_max) == 0 and len(aux_idx_min) == 0:
                idx_max = np.argmax(vn)
                idx_min = np.argmin(vn)

                # corrects the index by the removed points
                for i in idx_remove:
                    if idx_min > i:
                        idx_min += 1
                    if idx_max > i:
                        idx_max += 1
                node_max = np.round(np.array([idx_max]) / nn)
                node_min = np.round(np.array([idx_min]) / nn)

            if len(aux_idx_min) != 0:
                idx_min = np.where(vn == min(vn[aux_idx_min]))[0].tolist()

                # corrects the index by the removed points
                for i in idx_remove:
                    if idx_min[0] > i:
                        idx_min[0] += 1
                node_min = np.round(np.array(idx_min) / nn)

            if len(aux_idx_max) != 0:
                idx_max = np.where(vn == max(vn[aux_idx_max]))[0].tolist()

                # corrects the index by the removed points
                for i in idx_remove:
                    if idx_max[0] > i:
                        idx_max[0] += 1
                node_max = np.round(np.array(idx_max) / nn)

        elif self.rotor_type == "double_overhung":
            node_max = [max(df_disks['n'])]
            node_min = [min(df_disks['n'])]

        elif self.rotor_type == "single_overhung_l":
            node_min = [min(df_disks['n'])]

        elif self.rotor_type == "single_overhung_r":
            node_max = [max(df_disks['n'])]

        plot = figure(
            tools="pan,wheel_zoom,box_zoom,reset,save,box_select",
            width=1400,
            height=700,
            title="Undamped Mode Shape",
            x_axis_label="Rotor lenght",
            y_axis_label="Non dimensional rotor deformation",
        )
        plot.title.text_font_size = "14pt"
        plot.xaxis.axis_label_text_font_size = "20pt"
        plot.yaxis.axis_label_text_font_size = "20pt"
        plot.axis.major_label_text_font_size = "16pt"

        nodes_pos = np.array(nodes_pos)
        rpm_speed = (30 / np.pi) * modal.wn[mode]

        plot.line(
            x=zn,
            y=vn,
            line_width=4,
            line_color="red",
            legend_label="Mode = %s, Speed = %.1f RPM" % (mode, rpm_speed),
        )
        plot.line(
            x=nodes_pos,
            y=np.zeros(len(nodes_pos)),
            line_dash="dotdash",
            line_width=4.0,
            line_color="black",
        )
        plot.circle(
            x=nodes_pos[df_bearings["n"]],
            y=np.zeros(len(df_bearings)),
            size=12,
            fill_color="black",
        )

        pos0 = nodes_pos[min(df_bearings["n"])]
        pos1 = nodes_pos[max(df_bearings["n"])]
        plot.add_layout(
            Label(
                x=np.mean(nodes_pos[df_bearings["n"]]),
                y=0,
                angle=0,
                text="Bearing Span = %.2f" % (pos1 - pos0),
                text_font_style="bold",
                text_font_size="12pt",
                text_baseline="top",
                text_align="center",
                y_offset=20,
            )
        )
        for node in nodes_pos[df_bearings["n"]]:
            plot.add_layout(
                Span(
                    location=node,
                    dimension="height",
                    line_color="green",
                    line_dash="dashed",
                    line_width=3,
                )
            )

        return node_min, node_max
コード例 #6
0
def make_lightcurve_figure_elements(lc, lc_source):
    """Make the lightcurve figure elements.

    Parameters
    ----------
    lc : LightCurve
        Lightcurve to be shown.
    lc_source : bokeh.plotting.ColumnDataSource
        Bokeh object that enables the visualization.

    Returns
    ----------
    fig : `bokeh.plotting.figure` instance
    step_renderer : GlyphRenderer
    vertical_line : Span
    """
    if lc.mission == 'K2':
        title = "Lightcurve for {} (K2 C{})".format(lc.label, lc.campaign)
    elif lc.mission == 'Kepler':
        title = "Lightcurve for {} (Kepler Q{})".format(lc.label, lc.quarter)
    elif lc.mission == 'TESS':
        title = "Lightcurve for {} (TESS Sec. {})".format(lc.label, lc.sector)
    else:
        title = "Lightcurve for target {}".format(lc.label)

    fig = figure(title=title,
                 plot_height=340,
                 plot_width=600,
                 tools="pan,wheel_zoom,box_zoom,tap,reset",
                 toolbar_location="below",
                 border_fill_color="whitesmoke")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux (e/s)'
    fig.xaxis.axis_label = 'Time - 2454833 (days)'

    ylims = get_lightcurve_y_limits(lc_source)
    fig.y_range = Range1d(start=ylims[0], end=ylims[1])

    # Add step lines, circles, and hover-over tooltips
    fig.step('time',
             'flux',
             line_width=1,
             color='gray',
             source=lc_source,
             nonselection_line_color='gray',
             nonselection_line_alpha=1.0)
    circ = fig.circle('time',
                      'flux',
                      source=lc_source,
                      fill_alpha=0.3,
                      size=8,
                      line_color=None,
                      selection_color="firebrick",
                      nonselection_fill_alpha=0.0,
                      nonselection_fill_color="grey",
                      nonselection_line_color=None,
                      nonselection_line_alpha=0.0,
                      fill_color=None,
                      hover_fill_color="firebrick",
                      hover_alpha=0.9,
                      hover_line_color="white")
    tooltips = [("Cadence", "@cadence"),
                ("Time ({})".format(lc.time_format.upper()), "@time{0,0.000}"),
                ("Time (ISO)", "@time_iso"), ("Flux", "@flux"),
                ("Quality Code", "@quality_code"),
                ("Quality Flag", "@quality")]
    fig.add_tools(
        HoverTool(tooltips=tooltips,
                  renderers=[circ],
                  mode='mouse',
                  point_policy="snap_to_data"))

    # Vertical line to indicate the cadence
    vertical_line = Span(location=lc.time[0],
                         dimension='height',
                         line_color='firebrick',
                         line_width=4,
                         line_alpha=0.5)
    fig.add_layout(vertical_line)

    return fig, vertical_line
コード例 #7
0
def plot_rank(
    axes,
    length_plotters,
    rows,
    cols,
    figsize,
    plotters,
    bins,
    kind,
    colors,
    ref_line,
    labels,
    labeller,
    ref_line_kwargs,
    bar_kwargs,
    vlines_kwargs,
    marker_vlines_kwargs,
    backend_kwargs,
    show,
):
    """Bokeh rank plot."""
    if ref_line_kwargs is None:
        ref_line_kwargs = {}
    ref_line_kwargs.setdefault("line_dash", "dashed")
    ref_line_kwargs.setdefault("line_color", "black")

    if bar_kwargs is None:
        bar_kwargs = {}
    bar_kwargs.setdefault("line_color", "white")

    if vlines_kwargs is None:
        vlines_kwargs = {}
    vlines_kwargs.setdefault("line_width", 2)
    vlines_kwargs.setdefault("line_dash", "solid")

    if marker_vlines_kwargs is None:
        marker_vlines_kwargs = {}

    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(
            ("dpi", "plot.bokeh.figure.dpi"),
        ),
        **backend_kwargs,
    }
    figsize, *_ = _scale_fig_size(figsize, None, rows=rows, cols=cols)
    if axes is None:
        axes = create_axes_grid(
            length_plotters,
            rows,
            cols,
            figsize=figsize,
            sharex=True,
            sharey=True,
            backend_kwargs=backend_kwargs,
        )
    else:
        axes = np.atleast_2d(axes)

    for ax, (var_name, selection, isel, var_data) in zip(
        (item for item in axes.flatten() if item is not None), plotters
    ):
        ranks = compute_ranks(var_data)
        bin_ary = np.histogram_bin_edges(ranks, bins=bins, range=(0, ranks.size))
        all_counts = np.empty((len(ranks), len(bin_ary) - 1))
        for idx, row in enumerate(ranks):
            _, all_counts[idx], _ = histogram(row, bins=bin_ary)
        counts_normalizer = all_counts.max() / 0.95
        gap = 1
        width = bin_ary[1] - bin_ary[0]

        bar_kwargs.setdefault("width", width)
        # Center the bins
        bin_ary = (bin_ary[1:] + bin_ary[:-1]) / 2

        y_ticks = []
        if kind == "bars":
            for idx, counts in enumerate(all_counts):
                counts = counts / counts_normalizer
                y_ticks.append(idx * gap)
                ax.vbar(
                    x=bin_ary,
                    top=y_ticks[-1] + counts,
                    bottom=y_ticks[-1],
                    fill_color=colors[idx],
                    **bar_kwargs,
                )
                if ref_line:
                    hline = Span(location=y_ticks[-1] + counts.mean(), **ref_line_kwargs)
                    ax.add_layout(hline)
            if labels:
                ax.yaxis.axis_label = "Chain"
        elif kind == "vlines":
            ymin = np.full(len(all_counts), all_counts.mean())
            for idx, counts in enumerate(all_counts):
                ax.circle(
                    bin_ary,
                    counts,
                    fill_color=colors[idx],
                    line_color=colors[idx],
                    **marker_vlines_kwargs,
                )
                x_locations = [(bin, bin) for bin in bin_ary]
                y_locations = [(ymin[idx], counts_) for counts_ in counts]
                ax.multi_line(x_locations, y_locations, line_color=colors[idx], **vlines_kwargs)

            if ref_line:
                hline = Span(location=all_counts.mean(), **ref_line_kwargs)
                ax.add_layout(hline)

        if labels:
            ax.xaxis.axis_label = "Rank (all chains)"

            ax.yaxis.ticker = FixedTicker(ticks=y_ticks)
            ax.xaxis.major_label_overrides = dict(
                zip(map(str, y_ticks), map(str, range(len(y_ticks))))
            )

        else:
            ax.yaxis.major_tick_line_color = None
            ax.yaxis.minor_tick_line_color = None

            ax.xaxis.major_label_text_font_size = "0pt"
            ax.yaxis.major_label_text_font_size = "0pt"

        _title = Title()
        _title.text = labeller.make_label_vert(var_name, selection, isel)
        ax.title = _title

    show_layout(axes, show)

    return axes
コード例 #8
0
ファイル: traceplot.py プロジェクト: CentralLT/arviz
def plot_trace(
    data,
    var_names,
    divergences,
    kind,
    figsize,
    rug,
    lines,
    compact,
    compact_prop,
    combined,
    chain_prop,
    legend,
    plot_kwargs,
    fill_kwargs,
    rug_kwargs,
    hist_kwargs,
    trace_kwargs,
    rank_kwargs,
    plotters,
    divergence_data,
    axes,
    backend_kwargs,
    backend_config,
    show,
):
    """Bokeh traceplot."""
    # If divergences are plotted they must be provided
    if divergences is not False:
        assert divergence_data is not None

    if backend_config is None:
        backend_config = {}

    backend_config = {
        **backend_kwarg_defaults(("bounds_y_range", "plot.bokeh.bounds_y_range"), ),
        **backend_config,
    }

    # Set plot default backend kwargs
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ),
        **backend_kwargs,
    }
    dpi = backend_kwargs.pop("dpi")

    if figsize is None:
        figsize = (12, len(plotters) * 2)

    figsize, _, _, _, linewidth, _ = _scale_fig_size(figsize,
                                                     10,
                                                     rows=len(plotters),
                                                     cols=2)

    backend_kwargs.setdefault("height", int(figsize[1] * dpi // len(plotters)))
    backend_kwargs.setdefault("width", int(figsize[0] * dpi // 2))

    if lines is None:
        lines = ()

    num_chain_props = len(data.chain) + 1 if combined else len(data.chain)
    if not compact:
        chain_prop = ({
            "line_color":
            plt.rcParams["axes.prop_cycle"].by_key()["color"]
        } if chain_prop is None else chain_prop)
    else:
        chain_prop = ({
            "line_dash": ("solid", "dotted", "dashed", "dashdot"),
        } if chain_prop is None else chain_prop)
        compact_prop = ({
            "line_color":
            plt.rcParams["axes.prop_cycle"].by_key()["color"]
        } if compact_prop is None else compact_prop)

    if isinstance(chain_prop, str):
        chain_prop = {
            chain_prop: plt.rcParams["axes.prop_cycle"].by_key()[chain_prop]
        }
    if isinstance(chain_prop, tuple):
        warnings.warn(
            "chain_prop as a tuple will be deprecated in a future warning, use a dict instead",
            FutureWarning,
        )
        chain_prop = {chain_prop[0]: chain_prop[1]}
    chain_prop = {
        prop_name:
        [prop for _, prop in zip(range(num_chain_props), cycle(props))]
        for prop_name, props in chain_prop.items()
    }

    if isinstance(compact_prop, str):
        compact_prop = {
            compact_prop:
            plt.rcParams["axes.prop_cycle"].by_key()[compact_prop]
        }
    if isinstance(compact_prop, tuple):
        warnings.warn(
            "compact_prop as a tuple will be deprecated in a future warning, use a dict instead",
            FutureWarning,
        )
        compact_prop = {compact_prop[0]: compact_prop[1]}

    trace_kwargs = {} if trace_kwargs is None else trace_kwargs
    trace_kwargs.setdefault("alpha", 0.35)

    if hist_kwargs is None:
        hist_kwargs = {}
    hist_kwargs.setdefault("alpha", 0.35)

    if plot_kwargs is None:
        plot_kwargs = {}
    if fill_kwargs is None:
        fill_kwargs = {}
    if rug_kwargs is None:
        rug_kwargs = {}
    if rank_kwargs is None:
        rank_kwargs = {}

    trace_kwargs.setdefault("line_width", linewidth)
    plot_kwargs.setdefault("line_width", linewidth)

    if rank_kwargs is None:
        rank_kwargs = {}

    if axes is None:
        axes = []
        for i in range(len(plotters)):
            if i != 0:
                _axes = [
                    bkp.figure(**backend_kwargs),
                    bkp.figure(x_range=axes[0][1].x_range, **backend_kwargs),
                ]
            else:
                _axes = [
                    bkp.figure(**backend_kwargs),
                    bkp.figure(**backend_kwargs)
                ]
            axes.append(_axes)

    axes = np.atleast_2d(axes)

    cds_data = {}
    cds_var_groups = {}
    draw_name = "draw"

    for var_name, selection, value in list(
            xarray_var_iter(data, var_names=var_names, combined=True)):
        if selection:
            cds_name = "{}_ARVIZ_CDS_SELECTION_{}".format(
                var_name,
                "_".join(
                    str(item) for key, value in selection.items()
                    for item in ([key, value] if (
                        isinstance(value, str) or
                        not isinstance(value, Iterable)) else [key, *value])),
            )
        else:
            cds_name = var_name

        if var_name not in cds_var_groups:
            cds_var_groups[var_name] = []
        cds_var_groups[var_name].append(cds_name)

        for chain_idx, _ in enumerate(data.chain.values):
            if chain_idx not in cds_data:
                cds_data[chain_idx] = {}
            _data = value[chain_idx]
            cds_data[chain_idx][cds_name] = _data

    while any(key == draw_name for key in cds_data[0]):
        draw_name += "w"

    for chain_idx in cds_data:
        cds_data[chain_idx][draw_name] = data.draw.values

    cds_data = {
        chain_idx: ColumnDataSource(cds)
        for chain_idx, cds in cds_data.items()
    }

    for idx, (var_name, selection, value) in enumerate(plotters):
        value = np.atleast_2d(value)

        if len(value.shape) == 2:
            y_name = (var_name
                      if not selection else "{}_ARVIZ_CDS_SELECTION_{}".format(
                          var_name,
                          "_".join(
                              str(item) for key, value in selection.items()
                              for item in ((key, value) if (
                                  isinstance(value, str)
                                  or not isinstance(value, Iterable)) else (
                                      key, *value))),
                      ))
            if rug:
                rug_kwargs["y"] = y_name
            _plot_chains_bokeh(
                ax_density=axes[idx, 0],
                ax_trace=axes[idx, 1],
                data=cds_data,
                x_name=draw_name,
                y_name=y_name,
                chain_prop=chain_prop,
                combined=combined,
                rug=rug,
                kind=kind,
                legend=legend,
                trace_kwargs=trace_kwargs,
                hist_kwargs=hist_kwargs,
                plot_kwargs=plot_kwargs,
                fill_kwargs=fill_kwargs,
                rug_kwargs=rug_kwargs,
                rank_kwargs=rank_kwargs,
            )
        else:
            for y_name in cds_var_groups[var_name]:
                if rug:
                    rug_kwargs["y"] = y_name
                _plot_chains_bokeh(
                    ax_density=axes[idx, 0],
                    ax_trace=axes[idx, 1],
                    data=cds_data,
                    x_name=draw_name,
                    y_name=y_name,
                    chain_prop=chain_prop,
                    combined=combined,
                    rug=rug,
                    kind=kind,
                    legend=legend,
                    trace_kwargs=trace_kwargs,
                    hist_kwargs=hist_kwargs,
                    plot_kwargs=plot_kwargs,
                    fill_kwargs=fill_kwargs,
                    rug_kwargs=rug_kwargs,
                    rank_kwargs=rank_kwargs,
                )

        for col in (0, 1):
            _title = Title()
            _title.text = make_label(var_name, selection)
            axes[idx, col].title = _title
            axes[idx, col].y_range = DataRange1d(
                bounds=backend_config["bounds_y_range"], min_interval=0.1)

        for _, _, vlines in (j for j in lines
                             if j[0] == var_name and j[1] == selection):
            if isinstance(vlines, (float, int)):
                line_values = [vlines]
            else:
                line_values = np.atleast_1d(vlines).ravel()

            for line_value in line_values:
                vline = Span(
                    location=line_value,
                    dimension="height",
                    line_color="black",
                    line_width=1.5,
                    line_alpha=0.75,
                )
                hline = Span(
                    location=line_value,
                    dimension="width",
                    line_color="black",
                    line_width=1.5,
                    line_alpha=trace_kwargs["alpha"],
                )

                axes[idx, 0].renderers.append(vline)
                axes[idx, 1].renderers.append(hline)

        if legend:
            for col in (0, 1):
                axes[idx, col].legend.location = "top_left"
                axes[idx, col].legend.click_policy = "hide"
        else:
            for col in (0, 1):
                if axes[idx, col].legend:
                    axes[idx, col].legend.visible = False

        if divergences:
            div_density_kwargs = {}
            div_density_kwargs.setdefault("size", 14)
            div_density_kwargs.setdefault("line_color", "red")
            div_density_kwargs.setdefault("line_width", 2)
            div_density_kwargs.setdefault("line_alpha", 0.50)
            div_density_kwargs.setdefault("angle", np.pi / 2)

            div_trace_kwargs = {}
            div_trace_kwargs.setdefault("size", 14)
            div_trace_kwargs.setdefault("line_color", "red")
            div_trace_kwargs.setdefault("line_width", 2)
            div_trace_kwargs.setdefault("line_alpha", 0.50)
            div_trace_kwargs.setdefault("angle", np.pi / 2)

            div_selection = {
                k: v
                for k, v in selection.items() if k in divergence_data.dims
            }
            divs = divergence_data.sel(**div_selection).values
            divs = np.atleast_2d(divs)

            for chain, chain_divs in enumerate(divs):
                div_idxs = np.arange(len(chain_divs))[chain_divs]
                if div_idxs.size > 0:
                    values = value[chain, div_idxs]
                    tmp_cds = ColumnDataSource({"y": values, "x": div_idxs})
                    if divergences == "top":
                        y_div_trace = value.max()
                    else:
                        y_div_trace = value.min()
                    glyph_density = Dash(x="y", y=0.0, **div_density_kwargs)
                    glyph_trace = Dash(x="x",
                                       y=y_div_trace,
                                       **div_trace_kwargs)

                    axes[idx, 0].add_glyph(tmp_cds, glyph_density)
                    axes[idx, 1].add_glyph(tmp_cds, glyph_trace)

    show_layout(axes, show)

    return axes
コード例 #9
0
ファイル: mcseplot.py プロジェクト: sonawalepriyanca/arviz
def plot_mcse(
    ax,
    plotters,
    length_plotters,
    rows,
    cols,
    figsize,
    errorbar,
    rug,
    data,
    probs,
    kwargs,  # pylint: disable=unused-argument
    extra_methods,
    mean_mcse,
    sd_mcse,
    textsize,
    text_kwargs,  # pylint: disable=unused-argument
    rug_kwargs,
    extra_kwargs,
    idata,
    rug_kind,
    backend_kwargs,
    show,
):
    """Bokeh mcse plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(),
        **backend_kwargs,
    }

    (figsize, *_, _linewidth,
     _markersize) = _scale_fig_size(figsize, textsize, rows, cols)

    extra_kwargs = {} if extra_kwargs is None else extra_kwargs
    extra_kwargs.setdefault("linewidth", _linewidth / 2)
    extra_kwargs.setdefault("color", "black")
    extra_kwargs.setdefault("alpha", 0.5)

    if ax is None:
        ax = create_axes_grid(
            length_plotters,
            rows,
            cols,
            figsize=figsize,
            backend_kwargs=backend_kwargs,
        )
    else:
        ax = np.atleast_2d(ax)

    for (var_name, selection,
         x), ax_ in zip(plotters,
                        (item for item in ax.flatten() if item is not None)):
        if errorbar or rug:
            values = data[var_name].sel(**selection).values.flatten()
        if errorbar:
            quantile_values = _quantile(values, probs)
            ax_.dash(probs, quantile_values)
            ax_.multi_line(
                list(zip(probs, probs)),
                [(quant - err, quant + err)
                 for quant, err in zip(quantile_values, x)],
            )
        else:
            ax_.circle(probs, x)
            if extra_methods:
                mean_mcse_i = mean_mcse[var_name].sel(
                    **selection).values.item()
                sd_mcse_i = sd_mcse[var_name].sel(**selection).values.item()
                hline_mean = Span(
                    location=mean_mcse_i,
                    dimension="width",
                    line_color=extra_kwargs["color"],
                    line_width=extra_kwargs["linewidth"] * 2,
                    line_alpha=extra_kwargs["alpha"],
                )

                ax_.renderers.append(hline_mean)

                hline_sd = Span(
                    location=sd_mcse_i,
                    dimension="width",
                    line_color="black",
                    line_width=extra_kwargs["linewidth"],
                    line_alpha=extra_kwargs["alpha"],
                )

                ax_.renderers.append(hline_sd)

        if rug:
            if rug_kwargs is None:
                rug_kwargs = {}
            if not hasattr(idata, "sample_stats"):
                raise ValueError(
                    "InferenceData object must contain sample_stats for rug plot"
                )
            if not hasattr(idata.sample_stats, rug_kind):
                raise ValueError(
                    "InferenceData does not contain {} data".format(rug_kind))
            rug_kwargs.setdefault("space", 0.1)

            _rug_kwargs = {}
            _rug_kwargs.setdefault("size", 8)
            _rug_kwargs.setdefault("line_color",
                                   rug_kwargs.get("line_color", "black"))
            _rug_kwargs.setdefault("line_width", 1)
            _rug_kwargs.setdefault("line_alpha", 0.35)
            _rug_kwargs.setdefault("angle", np.pi / 2)

            mask = idata.sample_stats[rug_kind].values.flatten()
            values = rankdata(values, method="average")[mask]
            if errorbar:
                rug_x, rug_y = (
                    values / (len(mask) - 1),
                    np.full_like(
                        values,
                        min(
                            0,
                            min(quantile_values) -
                            (max(quantile_values) - min(quantile_values)) *
                            0.05,
                        ),
                    ),
                )

                hline = Span(
                    location=min(
                        0,
                        min(quantile_values) -
                        (max(quantile_values) - min(quantile_values)) * 0.05,
                    ),
                    dimension="width",
                    line_color="black",
                    line_width=_linewidth,
                    line_alpha=0.7,
                )

            else:
                rug_x, rug_y = (
                    values / (len(mask) - 1),
                    np.full_like(
                        values,
                        0,
                    ),
                )

                hline = Span(
                    location=0,
                    dimension="width",
                    line_color="black",
                    line_width=_linewidth,
                    line_alpha=0.7,
                )

            ax_.renderers.append(hline)

            glyph = Dash(x="rug_x", y="rug_y", **_rug_kwargs)
            cds_rug = ColumnDataSource({
                "rug_x": np.asarray(rug_x),
                "rug_y": np.asarray(rug_y)
            })
            ax_.add_glyph(cds_rug, glyph)

        title = Title()
        title.text = make_label(var_name, selection)
        ax_.title = title

        ax_.xaxis.axis_label = "Quantile"
        ax_.yaxis.axis_label = (r"Value $\pm$ MCSE for quantiles"
                                if errorbar else "MCSE for quantiles")

        if not errorbar:
            ax_.y_range._property_values["start"] = -0.05  # pylint: disable=protected-access
            ax_.y_range._property_values["end"] = 1  # pylint: disable=protected-access

    show_layout(ax, show)

    return ax
コード例 #10
0
for idx in range(0, len(tracking_keys)):
    print(f'Searching for {tracking_keys[idx]} in stream {idx}')
tracking_names = ['Beto O\'Rourke', 'Ted Cruz']

db_names = ['{0}.sqlite'.format(slugify(name)) for name in tracking_names]

feels = [TweetFeels(login, tracking=tracking, db=dbname) for tracking, dbname in zip(tracking_keys, db_names)]

p = figure(sizing_mode='stretch_both')
p.legend.location = "top_left"
colors = itertools.cycle(palette) 

rs = [p.line([], [], color=color, line_width=2, legend=name) for name, color in zip(tracking_names, colors)]

# Horizontal line
hline = Span(location=0, dimension='width', line_color='black', line_width=3)
pos_box = BoxAnnotation(left=-sys.maxsize, right=sys.maxsize, top=1, bottom=0, fill_color='green', fill_alpha=0.1)
neg_box = BoxAnnotation(left=-sys.maxsize, right=sys.maxsize, top=0, bottom=-1, fill_color='red', fill_alpha=0.1)

p.renderers.extend([hline, pos_box, neg_box])

dss = [r.data_source for r in rs]

most_recent_sentiment = [0 for _ in rs]

def print_feels(seconds=10):
    global most_recent_sentiment, feels
    while go_on:
        time.sleep(seconds)
        for idx, feel in enumerate(feels):
            try:
コード例 #11
0
wid = 2
p.line(x='x',
       y='y',
       line_width=wid,
       color="red",
       legend_label="Cost with investment",
       source=df)
p.line(x='x',
       y='y2',
       line_width=wid,
       color="blue",
       legend_label="Cost without investment",
       source=df)

eq_solve = Span(location=0, dimension='height', line_width=2)
p.add_layout(eq_solve)

slope_input = TextInput(value="1", name="slope_input")
var_input = TextInput(value="3", name="var_input")
int_input = TextInput(value="60", name="int_input")

curdoc().add_root(slope_input)
curdoc().add_root(var_input)
curdoc().add_root(int_input)

button = Button(label="Draw!", name="myButton")


def b_call(event):
    """
コード例 #12
0
ファイル: scatterCI.py プロジェクト: CIMCB/cimcb_lite
def scatterCI(x, ci=None, label=None, hoverlabel=None, hline=0, sort_abs=False, col_hline=True, col_palette=None, title="Scatter CI Plot", xlabel="Peak", ylabel="Value", width=200, height=300, legend=True, font_size="20pt", label_font_size="13pt", linkrange=None, grid_line=True, border_line=False, x_axis_location="below"):
    """Creates a scatterCI plot using Bokeh.

    Required Parameters
    -------------------
    X : array-like, shape = [n_samples]
        Inpute data
    """
    # If label is None, give an index based on input order
    if label is None:
        label_copy = []
        for i in range(len(x)):
            label_copy.append(str(i))
    else:
        label_copy = deepcopy(label)

    # Ensure label_copy is unique and under 60 characters until supported by Bokeh
    label_copy = [elem[:59] for elem in label_copy]  # Limit Label characters limit to 59
    label_copy = np.array(label_copy).tolist()
    label_unique = set(label_copy)
    label_indices = {value: [i for i, v in enumerate(label_copy) if v == value] for value in label_unique}
    for key, value in label_indices.items():
        if len(value) > 1:
            for i in range(len(value)):
                label_copy[value[i]] = (str(" ") * i) + label_copy[value[i]]

    # Make sure height accounts for the max length of label
    height = height + 5 * len(max(label_copy, key=len))

    # If colour palette is None (default):
    if col_palette is None:
        col_palette = ["blue", "red", "green"]

    # if col_hline is True, color depends on if error bar overlaps hline
    if col_hline is False:
        col = []
        for i in range(len(x)):
            col.append(col_palette[2])
    else:
        col = []
        if ci is None:
            for i in range(len(x)):
                if x[i] < hline < x[i]:
                    col.append(col_palette[0])
                else:
                    col.append(col_palette[1])
        else:
            for i in range(len(x)):
                if ci[:, 0][i] < hline < ci[:, 1][i]:
                    col.append(col_palette[0])
                else:
                    col.append(col_palette[1])

    # Sort data (absolute)
    if sort_abs is True:
        sorted_idx = np.argsort(abs(x))[::-1]
        x = x[sorted_idx]
        label_copy = np.array(label_copy)
        label_copy = label_copy[sorted_idx]
        col = np.array(col)
        col = col[sorted_idx]
        # Sort ci if it exists
        if ci is not None:
            ci_low = ci[:, 0][sorted_idx]
            ci_high = ci[:, 1][sorted_idx]
            ci = []
            for i in range(len(ci_low)):
                ci.append([ci_low[i], ci_high[i]])
            ci = np.array(ci)
        hoverlabel = hoverlabel.copy()
    elif sort_abs is False:
        pass

    if hoverlabel is None:
        hoverlabel_copy = {}
        hoverlabel_copy["Idx"] = list(range(len(x)))
    else:
        try:
            hoverlabel2 = hoverlabel.copy()
            hoverlabel2_dict = hoverlabel2.to_dict("series")
            hoverlabel_copy = hoverlabel2_dict
        except TypeError:
            hoverlabel2 = label.copy()
            hoverlabel_copy = {}
            hoverlabel_copy[label2.name] = hoverlabel2.values.tolist()

        # Sort hoverlabel
        if sort_abs is True:
            hoverlabel2 = {}
            for key, value in hoverlabel_copy.items():
                hoverlabel2[key] = np.array(value)[sorted_idx]
            hoverlabel_copy = hoverlabel2

    # Linking to another plot
    if linkrange is None:
        xrange = label_copy
    else:
        xrange = linkrange.x_range

    # Bokeh data source
    if ci is None:
        data = {"x": x, "col": col, "label": label_copy}
    else:
        data = {"x": x, "lowci": ci[:, 0], "uppci": ci[:, 1], "col": col, "label": label_copy}
    data_label = {}
    for name, val in hoverlabel_copy.items():
        data_label[name] = val
    data.update(data_label)
    source = ColumnDataSource(data=data)

    # Tool-tip
    TOOLTIPS = []
    for name, val in data_label.items():
        TOOLTIPS.append((str(name), "@" + str(name)))
    TOOLTIPS.append(("Value", "@x{1.111}"))
    TOOLTIPS.append(("Upper", "@uppci{1.111}"))
    TOOLTIPS.append(("Lower", "@lowci{1.111}"))

    if ci is None:
        y_range_max = max(abs(np.min(x)), abs(np.max(x)), abs(np.min(x)), abs(np.max(x))) * 0.1
        y_range = (min(np.min(x) - y_range_max, np.min(x) - y_range_max), max(np.max(x) + y_range_max, np.max(x) + y_range_max))
    else:
        y_range_max = max(abs(np.min(ci[:, 0])), abs(np.max(ci[:, 0])), abs(np.min(ci[:, 1])), abs(np.max(ci[:, 1]))) * 0.1
        y_range = (min(np.min(ci[:, 0]) - y_range_max, np.min(ci[:, 0]) - y_range_max), max(np.max(ci[:, 1]) + y_range_max, np.max(ci[:, 0]) + y_range_max))

    # Base figure
    if x_axis_location == 'above':
        fig = figure(title=title, x_axis_label=xlabel, y_axis_label=ylabel, x_range=xrange, y_range=y_range, plot_width=int(len(x) / 10 * width), plot_height=height, tooltips=TOOLTIPS, toolbar_location="left", toolbar_sticky=False, x_axis_location="above")
    else:
        fig = figure(title=title, x_axis_label=xlabel, y_axis_label=ylabel, x_range=xrange, y_range=y_range, plot_width=int(len(x) / 10 * width), plot_height=height, tooltips=TOOLTIPS, toolbar_location="left", toolbar_sticky=False)
    
    # Add circles
    fig.circle("label", "x", size=10, alpha=0.6, color="col", source=source)

    # Add hline
    hline = Span(location=hline, dimension="width", line_color="black", line_width=2, line_alpha=0.3)
    fig.add_layout(hline)

    # Add error bars
    if ci is not None:
        fig.add_layout(Whisker(base="label", lower="lowci", upper="uppci", line_color="col", line_width=1.5, source=source))

    # Font-sizes
    fig.title.text_font_size = font_size
    fig.xaxis.axis_label_text_font_size = label_font_size
    fig.yaxis.axis_label_text_font_size = label_font_size

    # X-axis orientation
    fig.xaxis.major_label_orientation = np.pi / 2

    # Extra padding
    fig.min_border_left = 20
    fig.min_border_right = 20
    fig.min_border_top = 20
    fig.min_border_bottom = 20
    
    # Remove grid lines
    if grid_line == False:
        fig.xgrid.visible = False
        fig.ygrid.visible = False
        
    # Add border
    if border_line == True:
        fig.outline_line_width = 2
        fig.outline_line_alpha = 1
        fig.outline_line_color = "black"
    return fig
コード例 #13
0
expected_line = p.line(x='index', y='defunciones_esperadas', source=merged_df, name='Expected Deaths', color=palette[1],
                       legend_label='Expected', line_width=1)

covid_line = p.line(x='index', y='expected_plus_covid', source=merged_df, name='COVID-19 Deaths', color='red',
                    legend_label='COVID-19', line_width=1)

# create and add bands
confidence_interval = Band(base='index', lower='defunciones_esperadas_q99', upper='defunciones_esperadas_q01',
                           source=ColumnDataSource(merged_df), level='underlay', fill_alpha=1.0, line_width=1,
                           line_color='black')
p.add_layout(confidence_interval)

# create lockdown span
lockdown_date = time.mktime(dt(2020, 3, 14, 0, 0, 0).timetuple()) * 1000
lockdown_start = Span(location=lockdown_date, dimension='height', line_color=palette[3], line_dash='dashed',
                      line_width=2)
lockdown_label = Label(x=lockdown_date, y=10, y_units='screen', text=' Lockdown', text_font='helvetica',
                       text_font_size='9pt')

# create phase 0 span
phase0_date = time.mktime(dt(2020, 5, 2, 0, 0, 0).timetuple()) * 1000
phase0_start = Span(location=phase0_date, dimension='height', line_color=palette[6], line_dash='dashed',
                    line_width=2)
phase0_label = Label(x=phase0_date, y=10, y_units='screen', text=' 0', text_font='helvetica',
                     text_font_size='9pt')

# create phase 1 span
phase1_date = time.mktime(dt(2020, 5, 11, 0, 0, 0).timetuple()) * 1000
phase1_start = Span(location=phase1_date, dimension='height', line_color=palette[7], line_dash='dashed',
                    line_width=2)
phase1_label = Label(x=phase1_date, y=10, y_units='screen', text=' 1', text_font='helvetica',
コード例 #14
0
    def _plot_indicators():
        """Strategy indicators"""
        def _too_many_dims(value):
            assert value.ndim >= 2
            if value.ndim > 2:
                warnings.warn(
                    f"Can't plot indicators with >2D ('{value.name}')",
                    stacklevel=5)
                return True
            return False

        class LegendStr(str):
            # The legend string is such a string that only matches
            # itself if it's the exact same object. This ensures
            # legend items are listed separately even when they have the
            # same string contents. Otherwise, Bokeh would always consider
            # equal strings as one and the same legend item.
            def __eq__(self, other):
                return self is other

        ohlc_colors = colorgen()
        indicator_figs = []

        for i, value in enumerate(indicators):
            value = np.atleast_2d(value)

            # Use .get()! A user might have assigned a Strategy.data-evolved
            # _Array without Strategy.I()
            if not value._opts.get('plot') or _too_many_dims(value):
                continue

            is_overlay = value._opts['overlay']
            is_scatter = value._opts['scatter']
            if is_overlay:
                fig = fig_ohlc
            else:
                fig = new_indicator_figure()
                indicator_figs.append(fig)
            tooltips = []
            colors = value._opts['color']
            colors = colors and cycle(_as_list(colors)) or (cycle(
                [next(ohlc_colors)]) if is_overlay else colorgen())
            legend_label = LegendStr(value.name)
            for j, arr in enumerate(value, 1):
                color = next(colors)
                source_name = f'{legend_label}_{i}_{j}'
                if arr.dtype == bool:
                    arr = arr.astype(int)
                source.add(arr, source_name)
                tooltips.append(f'@{{{source_name}}}{{0,0.0[0000]}}')
                if is_overlay:
                    ohlc_extreme_values[source_name] = arr
                    if is_scatter:
                        fig.scatter(
                            'index',
                            source_name,
                            source=source,
                            legend_label=legend_label,
                            color=color,
                            line_color='black',
                            fill_alpha=0.8,
                            marker='circle',
                            radius=BAR_WIDTH / 2 * 1.5,
                        )
                    else:
                        fig.line(
                            'index',
                            source_name,
                            source=source,
                            legend_label=legend_label,
                            line_color=color,
                            line_width=1.3,
                        )
                else:
                    if is_scatter:
                        r = fig.scatter(
                            'index',
                            source_name,
                            source=source,
                            legend_label=LegendStr(legend_label),
                            color=color,
                            marker='circle',
                            radius=BAR_WIDTH / 2 * 0.9,
                        )
                    else:
                        r = fig.line(
                            'index',
                            source_name,
                            source=source,
                            legend_label=LegendStr(legend_label),
                            line_color=color,
                            line_width=1.3,
                        )
                    # Add dashed centerline just because
                    mean = float(pd.Series(arr).mean())
                    if not np.isnan(mean) and (
                            abs(mean) < 0.1 or round(abs(mean), 1) == 0.5
                            or round(abs(mean), -1) in (50, 100, 200)):
                        fig.add_layout(
                            Span(
                                location=float(mean),
                                dimension='width',
                                line_color='#666666',
                                line_dash='dashed',
                                line_width=0.5,
                            ))
            if is_overlay:
                ohlc_tooltips.append((legend_label, NBSP.join(tooltips)))
            else:
                set_tooltips(
                    fig,
                    [(legend_label, NBSP.join(tooltips))],
                    vline=True,
                    renderers=[r],
                )
                # If the sole indicator line on this figure,
                # have the legend only contain text without the glyph
                if len(value) == 1:
                    fig.legend.glyph_width = 0
        return indicator_figs
コード例 #15
0
def plot_ess(
    ax,
    plotters,
    xdata,
    ess_tail_dataset,
    mean_ess,
    sd_ess,
    idata,
    data,
    kind,
    extra_methods,
    textsize,
    rows,
    cols,
    figsize,
    kwargs,
    extra_kwargs,
    text_kwargs,
    n_samples,
    relative,
    min_ess,
    labeller,
    ylabel,
    rug,
    rug_kind,
    rug_kwargs,
    hline_kwargs,
    backend_kwargs,
    show,
):
    """Bokeh essplot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(),
        **backend_kwargs,
    }

    (figsize, *_, _linewidth,
     _markersize) = _scale_fig_size(figsize, textsize, rows, cols)

    if ax is None:
        ax = create_axes_grid(
            len(plotters),
            rows,
            cols,
            figsize=figsize,
            backend_kwargs=backend_kwargs,
        )
    else:
        ax = np.atleast_2d(ax)

    for (var_name, selection, isel,
         x), ax_ in zip(plotters,
                        (item for item in ax.flatten() if item is not None)):
        bulk_points = ax_.circle(np.asarray(xdata), np.asarray(x), size=6)
        if kind == "evolution":
            bulk_line = ax_.line(np.asarray(xdata), np.asarray(x))
            ess_tail = ess_tail_dataset[var_name].sel(**selection)
            tail_points = ax_.line(np.asarray(xdata),
                                   np.asarray(ess_tail),
                                   color="orange")
            tail_line = ax_.circle(np.asarray(xdata),
                                   np.asarray(ess_tail),
                                   size=6,
                                   color="orange")
        elif rug:
            if rug_kwargs is None:
                rug_kwargs = {}
            if not hasattr(idata, "sample_stats"):
                raise ValueError(
                    "InferenceData object must contain sample_stats for rug plot"
                )
            if not hasattr(idata.sample_stats, rug_kind):
                raise ValueError(
                    "InferenceData does not contain {} data".format(rug_kind))

            rug_kwargs.setdefault("space", 0.1)
            _rug_kwargs = {}
            _rug_kwargs.setdefault("size", 8)
            _rug_kwargs.setdefault("line_color",
                                   rug_kwargs.get("line_color", "black"))
            _rug_kwargs.setdefault("line_width", 1)
            _rug_kwargs.setdefault("line_alpha", 0.35)
            _rug_kwargs.setdefault("angle", np.pi / 2)

            values = data[var_name].sel(**selection).values.flatten()
            mask = idata.sample_stats[rug_kind].values.flatten()
            values = rankdata(values, method="average")[mask]
            rug_space = np.max(x) * rug_kwargs.pop("space")
            rug_x, rug_y = values / (len(mask) -
                                     1), np.zeros_like(values) - rug_space

            glyph = Scatter(x="rug_x", y="rug_y", marker="dash", **_rug_kwargs)
            cds_rug = ColumnDataSource({
                "rug_x": np.asarray(rug_x),
                "rug_y": np.asarray(rug_y)
            })
            ax_.add_glyph(cds_rug, glyph)

            hline = Span(
                location=0,
                dimension="width",
                line_color="black",
                line_width=_linewidth,
                line_alpha=0.7,
            )

            ax_.renderers.append(hline)

        if extra_methods:
            mean_ess_i = mean_ess[var_name].sel(**selection).values.item()
            sd_ess_i = sd_ess[var_name].sel(**selection).values.item()

            hline = Span(
                location=mean_ess_i,
                dimension="width",
                line_color="black",
                line_width=2,
                line_dash="dashed",
                line_alpha=1.0,
            )

            ax_.renderers.append(hline)

            hline = Span(
                location=sd_ess_i,
                dimension="width",
                line_color="black",
                line_width=1,
                line_dash="dashed",
                line_alpha=1.0,
            )

            ax_.renderers.append(hline)

        hline = Span(
            location=400 / n_samples if relative else min_ess,
            dimension="width",
            line_color="red",
            line_width=3,
            line_dash="dashed",
            line_alpha=1.0,
        )

        ax_.renderers.append(hline)

        if kind == "evolution":
            legend = Legend(
                items=[("bulk", [bulk_points, bulk_line]),
                       ("tail", [tail_line, tail_points])],
                location="center_right",
                orientation="horizontal",
            )
            ax_.add_layout(legend, "above")
            ax_.legend.click_policy = "hide"

        title = Title()
        title.text = labeller.make_label_vert(var_name, selection, isel)
        ax_.title = title

        ax_.xaxis.axis_label = "Total number of draws" if kind == "evolution" else "Quantile"
        ax_.yaxis.axis_label = ylabel.format(
            "Relative ESS" if relative else "ESS")

    show_layout(ax, show)

    return ax
コード例 #16
0
                legend_label='unstained kde'
                )

            # generate gate annoatation and add to plot
            gate = zeros['bias'][
                (zeros['channel'] == channel)
                & (zeros['tissue'] == tissue)
                & (zeros['status'] == status)
                & (zeros['timepoint'] == timepoint)
                & (zeros['replicate'] == replicate)
                ]

            gate = Span(
                location=gate.iloc[0],
                dimension='height',
                line_color='dimgrey',
                line_dash='solid',
                line_width=4.0
                )
            p.add_layout(gate)

            # assign common min and max values for x and y axes
            p.x_range.start = 0.0
            p.x_range.end = 1.0
            p.y_range.start = 0.0
            p.y_range.end = max_count

            # format legend
            p.legend.location = 'top_right'
            p.legend.background_fill_color = 'white'
            p.legend.label_text_font_size = '15pt'
コード例 #17
0
def create_prediction_plot(df, current_date):
    """Crea gráfica de predicción a futuro.

    Parameters:
		df (Dataframe): Dataframe con los datos a mostrar en la visualización.
        current_date: Ultima fecha antes de la prediccion
    Returns:
		Figure: Gráfica de de predicción a futuro.
    """

    hover_tool = HoverTool(tooltips=[('Fecha', '$x{%b %Y}'),
                                     ('Predicción', '@Prediction')],
                           formatters={
                               '$x': 'datetime',
                           },
                           mode='mouse')

    # Estructuración de los tipos de datos del dataframe
    df['añomes'] = pd.to_datetime(df['añomes'], format='%m/%d/%y %I:%M %p')
    df['Prediction'] = pd.to_numeric(pd.Series(df['Prediction'].values))

    prediction_plot = figure(plot_height=400,
                             toolbar_location=None,
                             sizing_mode='stretch_width',
                             x_axis_type='datetime',
                             output_backend="webgl")

    source_cluster_0 = create_data_source_from_dataframe(
        df, 'cluster', 'cluster_0')
    source_cluster_1 = create_data_source_from_dataframe(
        df, 'cluster', 'cluster_1')
    source_cluster_2 = create_data_source_from_dataframe(
        df, 'cluster', 'cluster_2')
    source_cluster_3 = create_data_source_from_dataframe(
        df, 'cluster', 'cluster_3')

    x_axis_tick_vals = source_cluster_0.data['añomes'].astype(int) / 10**6

    prediction_plot.line(x='añomes',
                         y='Prediction',
                         source=source_cluster_0,
                         line_width=2,
                         line_color=bokeh_utils.LINE_COLORS_PALETTE[0],
                         legend_label='Cluster 0')
    prediction_plot.line(x='añomes',
                         y='Prediction',
                         source=source_cluster_1,
                         line_width=2,
                         line_color=bokeh_utils.LINE_COLORS_PALETTE[1],
                         legend_label='Cluster 1')
    prediction_plot.line(x='añomes',
                         y='Prediction',
                         source=source_cluster_2,
                         line_width=2,
                         line_color=bokeh_utils.LINE_COLORS_PALETTE[2],
                         legend_label='Cluster 2')
    prediction_plot.line(x='añomes',
                         y='Prediction',
                         source=source_cluster_3,
                         line_width=2,
                         line_color=bokeh_utils.LINE_COLORS_PALETTE[3],
                         legend_label='Cluster 3')

    prediction_plot.xaxis.major_label_orientation = np.pi / 4
    prediction_plot.xaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR

    prediction_plot.yaxis.major_label_text_color = bokeh_utils.LABEL_FONT_COLOR

    prediction_plot.legend.location = 'top_left'
    prediction_plot.legend.orientation = 'horizontal'
    prediction_plot.legend.click_policy = 'hide'
    prediction_plot.legend.label_text_color = bokeh_utils.LABEL_FONT_COLOR
    prediction_plot.xaxis[0].formatter = DatetimeTickFormatter(
        months=['%b %Y'])
    prediction_plot.xaxis[0].ticker = FixedTicker(ticks=list(x_axis_tick_vals))
    # Linea vertical para definir el horizonte de predicción
    # current_date = dt.now() - timedelta(days=1)
    prediction_date = time.mktime(current_date.timetuple()) * 1000
    vline = Span(location=prediction_date,
                 dimension='height',
                 line_color='gray',
                 line_alpha=0.6,
                 line_dash='dotted',
                 line_width=2)
    prediction_plot.add_layout(vline)
    # Etiqueta linea horizontal
    vlabel = Label(x=prediction_date,
                   y=25,
                   text='→Predicción',
                   text_color='gray',
                   text_alpha=0.6,
                   text_font_size='14px')
    prediction_plot.add_layout(vlabel)

    prediction_plot.title.text = 'Predicción de los clusters a futuro'
    prediction_plot.title.text_color = bokeh_utils.TITLE_FONT_COLOR
    prediction_plot.title.align = 'left'
    prediction_plot.title.text_font_size = '16px'
    prediction_plot.border_fill_color = bokeh_utils.BACKGROUND_COLOR
    prediction_plot.add_tools(hover_tool)
    prediction_plot.min_border_right = 15

    return prediction_plot
コード例 #18
0
ファイル: visual.py プロジェクト: mmilata/osbs-metrics
    def get_time_charts(self, time_selector, suffix, width=600, height=350):
        charts = []

        selector = time_selector(self.metrics['completion'])
        if not any(selector):
            return charts

        # hourly throughput
        s1 = figure(width=width,
                    height=height,
                    x_axis_type='datetime',
                    title='hourly throughput' + suffix)
        s1.legend.orientation = 'bottom_left'
        s1.circle(self.metrics[selector & self.completed]['completion'],
                  self.metrics[selector & self.completed]['throughput'],
                  color='blue',
                  alpha=0.2,
                  size=12,
                  legend='hourly throughput')
        peak = Span(location=self.metrics[selector]['throughput'].max(),
                    dimension='width',
                    line_color='green',
                    line_dash='dashed',
                    line_width=3)
        s1.renderers.extend([peak])
        charts.append(s1)

        # upload size / pulp upload time
        s2 = figure(width=width,
                    height=height,
                    title='upload size vs pulp upload time' + suffix)
        s2.xaxis.axis_label = 'Time uploading to pulp'
        s2.yaxis.axis_label = 'upload size (Mb)'
        s2.xaxis.formatter = NumeralTickFormatter(format="00:00:00")
        s2.xaxis.ticker = AdaptiveTicker(mantissas=[1, 3, 6])
        s2.square(self.metrics[selector]['plugin_pulp_push'],
                  self.metrics[selector]['upload_size_mb'],
                  color='orange',
                  alpha=0.2,
                  size=12)
        charts.append(s2)

        # concurrent builds
        s3 = figure(width=width,
                    height=height,
                    title='concurrent builds' + suffix,
                    x_axis_type='datetime')
        which_c = time_selector(self.concurrent['timestamp'])
        s3.line(self.concurrent[which_c]['timestamp'],
                self.concurrent[which_c]['nbuilds'],
                line_color='green',
                line_join='bevel')
        charts.append(s3)

        # squash time vs concurrent builds
        merged = self.metrics[selector].merge(self.concurrent[which_c],
                                              left_on=['completion'],
                                              right_on=['timestamp'],
                                              sort=False)
        sc = BoxPlot(merged,
                     values='plugin_squash',
                     label='nbuilds',
                     width=width,
                     height=height,
                     title='squash time vs (other) concurrent builds' + suffix)
        sc._yaxis.formatter = NumeralTickFormatter(format="00:00:00")
        sc._yaxis.ticker = AdaptiveTicker(mantissas=[1, 3, 6])
        charts.append(sc)

        # upload_size_mb
        valid = ~np.isnan(self.metrics['upload_size_mb'])
        hsize = MyHistogram(self.metrics['upload_size_mb'][selector][valid],
                            bins=10,
                            title='Upload size' + suffix,
                            plot_width=width,
                            plot_height=height)
        hsize.xaxis.axis_label = 'Mb'
        charts.append(hsize)

        # running time by plugin
        these_metrics = self.metrics[selector]
        for column, bins, title in [
            ('running', None, 'Total build time' + suffix),
            ('plugin_pull_base_image', 15, 'Time pulling base image' + suffix),
            ('plugin_distgit_fetch_artefacts', None,
             'Time fetching sources' + suffix),
            ('docker_build', None, 'Time in docker build' + suffix),
            ('plugin_squash', None, 'Time squashing layers' + suffix),
            ('plugin_pulp_push', None, 'Time uploading to pulp' + suffix),
        ]:
            values = these_metrics[column][~np.isnan(these_metrics[column])]
            h = MyHistogram(values,
                            title=title,
                            x_axis_type='datetime',
                            bins=bins or 10,
                            plot_width=width,
                            plot_height=height)
            h.xaxis.formatter = NumeralTickFormatter(format="00:00:00")
            h.xaxis.ticker = AdaptiveTicker(mantissas=[1, 3, 6])
            h.yaxis.bounds = (0, len(these_metrics))
            charts.append(h)

        # Now show plugin-level timings for a specific image
        # data looks like:
        # completion  image       plugin_x  plugin_y
        # 2016-03-18  image/name    205       60
        #
        # reshape to:
        # imgae       plugin      value
        # image/name  plugin_x    205
        # image/name  plugin_y    60
        if self.image:
            is_image = self.metrics[selector]['image'] == self.image
            image = self.metrics[selector][is_image]
            timings = pd.melt(image[[
                'image', 'running', 'plugin_pull_base_image',
                'plugin_distgit_fetch_artefacts', 'docker_build',
                'plugin_squash', 'plugin_compress', 'plugin_pulp_push'
            ]],
                              id_vars=['image'],
                              var_name='plugin')
            im = BoxPlot(timings,
                         values='value',
                         label='plugin',
                         width=width,
                         height=height * 2,
                         title='%s timings%s' % (self.image, suffix))
            im._yaxis.formatter = NumeralTickFormatter(format="00:00:00")
            im._yaxis.ticker = AdaptiveTicker(mantissas=[1, 3, 6])
            charts.append(im)

        return charts
コード例 #19
0
        .sort_values('month')

#-----------------------------------------------------------------#
# Plot

p = figure(title="Total Daily Movement Between Districts on a Given Day",
           plot_width=800, 
           plot_height=500,
           x_axis_type='datetime')
p.circle(i5_agg['date'], 
         i5_agg['subscriber_count_p'])

# Add lockdown dates vertical line

vline1 = Span(location= dt.date(2020, 3, 27), 
             dimension='height', 
             line_color='black',
             line_dash='dashed')
vline2 = Span(location= dt.date(2020, 3, 30), 
             dimension='height', 
             line_color='black',
             line_dash='dashed')

p.renderers.extend([vline1, vline2])

# Additional formatting
p.left[0].formatter.use_scientific = False
p.toolbar.logo = None
p.toolbar_location = None
p.xaxis.axis_label = "Date"
p.yaxis.axis_label = "Movement Day"
p.title.text_font_size = '15pt'
コード例 #20
0
ファイル: scatter.py プロジェクト: widdowquinn/cimcb_lite
def scatter(x,
            y,
            label=None,
            group=None,
            title="Scatter Plot",
            xlabel="x",
            ylabel="y",
            width=600,
            height=600,
            legend=True,
            size=4,
            shape="circle",
            font_size="16pt",
            label_font_size="13pt",
            col_palette=None,
            hover_xy=True,
            gradient=False,
            hline=False,
            vline=False,
            xrange=None,
            yrange=None):
    """Creates a scatterplot using Bokeh.

    Required Parameters
    -------------------
    x : array-like, shape = [n_samples]
        Inpute data for x-axis.

    y : array-like, shape = [n_samples]
        Inpute data for y-axis.
    """

    # Error check
    if len(x) != len(y):
        raise ValueError("length of X does not match length of Y.")

    # If label is None, give an index based on input order
    if label is None:
        label_copy = {}
        label_copy["Idx"] = list(range(len(x)))
    else:
        try:
            label2 = label.copy()
            label2_dict = label2.to_dict("series")
            label_copy = label2_dict  # Ensure I don't overwrite label (when plot_groupmean=True)
        except TypeError:
            label2 = label.copy()
            label_copy = {}
            label_copy[label2.name] = label2.values.tolist()

    # If colour palette is None (default):
    if col_palette is None:
        col_palette = [
            "red", "blue", "green", "orange", "blueviolet", "gold", "peru",
            "pink", "darkblue", "olive", "teal", "slategray"
        ]

    # Group is None or allow for multiple classes
    if group is None:
        group_copy = [None] * len(x)
        col = []
        for i in range(len(x)):
            col.append(col_palette[2])
    else:
        group_copy = group.copy()
        group_unique = np.sort(np.unique(group_copy))
        col = []
        for i in range(len(group_copy)):
            for j in range(len(group_unique)):
                if group_copy[i] == group_unique[j]:
                    col.append(col_palette[j])

    # Bokeh data source with data labels
    data = {"x": x, "y": y, "group": group_copy, "col": col}
    data_label = {}
    for name, val in label_copy.items():
        data_label[name] = val
    data.update(data_label)
    source = ColumnDataSource(data=data)

    # Tool-tip (add everything in label_copy)
    TOOLTIPS = []
    if hover_xy is True:
        TOOLTIPS = [("x", "@x{1.111}"), ("y", "@y{1.111}")]
    for name, val in data_label.items():
        TOOLTIPS.append((str(name), "@" + str(name)))

    # Base figure
    fig = figure(title=title,
                 x_axis_label=xlabel,
                 y_axis_label=ylabel,
                 plot_width=width,
                 plot_height=height,
                 x_range=xrange,
                 y_range=yrange)

    # Add to plot
    if shape is "circle":
        shape = fig.circle("x",
                           "y",
                           size=size,
                           alpha=0.6,
                           color="col",
                           legend="group",
                           source=source)
    elif shape is "triangle":
        shape = fig.triangle("x",
                             "y",
                             size=size,
                             alpha=0.6,
                             color="col",
                             legend="group",
                             source=source)
    else:
        raise ValueError("shape has to be either 'circle' or 'triangle'.")

    shape_hover = HoverTool(renderers=[shape], tooltips=TOOLTIPS)
    fig.add_tools(shape_hover)

    if gradient is not False:
        slope = Slope(gradient=gradient,
                      y_intercept=0,
                      line_color="black",
                      line_width=2,
                      line_alpha=0.3)
        fig.add_layout(slope)
        new_gradient = -(1 / gradient)
        slope2 = Slope(gradient=new_gradient,
                       y_intercept=0,
                       line_color="black",
                       line_dash="dashed",
                       line_width=2,
                       line_alpha=0.10)
        fig.add_layout(slope2)

    if hline is not False:
        h = Span(location=0,
                 dimension="width",
                 line_color="black",
                 line_width=3,
                 line_alpha=0.15)
        fig.add_layout(h)

    if vline is not False:
        v = Span(location=0,
                 dimension="height",
                 line_color="black",
                 line_width=3,
                 line_alpha=0.15)
        fig.add_layout(v)

    # Font-sizes
    fig.title.text_font_size = font_size
    fig.xaxis.axis_label_text_font_size = label_font_size
    fig.yaxis.axis_label_text_font_size = label_font_size

    # Extra padding
    fig.min_border_left = 20
    fig.min_border_right = 20
    fig.min_border_top = 20
    fig.min_border_bottom = 20

    # Remove legend
    if legend is False:
        fig.legend.visible = False

    return fig
コード例 #21
0
    p_breakoutLine.location = breakoutSlider.value * 1e-9
    #y_spline = ds_splinefit.data['y_spline']
    #y_spline[0:ndx] = 0
    #ds_splinefit.data['y_spline'] = y_spline


breakoutSlider = Slider(title="Velocity breakout position (ns)",
                        value=0,
                        start=0,
                        end=10,
                        step=sampling_dt)

breakoutSlider.on_change('value', SetBreakout)

p_breakoutLine = Span(location=0,
                      dimension='height',
                      line_color='green',
                      line_width=1)
p_rawData.add_layout(p_breakoutLine)


def DetectBreakout():
    detectBreakout.button_type = "warning"
    # Find velocity breakout
    x = ds_analysis.data['x']
    y = ds_analysis.data['y']
    ySpline = ds_analysis.data['y']
    dt = np.abs(
        np.abs(ds_analysis.data['x'][1]) - np.abs(ds_analysis.data['x'][0]))
    yMean = np.mean(y[0:30])
    ySd = np.std(y[0:30])
    for ndx, val in enumerate(y):
コード例 #22
0
ファイル: main.py プロジェクト: ValentinQ/pea_femto
# Top figure
p_top = figure(title='decay',
               x_axis_label='time (ps)',
               y_axis_label='DA',
               x_axis_type='log',
               plot_width=500,
               plot_height=250,
               tools="pan,save,wheel_zoom,reset")
p_top.x_range.range_padding = p_top.y_range.range_padding = 0
p_top.y_range = Range1d(amplitude_min, amplitude_max)
p_top.x_range = Range1d(y_min, y_max)

source_top = ColumnDataSource(data=dict(x=new_y, y=all_data[650].iloc[:, 100]))
top_line = p_top.line('x', 'y', source=source_top, color='red')
hline = Span(location=0, dimension='width', line_color='black', line_width=1)
p_top.renderers.extend([hline])

# central figure
p_center = figure(title='map',
                  x_axis_label='wavelength (nm)',
                  y_axis_label='time (ps)',
                  y_axis_type='log',
                  plot_width=500,
                  plot_height=500,
                  tools="pan,save,wheel_zoom,reset")
p_center.x_range.range_padding = p_center.y_range.range_padding = 0

source_image = ColumnDataSource(data=dict(image=[all_data[650].values]))
p_center.image('image',
               source=source_image,
コード例 #23
0
    def interact(self, lc=None):
        """Display an interactive IPython Notebook widget to inspect the data.

        The widget will show both the lightcurve and pixel data.  By default,
        the lightcurve shown is obtained by calling the `to_lightcurve()` method,
        unless the user supplies a custom `LightCurve` object.

        Note: at this time, this feature only works inside an active Jupyter
        Notebook, and tends to be too slow when more than ~30,000 cadences
        are contained in the TPF (e.g. short cadence data).

        Parameters
        ----------
        lc : LightCurve object
            An optional pre-processed lightcurve object to show.
        """
        try:
            from ipywidgets import interact
            import ipywidgets as widgets
            from bokeh.io import push_notebook, show, output_notebook
            from bokeh.plotting import figure, ColumnDataSource
            from bokeh.models import Span, LogColorMapper
            from bokeh.layouts import row
            from bokeh.models.tools import HoverTool
            from IPython.display import display
            output_notebook()
        except ImportError:
            raise ImportError(
                'The quicklook tool requires Bokeh and ipywidgets. '
                'See the .interact() tutorial')

        ytitle = 'Flux'
        if lc is None:
            lc = self.to_lightcurve()
            ytitle = 'Flux (e/s)'

        # Bokeh cannot handle many data points
        # https://github.com/bokeh/bokeh/issues/7490
        if len(lc.cadenceno) > 30000:
            raise RuntimeError(
                'Interact cannot display more than 20000 cadences.')

        # Map cadence to index for quick array slicing.
        n_lc_cad = len(lc.cadenceno)
        n_cad, nx, ny = self.flux.shape
        lc_cad_matches = np.in1d(self.cadenceno, lc.cadenceno)
        if lc_cad_matches.sum() != n_lc_cad:
            raise ValueError(
                "The lightcurve provided has cadences that are not "
                "present in the Target Pixel File.")
        min_cadence, max_cadence = np.min(self.cadenceno), np.max(
            self.cadenceno)
        cadence_lookup = {cad: j for j, cad in enumerate(self.cadenceno)}
        cadence_full_range = np.arange(min_cadence,
                                       max_cadence,
                                       1,
                                       dtype=np.int)
        missing_cadences = list(set(cadence_full_range) - set(self.cadenceno))

        # Convert binary quality numbers into human readable strings
        qual_strings = []
        for bitmask in lc.quality:
            flag_str_list = KeplerQualityFlags.decode(bitmask)
            if len(flag_str_list) == 0:
                qual_strings.append(' ')
            if len(flag_str_list) == 1:
                qual_strings.append(flag_str_list[0])
            if len(flag_str_list) > 1:
                qual_strings.append("; ".join(flag_str_list))

        # Convert time into human readable strings, breaks with NaN time
        # See https://github.com/KeplerGO/lightkurve/issues/116
        if (self.time == self.time).all():
            human_time = self.astropy_time.isot[lc_cad_matches]
        else:
            human_time = [' '] * n_lc_cad

        # Each data source will later become a hover-over tooltip
        source = ColumnDataSource(data=dict(time=lc.time,
                                            time_iso=human_time,
                                            flux=lc.flux,
                                            cadence=lc.cadenceno,
                                            quality_code=lc.quality,
                                            quality=np.array(qual_strings)))

        # Provide extra metadata in the title
        if self.mission == 'K2':
            title = "Quicklook lightcurve for EPIC {} (K2 Campaign {})".format(
                self.keplerid, self.campaign)
        elif self.mission == 'Kepler':
            title = "Quicklook lightcurve for KIC {} (Kepler Quarter {})".format(
                self.keplerid, self.quarter)

        # Figure 1 shows the lightcurve with steps, tooltips, and vertical line
        fig1 = figure(title=title,
                      plot_height=300,
                      plot_width=600,
                      tools="pan,wheel_zoom,box_zoom,save,reset")
        fig1.yaxis.axis_label = ytitle
        fig1.xaxis.axis_label = 'Time - 2454833 days [BKJD]'
        fig1.step('time',
                  'flux',
                  line_width=1,
                  color='gray',
                  source=source,
                  nonselection_line_color='gray',
                  mode="center")

        r = fig1.circle('time',
                        'flux',
                        source=source,
                        fill_alpha=0.3,
                        size=8,
                        line_color=None,
                        selection_color="firebrick",
                        nonselection_fill_alpha=0.0,
                        nonselection_line_color=None,
                        nonselection_line_alpha=0.0,
                        fill_color=None,
                        hover_fill_color="firebrick",
                        hover_alpha=0.9,
                        hover_line_color="white")

        fig1.add_tools(
            HoverTool(tooltips=[("Cadence", "@cadence"),
                                ("Time (BKJD)", "@time{0,0.000}"),
                                ("Time (ISO)", "@time_iso"), ("Flux", "@flux"),
                                ("Quality Code", "@quality_code"),
                                ("Quality Flag", "@quality")],
                      renderers=[r],
                      mode='mouse',
                      point_policy="snap_to_data"))
        # Vertical line to indicate the cadence shown in Fig 2
        vert = Span(location=0,
                    dimension='height',
                    line_color='firebrick',
                    line_width=4,
                    line_alpha=0.5)
        fig1.add_layout(vert)

        # Figure 2 shows the Target Pixel File stamp with log screen stretch
        fig2 = figure(plot_width=300,
                      plot_height=300,
                      tools="pan,wheel_zoom,box_zoom,save,reset",
                      title='Pixel data (CCD {}.{})'.format(
                          self.module, self.output))
        fig2.yaxis.axis_label = 'Pixel Row Number'
        fig2.xaxis.axis_label = 'Pixel Column Number'

        pedestal = np.nanmin(self.flux[lc_cad_matches, :, :])
        stretch_dims = np.prod(self.flux[lc_cad_matches, :, :].shape)
        screen_stretch = self.flux[lc_cad_matches, :, :].reshape(
            stretch_dims) - pedestal
        screen_stretch = screen_stretch[np.isfinite(
            screen_stretch)]  # ignore NaNs
        screen_stretch = screen_stretch[screen_stretch > 0.0]
        vlo = np.min(screen_stretch)
        vhi = np.max(screen_stretch)
        vstep = (np.log10(vhi) -
                 np.log10(vlo)) / 300.0  # assumes counts >> 1.0!
        lo, med, hi = np.nanpercentile(screen_stretch, [1, 50, 95])
        color_mapper = LogColorMapper(palette="Viridis256", low=lo, high=hi)

        fig2_dat = fig2.image([self.flux[0, :, :] - pedestal],
                              x=self.column,
                              y=self.row,
                              dw=self.shape[2],
                              dh=self.shape[1],
                              dilate=False,
                              color_mapper=color_mapper)

        # The figures appear before the interactive widget sliders
        show(row(fig1, fig2), notebook_handle=True)

        # The widget sliders call the update function each time
        def update(cadence, log_stretch):
            """Function that connects to the interact widget slider values"""
            fig2_dat.glyph.color_mapper.high = 10**log_stretch[1]
            fig2_dat.glyph.color_mapper.low = 10**log_stretch[0]
            if cadence not in missing_cadences:
                index_val = cadence_lookup[cadence]
                vert.update(line_alpha=0.5)
                if self.time[index_val] == self.time[index_val]:
                    vert.update(location=self.time[index_val])
                else:
                    vert.update(line_alpha=0.0)
                fig2_dat.data_source.data['image'] = [
                    self.flux[index_val, :, :] - pedestal
                ]
            else:
                vert.update(line_alpha=0)
                fig2_dat.data_source.data['image'] = [
                    self.flux[0, :, :] * np.NaN
                ]
            push_notebook()

        # Define the widgets that enable the interactivity
        play = widgets.Play(interval=10,
                            value=min_cadence,
                            min=min_cadence,
                            max=max_cadence,
                            step=1,
                            description="Press play",
                            disabled=False)
        play.show_repeat, play._repeat = False, False
        cadence_slider = widgets.IntSlider(min=min_cadence,
                                           max=max_cadence,
                                           step=1,
                                           value=min_cadence,
                                           description='Cadence',
                                           layout=widgets.Layout(
                                               width='40%', height='20px'))
        screen_slider = widgets.FloatRangeSlider(
            value=[np.log10(lo), np.log10(hi)],
            min=np.log10(vlo),
            max=np.log10(vhi),
            step=vstep,
            description='Pixel Stretch (log)',
            style={'description_width': 'initial'},
            continuous_update=False,
            layout=widgets.Layout(width='30%', height='20px'))
        widgets.jslink((play, 'value'), (cadence_slider, 'value'))
        ui = widgets.HBox([play, cadence_slider, screen_slider])
        out = widgets.interactive_output(update, {
            'cadence': cadence_slider,
            'log_stretch': screen_slider
        })
        display(ui, out)
コード例 #24
0
ファイル: plot.py プロジェクト: Ritbit1111/app_770
def plot_iv(doc):

    init_calc = iv.iv_data(72, 800, 25, 45.9, 9.25, 37.2, 8.76, 7.47, 100)
    source = ColumnDataSource(data=init_calc[0])
    source_translated = ColumnDataSource(data=init_calc[1])
    res_source = ColumnDataSource(data=init_calc[2])
    status_param = init_calc[3]
    print(status_param)

    plot = Figure(plot_width=600,
                  plot_height=600,
                  y_range=(-1, 10),
                  x_range=(0, 60))
    plot.xaxis.axis_label = 'Voltage (V)'
    plot.yaxis.axis_label = 'Current (I)'
    plot.scatter(
        'x',
        'y',
        source=source,
        line_width=3,
        line_alpha=0.6,
    )
    plot.scatter(
        'x',
        'y',
        source=source_translated,
        line_width=3,
        line_alpha=0.6,
        line_color='red',
    )

    sig_plot = Figure(plot_width=300,
                      plot_height=300,
                      x_axis_label='Series Resistance (Rs)',
                      y_axis_label='Shunt Resistance (Rsh)',
                      title='Calculated Resistances')
    sig_plot.scatter('x', 'y', source=res_source, line_width=10)
    vline = Span(location=0,
                 dimension='height',
                 line_color='red',
                 line_width=3)
    # Horizontal line
    hline = Span(location=0,
                 dimension='width',
                 line_color='green',
                 line_width=3)
    sig_plot.renderers.extend([vline, hline])

    error_plt = Figure(
        plot_width=100,
        plot_height=50,
        toolbar_location=None,
    )

    if (status_param.success == True):
        print('Successful Entry to the landing page')
        cite = Label(text='Success',
                     render_mode='css',
                     text_color='white',
                     border_line_color='green',
                     background_fill_color='green')
    else:
        print('Inside fail')
        cite = Label(text='False',
                     render_mode='css',
                     text_color='white',
                     border_line_color='red',
                     background_fill_color='red')
    error_plt.add_layout(cite)
    error_plt.add_layout(
        Label(text='Success',
              render_mode='css',
              text_color='white',
              border_line_color='green',
              background_fill_color='green'))

    Ncell_input = TextInput(value='72', title='No. of cells')
    Irrad_input = TextInput(value='800', title='Irradiance')
    Temp_input = TextInput(value='25', title='Temperature (Celcius)')
    Isc_input = TextInput(value='9.25', title='I_sc at STC')
    Im_input = TextInput(value='8.76', title='I_m')
    Voc_input = TextInput(value='45.9', title='V_oc')
    Vm_input = TextInput(value='37.2', title='V_m')
    Isc_N_input = TextInput(value='7.47', title='I_sc at NOTC(G=800, T=45C)')
    Data_input = TextInput(value='100', title='Data Size')
    submit = Button(label='Submit', button_type='success')
    download_button_STC = Button(label='Download data (STC)')
    download_button_GT = Button(label='Download data (Translated)')

    def get_inputs():
        return (float(Ncell_input.value), float(Irrad_input.value),
                float(Temp_input.value), float(Voc_input.value),
                float(Isc_input.value), float(Vm_input.value),
                float(Im_input.value), float(Isc_N_input.value),
                float(Data_input.value))

    def update_plot(event):
        N, G, T, V, I, Vm, Im, I_N, datapoints = get_inputs()
        print('#' * 30)
        print('Updating the plot')
        print('#' * 30)
        updated_data = iv.iv_data(N, G, T, V, I, Vm, Im, I_N, datapoints)
        source.data = updated_data[0]
        source_translated.data = updated_data[1]
        res_source.data = updated_data[2]
        global status_param
        status_param = updated_data[3]
        print(status_param)
        if (status_param.success == True):
            print('Inside success')
            cite = Label(text='Successful Parameter Extraction',
                         render_mode='css',
                         text_color='white',
                         border_line_color='green',
                         background_fill_color='green')
        else:
            print('Inside fail')
            cite = Label(text='Parameter extraction not converging',
                         render_mode='css',
                         text_color='white',
                         border_line_color='red',
                         background_fill_color='red')
        error_plt = Figure(
            plot_width=100,
            plot_height=50,
            toolbar_location=None,
        )

        error_plt.add_layout(cite)
        layout.children[2].children[1] = error_plt

    def update_success():
        if (status_param.success == True):
            print('Inside success')
            cite = Label(text='Success',
                         render_mode='css',
                         text_color='white',
                         border_line_color='green',
                         background_fill_color='green')
        else:
            print('Inside fail')
            cite = Label(text='False',
                         render_mode='css',
                         text_color='white',
                         border_line_color='red',
                         background_fill_color='red')
        error_plt = Figure(
            plot_width=100,
            plot_height=50,
            toolbar_location=None,
        )

        error_plt.add_layout(cite)
        layout.children[2].children[1] = error_plt

    submit.on_click(update_plot)
    download_button_STC.js_on_click(
        CustomJS(args=dict(source=source),
                 code=open(join(dirname(__file__), "download.js")).read()))
    download_button_GT.js_on_click(
        CustomJS(args=dict(source=source_translated),
                 code=open(join(dirname(__file__), "download.js")).read()))

    #doc.add_periodic_callback(update_success, 1000)

    layout = row(
        plot,
        column(Ncell_input, Irrad_input, Temp_input, Isc_input, Im_input,
               Voc_input, Vm_input, Isc_N_input, Data_input, submit,
               download_button_STC, download_button_GT),
        column(sig_plot, error_plt))
    return (layout)
コード例 #25
0
    def plot_hdf5(self, filepath, image_downscale=1):
        """Experimental viewer for hdf5 files in a jupyter notebook.

        Args:
            filepath: hdf5 file to be processed
            image_downscale: an image resampling factor
        """
        global hold_image_ref
        results = self.process_hdf5(filepath, debug=True)

        images = results['images']
        edge_pos = results['edge_pos']
        xcorr_data = results['xcorr']
        orig_data = results['raw_input']
        is_dark = results['is_dark']

        n_im, size_y, size_x = images.shape
        if self.roi[0] is None:
            _roi_start = 0
        else:
            _roi_start = self.roi[0]

        if self.roi[1] is None:
            _roi_end = _roi_start + size_y
        else:
            _roi_end = self.roi[1]

        # avoid locking reference to `images` inside the slider_callback, see
        # https://github.com/jupyter-widgets/ipywidgets/issues/1345
        # https://github.com/jupyter-widgets/ipywidgets/issues/2304
        hold_image_ref = images[0]
        images_weak = weakref.ref(images)

        images_proj = images.mean(axis=1)
        image_bkg = images[is_dark].mean(axis=0)

        # avoid locking reference to `images` in bokeh objects, see
        # https://github.com/bokeh/bokeh/issues/8626
        image = images[0].copy()

        source_im = ColumnDataSource(data=dict(
            image=[image[::image_downscale, ::image_downscale]],
            x=[-0.5],
            y=[_roi_start],
            dw=[size_x],
            dh=[size_y],
        ))

        image_nobkg = image - image_bkg
        source_im_nobkg = ColumnDataSource(data=dict(
            image=[image_nobkg[::image_downscale, ::image_downscale]],
            x=[-0.5],
            y=[_roi_start],
            dw=[size_x],
            dh=[size_y],
        ))

        data_len = orig_data.shape[1]
        source_orig = ColumnDataSource(data=dict(x=np.arange(data_len),
                                                 y=orig_data[0],
                                                 y_bkg=self._background,
                                                 y_proj=images_proj[0]))

        xcorr_len = xcorr_data.shape[1]
        source_xcorr = ColumnDataSource(data=dict(
            x=np.arange(xcorr_len) * self.refinement +
            np.floor(self.step_length / 2),
            y=xcorr_data[0],
        ))

        p_im = figure(
            height=200,
            width=800,
            title='Camera ROI Image',
            x_range=(0, size_x),
            y_range=(_roi_start, _roi_end),
        )
        p_im.image(image='image',
                   x='x',
                   y='y',
                   dw='dw',
                   dh='dh',
                   source=source_im,
                   palette='Viridis256')

        p_im_nobkg = figure(
            height=200,
            width=800,
            title='No Background Image',
            x_range=(0, size_x),
            y_range=(_roi_start, _roi_end),
        )
        p_im_nobkg.image(
            image='image',
            x='x',
            y='y',
            dw='dw',
            dh='dh',
            source=source_im_nobkg,
            palette='Viridis256',
        )
        p_im_nobkg.x_range = p_im.x_range

        p_nobkg = figure(height=200,
                         width=800,
                         title='Projection and background')
        p_nobkg.line('x', 'y_bkg', source=source_orig, line_color='black')
        p_nobkg.line('x', 'y_proj', source=source_orig)
        p_nobkg.x_range = p_im.x_range

        p_orig = figure(height=200, width=800, title='Background removed')
        p_orig.line('x', 'y', source=source_orig)
        p_orig.x_range = p_im.x_range

        p_xcorr = figure(height=200, width=800, title='Xcorr')
        p_xcorr.line('x', 'y', source=source_xcorr)
        p_xcorr.x_range = p_im.x_range

        # Vertical spans
        span_args = dict(dimension='height', line_color='red')
        if np.isnan(edge_pos[0]):
            span_args['location'] = 0
            span_args['visible'] = False
        else:
            span_args['location'] = edge_pos[0]

        s_im = Span(**span_args)
        p_im.add_layout(s_im)

        s_im_nobkg = Span(**span_args)
        p_im_nobkg.add_layout(s_im_nobkg)

        s_nobkg = Span(**span_args)
        p_nobkg.add_layout(s_nobkg)

        s_orig = Span(**span_args)
        p_orig.add_layout(s_orig)

        s_xcorr = Span(**span_args)
        p_xcorr.add_layout(s_xcorr)

        spans = [s_im, s_im_nobkg, s_nobkg, s_orig, s_xcorr]

        # Final layout
        layout = gridplot([p_im, p_im_nobkg, p_nobkg, p_orig, p_xcorr],
                          ncols=1,
                          toolbar_options=dict(logo=None))

        handle = show(layout, notebook_handle=True)

        # Slider
        def slider_callback(change):
            new = change['new']
            image = images_weak()[new].copy()

            source_im.data.update(
                image=[image[::image_downscale, ::image_downscale]])
            image_nobkg = image - image_bkg
            source_im_nobkg.data.update(
                image=[image_nobkg[::image_downscale, ::image_downscale]])
            source_orig.data.update(y=orig_data[new], y_proj=images_proj[new])
            source_xcorr.data.update(y=xcorr_data[new])

            for span in spans:
                if np.isnan(edge_pos[new]):
                    span.visible = False
                else:
                    span.visible = True
                    span.location = edge_pos[new]

            push_notebook(handle=handle)

        slider = IntSlider(
            min=0,
            max=n_im - 1,
            value=0,
            step=1,
            description="Shot",
            continuous_update=False,
            layout=Layout(width='800px'),
        )

        slider.observe(slider_callback, names='value')
        return slider
コード例 #26
0
def plot_training_error(y, best_epoch, nome_title):
    
    
    
    
    if best_epoch != np.argmin(y[1:,1]):
        lowest_loss = y[best_epoch, 1]
    else:   
        best_epoch = np.argmin(y[1:,1])
        lowest_loss = np.min(y[1:,1])
    
    
    
    legend=["Train error", "Test error"]
    color=["blue", "red"]

    x = np.arange(y.shape[0])

    fig = figure(
        x_axis_label="Epoch",
        y_axis_label="Error",
#        sizing_mode="stretch_both",
#        sizing_mode="fixed",
        plot_width=800, plot_height=400,
        title="Error vs epoch" + nome_title,
        y_axis_type="log",
        toolbar_location=None,
        
    )
    
    for i in range(y.shape[1]):
        source = ColumnDataSource(data=dict(x=x, y=y[:, i]))

        fig.line("x", "y",
            legend=legend[i],
            line_width=2,
            source=source,
            color=color[i],
            alpha=1,
        )

#    fig.circle(
#               x=best_epoch+1,
#               y=lowest_loss,
#        legend='Best epoch',
#        size=30,
#        line_width=3,
#        line_color='green',
#        fill_color=None,
##            color='red',
#        alpha=1,
#    )

    v_line = Span(location=best_epoch+1,
                  dimension='height', 
                  line_color='green',
                  line_width=2,
                  )
    fig.add_layout(v_line)
    
#    fig.add_layout(
#            Label(
#                x=best_epoch-2,
##                x=0,
#                y=lowest_loss + 0.001,
#                angle=0,
#                text='Best Epoch: ' + str(best_epoch+1)+'  Test error: {0:.3f}'.format(lowest_loss, 5),
#                
#                text_font_style="bold",
#                text_font_size="12pt",
#                text_baseline="top",
#                text_align="right",
#                x_offset=20,
#                y_offset=200,
#            )
#        )
    
    
    fig.legend.location = "bottom_left"
    fig.legend.click_policy = "hide"
    

    
    return fig
コード例 #27
0
ファイル: test_annotations.py プロジェクト: zhiwuya/bokeh
def test_Span_accepts_datetime_location() -> None:
    obj = Span(location=datetime(2018, 8, 7, 0, 0))
    assert obj.location == 1533600000000.0
コード例 #28
0
# set up static line and annotations
plot.line(x_line, y_line, line_width=5, color='blue', line_alpha=0.3)
plot.circle(x_points, y_points, size=10, color='blue', line_alpha=0.3)

mytext = Label(x=-7,
               y=105,
               text='pIC50 = 6, Hill Coefficient = 1',
               text_color="blue",
               text_alpha=0.5)
plot.add_layout(mytext)

# add axes lines
vline = Span(location=0,
             dimension='height',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
hline = Span(location=0,
             dimension='width',
             line_color='black',
             line_width=1,
             line_alpha=0.3)
plot.renderers.extend([vline, hline])

# set up java script callback function to make plot interactive
pIC50_slider = Slider(start=3, end=8, value=6, step=0.1, title="pIC50")
hill_slider = Slider(start=0.1,
                     end=4,
                     value=1,
                     step=0.1,
コード例 #29
0
def forecast_plot(data):
    last_timestamp = data['displayTime'].dt.time.max()
    last_timestamp = last_timestamp.strftime('%H:%M')
    day = data['displayTime'].dt.date.max()
    day = day.strftime('%m/%d/%Y')
    source = ColumnDataSource(data)

    p = figure(title='Blood Sugar Forecast at ' + last_timestamp + ' on ' +
               day,
               tools=["save"],
               background_fill_color="#A9A9A9",
               width=1250,
               height=600,
               x_axis_type='datetime')
    p.title.text_font_size = "25px"
    p.title.align = "center"
    p.circle('displayTime',
             'value',
             source=source,
             size=15,
             color="black",
             alpha=0.5,
             legend='Historical Values')
    p.circle('displayTime',
             'forecast',
             source=source,
             size=15,
             color="green",
             alpha=0.5,
             legend='Forecast Values')
    p.circle('displayTime',
             'forecast_lower',
             source=source,
             size=15,
             color="red",
             alpha=0.5,
             legend='Lower Bound')
    p.circle('displayTime',
             'forecast_upper',
             source=source,
             size=15,
             color="blue",
             alpha=0.5,
             legend='Upper Bound')

    # add boundaries
    hline1 = Span(location=80,
                  dimension='width',
                  line_color='black',
                  line_width=2)
    hline2 = Span(location=180,
                  dimension='width',
                  line_color='black',
                  line_width=2)
    p.renderers.extend([hline1, hline2])

    p.xaxis.axis_label = 'Hour of Day'

    p.yaxis.axis_label = 'mg/dL'
    p.xaxis.axis_label_text_font_size = "14pt"

    x_min = data['displayTime'].min() - datetime.timedelta(minutes=2)
    x_max = data['displayTime'].max() + datetime.timedelta(minutes=2)
    p.yaxis.axis_label_text_font_size = "14pt"
    p.y_range = Range1d(20, 400)
    p.x_range = Range1d(x_min, x_max)
    return p
コード例 #30
0
            source=yright['source'],
            x=yright['x'],
            y=yright_each['y'][n],
            legend_label=yright_each['legend_label'][n],
            line_color=yright_each['line_color'][n],
            color=yright_each['line_color'][n],
            line_width=yright_each['line_width'][n],
            line_dash=yright_each['line_dash'][n],
            name=yright_each['name'][n],
        ))

# Horizontal right axis zero span
zero_span = Span(
    location=0,  # Span the 0 line of the right y axis
    dimension='width',
    line_color='gray',
    line_dash='solid',
    line_width=3,
    line_alpha=0.4,
    y_range_name=yright['y_range_name'])
p_state_covid.add_layout(zero_span)

# Weekly span marks
ds = np.arange(ax_limits['x'][0], ax_limits['x'][1], dtype='datetime64[D]')
# use of timezones was depricated, before timezone=None was needed
day = np.timedelta64(1, 'D')
for d in ds:
    if ((np.timedelta64(ds.max() - d) / day) % 7) == 0:
        ts = (np.datetime64(d) -
              np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
        wloc = ts * 1000  # get the week mark location in a format compatible with annotations
        p_state_covid.add_layout(