예제 #1
0
    def _plot_bokeh(self, current_plot, show_legend=True):
        from bokeh.models.tools import HoverTool
        from collections import OrderedDict
        from bokeh.models.ranges import FactorRange
        import bokeh.plotting as bkh

        value_lst = self.matrix.flatten()
        min_el = min(value_lst)
        vmax = float(max(value_lst) - min_el)
        color_lst = [BOKEH_CMAP[int((v - min_el) / vmax * (len(BOKEH_CMAP) - 1))] \
                     for v in value_lst]

        source = bkh.ColumnDataSource(
            data=dict(
                x=self.labels * self.matrix.shape[0],
                y=numpy.array([[i] * self.matrix.shape[1] for i in self.labels]).flatten(),
                color=color_lst,
                value=value_lst,
            )
        )
        # current_plot._below = []
        current_plot.x_range = FactorRange(factors=self.labels)
        current_plot.y_range = FactorRange(factors=self.labels)
        # current_plot._left = []

        # current_plot.extra_y_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(y_range_name="foo"), place='left')
        # current_plot.extra_x_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(x_range_name="foo"), place='top')

        current_plot.rect('x', 'y', 0.98, 0.98, source=source, color='color', line_color=None)
        current_plot.grid.grid_line_color = None
        current_plot.axis.axis_line_color = None
        current_plot.axis.major_tick_line_color = None
        hover = current_plot.select(dict(type=HoverTool))
        if not hover:
            hover = HoverTool(plot=current_plot)
        hover.tooltips = OrderedDict([
            ('labels', '@x @y'),
            ('value', '@value')
        ])
        current_plot.tools.append(hover)
        return current_plot
예제 #2
0
au = orig_au = lx = orig_lx = p1 = orig_p1 = p2 = orig_p2 = []
lp_p1 = orig_lp_p1 = lp_p2 = orig_lp_p2 = timepts = []
raw_p1 = raw_p2 = raw_lp_p1 = raw_lp_p2 = raw_lp_decim_p1 = raw_lp_decim_p2 = []
p1_cal = p2_cal = None
width = 800
height = 200
cutoff = 50
order = 3
source = ColumnDataSource(data=dict(
    x=timepts, au=au, p1=p1, raw_lp_decim_p1=p1, p2=p2, raw_lp_decim_p2=p2))

# Create the tools for the toolbar
ts_cnt = np.arange(3)
cross = [CrosshairTool() for n in ts_cnt]
hover = [
    HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p1'), ('raw', '@raw_lp_decim_p1')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p2'), ('raw', '@raw_lp_decim_p2')])
]
xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt]
xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt]
xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt]
xtsel = [TapTool() for n in ts_cnt]
xpan = [PanTool(dimensions=['width']) for n in ts_cnt]
save = [SaveTool() for n in ts_cnt]
reset = [ResetTool() for n in ts_cnt]
tools = [[
    cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n],
    save[n], reset[n]
예제 #3
0
p = figure(
    x_range=x_range,
    y_range=y_range,
    x_axis_type="mercator",
    y_axis_type="mercator",
    aspect_ratio=.9,
    sizing_mode='scale_both',
    align='center',
    output_backend="webgl",
)
p.add_tile(tile_provider)
p.add_tools(
    HoverTool(tooltips=[
        ('Year Sold', '@{DEED YEAR}'),
        ('Price', '$@{SALE PRICE}{0,0,0}'),
        ('Property Type', '@{PROP CLASS DESCRIPTION}'),
        ('Address', '@{ADDRESS}'),
    ], ))

# create linear color mapper and color bar
color_mapper = LinearColorMapper(palette=Viridis256, low=10000, high=200000)
formatter = NumeralTickFormatter(format='($ 0 a)')
color_bar = ColorBar(color_mapper=color_mapper,
                     label_standoff=12,
                     formatter=formatter)
p.add_layout(color_bar, 'right')

# Add Points
points = p.circle(
    x='x',
    y='y',
예제 #4
0
    async def get(self):
        """Fetch and publish metric values asynchronously."""
        for predictor_model in self.settings["model_list"]:
            df = predictor_model.predicted_df

            output_file('static/graph.html')
            TOOLS = "pan,wheel_zoom,reset,save"
            plot = figure(plot_width=800, plot_height=300, x_axis_type="datetime", title=predictor_model.model_name,
                          tools=TOOLS, toolbar_location="above")
            plot.xaxis.axis_line_color = "rgb(173, 173, 173)"
            plot.yaxis.axis_line_color = "white"
            plot.yaxis.major_tick_line_color = "white"
            plot.xaxis.major_tick_in = 1

            metric_values = predictor_model.metric.metric_values
            source_real = ColumnDataSource(data=dict(values=metric_values.values[:, 1], dates=metric_values.values[:, 0]))
            source_yhat = ColumnDataSource(data=dict(values=df.yhat.values, dates=df.yhat.index.values))
            source_yhat_bound = ColumnDataSource(data=dict(yhat_upper=df.yhat_upper.values, yhat_lower=df.yhat_lower.values,dates=df.yhat_upper.index.values))
            band = Band(base='dates', lower='yhat_lower', upper='yhat_upper', source=source_yhat_bound,
                        level='overlay', fill_alpha=0.7, fill_color="rgb(200, 200, 200)", line_width=0)
            plot.add_layout(band)

            plot.line(x='dates', y='values', source=source_yhat, color="black")
            plot.line(x='dates', y='values', source=source_real, color="red")
            plot.xgrid.visible = False
            plot.title.text_color = "rgb(173, 173, 173)"
            plot.yaxis.minor_tick_line_color = None
            plot.add_tools(HoverTool(
                tooltips=[
                    ('date', '@dates{|%F %T|}'),
                    ('value', '$y'),
                ],
                formatters={
                    '@dates': 'datetime'
                },
                mode='vline'
            ))

            script_bokeh, div_bokeh = components(plot)
            resources_bokeh = CDN.render()

            template = Template(
                '''<!DOCTYPE html>
                    <html lang="en">
                        <head>
                            <meta charset="utf-8">
                            <title>Overview</title>
                            {{ resources }}
                            {{ script }}
                            <style>
                                .embed-wrapper {
                                    display: flex;
                                    justify-content: space-evenly;
                                }
                                .bk-logo {
                                    display:none !important;
                                }
                                .bk-tool-icon-hover {
                                    display:none !important;
                                }
                            </style>
                        </head>
                        <body style="background-color:rgb(246, 246, 246);>                  
                            <div class="embed-wrapper">
                                {{ div }}
                            </div>
                        </body>
                    </html>
                    ''')

            html = template.render(resources=resources_bokeh,
                                   script=script_bokeh,
                                   div=div_bokeh)

            out_file_path = "static/graph.html"
            with io.open(out_file_path, mode='w') as f:
                f.write(html)
        self.render("static/graph.html")
예제 #5
0
part = df
source = ColumnDataSource(part)
print(source)
values_x = [1, 2, 3, 4, 5, 6, 7, 8]
values_y = [a for a in part.stock_price]

plot = figure(title="Stock price",
              x_axis_label='Date',
              y_axis_label='stock price',
              x_axis_type='datetime')
plot.line(x=part.time, y=values_y, line_color='blue', line_width=5)

for a in range(len(values_y)):
    if part.Sentiment[a] > 10:
        plot.circle(df.iloc[a]["time"],
                    values_y[a],
                    fill_color='blue',
                    size=50)
    else:
        plot.circle(df.iloc[a]["time"],
                    values_y[a],
                    fill_color='green',
                    size=50)

hover = HoverTool()
hover.tooltips = [('Average sentiment', '@time')]

plot.add_tools(hover)

output_file('index.html')
show(plot)
예제 #6
0
p12.annulus(x=c1,
            y=d1,
            inner_radius=0.1,
            outer_radius=0.25,
            color=color2,
            alpha=0.8)
p12.segment(c1, -1000, c1, d1, line_width=3, line_color=color2, alpha=0.8)
p12.y_range.start = -200
p12.xgrid.visible = False
p12.ygrid.visible = False
p12.axis.minor_tick_line_color = None
p12.title.align = "center"
p12.title.text_font_size = "20px"
p12.xaxis.major_label_orientation = math.pi / 2
p12.xaxis.major_label_text_font_size = "8px"
hover = HoverTool(tooltips=([('Date_Month_Year', '@x'), ('New_Cases', '@y')]),
                  renderers=[a])
p12.add_tools(hover)
"""c2 = list(df['Date'].values)
d2=df['Total_Cases'].tolist()
l=len(c2)
color3=linear_palette(Viridis256,l)
p13 = figure(x_range=c2, plot_height=350, title="Total Cases in India - Till date on daily basis",
           toolbar_location='right', tools="zoom_in,zoom_out,reset,save,pan,box_select,box_zoom",plot_width=650,y_axis_label='No.of.cases')
p13.segment(c2,-5000, c2,d2, line_width=3, line_color=color3, alpha=0.8 )
a=p13.circle(x=c2,y= d2, size=8, fill_color=color3, line_color="black", line_width=2,alpha=0.65 )
p13.xgrid.visible = False
p13.ygrid.visible = False
p13.axis.minor_tick_line_color = None

hover=HoverTool(tooltips=([('Date','@x'),('Cases','@y')]),renderers=[a])
p13.add_tools(hover)
예제 #7
0
    top_weapon_kills_wide.sum(axis=1), axis=0)
from bokeh.models.tools import HoverTool
from bokeh.palettes import brewer
from bokeh.plotting import figure, show, output_notebook
from bokeh.models.sources import ColumnDataSource


def stacked(df):
    df_top = df.cumsum(axis=1)
    df_bottom = df_top.shift(axis=1).fillna(0)[::-1]
    df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
    return df_stack


hover = HoverTool(tooltips=[("index", "$index"), ("weapon", "@weapon"),
                            ("(x,y)", "($x, $y)")],
                  point_policy='follow_mouse')

areas = stacked(top_weapon_kills_wide)

colors = brewer['Spectral'][areas.shape[1]]
x2 = np.hstack(
    (top_weapon_kills_wide.index[::-1], top_weapon_kills_wide.index)) / 0.095

TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave"
output_notebook()
p = figure(x_range=(1, 800),
           y_range=(0, 1),
           tools=[TOOLS, hover],
           plot_width=800)
p.grid.minor_grid_line_color = '#eeeeee'
예제 #8
0
def add_gaia_figure_elements(tpf, fig, magnitude_limit=18):
    """Make the Gaia Figure Elements"""
    # Get the positions of the Gaia sources
    c1 = SkyCoord(tpf.ra, tpf.dec, frame='icrs', unit='deg')
    # Use pixel scale for query size
    pix_scale = 4.0  # arcseconds / pixel for Kepler, default
    if tpf.mission == 'TESS':
        pix_scale = 21.0
    # We are querying with a diameter as the radius, overfilling by 2x.
    from astroquery.vizier import Vizier
    Vizier.ROW_LIMIT = -1
    result = Vizier.query_region(c1,
                                 catalog=["I/345/gaia2"],
                                 radius=Angle(
                                     np.max(tpf.shape[1:]) * pix_scale,
                                     "arcsec"))
    no_targets_found_message = ValueError(
        'Either no sources were found in the query region '
        'or Vizier is unavailable')
    too_few_found_message = ValueError(
        'No sources found brighter than {:0.1f}'.format(magnitude_limit))
    if result is None:
        raise no_targets_found_message
    elif len(result) == 0:
        raise too_few_found_message
    result = result["I/345/gaia2"].to_pandas()
    result = result[result.Gmag < magnitude_limit]
    if len(result) == 0:
        raise no_targets_found_message
    radecs = np.vstack([result['RA_ICRS'], result['DE_ICRS']]).T
    coords = tpf.wcs.all_world2pix(
        radecs, 1)  ## TODO, is origin supposed to be zero or one?
    year = ((tpf.astropy_time[0].jd - 2457206.375) * u.day).to(u.year)
    pmra = (
        (np.nan_to_num(np.asarray(result.pmRA)) * u.milliarcsecond / u.year) *
        year).to(u.arcsec).value
    pmdec = (
        (np.nan_to_num(np.asarray(result.pmDE)) * u.milliarcsecond / u.year) *
        year).to(u.arcsec).value
    result.RA_ICRS += pmra
    result.DE_ICRS += pmdec

    # Gently size the points by their Gaia magnitude
    sizes = 64.0 / 2**(result['Gmag'] / 5.0)
    one_over_parallax = 1.0 / (result['Plx'] / 1000.)
    source = ColumnDataSource(data=dict(ra=result['RA_ICRS'],
                                        dec=result['DE_ICRS'],
                                        source=result['Source'].astype(str),
                                        Gmag=result['Gmag'],
                                        plx=result['Plx'],
                                        one_over_plx=one_over_parallax,
                                        x=coords[:, 0] + tpf.column,
                                        y=coords[:, 1] + tpf.row,
                                        size=sizes))

    r = fig.circle('x',
                   'y',
                   source=source,
                   fill_alpha=0.3,
                   size='size',
                   line_color=None,
                   selection_color="firebrick",
                   nonselection_fill_alpha=0.0,
                   nonselection_line_color=None,
                   nonselection_line_alpha=0.0,
                   fill_color="firebrick",
                   hover_fill_color="firebrick",
                   hover_alpha=0.9,
                   hover_line_color="white")

    fig.add_tools(
        HoverTool(tooltips=[("Gaia source", "@source"), ("G", "@Gmag"),
                            ("Parallax (mas)",
                             "@plx (~@one_over_plx{0,0} pc)"),
                            ("RA", "@ra{0,0.00000000}"),
                            ("DEC", "@dec{0,0.00000000}"), ("x", "@x"),
                            ("y", "@y")],
                  renderers=[r],
                  mode='mouse',
                  point_policy="snap_to_data"))
    return fig, r
def plot_weekly_stats(plot_df, stat, save_filepath=None, plot_team=TEAM_NAME):
    """
    """
    plot_df = plot_df.rename(columns={'FG%': 'FG_PCT', 'FT%': 'FT_PCT'})
    runtime = datetime.datetime.now()

    p = figure(
        title=
        f'{stat}   (last updated: {get_weekday(runtime.weekday())} {runtime.strftime("%m/%d %H:%M")})',
        x_axis_label='Week',
        y_axis_label=stat,
        width=600,
        height=400)

    xs = [plot_df.week.unique()] * 12

    ys = [plot_df[plot_df.team_name == plot_team][stat].values]
    for team in plot_df[plot_df.team_name != plot_team].team_name.unique():
        ys.append(plot_df[plot_df.team_name == team][stat].values)

    opps = plot_df[plot_df.team_name ==
                   plot_team]['opponent_team_name'].to_numpy()
    opp_vals = plot_df[(plot_df.team_name.isin(opps)) &
                       (plot_df.opponent_team_name == plot_team)][stat].values

    r = p.multi_line(xs,
                     ys,
                     line_color=['blue'] + ['grey'] * 11,
                     alpha=[1] + [0.5] * 11,
                     line_width=2)
    r2 = p.line('week',
                f'{stat}',
                source=plot_df[plot_df.team_name == opps[-1]],
                color='red',
                alpha=1,
                line_width=2)
    p.circle('week',
             f'{stat}',
             source=plot_df[(plot_df.team_name == plot_team)],
             color='blue',
             fill_color='white',
             size=12)
    p.circle('week',
             f'{stat}',
             source=plot_df[(plot_df.team_name.isin(opps))
                            & (plot_df.opponent_team_name == plot_team)],
             color='red',
             fill_color='white',
             size=12)

    legend = Legend(items=[
        LegendItem(label=plot_team, renderers=[r], index=0),
        LegendItem(label=opps[-1], renderers=[r2], index=1)
    ])

    p.add_tools(
        HoverTool(tooltips=[('Team', '@team_name'), (f'{stat}', f'@{stat}')]))

    p.add_layout(legend)
    p.xaxis.ticker = plot_df.week.unique()

    if save_filepath:
        print('Saving to', save_filepath)
        bokeh.plotting.output_file(save_filepath)
        show(p)
    else:
        show(p)
    return p
def plot_with_pca():
    labels = []
    tokens = []
    for word in model.wv.vocab:
        if (word.startswith("rex")):
            continue
        tokens.append(model[word])
        labels.append(word)

    tsne_model = TSNE(perplexity=40,
                      n_components=2,
                      init='pca',
                      n_iter=2500,
                      random_state=23)

    new_values = tsne_model.fit_transform(tokens)
    x = []
    y = []
    for value in new_values:
        x.append(value[0])
        y.append(value[1])
    vector = [
        'valign', 'vp', 'vblend', 'vbroadcast', 'vcompress', 'vcvt', 'vdbs',
        'vexpand', 'vextract', 'vfixup', 'vfmadd', 'vfmsub', 'vfnmadd',
        'vfnmsub', 'vfpclass', 'vgather', 'vget', 'vinsert', 'vmask', 'vmov',
        'vpblend', 'vpbroadcast', 'vpcmp', 'vpcompress', 'vpconflict', 'vperm',
        'vpexpand', 'vpgather', 'vplzcnt', 'vpmadd', 'vpmask', 'vpmov',
        'vmult', 'vpro', 'vpscatter', 'vps', 'vpt', 'vran', 'vrcp', 'vred',
        'vrnd', 'vrsq', 'vsca', 'vshuf', 'vtest', 'vzero', 'vector'
    ]
    read = ['rdpid', 'rdpkru', 'rdpmc', 'rdrand', 'rdseed', 'rdtsc']
    mask = [
        'kadd', 'kand', 'kor', 'kmov', 'knot', 'kshift', 'ktest', 'kunpck',
        'kxnor', 'kxor'
    ]
    bound = ['bndcl', 'bndcn', 'bndcu', 'bndldx', 'bndmk', 'bndmov', 'bndstx']
    string = [
        'cmps', 'cmpsb', 'cmpsq', 'cmpsw', 'lods', 'movs', 'rep', 'scas',
        'stos'
    ]
    flag = [
        'clac', 'clc', 'cld', 'cli', 'clts', 'cmc', 'lahf', 'popf', 'pushf',
        'sahf', 'stac', 'stc', 'std'
    ]
    segment_reg = [
        'lds', 'les', 'lfs', 'lgs', 'lss', 'rdfs', 'rdgs', 'rdmsr', 'swapgs',
        'verr', 'verw', 'wrfs', 'wrgs', 'xgetbv', 'xsetbv'
    ]
    misc = ['cpuid', 'lea', 'nop', 'xlat']
    floating_control = [
        'fclex', 'fcmov', 'fdecstp', 'ffree', 'fincstp', 'finit', 'fldcw',
        'fldenv', 'fnclex', 'fninit', 'fnop', 'fnsave', 'fnstcw', 'fnstenv',
        'fnstsw', 'frstor', 'fsave', 'fstcw', 'fstenv', 'fstsw', 'fwait',
        'fxrstor', 'fxsave'
    ]
    floating_data = ['fbld', 'fbstp', 'fild', 'fist', 'fld', 'fst', 'fxch']
    floating_arith = [
        'fabs', 'fadd', 'faddp', 'fchs', 'fdiv', 'fiadd', 'fidiv', 'fimul',
        'fisub', 'fmul', 'frndint', 'fscale', 'fsub'
    ]
    floating_comparison = ['fcom', 'ficom', 'ftst', 'fucom', 'fxam']
    floating_transcendental = [
        'f2xmi', 'fcos', 'fpatan', 'fprem', 'fptan', 'fsin', 'fsqrt',
        'fxtract', 'fyl2x'
    ]
    simd_state = ['fxrstor', 'fxsave']
    mmx = [
        'packssdw', 'packsswb', 'packusdw', 'packuswb', 'pabs', 'padd',
        'palignr', 'pblend', 'pclmulqdql', 'phadd', 'phmin', 'phsub', 'pmadd',
        'psadbw', 'psign', 'package', 'pcmp', 'pand', 'por', 'ptest', 'pxor',
        'psra', 'psrl', 'emms', 'xabort', 'xacquire', 'xbegin', 'xrelease',
        'xrstor', 'xsave', 'xtest', 'xend'
    ]
    sse = [
        'extractps', 'movaps', 'movups', 'addps', 'addss', 'addsubps',
        'blendps', 'blendvps', 'divps', 'divss', 'dpps', 'haddps', 'hsubps',
        'maxps', 'maxss', 'minps', 'minss', 'mulps', 'mulss', 'sqrtps',
        'sqrtss', 'subps', 'subss', 'cmpps', 'cmpss', 'comiss', 'rcpps',
        'rcpss', 'ucomiss', 'andnps', 'andps', 'orps', 'xorps', 'shufps',
        'unpckhps', 'unpckhlps', 'cvtdq2ps', 'cvtdpd2ps', 'cvtpi2ps',
        'cvtps2dq', 'cvtps2pd', 'cvtps2pi', 'cvtss2sd', 'cvtss2si',
        'cvttps2dq', 'cvttps2pi', 'movhlps', 'movhps', 'movlhps', 'movlps',
        'movmskps', 'rsqrt', 'maskmovq', 'movntps', 'movntq', 'pause',
        'prefetch', 'sfence'
    ]
    sse2 = [
        'movapd', 'movddup', 'movupd', 'addpd', 'addsd', 'addsubpd', 'blendpd',
        'blendvpd', 'divpd', 'divsd', 'dppd', 'haddpd', 'hsubpd', 'maxpd',
        'maxsd', 'minpd', 'minsd', 'mpsadbw', 'mulpd', 'mulsd', 'sqrtpd',
        'sqrtsd', 'subpd', 'subsd', 'cmppd', 'cmpsd', 'comisd', 'ucomisd',
        'andnpd', 'andpd', 'orpd', 'xorpd', 'shufpd', 'unpckhpd', 'unpckhlpd',
        'cvtdq2pd', 'cvtdpd2dq', 'cvtdpd2pi', 'cvtpi2pd', 'cvtsd2si',
        'cvtsd2ss', 'cvtsi2ss', 'cvtsi2sd', 'cvttpd2dq', 'cvttpd2pi',
        'cvttsd2si', 'cvttss2si', 'movdq2q', 'movdqa', 'movdqu', 'movhpd',
        'movlpd', 'movmskpd', 'movq2dq', 'pavg', 'pextr', 'pinsr', 'pmax',
        'pmin', 'pmov', 'pmul', 'pshuf', 'psll', 'psub', 'punpck', 'roundpd',
        'roundps', 'roundsd', 'roundss', 'clflush', 'clflushopt', 'clwb',
        'lfence', 'maskmovdqu', 'mfence', 'movntdq', 'movnti', 'movntpd'
    ]
    system = [
        'hlt', 'invd', 'invlpg', 'invpcid', 'lgdt', 'lidt', 'lldt', 'lmsw',
        'lock', 'lsl', 'ltr', 'rsm', 'sgdt', 'sidt', 'sldt', 'smsw', 'stmxcsr',
        'str', 'wbinvd', 'wrmsr', 'wrpkru', 'ldmxcsr'
    ]
    encryption = [
        'aesdec', 'aesdeclast', 'aesenc', 'aesenclast', 'aesimc',
        'aeskeygenassist', 'sha1', 'sha256'
    ]
    mmx_data = ['movd', 'movq']
    dec_arith = ['aaa', 'aad', 'aam', 'aas', 'adcx', 'daa', 'das']
    binary_arith = [
        'adc', 'add', 'adox', 'cmp', 'dec', 'div', 'idiv', 'imul', 'inc',
        'mul', 'neg', 'sbb', 'sub', 'tzcnt'
    ]
    logical = ['and', 'andn', 'not', 'or', 'xor']
    shift = ['rcl', 'rcr', 'rol', 'ror', 'sal', 'sar', 'shl', 'shr']
    bit_byte = [
        'bextr', 'blsi', 'blsmsk', 'blsr', 'bsf', 'bsr', 'bt', 'btc', 'btr',
        'bts', 'lzcnt', 'set', 'test'
    ]
    control_transfer = [
        'bound', 'call', 'enter', 'int', 'iret', 'jmp', 'leave', 'loop', 'ret',
        'wait', 'sysret'
    ]
    data_transfer = [
        'bswap', 'bzhi', 'cbw', 'cdq', 'cdqe', 'cmov', 'cmpxchg', 'cqo',
        'crc32', 'cwd', 'cwde', 'lar', 'lddqu', 'mov', 'pdep', 'pext', 'pop',
        'ptwrite', 'push', 'xadd'
    ]
    io = ['in', 'ins', 'out']
    color = []
    type1 = []
    for i in range(len(labels)):
        c = '#000000'
        t = ''
        if (labels[i].lower().startswith(tuple(vector)) > 0):
            c = '#800000'
            t = 'vector'
        elif (labels[i].lower().startswith(tuple(read)) > 0):
            c = '#CD853F'
            t = 'read'
        elif (labels[i].lower().startswith(tuple(mask)) > 0):
            c = '#D2691E'
            t = 'mask'
        elif (labels[i].lower().startswith(tuple(bound)) > 0):
            c = '#DAA520'
            t = 'bound'
        elif (labels[i].lower().startswith(tuple(string)) > 0):
            c = '#CD5C5C'
            t = 'string'
        elif (labels[i].lower().startswith(tuple(flag)) > 0):
            c = '#FA8072'
            t = 'flag'
        elif (labels[i].lower().startswith(tuple(segment_reg)) > 0):
            c = '#DC143C'
            t = 'segment register'
        elif (labels[i].lower().startswith(tuple(misc)) > 0):
            c = '#FF0000'
            t = 'misc'
        elif (labels[i].lower().startswith(tuple(floating_control)) > 0):
            c = '#8B0000'
            t = 'floating control'
        elif (labels[i].lower().startswith(tuple(floating_data)) > 0):
            c = '#FFC0CB'
            t = 'floating data'
        elif (labels[i].lower().startswith(tuple(floating_arith)) > 0):
            c = '#FF69B4'
            t = 'floating arith'
        elif (labels[i].lower().startswith(tuple(floating_comparison)) > 0):
            c = '#FF1493'
            t = 'floating comparison'
        elif (labels[i].lower().startswith(tuple(floating_transcendental)) >
              0):
            c = '#DB7093'
            t = 'floating transcendental'
        elif (labels[i].lower().startswith(tuple(simd_state)) > 0):
            c = '#FF7F50'
            t = 'simd state'
        elif (labels[i].lower().startswith(tuple(mmx)) > 0):
            c = '#FF4500'
            t = 'mmx'
        elif (labels[i].lower().startswith(tuple(sse)) > 0):
            c = '#FFFF00'
            t = 'sse'
        elif (labels[i].lower().startswith(tuple(sse2)) > 0):
            c = '#FFE4B5'
            t = 'sse2'
        elif (labels[i].lower().startswith(tuple(system)) > 0):
            c = '#F0E68C'
            t = 'system'
        elif (labels[i].lower().startswith(tuple(encryption)) > 0):
            c = '#E6E6FA'
            t = 'encryption'
        elif (labels[i].lower().startswith(tuple(mmx_data)) > 0):
            c = '#DDA0DD'
            t = 'mmx_data'
        elif (labels[i].lower().startswith(tuple(dec_arith)) > 0):
            c = '#EE82EE'
            t = 'dec_arith'
        elif (labels[i].lower().startswith(tuple(binary_arith)) > 0):
            c = '#4B0082'
            t = 'binary arith'
        elif (labels[i].lower().startswith(tuple(logical)) > 0):
            c = '#008000'
            t = 'logical'
        elif (labels[i].lower().startswith(tuple(shift)) > 0):
            c = '#808000'
            t = 'shift'
        elif (labels[i].lower().startswith(tuple(bit_byte)) > 0):
            c = '#00FFFF'
        elif (labels[i].lower().startswith(tuple(control_transfer)) > 0):
            c = '#00BFFF'
            t = 'bit byte'
        elif (labels[i].lower().startswith(tuple(data_transfer)) > 0):
            c = '#0000FF'
            t = 'data transfer'
        elif (labels[i].lower().startswith(tuple(io)) > 0):
            c = '#00FF00'
            t = 'IO'
        color.append(c)
        type1.append(t)

    output_file("Models/word2vec_some_pca.html", title="word2vec_out example")

    source = ColumnDataSource(
        data=dict(x=x, y=y, desc=labels, typ=type1, fill_color=color))
    hover = HoverTool(tooltips=[("desc", "@desc"), ("typ", "@typ")])

    p = figure(plot_width=1500,
               plot_height=1000,
               tools=[hover],
               title="Word2Vec Plot With PCA (3 Iter)")

    p.circle('x', 'y', size=10, source=source, fill_color="fill_color")
    labels1 = LabelSet(x='x',
                       y='y',
                       text='desc',
                       level='glyph',
                       x_offset=5,
                       y_offset=5,
                       source=source,
                       render_mode='canvas')
    p.add_layout(labels1)
    show(p)
예제 #11
0
def make_bls_figure_elements(result, bls_source, help_source):
    """Make a line plot of a BLS result.

    Parameters
    ----------
    result : BLS.model result
        BLS model result to plot
    bls_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting BLS source
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    vertical_line : bokeh.models.Span
        Vertical line to highlight current selected period
    """

    # Build Figure
    fig = figure(title='BLS Periodogram',
                 plot_height=340,
                 plot_width=450,
                 tools="pan,box_zoom,tap,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF",
                 x_axis_type='log',
                 active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Power'
    fig.xaxis.axis_label = 'Period [days]'
    fig.y_range = Range1d(start=result.power.min() * 0.95,
                          end=result.power.max() * 1.05)
    fig.x_range = Range1d(start=result.period.min(), end=result.period.max())

    # Add circles for the selection of new period. These are always hidden
    fig.circle('period',
               'power',
               source=bls_source,
               fill_alpha=0.,
               size=6,
               line_color=None,
               selection_color="white",
               nonselection_fill_alpha=0.0,
               nonselection_fill_color='white',
               nonselection_line_color=None,
               nonselection_line_alpha=0.0,
               fill_color=None,
               hover_fill_color="white",
               hover_alpha=0.,
               hover_line_color="white")

    # Add line for the BLS power
    fig.line('period',
             'power',
             line_width=1,
             color='#191919',
             source=bls_source,
             nonselection_line_color='#191919',
             nonselection_line_alpha=1.0)

    # Vertical line to indicate the current period
    vertical_line = Span(location=0,
                         dimension='height',
                         line_color='firebrick',
                         line_width=3,
                         line_alpha=0.5)
    fig.add_layout(vertical_line)

    # Help button
    question_mark = Text(x="period",
                         y="power",
                         text="helpme",
                         text_color="grey",
                         text_align='center',
                         text_baseline="middle",
                         text_font_size='12px',
                         text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('period',
                      'power',
                      alpha=0.0,
                      size=15,
                      source=help_source,
                      line_width=2,
                      line_color='grey',
                      line_alpha=0.6)
    tooltips = help_source.data['help'][0]
    fig.add_tools(
        HoverTool(tooltips=tooltips,
                  renderers=[help],
                  mode='mouse',
                  point_policy="snap_to_data"))

    return fig, vertical_line
예제 #12
0
def make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source,
                                help_source):
    """Make a scatter plot of a FoldedLightCurve.

    Parameters
    ----------
    f : lightkurve.LightCurve
        Folded light curve to plot
    f_model_lc :  lightkurve.LightCurve
        Model folded light curve to plot
    f_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting folded light curve
    f_model_lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting model folded light curve
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    """

    # Build Figure
    fig = figure(title='Folded Light Curve',
                 plot_height=340,
                 plot_width=450,
                 tools="pan,box_zoom,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF",
                 active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux'
    fig.xaxis.axis_label = 'Phase'

    # Scatter point for data
    fig.circle('phase',
               'flux',
               line_width=1,
               color='#191919',
               source=f_source,
               nonselection_line_color='#191919',
               nonselection_line_alpha=1.0,
               size=0.1)

    # Line plot for model
    fig.step('phase',
             'flux',
             line_width=3,
             color='firebrick',
             source=f_model_lc_source,
             nonselection_line_color='firebrick',
             nonselection_line_alpha=1.0)

    # Help button
    question_mark = Text(x="phase",
                         y="flux",
                         text="helpme",
                         text_color="grey",
                         text_align='center',
                         text_baseline="middle",
                         text_font_size='12px',
                         text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('phase',
                      'flux',
                      alpha=0.0,
                      size=15,
                      source=help_source,
                      line_width=2,
                      line_color='grey',
                      line_alpha=0.6)

    tooltips = help_source.data['help'][0]
    fig.add_tools(
        HoverTool(tooltips=tooltips,
                  renderers=[help],
                  mode='mouse',
                  point_policy="snap_to_data"))
    return fig
예제 #13
0
def make_lightcurve_figure_elements(lc, model_lc, lc_source, model_lc_source,
                                    help_source):
    """Make a figure with a simple light curve scatter and model light curve line.

    Parameters
    ----------
    lc : lightkurve.LightCurve
        Light curve to plot
    model_lc :  lightkurve.LightCurve
        Model light curve to plot
    lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting light curve
    model_lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting model light curve
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    """
    # Make figure
    fig = figure(title='Light Curve',
                 plot_height=300,
                 plot_width=900,
                 tools="pan,box_zoom,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF",
                 active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux (e/s)'
    if lc.time_format == 'bkjd':
        fig.xaxis.axis_label = 'Time - 2454833 (days)'
    elif lc.time_format == 'btjd':
        fig.xaxis.axis_label = 'Time - 2457000 (days)'
    else:
        fig.xaxis.axis_label = 'Time (days)'
    ylims = [np.nanmin(lc.flux), np.nanmax(lc.flux)]
    fig.y_range = Range1d(start=ylims[0], end=ylims[1])

    # Add light curve
    fig.circle('time',
               'flux',
               line_width=1,
               color='#191919',
               source=lc_source,
               nonselection_line_color='#191919',
               size=0.5,
               nonselection_line_alpha=1.0)
    # Add model
    fig.step('time',
             'flux',
             line_width=1,
             color='firebrick',
             source=model_lc_source,
             nonselection_line_color='firebrick',
             nonselection_line_alpha=1.0)

    # Help button
    question_mark = Text(x="time",
                         y="flux",
                         text="helpme",
                         text_color="grey",
                         text_align='center',
                         text_baseline="middle",
                         text_font_size='12px',
                         text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('time',
                      'flux',
                      alpha=0.0,
                      size=15,
                      source=help_source,
                      line_width=2,
                      line_color='grey',
                      line_alpha=0.6)
    tooltips = help_source.data['help'][0]
    fig.add_tools(
        HoverTool(tooltips=tooltips,
                  renderers=[help],
                  mode='mouse',
                  point_policy="snap_to_data"))
    return fig
예제 #14
0
def create_radar_plot(df):
	"""Crea gráfica de radar afectando en cada tipo de calidad de agua con valores normalizados
	
	Parameters:
		df (Dataframe): Dataframe con los datos a mostrar en la visualización

	Returns:
		Figure: Gráfica de radar afectando en cada tipo de calidad de agua con valores normalizados
	"""

	def unit_poly_verts(theta, r=0.5, center=0.5):
		"""Return vertices of polygon for subplot axes.
		This polygon is circumscribed by a unit circle centered at center(def:(0.5, 0.5))
		"""
		x0, y0 = [center] * 2
		verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
		return verts

	def radar_patch(r, theta, center):
		yt = (r + 0.01) * np.sin(theta) + center
		xt = (r + 0.01) * np.cos(theta) + center
		return xt, yt

	NUM_VARS = df.Indicador.nunique() # Extraer numero de indicadores
	CENTER = 0.5 # Centro del gráfico de araña
	GRID_STEPS = 5 # Grid Subdivisions

	theta = np.linspace(0, 2*np.pi, NUM_VARS, endpoint=False)
	# rotate theta such that the first axis is at the top
	theta += np.pi/2

	x = [] # x-vertices
	y = [] # y-vertices
	# x_var_label = [] # x-vertices for variable labels
	x_ticks = [0.5]*(GRID_STEPS-1) # x-vertices for circular grid ticks
	y_ticks = [] # y-vertices for circular grid tick
	text = list(df.Indicador.unique()) # List with variable names

	#Tooltip creation
	TOOLTIPS = [('Indicador', '@Indicador'),
				('Valor', '@valor'),
				('Valor(esc)', '@valor_map')]
	hover = HoverTool(names=['radar_plt'], tooltips=TOOLTIPS)

	# Create radar figure
	nor_rad_pl = figure(plot_height=340, toolbar_location=None, x_range=(-0.2,1.4),
						y_range=(-0.1,1.1), tools=[hover,], sizing_mode='stretch_width')

	for i in range(GRID_STEPS):
		verts=unit_poly_verts(theta, (GRID_STEPS-i)*0.5/GRID_STEPS, CENTER)
		x.append([v[0] for v in verts])
		y.append([v[1] for v in verts])
		if i==0:
			source = ColumnDataSource({'x':x[i]+ [CENTER],'y':y[i]+ [(GRID_STEPS-i)*0.5/GRID_STEPS+CENTER],'text':text+ ['']})
			# source_test = ColumnDataSource({'x':x_var_label + [CENTER],'y':y[i]+ [(GRID_STEPS-i)*0.5/GRID_STEPS+CENTER],'text':text+ ['']})
			var_labels = LabelSet(x="x",y="y",text="text",source=source, text_color=bokeh_utils.LABEL_FONT_COLOR, text_font_size='15px') # Position variable labels
			nor_rad_pl.add_layout(var_labels) # Add variable labels
			color='black'
		else:
			source = ColumnDataSource({'x':x[i]+ [CENTER],'y':y[i]+ [(GRID_STEPS-i)*0.5/GRID_STEPS+CENTER]}) #radius*i/GRID_STEPS+CENTER
			color='gainsboro'
		nor_rad_pl.line(x="x", y="y", source=source, line_color=color) # Create poligons
		y_ticks.append(y[i][0]) # Store y-vertices grid ticks positions

	for i in range(NUM_VARS):
		nor_rad_pl.line(x=[CENTER,x[0][i]], y=[CENTER,y[0][i]], line_color='gainsboro') # Create grid lines from center to vertix

	y_ticks.reverse()
	text_labels_ticks = np.around(list(np.linspace(0, 1, GRID_STEPS, endpoint=False)), decimals=2) # Create text for grid ticks
	source_labels_ticks = ColumnDataSource({'x':x_ticks,'y':y_ticks[:-1],'text':text_labels_ticks[1:]})
	tick_labels = LabelSet(x="x",y="y",text="text",source=source_labels_ticks, text_color=bokeh_utils.LABEL_FONT_COLOR, text_font_size='14px') # Position grid tick labels
	nor_rad_pl.add_layout(tick_labels) # Add grid tick labels

	clist = []	# Cluster data list for spider pl patches
	colors = bokeh_utils.LINE_COLORS_PALETTE
	DATA_MIN = -2
	DATA_MAX = 3

	for i, cluster in enumerate(df.cluster.unique()):
		clist.append(df[df['cluster'] == cluster])
		xt, yt = radar_patch((clist[i].valor-DATA_MIN)/(DATA_MAX-DATA_MIN) * 0.5, theta, CENTER)
		clist[i]=clist[i].assign(**{'xt':xt, 'yt':yt, 'valor_map':(clist[i].valor-DATA_MIN)/(DATA_MAX-DATA_MIN)})
		nor_rad_pl.patch(x='xt', y='yt', fill_alpha=0.15, fill_color=colors[i], line_color=colors[i], legend_label=f'Cluster {i}', source=ColumnDataSource(clist[i]))
		nor_rad_pl.circle(x='xt', y='yt', size=15, fill_color=None, line_color=None ,source=ColumnDataSource(clist[i]), name='radar_plt')

	nor_rad_pl.legend.location = 'bottom_left'
	nor_rad_pl.legend.orientation = 'vertical'
	nor_rad_pl.legend.click_policy = 'hide'
	nor_rad_pl.legend.background_fill_alpha = 0
	nor_rad_pl.legend.border_line_alpha = 0
	nor_rad_pl.xgrid.visible = False
	nor_rad_pl.ygrid.visible = False
	nor_rad_pl.xaxis.visible = False
	nor_rad_pl.yaxis.visible = False
	nor_rad_pl.min_border = 0
	nor_rad_pl.outline_line_color = None
	nor_rad_pl.border_fill_color = bokeh_utils.BACKGROUND_COLOR
	nor_rad_pl.background_fill_color = bokeh_utils.BACKGROUND_COLOR
	return nor_rad_pl
                 click_policy='hide',
                 title="Click on States to Switch ON/OFF",
                 title_text_font_style="bold")
legend2 = Legend(items=legend_it[17:33],
                 location=(10, 0),
                 click_policy='hide',
                 title="Click on States to Switch ON/OFF",
                 title_text_font_style="bold")

p.add_layout(legend1, 'right')
p.add_layout(legend2, 'right')

cases_summary['day'] = cases_summary['day'].astype('str')
source = ColumnDataSource(cases_summary)

hover = HoverTool(line_policy='next')
hover.tooltips = [
    ('Date', '@x{%F}'),
    ('Cases', '@y{0000}')  # @$name gives the value corresponding to the legend
]
hover.formatters = {'@x': 'datetime'}
p.add_tools(hover)

citation = Label(x=0,
                 y=0,
                 x_units='screen',
                 y_units='screen',
                 text='Last Updated : {}'.format(latest_date),
                 render_mode='css',
                 text_font_size='12px')
p.add_layout(citation, 'above')
예제 #16
0
def make_lightcurve_figure_elements(lc, lc_source, ylim_func=None):
    """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 (days)'
    try:
        if (lc.mission == 'K2') or (lc.mission == 'Kepler'):
            fig.xaxis.axis_label = 'Time - 2454833 (days)'
        elif lc.mission == 'TESS':
            fig.xaxis.axis_label = 'Time - 2457000 (days)'
    except AttributeError:  # no mission keyword available
        pass

    if ylim_func is None:
        ylims = get_lightcurve_y_limits(lc_source)
    else:
        ylims = ylim_func(lc)
    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
예제 #17
0
def distribution_bokeh(critere_correction, 
                         mode_correction,
                         prob, 
                         k_erreurs,
                         nbre_sommets_GR,
                         rep_, 
                         bool_data_revue):
    """
    visualiser les distributions de moy_dc, moy_dh, correl_dc_dh, cumul_dh.
    """
    rep, rep_dist = "", "";
    df_kerrs = None;
    if not bool_data_revue:
        rep = rep_ + "/" \
              + critere_correction +"_sommets_GR_" + str(nbre_sommets_GR) + "/" \
              + mode_correction + "/" \
              + DATA_P_REP + str(prob);
        rep_dist = rep + "/" + "distribution" + "/";
        df_kerrs = create_dataframe(rep_dist, k_erreurs); 
    else:
        rep = rep_ + "/" \
              + mode_correction + "/" \
              + critere_correction + "/" \
              + DATA_P_REP + str(prob);
        rep_dist = rep + "/" + "distribution" + "/";
        df_kerrs = create_dataframe_data_revue(rep_dist, k_erreurs);
    
    # configuration figure
    output_file(rep_dist+"../../visualisation/"+"distribution_dashboard.html");
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select,lasso_select";
        
    p_cols = []
    
    for ind, k_erreur in enumerate(k_erreurs):
        p_cols_k = [];
        
        ###### moy_dc
        mu = df_kerrs["moy_dc_"+str(k_erreur)].mean(); 
        sigma = df_kerrs["moy_dc_"+str(k_erreur)].std();
        title, xlabel, ylabel = title_xlabel_ylabel_figure("moy_dc", k_erreur, 
                                                           mu, sigma)
        arr_hist, edges = np.histogram(df_kerrs['moy_dc_'+str(k_erreur)],
                            bins=int(max(df_kerrs['moy_dc_'+str(k_erreur)]) / 2), 
                            range=[min(df_kerrs['moy_dc_'+str(k_erreur)]), 
                                   max(df_kerrs['moy_dc_'+str(k_erreur)])]
                            )
                
        df_dc_k = pd.DataFrame({"moy_dc":arr_hist, 
                                'left':edges[:-1],
                                'right':edges[1:]})
        # Create the blank plot
        p_dc = figure(plot_height = HEIGHT, plot_width = WIDTH, 
                      title = title,
                      x_axis_label = xlabel, 
                      y_axis_label = ylabel, 
                      tools = TOOLS
                    )
        # Add a quad glyph
        src = ColumnDataSource(df_dc_k)
        p_dc.quad(source = src, bottom=0, top='moy_dc', 
                  left='left', right='right',
                  fill_color='red', line_color='black')
        # Add a hover tool referring to the formatted columns
        hover = HoverTool(tooltips = [('correction distance', '@moy_dc'),
                                      ('(min_dc, max_dc)', '($x, $y)') ])
        # Style the plot
#        p_dc = style(p_dc)
        # TODO comment remplacer le nombre par un pourcentage
#        tickers = np.around(arr_hist * 100 / df_kerrs['moy_dc_'+str(k_erreur))
#        p_dc.yaxis.ticker = ['{:3.2f}%'.format(
#                        x*100/df_kerrs["moy_dc_"+str(k_erreur)].count()) \
#                    for x in p_dc.yaxis.get_yticks()]
        
#        p_dc.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
#        def ticker():
#            return '{:3.2f}%'.format(tick * 100/df_kerrs["moy_dc_"+str(k_erreur)].count())
#        p_dc.yaxis.formatter = FuncTickFormatter(
#                                code=""" 
#                                    return tick * 100/df_kerrs["moy_dc_"+str(k_erreur)].count()
#                                """)
                                    

        # Add the hover tool to the graph
        p_dc.add_tools(hover)
        
        p_cols_k.append(p_dc)
        
        ###### moy_dh
        mu = df_kerrs["moy_dh_"+str(k_erreur)].mean(); 
        sigma = df_kerrs["moy_dh_"+str(k_erreur)].std();
        title, xlabel, ylabel = title_xlabel_ylabel_figure("moy_dh", k_erreur, 
                                                           mu, sigma)       
        arr_hist, edges = np.histogram(df_kerrs['moy_dh_'+str(k_erreur)],
                            bins=int(max(df_kerrs['moy_dh_'+str(k_erreur)]) / 2), 
                            range=[min(df_kerrs['moy_dh_'+str(k_erreur)]), 
                                   max(df_kerrs['moy_dh_'+str(k_erreur)])]
                            )
                
        df_dh_k = pd.DataFrame({"moy_dh":arr_hist, 
                                'left':edges[:-1],
                                'right':edges[1:]})
        # Create the blank plot
        p_dh = figure(plot_height = HEIGHT, plot_width = WIDTH, 
                      title = title,
                      x_axis_label = xlabel, 
                      y_axis_label = ylabel, 
                      tools = TOOLS)
        # Add a quad glyph
        src = ColumnDataSource(df_dh_k)
        p_dh.quad(source = src, bottom=0, top='moy_dh', 
                  left='left', right='right',
                  fill_color='red', line_color='black')
        # Add a hover tool referring to the formatted columns
        hover = HoverTool(tooltips = [('correction distance', '@moy_dh'),
                                      ('(min_dc, max_dh)', '($x, $y)') ])
        # Style the plot
#        p_dh = style(p_dh)

        # Add the hover tool to the graph
        p_dh.add_tools(hover)
        
        p_cols_k.append(p_dh)
        
        #### correl_dc_dh
        df_corr_k = df_kerrs[['moy_dh_'+str(k_erreur), 'moy_dc_'+str(k_erreur),
                              'correl_dc_dh_'+str(k_erreur)]];
        df_corr_k_sorted = df_corr_k.sort_values(
                                by='correl_dc_dh_'+str(k_erreur),
                                axis=0, ascending=True);
        df_corr_k_sorted['cumsum_k'] = df_corr_k_sorted['correl_dc_dh_'+str(k_erreur)].cumsum(axis=0);
        
        src = ColumnDataSource(df_corr_k_sorted)
        title = "fonction de repartition de \n" \
                +"correlation entre moy_dc et moy_dh \n pour " \
                +str(k_erreur)+" cases modifiees."
        title, xlabel, ylabel = title_xlabel_ylabel_figure("correl", k_erreur, 
                                                           0, 0)
        p_corr_k = figure(plot_height = HEIGHT, plot_width = WIDTH, 
                      title = title,
                      x_axis_label = xlabel, 
                      y_axis_label = ylabel, 
                      tools = TOOLS)
        p_corr_k.line(source=src, 
                      x='correl_dc_dh_'+str(k_erreur),
                      y='cumsum_k')
        
        p_cols_k.append(p_corr_k)
        
        #### cumul_correl_dc_dh
        df_corr_k_sorted = df_corr_k.sort_values(
                                by='correl_dc_dh_'+str(k_erreur),
                                axis=0, ascending=True);
        df_corr_k_sorted["nb_graphe_correl<x"] = \
            df_corr_k_sorted["moy_dh_"+str(k_erreur)]\
            .apply( lambda x: \
                   df_corr_k_sorted["correl_dc_dh_"\
                            +str(k_erreur)][df_corr_k_sorted["correl_dc_dh_"\
                                            +str(k_erreur)] < x].count()/\
                   df_corr_k_sorted["correl_dc_dh_"\
                            +str(k_erreur)].count())
        
        src = ColumnDataSource(df_corr_k_sorted)
        title = "cumulative moy_dh pour \n"+str(k_erreur)+" cases modifiees";
        title, xlabel, ylabel = title_xlabel_ylabel_figure("cumul_correl", 
                                                           k_erreur, 0, 0)
        p_corr_sup_x_k = figure(plot_height = HEIGHT, plot_width = WIDTH, 
                      title = title,
                      x_axis_label = xlabel, 
                      y_axis_label = ylabel, 
                      tools = TOOLS)
        p_corr_sup_x_k.line(source=src, 
                      x="correl_dc_dh_"+str(k_erreur),
                      y="nb_graphe_correl<x")
        
        p_cols_k.append(p_corr_sup_x_k)
                
        p_cols.append(p_cols_k);
        
    p = gridplot(p_cols)
    show(p)
    return df_kerrs
예제 #18
0
                      x_start=initial_votes + max(pokemon_votes)*0.05, x_end=initial_votes, 
                      y_start=y_coord, y_end=y_coord)
p_overall.add_layout(arrow_overall)

legend = Legend(items=[
    LegendItem(label='1', renderers=[r_overall], index=6),
    LegendItem(label='2', renderers=[r_overall], index=37),
    LegendItem(label='3', renderers=[r_overall], index=1),
    LegendItem(label='4', renderers=[r_overall], index=10),
    LegendItem(label='5', renderers=[r_overall], index=2),
    LegendItem(label='6', renderers=[r_overall], index=14),
    LegendItem(label='7', renderers=[r_overall], index=8),
], title='Generation', location='bottom_right')
p_overall.add_layout(legend)

hover_overall = HoverTool(mode='hline')
hover_overall.tooltips = """
<table style="width:175px">
  <tr>
    <th>@name</th>
    <td rowspan=4><image src=@sprite_source alt="" width="75"/></td>
  </tr>
  <tr>
    <td><strong>Generation: </strong>@generation</td>
  </tr>
  <tr>
    <td><strong>Votes: </strong>@votes</td>
  </tr>
  <tr>
    <td><strong>Ranking: </strong>@ranking_overall</td>
  </tr>
예제 #19
0
MARKERS = [
    "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "P", "*", "h",
    "H", "+", "x", "X", "D", "d"
]
COLORS = Category20[
    19]  #["red", "yellow", "blue", "green", "rosybrown","darkorange", "fuchsia", "grey", ]

TOOLS = [
    PanTool(),
    BoxZoomTool(),
    WheelZoomTool(),
    UndoTool(),
    RedoTool(),
    ResetTool(),
    SaveTool(),
    HoverTool(tooltips=[("Price", "$y"), ("Time", "$x")])
]

NAME_RESULT_SHOW_VARS = "resultat_show_variables_pi_plus_{}_pi_minus_{}.html"

#------------------------------------------------------------------------------
#                   definitions of functions
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
#                   definitions of functions
#------------------------------------------------------------------------------

# _____________________________________________________________________________
#
#        get local variables and turn them into dataframe --> debut
예제 #20
0
* When a circle is clicked, the corresponding month is displayed in the right-hand-side plot.

Interesting points to note:
* The primary immediately tells us that the period between June-September is the busiest time of the year for the preserve. Sensors get
  triggered with high frequency, and the traffic consists mostly of motorcycles(type 1) and light cars(type 2). Heavier vehicles are relatively
  sparse in comparison.
* In the off-seasons, most of the traffic consists of ranger vehicles(type 2P).
* Traffic generally drops during the middle of the week, and is higher during the weekends.
""",
width=1200, height=420)
curdoc().add_root(pre_intro)

##### PLOT FOR EACH MONTH #####################################################

monthView = figure(x_range=[0,13], tools=['wheel_zoom', 'pan', 'tap', 'reset'], title="Monthly Plot of Traffic by Car Type")
monthHover = HoverTool(tooltips=[('Car Type', '@cartype'), ('Count', '$y{00000}'), ('Month', '@month')])
monthView.add_tools(monthHover)
monthLines = monthView.multi_line(xs="x", ys="y", line_color="colors", line_width=3, alpha="alpha", legend="cartype", source=monthLineCDS)
monthCircles = monthView.circle(x="x", y="y", size=10, fill_color="colors", line_color="colors", alpha="alpha", source=monthCircleCDS)
monthView.xaxis.axis_label = "Month"
monthView.yaxis.axis_label = "Traffic activity"
monthView.xaxis.ticker = []
monthView.min_border_bottom=100;
monthCircles.selection_glyph = Circle(fill_alpha=0.8, line_alpha=0.8)
monthCircles.nonselection_glyph = Circle(fill_alpha=0.3, line_alpha=0.3)

monthLines.data_source.on_change('selected', line_callback)
monthCircles.data_source.on_change('selected', circle_callback)

##### PLOT FOR A WEEK #########################################################
예제 #21
0
def plot_bar_Perf_t_all_algos(df_ra_pri, rate, price, t):
    """
    plot the Perf_t at each learning step for all states 
    considering all scenarios and all algorithms.
    each figure is for one state, one scenario, one prob_Ci, one learning_rate 
    and one price.
    
    Perf_t = \sum\limits_{1\leq i \leq N} ben_i-cst_i
    
    x-axis : one time t
    y-axis : Perf_t
    """
    algos = df_ra_pri["algo"].unique()
    nb_instances = df_ra_pri.num_instance.unique().tolist()
    num_pl_is = df_ra_pri.pl_i.unique().tolist()
    tup_legends = []

    dico_algo_instance = dict()
    dico_algo_instance["pl_i"] = []
    dico_algo_instance["k"] = []
    dico_algo_instance["ben"] = []
    dico_algo_instance["cst"] = []
    dico_algo_instance["num_instance"] = []
    dico_algo_instance["algo"] = []
    for algo in algos:

        mask_algo = (df_ra_pri.algo == algo)
        df_ra_pr_al = df_ra_pri[mask_algo]
        # delete rows with nan values of columns = [ben, cst]
        df_ra_pr_al = df_ra_pr_al[df_ra_pr_al['ben'].notna()
                                  & df_ra_pr_al['cst'].notna()]
        # for each instance, select the k_stop and put it to a new dataframe.
        num_instances = df_ra_pr_al.num_instance.unique().tolist()
        for num_instance in num_instances:
            for num_pl_i in num_pl_is:
                mask_inst_pl_i = (df_ra_pr_al.pl_i==num_pl_i) \
                                    & (df_ra_pr_al.num_instance==num_instance)
                k_max = df_ra_pr_al[mask_inst_pl_i].k.max()
                mask_inst_pl_i_k_max = (df_ra_pr_al.pl_i==num_pl_i) \
                                    & (df_ra_pr_al.num_instance==num_instance) \
                                    & (df_ra_pr_al.k==k_max)
                index = df_ra_pr_al[mask_inst_pl_i_k_max].index[0]
                ben = df_ra_pr_al[mask_inst_pl_i].loc[index, 'ben']
                cst = df_ra_pr_al[mask_inst_pl_i].loc[index, 'cst']
                dico_algo_instance["pl_i"].append(num_pl_i)
                dico_algo_instance["k"].append(k_max)
                dico_algo_instance["ben"].append(ben)
                dico_algo_instance["cst"].append(cst)
                dico_algo_instance["num_instance"].append(num_instance)
                dico_algo_instance["algo"].append(algo)

    df = pd.DataFrame.from_dict(dico_algo_instance)

    df["Vi"] = df["ben"] - df["cst"]

    df_res = df.groupby(['algo'])['Vi'].aggregate([np.sum, np.mean, np.std])\
                .reset_index()

    TOOLS[7] = HoverTool(
        tooltips=[("algo", "@algo"), ("mean",
                                      "@mean"), ("sum", "@sum"), ("std",
                                                                  "@std")])
    idx = df_res.algo.unique().tolist()
    cols = ["algo", "mean", "std", "sum"]
    px = figure(x_range=idx,
                y_range=(df_res[cols[1]].values.min(),
                         df_res[cols[1]].values.max()),
                plot_height=int(HEIGHT * MULT_HEIGHT),
                plot_width=int(WIDTH * MULT_WIDTH),
                tools=TOOLS,
                toolbar_location="above")
    title = "Average of Vi over 50 executions (rate:{}, price={})".format(
        rate, price)
    px.title.text = title

    source = ColumnDataSource(data=df_res)

    width = 0.1  #0.5
    px.vbar(x=dodge('algo', -0.0, range=px.x_range),
            top=cols[1],
            width=width,
            source=source,
            color="#2E8B57",
            legend_label=cols[1])
    # px.vbar(x=dodge('algo', -0.3+1*width, range=px.x_range), top=cols[2],
    #                 width=width, source=source,
    #                 color="#718dbf", legend_label=cols[2])
    # px.vbar(x=dodge('t', -0.3+2*width, range=px.x_range), top=cols[3],
    #                width=width, source=source,
    #                color="#e84d60", legend_label=cols[3])

    px.x_range.range_padding = width
    px.xgrid.grid_line_color = None
    px.legend.location = "top_left"
    px.legend.orientation = "horizontal"
    px.xaxis.axis_label = "t_periods"
    px.yaxis.axis_label = "values"

    return px
예제 #22
0
    ax_limits['x'][1],  #bounds=ax_limits['x']
)
# #p_state_covid.xaxis[0].ticker.desired_num_ticks =round(np.busday_count(np.datetime64(source.data['date'].min(),'D'),np.datetime64(source.data['date'].max(),'D'))/3); # prefer number of labels (divide by 7 for week)
p_state_covid.xaxis.major_label_orientation = -np.pi / 3  # slant the labels
dtformat = "%b-%d"
p_state_covid.xaxis.formatter = formatter = DatetimeTickFormatter(  # Always show the same date formatting regardless of zoom
    days=dtformat,
    months=dtformat,
    hours=dtformat,
    minutes=dtformat)

# Add legend
p_state_covid.legend.location = "top_left"

# Add a hover tool
hover = HoverTool()
hover.tooltips = [
    #('Type', "$name"),
    ('', '$name: @$name{0,0.} on @date{%a-%b-%d}'),
]
# hover.mode = 'vline'
hover.formatters = {
    '@date': 'datetime',  # use 'datetime' formatter for '@date' field
    '$name': 'printf'  # use 'printf' formatter for the name of the column
}
hover.renderers = glyphs
p_state_covid.add_tools(hover)

# # Extra formatting
# for ax in p_state_covid.yaxis:
#     ax.axis_label_text_font_style = 'bold'
예제 #23
0
def plot_bar_moyVi_4_one_algo_many_state_instance(df_algo, algo):
    """
    bar plot Vi mean for one algo knowing states and instances
    plot is the bar plot with key is (instance, stateX) (X={1,2,3})
    
    on x-axis, there are instance and state
    on y-axis, there is Vi mean (moyVi)
    """
    # order df_algo by num_instance

    cols = ["num_instance", "state_i"]
    x = list(map(tuple, list(df_algo[cols].values)))
    moy_Vi = list(df_algo["moy_Vi"])

    TOOLS[7] = HoverTool(tooltips=[
        ("nb_players", "@nb_players"),
        ("id_players", "@id_players"),
        ("state_i", "@state_i"),
        ("moy_Vi", "@moy_Vi"),
        ("instance", "@num_instance"),
        ("algo", "@algo"),
    ])
    print("HEIGHT={},MULT_HEIGHT{},WIDTH={},MULT_WIDTH={}".format(
        HEIGHT, MULT_HEIGHT, WIDTH, MULT_WIDTH))
    px = figure(x_range=FactorRange(*x),
                plot_height=int(HEIGHT * MULT_HEIGHT),
                plot_width=int(WIDTH * MULT_WIDTH),
                title="mean of Vi by instances for {}".format(algo),
                toolbar_location="above",
                tools=TOOLS)
    # px= figure(x_range=FactorRange(*x),
    #            plot_height=int(500),
    #            plot_width = int(1500),
    #            title="mean of Vi by instances for {}".format(algo),
    #            toolbar_location="above", tools=TOOLS)

    data = dict(x=x,
                moy_Vi=moy_Vi,
                nb_players=df_algo.nb_players.tolist(),
                id_players=df_algo.id_players.tolist(),
                state_i=df_algo.state_i.tolist(),
                num_instance=df_algo.num_instance.tolist(),
                algo=df_algo.algo.tolist())

    source = ColumnDataSource(data=data)
    px.vbar(x='x',
            top='moy_Vi',
            width=0.9,
            source=source,
            fill_color=factor_cmap('x',
                                   palette=Category20[20],
                                   factors=list(df_algo.state_i.unique()),
                                   start=1,
                                   end=2))

    px.y_range.start = df_algo.moy_Vi.min()  # 0
    px.x_range.range_padding = 0.1
    px.xaxis.major_label_orientation = 1
    px.xgrid.grid_line_color = None
    px.xaxis.axis_label = 'instances'
    px.yaxis.axis_label = 'moy_Vi'

    return px
예제 #24
0
def create_plot(df, title, energy_unit, ylimit=None):
    """

    :param df:
    :param title: string, plot title
    :param energy_unit: string, the unit of energy used in the database/model
    :param ylimit: float/int, upper limit of heatmap colorbar; optional
    :return:
    """

    if df.empty:
        return figure()

    # Round hours and convert to string (required for x-axis)
    # TODO: figure out a way to handle subhourly data properly!
    df["hour_of_day"] = df["hour_of_day"].map(int).map(str)

    # Get list of hours and months (used in xrange/yrange)
    hours = list(df["hour_of_day"].unique())
    months = list(reversed(df["month"].unique()))

    # Set up color mapper
    # colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce",
    #           "#ddb7b1", "#cc7878", "#933b41", "#550b1d"]
    colors = list(reversed(Reds[9]))

    high = ylimit if ylimit is not None else df.scheduled_curtailment_mwh.max()
    mapper = LinearColorMapper(palette=colors,
                               low=df.scheduled_curtailment_mwh.min(),
                               high=high)

    # Set up the figure
    plot = figure(
        plot_width=800,
        plot_height=500,
        tools=["pan", "reset", "zoom_in", "zoom_out", "save", "help"],
        toolbar_location="below",
        x_axis_location="above",
        title=title,
        x_range=hours,
        y_range=months,
    )

    # Plot heatmap rectangles
    hm = plot.rect(x="hour_of_day",
                   y="month",
                   width=1,
                   height=1,
                   source=df,
                   fill_color={
                       'field': 'scheduled_curtailment_mwh',
                       'transform': mapper
                   },
                   line_color="white")

    # Add color bar legend
    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="7pt",
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=NumeralTickFormatter(format="0,0"),
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    plot.add_layout(color_bar, 'right')

    # Format Axes (labels, number formatting, range, etc.)
    plot.xaxis.axis_label = "Hour Ending"
    plot.yaxis.axis_label = "Month"
    plot.grid.grid_line_color = None
    plot.axis.axis_line_color = None
    plot.axis.major_tick_line_color = None
    plot.axis.major_label_standoff = 0

    # Add HoverTool
    hover = HoverTool(tooltips=[
        ("Month", "@month"), ("Hour", "@hour_of_day"),
        ("Curtailment", "@scheduled_curtailment_mwh{0,0} %s" % energy_unit)
    ],
                      renderers=[hm],
                      toggleable=True)
    plot.add_tools(hover)

    return plot
예제 #25
0
def plot_bar_moyVi_4_algo_state(df_algo_instance_state_moyVi):
    """
    for each row of plot, draw a bar plot of Vi mean for all algos.
    the bar plot has algo and state on x-axis ie key = (algo, stateX) (X={1,2,3})
        and moyVi on y-axis

    Parameters
    ----------
    df_algo_instance_state_moyVi : TYPE
        DESCRIPTION.

    Returns
    -------
    None.

    """

    dico_pxs = dict()
    cols = ["algo", "state_i"]
    df_groupby_algo_state_i = df_algo_instance_state_moyVi\
                                .groupby(cols)["moy_Vi"]\
                                .aggregate([np.sum, np.mean, np.std])\
                                .reset_index()
    df_groupby_algo_state_i.rename(columns={
        "mean": "moy_Vi",
        "sum": "sum_Vi",
        "std": "std_Vi"
    },
                                   inplace=True)
    x = list(map(tuple, list(df_groupby_algo_state_i[cols].values)))
    moy_Vi = list(df_groupby_algo_state_i["moy_Vi"])

    TOOLS[7] = HoverTool(tooltips=[
        ("state_i", "@state_i"),
        ("moy_Vi", "@moy_Vi"),
        ("sum_Vi", "@sum_Vi"),
        ("std_Vi", "@std_Vi"),
        ("algo", "@algo"),
    ])
    px = figure(x_range=FactorRange(*x),
                plot_height=int(HEIGHT * MULT_HEIGHT),
                plot_width=int(WIDTH * MULT_WIDTH),
                title="mean of Vi by algorithm and states",
                toolbar_location="above",
                tools=TOOLS)

    data = dict(x=x,
                moy_Vi=moy_Vi,
                sum_Vi=df_groupby_algo_state_i.sum_Vi.tolist(),
                std_Vi=df_groupby_algo_state_i.std_Vi.tolist(),
                state_i=df_groupby_algo_state_i.state_i.tolist(),
                algo=df_groupby_algo_state_i.algo.tolist())

    source = ColumnDataSource(data=data)
    px.vbar(x='x', top='moy_Vi', width=0.9, source=source,
            fill_color=factor_cmap('x',
                                    palette=Category20[20],
                                    factors=list(df_groupby_algo_state_i\
                                                 .state_i.unique()),
                                    start=1, end=2))

    px.y_range.start = df_groupby_algo_state_i.moy_Vi.min()  # 0
    px.x_range.range_padding = 0.1
    px.xaxis.major_label_orientation = 1
    px.xgrid.grid_line_color = None
    px.xaxis.axis_label = 'algorithms'
    px.yaxis.axis_label = 'moy_Vi'

    col_px = column(px)
    col_px = column(children=[col_px], sizing_mode='stretch_both')
    return col_px
예제 #26
0
    def setup_plot(
        self,
        x_axis_type="linear",
        y_axis_type="linear",
        x_flip=False,
        y_flip=False,
    ):
        # Set up the plot
        self.plot = figure(
            plot_height=620,
            min_width=600,
            title="",
            x_axis_type=x_axis_type,
            y_axis_type=y_axis_type,
            tools="",
            sizing_mode="stretch_both",
        )

        # Enable Bokeh tools
        self.plot.add_tools(PanTool(), TapTool(), ResetTool())

        # Axes orientation and labels
        self.plot.x_range.flipped = x_flip
        self.plot.y_range.flipped = y_flip
        self.plot.xaxis.axis_label = self.xaxis.value
        self.plot.yaxis.axis_label = self.yaxis.value

        # Plot the data
        self.plot.circle(
            x="x",
            y="y",
            source=self.source,
            size="size",
            color=linear_cmap(field_name="color",
                              palette=Viridis256,
                              low=0,
                              high=1),
            line_color=None,
        )

        # -- HACKZ --

        # Update the plot element in the HTML layout
        if hasattr(self.parent, "layout"):
            self.parent.layout.children[0].children[-1] = self.plot

        # Make the cursor a grabber when panning
        code_pan_start = """
            Bokeh.grabbing = true
            var elm = document.getElementsByClassName('bk-canvas-events')[0]
            elm.style.cursor = 'grabbing'
        """
        code_pan_end = """
            if(Bokeh.grabbing) {
                Bokeh.grabbing = false
                var elm = document.getElementsByClassName('bk-canvas-events')[0]
                elm.style.cursor = 'grab'
            }
        """
        self.plot.js_on_event("panstart", CustomJS(code=code_pan_start))
        self.plot.js_on_event("panend", CustomJS(code=code_pan_end))

        # Add a hover tool w/ a pointer cursor
        code_hover = """
        if((Bokeh.grabbing == 'undefined') || !Bokeh.grabbing) {
            var elm = document.getElementsByClassName('bk-canvas-events')[0]
            if (cb_data.index.indices.length > 0) {
                elm.style.cursor = 'pointer'
                Bokeh.pointing = true
            } else {
                if((Bokeh.pointing == 'undefined') || !Bokeh.pointing)
                    elm.style.cursor = 'grab'
                else
                    Bokeh.pointing = false
            }
        }
        """
        self.plot.add_tools(
            HoverTool(
                callback=CustomJS(code=code_hover),
                tooltips=[("TIC ID", "@ticid")],
            ))
# source = ColumnDataSource(sample)
# source = ColumnDataSource(sample)
d = dict(
    one=sample['one'],
    two=sample['two'],
    color=colors,
    Label=sample['Label'],
    Metadata_Plate=sample['Metadata_Plate'],
    Metadata_Well=sample['Metadata_Well'],
    Metadata_FieldID=sample['Metadata_FieldID'],
    #         actual_image_number=sample['actual_image_number'],
    ObjectNumber=sample['ObjectNumber'])
source = ColumnDataSource(data=d)

hover = HoverTool()
hover.tooltips = [
    ('Label', '@Label'),
    ('Metadata_Plate', '@Metadata_Plate'),
    ('Metadata_Well', '@Metadata_Well'),
    ('Metadata_FieldID', '@Metadata_FieldID'),
    ('ObjectNumber', '@ObjectNumber'),
]

p = figure(tools="tap,reset", tooltips=hover.tooltips)
p.circle(x='one', y='two', source=source, size=2, color='color')

p.title.text = 'TSNE - Applied on Mito features of single cells'
p.xaxis.axis_label = 'one'
p.yaxis.axis_label = 'two'
예제 #28
0
           plot_width=800,
           plot_height=600,
           title='Car with Top HorsePower',
           x_axis_label='Horse Power')
# Render glyph
p.hbar(
    y='Car',
    right='Horsepower',
    left=0,
    height=0.4,
    color='blue',
    fill_alpha=0.5,
    source=source,
)
# hover tools
hover = HoverTool()
hover.tooltips = """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="">
    <h3>@Car</h3>
    <div><strong>Price:</strong>@Price</div>
    <div><strong>HP:</strong>@Horsepower</div>
    <div><img src="@Image" class="circle" alt = "" width="200"/></div>
</div>

"""
p.add_tools(hover)
# show result
# show(p)

# save file
예제 #29
0
    def __init__(self, log_level=logutil.logging.NOTSET, **figure_dict):
        # set logging level to user-specified level
        log.setLevel(log_level)

        # Set the location for the figure tools
        fig_tool_loc = figure_dict.get('toolbar_location', 'right')

        # Set up the actual figure tools for use
        # If hover tooltips are to be used, they are appended below
        self.fig = figure(tools=FIGURE_TOOLS_BASE,
                          toolbar_location=fig_tool_loc)

        # Basic figure attributes
        self.fig.xaxis.axis_label = figure_dict.get('x_label', '')
        self.fig.yaxis.axis_label = figure_dict.get('y_label', '')
        self.fig.title.text = figure_dict.get('title', '')
        self.fig.background_fill_color = figure_dict.get(
            'background_fill_color', 'gainsboro')
        self.fig.background_fill_alpha = figure_dict.get(
            'background_fill_alpha', 0.5)

        # Determine if the hover tooltips should be turned off
        use_hover_tips = figure_dict.get('use_hover_tips', True)

        # If hover tooltips are desired, set up the tips and add the hover tool
        # to the figure tools
        if use_hover_tips:
            # Append any user requested tooltips to the base set
            user_tips = figure_dict.get('hover_tips', [])
            hover_fig = HoverTool()
            hover_fig.tooltips = HOVER_BASIC_TIPS + user_tips
            self.fig.add_tools(hover_fig)

        # Do not set up defaults for these at this time
        if 'x_range' in figure_dict:
            self.fig.x_range = figure_dict.get('x_range')
        if 'y_range' in figure_dict:
            self.fig.y_range = figure_dict.get('y_range')
        if 'xstart' in figure_dict:
            self.fig.x_range.start = figure_dict.get('xstart')
        if 'ystart' in figure_dict:
            self.fig.y_range.start = figure_dict.get('ystart')
        self.fig.grid.grid_line_color = figure_dict.get(
            'grid_line_color', 'white')

        # These attributes are not for the figure, but are styling attributes
        # used for the "shape" glyphs.  They may be set to non-default values when
        # the build_glyph() routine is invoked.
        self.glyph_color = 'blue'
        self.color = 'blue'
        self.size = 10
        self.legend_group = ''
        self.legend_label = ''
        self.fill_alpha = 0.5
        self.line_alpha = 0.5
        self.line_width = 1
        self.fig.legend.location = 'top-right'
        self.fill_color = 'gainsboro'
        self.angle = 0.0
        self.text_size = '10px'

        # This value is set so the functionality is always active - this allows
        # the user click on an item in the legend and turn on/off the display of
        # that particular dataset.  NOTE: This functionality does not work for
        # 'legend_group' (yet) according to Bokeh documentation.
        self.fig.legend.click_policy = 'hide'
예제 #30
0
    def __init__(self, dataset, parameters):

        self.dataset = dataset

        # Set up the controls
        self.specials = Selector(
            name="Specials",
            kind="specials",
            css_classes=["specials"],
            entries={
                "Color-magnitude diagram": "cmd",
                "Period vs. radius": "pr",
                "Period vs. transit duration": "pdt",
            },
            default="Color-magnitude diagram",
        )
        self.data = Selector(
            name="Datasets",
            kind="datasets",
            css_classes=["data"],
            entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"},
            default="Confirmed Planets",
        )
        self.xaxis = Selector(
            name="Build-Your-Own",
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="ra",
            title="X Axis",
        )
        self.yaxis = Selector(
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="dec",
            title="Y Axis",
        )
        self.size = Selector(
            name="Sides",
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Size",
            none_allowed=True,
        )
        self.color = Selector(
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Color",
            none_allowed=True,
        )

        # Set up the plot
        self.source = ColumnDataSource(
            data=dict(x=[], y=[], size=[], color=[])
        )
        self.plot = figure(
            plot_height=600,
            plot_width=700,
            title="",
            tooltips=[("TIC ID", "@ticid")],
            sizing_mode="scale_both",
        )
        self.plot.circle(
            x="x",
            y="y",
            source=self.source,
            size="size",
            color=linear_cmap(
                field_name="color", palette=Viridis256, low=0, high=1
            ),
            line_color=None,
        )
        self.plot.add_tools(
            BoxSelectTool(),
            BoxZoomTool(),
            LassoSelectTool(),
            PanTool(),
            PolySelectTool(),
            TapTool(),
            WheelZoomTool(),
            WheelPanTool(),
            ZoomInTool(),
            ZoomOutTool(),
            HoverTool(),
            CrosshairTool(),
        )

        # Register the callback
        for control in [
            self.specials,
            self.data,
            self.xaxis,
            self.yaxis,
            self.size,
            self.color,
        ]:
            control.widget.on_change("value", self.callback)
예제 #31
0
# ___Panel 1_______________________________________________________________________________________
p1 = figure(
    x_axis_type="datetime",
    title="Bouy 45183 Temperature Measurements",
    #             tooltips=TOOLTIPS,
    background_fill_color="white",
    width=1000,
)

p1.add_tools(
    HoverTool(
        tooltips=[
            ("index", "$index"),
            ("datetime", "@x{%F}"),  # use @{ } for field names with spaces
            ("Temperature", "@y{0.0}"),
        ],
        formatters={
            "@x": "datetime",
        },  # use 'datetime' formatter for '@date' field
        # display a tooltip whenever the cursor is vertically in line with a glyph
        #     mode='vline'
    ))

p1.line(
    data.index,
    c_to_f(data.ATMP),
    color="green",
    line_alpha=0.5,
    legend_label=data.ATMP.name,
)
p1.line(
    data.index,