示例#1
0
def _internal_bokeh(doc, example=None):
    from bokeh.layouts import row
    import asyncio

    async def clock_retrieve(period_secs: float, ttyout=False) -> None:
        import asyncio

        while True:
            await asyncio.sleep(period_secs)
            clock(period_secs=None, ttyout=ttyout)  # calling itself synchronously

    # tick always in background but we retrieve its measurement every second.
    asyncio.get_running_loop().create_task(clock_retrieve(period_secs=1, ttyout=True))
    # TODO : turn off retrieval when document is detached ?

    clocksourceview = inspect.getsource(Clock)
    thissourceview = inspect.getsource(_internal_bokeh)

    doc.add_root(
        grid(
            [
                [PreText(text=clocksourceview), PreText(text=thissourceview)],
                # to help compare / visually debug
                [clock[["minute", "second"]].plot, clock[["minute", "second"]].table],
                # Note : even if we create multiple clock instances here,
                # the model is the same, and propagation will update all datasources...
            ]
        )
    )
示例#2
0
def build_choropleth_doc(cpleth_df_instances: List[pd.DataFrame], county_date_instances: List,
                         debug_mode: bool = False) -> None:
    df_instances, states = build_cpleth_df(cpleth_df_instances)
    curdoc().clear()
    national_cpleth_sources, cpleth_sources, stateplot, nationalplots = build_cpleth_plot_df(states, df_instances)
    ttldiv = Div(text="""Effective Reproduction Number ( R<sub>t</sub> )""", orientation='vertical',
                 height_policy='min',
                 width_policy='min', css_classes=['cbar_title'], align='center')
    ttldiv.visible = True
    menu = []
    for full_name, state in zip(constants.full_names, states):
        menu.append((state, full_name))
    select = Select(title="", value="Choose", options=menu, name='state_select', css_classes=['bk_select'],
                    width_policy='min', background=None)
    someargs = dict(plot=stateplot, select=select, ttldiv=ttldiv, cpleth_sources=cpleth_sources)
    select_callback = CustomJS(args=someargs, code=constants.select_callback_code)
    select.js_on_change('value', select_callback)
    row_layout = row(stateplot, ttldiv)
    gridlayout = grid([
        [select],
        [row_layout]
    ])
    if not debug_mode:
        for i, natp in enumerate(nationalplots):
            gen_national_imgs(i, natp, county_date_instances)
        script, div = components([gridlayout])
        covid_utils.save_bokeh_tags([div[0], script], config.choro_covid_explorer_tags)
    else:
        show(gridlayout)
示例#3
0
    def __init__(self):
        """Create text field and empty plotting grid."""

        self.file_input = TextInput(placeholder='Enter file path')
        self.layout = grid([], ncols=2)
        self.i = 0
        self.j = 0
示例#4
0
def print_tab(df, titre):
    grid_ = grid(
        children=[print_table(df)],
        sizing_mode="stretch_width",
    )

    return bokeh.models.Panel(child=grid_, title=titre)
示例#5
0
def build_dashboard_doc(rt_df: pd.DataFrame, status_df: pd.DataFrame, debug_mode: bool = False) \
        -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.Index]:
    # define core document objects
    curdoc().clear()
    primary_rt_plot_df, counties_df, main_plot_df, counties, status_df = build_dashboard_dfs(rt_df, status_df)
    default_county = counties.tolist()[0]
    patchsources = build_patchsources(counties, counties_df)
    countytable, countytable_cds = build_countytable(status_df)
    rtsource = ColumnDataSource(counties_df)
    rtplot, plots, ms_plot, choices = build_dynamic_plots(constants.cust_rg_palette, patchsources, rtsource, counties,
                                                          default_county)
    set_tbl_logic(rtsource, choices, patchsources, countytable_cds, rtplot, plots, ms_plot)
    # set initial default
    plots = [p['plot'] for p in plots]
    plots.extend([rtplot, ms_plot])
    set_plots_blank(plots)
    gridlayout = grid([
        [None, None, choices],
        [plots[1], plots[0], plots[2]],
        [countytable]
    ])
    if not debug_mode:
        script, div = components([gridlayout])
        covid_utils.save_bokeh_tags([div[0], script], config.county_covid_explorer_tags)
    else:
        show(gridlayout)
    return primary_rt_plot_df, counties_df, main_plot_df, counties
示例#6
0
    def _build_figure(self, file_path, figure_matrix):

        # Make figure matrix html file and embed
        file_name = 'integrated_scatterplot_output.html'
        figure_html_path = os.path.join(file_path, file_name)
        output_file(figure_html_path)
        save(grid(figure_matrix))

        return file_name
示例#7
0
 def show_plot(self):
     """
     :return:
     """
     l = grid([
         row([
             column([self.map, self.plot, self.slider]),
             column([*[t.layout for t in self.text_inputs], self.text])])],
         sizing_mode='stretch_both')
     show(l)
 def generate_tabbed_output(self):
     self.patient_graph()
     tab_bicarb, tab_chloride = self.graphs['Patient']
     tab_bicarb.plot_width = 800
     tab_chloride.plot_width = 800
     panel_bicarb = Panel(child=tab_bicarb, title="Bicarbonate Transport")
     panel_chloride = Panel(child=tab_chloride, title="Chloride Transport")
     tabs = Tabs(tabs=[panel_bicarb, panel_chloride], width=1000)
     var_menu = self.gen_var_menu()
     widget_column, widgets = self.process_widgets(var_menu)
     layout = grid([[widget_column, tabs]])
     return layout, widgets, tab_bicarb, tab_chloride
示例#9
0
    def callback(attr, old, new):

        layout.children[1] = grid([
            create_figure1(),
            create_figure2(),
            create_figure3(),
            create_figure4(),
            create_figure5()
        ],
                                  ncols=2)

        callback = CustomJS(code="console.log('tap event occurred')")
示例#10
0
def show_model_introspect(model,
                          tr_data,
                          tr_data_ind,
                          val_data,
                          val_data_ind,
                          device,
                          n_sampl=3,
                          n_lat_sampl=300,
                          fix_fig=True):
    fig1, fig2, fig3, fig4, fig5, fig6 = get_model_introspect(
        model, tr_data, tr_data_ind, val_data, val_data_ind, device, n_sampl,
        n_lat_sampl, fix_fig)
    show(grid([[fig1, fig2], [fig3, fig4], [fig5, fig6]]))
示例#11
0
def month(month):
    f'''
    # Month: {month}
    '''
    '''
    $contents
    '''
    '''
    ## Preparation
    '''

    s = session('-v2')
    output_file(filename='/dev/null')
    map_size = 100
    month_start = to_date(month).replace(day=1)
    '''
    ## Generate Plot
    '''
    def days():

        for i in Calendar().iterweekdays():
            yield Div(text=f'<h2>{day_name[i]}</h2>')

        day = month_start - dt.timedelta(days=month_start.weekday())
        while day.month <= month_start.month:
            for weekday in range(7):
                if day.month == month_start.month:
                    contents = [Div(text=f'<h1>{day.strftime("%d")}</h1>')]
                    for a in s.query(ActivityJournal). \
                            filter(ActivityJournal.start >= local_date_to_time(day),
                                   ActivityJournal.finish < local_date_to_time(day + dt.timedelta(days=1))).all():
                        df = activity_statistics(s,
                                                 SPHERICAL_MERCATOR_X,
                                                 SPHERICAL_MERCATOR_Y,
                                                 activity_journal=a)
                        contents.append(
                            map_thumbnail(map_size, map_size, df, title=False))
                        df = activity_statistics(s,
                                                 ACTIVE_DISTANCE,
                                                 ACTIVE_TIME,
                                                 activity_journal=a)
                        contents.append(
                            Div(text=
                                f'{format_metres(df[ACTIVE_DISTANCE][0])} {format_seconds(df[ACTIVE_TIME][0])}'
                                ))
                else:
                    contents = [Spacer()]
                yield column(contents)
                day += dt.timedelta(days=1)

    show(grid(list(days()), ncols=7))
示例#12
0
    def get_layout(self):
        """Return the complete bokeh layout."""
        tabs = self.get_tab_layout()
        tab_kwargs = {
            'Data': [
                'text_index_selection',
                ('select_all_button', 'deselect_all_button'),
                'pressure_slider', 'text_multi_serie_flagging',
                'parameter_selector', 'multi_flag_widget'
            ],
            'Metadata': [
                'text_meta', 'comnt_visit', 'comnt_visit_button', 'comnt_samp',
                'comnt_samp_selector', 'comnt_samp_button'
            ],
            'Info': ['info_block']
        }
        if not self.as_standalone:
            tab_kwargs['Import'] = ['text_import', 'file_button']
            tab_kwargs['Export'] = ['text_export', 'download_button']

        meta_tabs = self.get_tabs(**tab_kwargs)
        std_parameter_tabs = self.get_std_parameter_tab_layout()
        widgets_1 = column(
            [self.month_selector, self.spacer, self.selected_series],
            sizing_mode="fixed",
            height=400,
            width=200)
        widgets_2 = column([Spacer(height=10, width=125)],
                           sizing_mode="fixed",
                           height=10,
                           width=125)
        widgets_3 = column([meta_tabs],
                           sizing_mode="stretch_both",
                           height=100,
                           width=100)
        return grid([
            row([self.map, widgets_1, widgets_2, widgets_3]),
            row([*std_parameter_tabs, column([tabs])])
        ])
示例#13
0
    offset_slider.js_on_change('value', callback)

    widgets = column(amp_slider, freq_slider, phase_slider, offset_slider)
    return [widgets, plot]


def linked_panning():
    N = 100
    x = np.linspace(0, 4 * np.pi, N)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x) + np.cos(x)

    s1 = figure(tools=tools)
    s1.circle(x, y1, color="navy", size=8, alpha=0.5)
    s2 = figure(tools=tools, x_range=s1.x_range, y_range=s1.y_range)
    s2.circle(x, y2, color="firebrick", size=8, alpha=0.5)
    s3 = figure(tools='pan, box_select', x_range=s1.x_range)
    s3.circle(x, y3, color="olive", size=8, alpha=0.5)
    return [s1, s2, s3]


l = grid([
    bollinger(),
    slider(),
    linked_panning(),
],
         sizing_mode='stretch_both')

show(l)
示例#14
0
	packet_id = str(entry[0])
	packet_val = get_packet_val(metadata, packet_id, entry[1:5])
	packet_ts = get_packet_ts(entry[5:9])
	packet_module = str(entry[-1])
	channel_id = '%s;%s' % (packet_id, packet_module)
	channel = channels.get(channel_id, None)
	if not channel:
		channel = {
				'name': metadata['ids'][packet_id]['name'],
				'x': [],
				'y': []
				}
	channels[channel_id] = append_time_val(channel, packet_ts, packet_val)
print('Done loading. Generating plots..')
row = 0
for channel in channels:
	if len(figures[row]) == 4:
		figures.append([])
		row += 1
	channel_id, channel_origin = channel.split(';')
	new_fig = figure(width=350, height=350, title='%s:%s, module: %s' % (channel_id, channels[channel]['name'], modules[int(channel_origin)]))
	new_fig.line(channels[channel]['x'], channels[channel]['y'])
	figures[row].append(new_fig)

# For generating html file
output_file('%s.html' % sys.argv[1])
show(grid(figures))

# For serving plots from web server
#curdoc().add_root(grid(figures))
示例#15
0
options = dict(tools="", toolbar_location=None, plot_height=300, plot_width=300, sizing_mode="fixed")

p1 = figure(title="Line (300 x 100)", **options)
p1.plot_height = 100
p1.line(x, y)

p2 = figure(title="Annular wedge (100 x 300)", title_location='right', **options)
p2.plot_width = 200
p2.annular_wedge(x, y, 10, 20, 0.6, 4.1, inner_radius_units="screen", outer_radius_units="screen")

p3 = figure(title="Bezier (300 x 300)", **options)
p3.bezier(x, y, x + 0.4, y, x + 0.1, y + 0.2, x - 0.1, y - 0.2)

p4 = figure(title="Quad (300 x 300)", **options)
p4.quad(x, x - 0.2, y, y - 0.2)

paragraph = Paragraph(text="We build up a grid plot manually. Try changing the mode of the plots yourself.")

select = Select(title="Sizing mode", value="fixed", options=list(SizingMode), width=300)

plots = grid([[None, p1, None], [p2, p3, p4]])
layout = column([paragraph, select, plots])

select.js_link('value', p1, 'sizing_mode')
select.js_link('value', p2, 'sizing_mode')
select.js_link('value', p3, 'sizing_mode')
select.js_link('value', p4, 'sizing_mode')
select.js_link('value', layout, 'sizing_mode')

show(layout)
示例#16
0
s1 = figure(plot_width=450, plot_height=420, title=title)
s1.vbar(returns['Rank'], width=0.5, top=returns['Return'])
s1.line(returns['Rank'], returns['Pred'], line_color='red')
s1.xaxis.axis_label = 'Symbol Rank'
s1.yaxis.axis_label = 'Following Month Return'

s2 = figure(x_range=distro['Symbol'],
            plot_width=450,
            plot_height=420,
            title="Average Allocation by Symbol")
s2.vbar(distro['Symbol'], width=0.5, top=distro['Alloc'])

mp = figure(plot_width=650, plot_height=420, title="Model Performance")
dd = figure(plot_width=650, plot_height=420, title="Drawdown")
mp.xaxis.major_label_overrides = {
    i: date.strftime('%b %y')
    for i, date in enumerate(pd.to_datetime(ref_price['Date']))
}
dd.xaxis.major_label_overrides = {
    i: date.strftime('%b %y')
    for i, date in enumerate(pd.to_datetime(ref_price['Date']))
}
ref_price.drop(ref_price.index[:lookback], inplace=True)
mp.line(ref_price['ID'], ref_price['SPY_Bal'], line_color='red', legend="SPY")
mp.line(ref_price['ID'], model['End_Bal'], line_color='black', legend="Model")
mp.legend.location = "top_left"
dd.line(ref_price['ID'], model['DD'], line_color='red')

output_file('chart.htm')
l = grid([[para1, corr_grid_display], [s1, mp], [s2, dd]])
show(l, browser=None)
示例#17
0
    if len(signal) == len(signal_source.data['y']):
        signal_source.data['y'] = signal*gain.value
    else:
        t = np.linspace(0, TIMESLICE, len(signal))
        signal_source.data = dict(t=t, y=signal*gain.value)

    if len(spectrum) == len(spectrum_source.data['y']):
        spectrum_source.data['y'] = spectrum
    else:
        f = np.linspace(0, MAX_FREQ_KHZ, len(spectrum))
        spectrum_source.data = dict(f=f, y=spectrum)
    spectrum_plot.x_range.end = freq.value*0.001

    alphas = []
    for x in bins:
        a = np.zeros_like(eq_range)
        N = int(ceil(x))
        a[:N] = (1 - eq_range[:N]*0.05)
        alphas.append(a)
    eq_source.data['alpha'] = np.hstack(alphas)
curdoc().add_periodic_callback(update, 80)

controls = row(gain, freq)

plots = grid(column(waterfall_plot, row(column(signal_plot, spectrum_plot), eq)))

curdoc().add_root(desc)
curdoc().add_root(controls)
curdoc().add_root(plots)
示例#18
0
    freq_slider.js_on_change('value', callback)
    phase_slider.js_on_change('value', callback)
    offset_slider.js_on_change('value', callback)

    widgets = column(amp_slider, freq_slider, phase_slider, offset_slider)
    return [widgets, plot]


def linked_panning():
    N = 100
    x = np.linspace(0, 4 * np.pi, N)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x) + np.cos(x)

    s1 = figure(tools=tools)
    s1.circle(x, y1, color="navy", size=8, alpha=0.5)
    s2 = figure(tools=tools, x_range=s1.x_range, y_range=s1.y_range)
    s2.circle(x, y2, color="firebrick", size=8, alpha=0.5)
    s3 = figure(tools='pan, box_select', x_range=s1.x_range)
    s3.circle(x, y3, color="olive", size=8, alpha=0.5)
    return [s1, s2, s3]

l = grid([
    bollinger(),
    slider(),
    linked_panning(),
], sizing_mode='stretch_both')

show(l)
示例#19
0
from bokeh.models.tools import HoverTool
from bokeh.models.axes import LinearAxis
from MA import *
import math

renderer = Renderer()

with renderer.measure("render"):
    redered_everything = renderer.setup()

# render this document
curdoc().add_root(
    row(
        grid([[
            renderer.seed_plot.left_plot, renderer.nuc_plot.left_plot,
            renderer.main_plot.plot
        ], [None, None, renderer.nuc_plot.bottom_plot],
              [None, None, renderer.seed_plot.bottom_plot]]),
        column(
            row(renderer.widgets.file_input, renderer.widgets.run_id_dropdown,
                renderer.widgets.ground_truth_id_dropdown),
            renderer.widgets.score_slider,
            renderer.widgets.max_elements_slider,
            renderer.widgets.range_link_radio,
            row(renderer.widgets.full_render_button,
                renderer.widgets.render_mems_button,
                renderer.widgets.delete_button),
            renderer.widgets.force_read_id,
            grid([[
                renderer.read_plot.nuc_plot.left_plot, renderer.read_plot.plot
            ], [None, renderer.read_plot.nuc_plot.bottom_plot]
        document.body.removeChild(elem);
        """,
)

# add Hover tool
# define what is displayed in the tooltip
tooltips = [
    ("X:", "@x"),
    ("Y:", "@y"),
    ("static text", "static text"),
]

fig02.add_tools(HoverTool(tooltips=tooltips))

# display results
# demo linked plots
# demo zooms and reset
# demo hover tool
# demo table
# demo save selected results to file

layout = grid([fig01, fig02, table, savebutton], ncols=3)

output_notebook()
show(layout)

# things to try:
# select random shape of blue dots with lasso tool in 'Select Here' graph
# only selected points appear as red dots in 'Watch Here' graph -- try zooming, saving that graph separately
# selected points also appear in the table, which is sortable
# click the 'Save' button to export a csv
示例#21
0
def test_grid():
    s0 = Spacer()
    s1 = Spacer()
    s2 = Spacer()
    s3 = Spacer()
    s4 = Spacer()
    s5 = Spacer()
    s6 = Spacer()

    g0 = grid([])
    assert g0.children == []

    g1 = grid(column(s0, row(column(s1, s2, s3, s4, s5), s6)))
    assert g1.children == [
        (s0, 0, 0, 1, 2),
        (s1, 1, 0, 1, 1),
        (s2, 2, 0, 1, 1),
        (s3, 3, 0, 1, 1),
        (s4, 4, 0, 1, 1),
        (s5, 5, 0, 1, 1),
        (s6, 1, 1, 5, 1),
    ]

    g2 = grid([s0, [[s1, s2, s3, s4, s5], s6]])
    assert g2.children == [
        (s0, 0, 0, 1, 2),
        (s1, 1, 0, 1, 1),
        (s2, 2, 0, 1, 1),
        (s3, 3, 0, 1, 1),
        (s4, 4, 0, 1, 1),
        (s5, 5, 0, 1, 1),
        (s6, 1, 1, 5, 1),
    ]

    g3 = grid([s0, s1, s2, s3, s4, s5, s6], ncols=2)
    assert g3.children == [
        (s0, 0, 0, 1, 1),
        (s1, 0, 1, 1, 1),
        (s2, 1, 0, 1, 1),
        (s3, 1, 1, 1, 1),
        (s4, 2, 0, 1, 1),
        (s5, 2, 1, 1, 1),
        (s6, 3, 0, 1, 2),
    ]

    g4 = grid([s0, s1, s2, s3, s4, s5, s6, None], ncols=2)
    assert g4.children == [
        (s0, 0, 0, 1, 1),
        (s1, 0, 1, 1, 1),
        (s2, 1, 0, 1, 1),
        (s3, 1, 1, 1, 1),
        (s4, 2, 0, 1, 1),
        (s5, 2, 1, 1, 1),
        (s6, 3, 0, 1, 1),
    ]

    with pytest.raises(NotImplementedError):
        grid("""
        +----+----+----+----+
        | s1 | s2 | s3 |    |
        +---------+----+ s4 |
        |    s5   | s5 |    |
        +---------+----+----+
        """)
    'radar': rt,
    'circle': cr.data_source,
    'latt': lat3,
    'lonn': lon3
},
                          code=hover_code)
waveforms.add_tools(
    HoverTool(tooltips=None,
              callback=hover_callback,
              renderers=[ln, cr, av, tr]))

# add slider functionality
slider_callback = CustomJS(args={
    'track': tr.data_source,
    'latt': lat,
    'lonn': lon,
    'inc': slid_inc
},
                           code=slider_code)
slider.js_on_change('value', slider_callback)

# create layout to display all figures
p = grid([
    [slider],
    [waveforms],
    [map, ind_wf],
], sizing_mode='fixed')

# display figures
show(p)
示例#23
0
def create_app(doc, default_dir=".", update=10):
    """Creates a Bokeh document that the server will display"""
    # start loading the dashboard
    log.info(f"Creating Bokeh app")
    log.debug(f"Default directory: {os.path.realpath(default_dir)}")
    log.debug(f"Update rate for mdinfo callback: {update}s")
    doc.title = "DashMD"
    document = Dashboard(default_dir)

    def callback_load_dir(new_value):
        if document.anim_button.active:
            document.anim_button.label = "◼ Stop"
            document.anim_button.button_type = "danger"
            document.autocomp_results.children = []
            global mdinfo_callback
            # first update of the dashboard
            document.get_mdout_files()
            document.parse_mdinfo()
            for mdout in document.mdout_files[:document.slider.value]:
                document.read_mdout_header(mdout)
            document.display_simulations_length()
            document.mdinfo_callback = doc.add_periodic_callback(document.update_dashboard, update*1e3)
        else:
            document.anim_button.label = "▶ Load"
            document.anim_button.button_type = "success"
            doc.remove_periodic_callback(document.mdinfo_callback)
    document.anim_button.on_click(callback_load_dir)

    # arrange display with tabs
    dashboard = Panel(
        title="Dashboard",
        child=grid([
        row([
            column([document.md_dir, document.autocomp_results]),
            document.anim_button,
        ]),
        row([
            column([document.pie]),
            column([
                document.progressbar,
                document.calc_speed,
                document.eta,
                document.last_update,
                document.slider,
            ]),
        ]),
        row([document.bar]),
        row([document.mdout_sel, document.mdout_button]),
        ], sizing_mode="scale_both")
    )
    temp_tab = Panel(title="Temperature", child=document.temperature_fig)
    press_tab = Panel(title="Pressure", child=document.pressure_fig)
    e_tab = Panel(title="Energy", child=document.energy_fig)
    vol_tab = Panel(title="Volume", child=document.vol_fig)
    dens_tab = Panel(title="Density", child=document.density_fig)
    rmsd_tab = Panel(title="RMSD", child=grid([column([
        row([document.topology, document.trajectory, document.rmsd_button]),
        document.rmsd_fig,
    ])]))
    view_tab = Panel(title="View", child=grid([
        column([
            row([document.topology, document.trajectory, document.view_button]),
            document.view_canvas,
        ])
    ]))
    tabs = Tabs(tabs=[ dashboard, view_tab, rmsd_tab, temp_tab, press_tab, e_tab, vol_tab, dens_tab])
    doc.add_root(tabs)
示例#24
0
    def modify_document(self, doc):
        self.tb.lock()
        sink = bokehgui.vec_sink_f_proc(self.tb.get_num_channels(), "", 1)
        self.tb.connect((self.mag_to_zW, 0), (sink, 0))
        self.tb.unlock()

        log_cds = ColumnDataSource(data=self.lw.get_table())
        blw = BokehLogWatcher(doc, log_cds)
        logging.getLogger().addHandler(blw)

        def cleanup_session(session_context):
            self.tb.lock()
            self.tb.disconnect((self.mag_to_zW, 0), (sink, 0))
            self.tb.unlock()
            logging.getLogger().removeHandler(blw)

        doc.on_session_destroyed(cleanup_session)

        doc.title = "Gal Scan GUI"

        plot_lst = []

        plot = vec_sink_f(doc, plot_lst, sink, is_message=False)

        plot.initialize(update_time=100, legend_list=[''])
        plot.get_figure().aspect_ratio = 2
        plot.set_y_axis([0, 10])
        plot.set_y_label("Power at feed (zW / Hz)")
        plot.set_x_label("Frequency (MHz)")

        def set_x_values():
            plot.set_x_values(
                np.linspace(
                    self.tb.get_sdr_frequency() -
                    (self.tb.get_output_vector_bandwidth() / 2),
                    self.tb.get_sdr_frequency() +
                    (self.tb.get_output_vector_bandwidth() / 2),
                    self.tb.get_num_channels()) / 1e6)

        set_x_values()
        plot.enable_axis_labels(True)
        plot.set_layout(1, 0)
        plot.enable_max_hold()
        plot.format_line(0, "blue", 1, "solid", None, 1.0)

        azimuth = Knob(title="Azimuth", max=360, min=0, unit="°")
        elevation = Knob(title="Elevation", max=360, min=0, unit="°")
        rx_power = Knob(title="Average RX Power",
                        digits=4,
                        decimals=1,
                        unit="dB(mW/Hz)")
        plot.stream.js_on_change(
            "streaming",
            CustomJS(
                args=dict(rx_power=rx_power),
                code="""
            const data = cb_obj.data
            const average = data['y0'].reduce((a,b) => a+b)/data['y0'].length
            rx_power.value = (10*Math.log10(average))-180
            """,
            ))

        log_table = SortedDataTable(
            source=log_cds,
            columns=[
                TableColumn(field="asctime", title="Time", width=140),
                TableColumn(field="levelname", title="Level", width=60),
                TableColumn(field="message", title="Message", width=1500),
            ],
            autosize_mode="none",
            aspect_ratio=2,
            sizing_mode="stretch_width",
            sortable=True,
        )

        gain = Slider(title="gain",
                      value=self.tb.get_sdr_gain(),
                      start=0,
                      end=65)
        gain.on_change('value', lambda name, old, new: self.set_gain(new))

        rx = ActiveButton(label="RX enabled")
        rx.on_click(lambda: self.set_rx(not rx.active))

        frequency = Knob(title="center frequency",
                         writable=True,
                         value=self.tb.get_sdr_frequency(),
                         digits=10,
                         decimals=0,
                         unit="Hz")
        frequency.on_change('value',
                            lambda name, old, new: self.set_frequency(new))

        bandwidth = Knob(title="filter bandwidth",
                         writable=False,
                         value=self.tb.get_bandwidth(),
                         digits=7,
                         decimals=0,
                         unit="Hz")
        bandwidth.on_change('value',
                            lambda name, old, new: self.set_bandwidth(new))

        reset = Button(label="Reset")

        def on_reset():
            gain.value = run.flowgraph_defaults['sdr_gain']
            frequency.value = run.flowgraph_defaults['sdr_frequency']
            bandwidth.value = run.flowgraph_defaults['bandwidth']

        reset.on_click(on_reset)

        manual = Panel(title="Manual",
                       child=column(
                           row(rx, gain),
                           row(frequency, bandwidth),
                           reset,
                       ))

        run_models = {}
        automated_panels = []
        for group, args in run.arg_groups.items():
            # TODO: show grouping
            panel_models = []
            for key, arg in args.items():
                key = key.replace('-', '_')
                bokeh_args = arg.get('bokeh', {})
                bokeh_args['name'] = key
                bokeh_args['tags'] = ['args']
                if 'default' in arg:
                    bokeh_args['value'] = arg['default']
                if 'help' in arg:
                    bokeh_args['title'] = arg['help']
                    if 'metavar' in arg:
                        bokeh_args['title'] += " (%s)" % (arg['metavar'])
                type = TextInput
                if arg.get('type') in (float, int):
                    type = Spinner
                    if 'bokeh' in arg and 'start' in arg[
                            'bokeh'] and 'end' in arg['bokeh']:
                        type = Slider
                    if 'step' not in bokeh_args:
                        if arg['type'] == int:
                            bokeh_args['step'] = 1
                        else:
                            bokeh_args['step'] = 0.01
                    if arg.get('metavar') == 'Hz':
                        if 'digits' not in bokeh_args:
                            bokeh_args['digits'] = 10
                            if bokeh_args.get('max'):
                                bokeh_args['digits'] = len("%d" %
                                                           bokeh_args['max'])
                        type = functools.partial(Knob,
                                                 decimals=0,
                                                 unit=arg['metavar'])
                        del bokeh_args['step']
                        del bokeh_args['tags']
                        if 'writable' not in bokeh_args:
                            bokeh_args['writable'] = True
                elif 'choices' in arg:
                    type = Select
                    bokeh_args['options'] = [str(x) for x in arg['choices']]
                    if 'value' in bokeh_args:
                        bokeh_args['value'] = str(bokeh_args['value'])
                elif arg.get('action') in ('store_true', 'store_false'):
                    type = Select
                    bokeh_args['options'] = [('0', 'False'), ('1', 'True')]
                    bokeh_args['value'] = str(int(bokeh_args['value']))
                    bokeh_args['tags'] = ['boolean'] + bokeh_args.get(
                        'tags', [])
                if group.startswith("mode="):
                    # Make this smarter if we ever have a mode=gal tab
                    bokeh_args['disabled'] = True
                m = type(**bokeh_args)
                run_models[key] = m
                panel_models.append(m)
            automated_panels.append(
                Panel(title=group, child=grid(panel_models, ncols=2)))
        for panel in automated_panels:
            if panel.title.startswith("mode="):
                mode_str = panel.title.split('=')[1]
                run_models['mode'].js_on_change(
                    'value',
                    CustomJS(
                        args=dict(panel=panel, mode=mode_str),
                        code=
                        """panel.select(Bokeh.require("models/widgets/control").Control).forEach(c => c.disabled = (this.value != mode))""",
                    ))

        plan_p = Paragraph(sizing_mode="stretch_width", )

        load = UploadButton(name="load-settings",
                            accept=".json,application/json",
                            label="Load settings")

        def on_load(attr, old, new):
            data = json.loads(base64.b64decode(new))
            for key, value in data.items():
                if isinstance(run_models[key], Select):
                    value = str(value)
                run_models[key].value = value

        load.on_change('value', on_load)

        save = DownloadButton(label="Save settings",
                              filename="gal_scan_settings.json",
                              mime_type="application/json",
                              data=CustomJS(args=dict(run_models=run_models),
                                            code="""
                const out = {}
                for (let k in run_models) {
                  if (!run_models[k].disabled) {
                    out[k] = run_models[k].value
                    const tags = run_models[k].tags
                    if (tags && tags.indexOf("boolean") >= 0) {
                      out[k] = parseInt(out[k])
                    }
                  }
                }
                return JSON.stringify(out, null, 2);
                """))
        start = Button(label="Start scan")

        def get_args(output_dir):
            return run.parse_args(
                [output_dir],
                {
                    k: int(v.value) if "boolean" in v.tags else v.value
                    for k, v in run_models.items() if not v.disabled
                },
            )

        def on_start():
            try:
                output_dir = os.path.join(
                    self.runs_dir, "run_" +
                    datetime.datetime.now().replace(microsecond=0).isoformat())
                args = get_args(output_dir)
                self.enqueue_run(args)
            except SystemExit:
                pass

        start.on_click(on_start)
        automated = Panel(title="Plan",
                          child=column(Tabs(tabs=automated_panels), plan_p,
                                       row(load, save, start)))

        # TODO: Show cancel buttons for active or queued actions
        queue_cds = ColumnDataSource(data=self.get_queue_data())
        action_column = ActionMenuColumn(
            field="id",
            title="Action",
            menu=[
                ("Cancel", "cancel"),
            ],
        )

        def on_action_menu_click(event):
            if event.item == "cancel":
                self.cancel_action(event.value)
            else:
                logging.warn("Unknown action clicked: %s", event.item)

        action_column.on_event(ActionMenuClick, on_action_menu_click)
        queue_table = SortedDataTable(
            source=queue_cds,
            columns=[
                TableColumn(
                    field="time",
                    title="Time",
                    formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"),
                ),
                TableColumn(field="user", title="User"),
                TableColumn(field="name", title="Job"),
                action_column,
            ],
            highlight_field="active",
            sort_ascending=True,
            autosize_mode="fit_viewport",
            aspect_ratio=2,
            sizing_mode="stretch_width",
        )
        queue = Panel(title="Queue", child=queue_table)

        results_cds = ColumnDataSource(data={"name": [], "mtime": []})
        results_table = SortedDataTable(
            source=results_cds,
            columns=[
                TableColumn(
                    field="mtime",
                    title="Time",
                    formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"),
                ),
                TableColumn(
                    field="name",
                    title="Name",
                    formatter=HTMLTemplateFormatter(
                        template=
                        '<a href="/runs/<%= value %>/" target="_blank"><%= value %></a>'
                    )),
            ],
            autosize_mode="fit_viewport",
            aspect_ratio=2,
            sizing_mode="stretch_width",
            sortable=True,
        )
        results = Panel(title="Results", child=results_table)

        tabs = Tabs(tabs=[manual, automated, queue, results])

        status_p = Paragraph(sizing_mode="stretch_width", )

        controls = column(row(azimuth, elevation, rx_power), status_p, tabs,
                          log_table)

        def get_survey_data():
            pointers = {
                'ra': [],
                'dec': [],
                'label': [],
                'colour': [],
            }
            for o in self.messier:
                pointers['ra'].append(o['ra'])
                pointers['dec'].append(o['dec'])
                pointers['label'].append(o['label'])
                pointers['colour'].append('')
            survey = self.active_action.get('survey')
            out = {
                'pointers': pointers,
                'status_message': 'Idle',
                'plan_message': 'Invalid parameters'
            }
            if survey:
                groups = survey.coord_groups
                i = 0
                for sc, colour in zip(reversed(groups),
                                      ('rgb(0, 192, 0)', 'rgb(192, 0, 0)')):
                    sc = sc.icrs
                    for sc in sc:
                        pointers['ra'].append(sc.ra.to(u.degree).value)
                        pointers['dec'].append(sc.dec.to(u.degree).value)
                        pointers['label'].append(str(i + 1))
                        pointers['colour'].append(colour)
                        i += 1
                out['status_message'] = 'Time remaining on current survey: %s' % (
                    survey.time_remaining.to_datetime())
            survey = None
            try:
                survey = run.Survey(get_args('bogus'))
                out['plan_message'] = 'Estimated runtime: %s' % (
                    survey.time_remaining.to_datetime())
                if tabs.tabs[tabs.active] == automated:
                    # TODO: Use the underlying numpy arrays
                    sc = survey.iterator.coords_now.icrs
                    for i, sc in enumerate(sc[:1000]):
                        pointers['ra'].append(sc.ra.to(u.degree).value)
                        pointers['dec'].append(sc.dec.to(u.degree).value)
                        pointers['label'].append(str(i + 1))
                        pointers['colour'].append('rgb(148,0,211)')
            except:
                logging.getLogger('stderr').exception('Invalid parameters')
            return out

        sd = get_survey_data()
        pointers_cds = ColumnDataSource(data=sd['pointers'])

        def update_pointers(attr, old, new):
            logging.debug('Updating pointers')
            sd = get_survey_data()
            pointers_cds.data = sd['pointers']
            plan_p.text = sd['plan_message']
            status_p.text = sd['status_message']

        update_pointers(None, None, None)

        log_cds.on_change('data', update_pointers)
        tabs.on_change('active', update_pointers)
        for m in run_models.values():
            m.on_change('value', update_pointers)

        skymap = Skymap(
            height=600,
            sizing_mode="stretch_height",
            pointer_data_source=pointers_cds,
        )
        skymap.on_event(Tap, lambda event: self.point(event.x, event.y))

        doc.add_root(row(
            column(
                skymap,
                plot.get_figure(),
            ),
            controls,
        ), )

        async def update_status(last_status={}):
            set_x_values()
            status = self.client.status
            skymap.latlon = (status['Latitude'], status['Longitude'])
            skymap.azel = (status['AzPos'], status['ElPos'])
            if status['CommandAzFlags'] == 'POSITION' or status[
                    'CommandElFlags'] == 'POSITION':
                skymap.targetAzel = (status['CommandAzPos'],
                                     status['CommandElPos'])
            else:
                skymap.targetAzel = None
            azimuth.value = status['AzPos']
            elevation.value = status['ElPos']
            rx_active = status['Sequencer']['Bands'][0]['CommandRX']
            if not last_status or rx_active != last_status['Sequencer'][
                    'Bands'][0]['CommandRX']:
                if rx_active:
                    rx.label = "RX enabled"
                else:
                    rx.label = "RX disabled (50Ω load)"
                rx.active = rx_active
            queue_data = self.get_queue_data()
            if queue_cds.data != queue_data:
                queue_cds.data = queue_data
            with os.scandir(self.runs_dir) as it:
                files = list(
                    sorted(it, reverse=True, key=lambda f: f.stat().st_mtime))
                results_data = {
                    "name": [f.name for f in files],
                    "mtime": [int(f.stat().st_mtime * 1000) for f in files],
                }
                if results_data != results_cds.data:
                    results_cds.data = results_data
            last_status.update(status)

        doc.add_periodic_callback(update_status, 200)
示例#25
0
                 4.1,
                 inner_radius_units="screen",
                 outer_radius_units="screen")

p3 = figure(title="Bezier (300 x 300)", **options)
p3.bezier(x, y, x + 0.4, y, x + 0.1, y + 0.2, x - 0.1, y - 0.2)

p4 = figure(title="Quad (300 x 300)", **options)
p4.quad(x, x - 0.2, y, y - 0.2)

paragraph = Paragraph(
    text=
    "We build up a grid plot manually. Try changing the mode of the plots yourself."
)

select = Select(title="Sizing mode",
                value="fixed",
                options=list(SizingMode),
                width=300)

plots = grid([[None, p1, None], [p2, p3, p4]])
layout = column(paragraph, select, plots)

select.js_link('value', p1, 'sizing_mode')
select.js_link('value', p2, 'sizing_mode')
select.js_link('value', p3, 'sizing_mode')
select.js_link('value', p4, 'sizing_mode')
select.js_link('value', layout, 'sizing_mode')

show(layout)
示例#26
0
def interactive_hist(adata, keys=['n_counts', 'n_genes'],
                     bins='auto',  max_bins=100,
                     groups=None, fill_alpha=0.4,
                     palette=None, display_all=True,
                     tools='pan, reset, wheel_zoom, save',
                     legend_loc='top_right',
                     plot_width=None, plot_height=None, save=None,
                     *args, **kwargs):
    """Utility function to plot distributions with variable number of bins.

    Params
    --------
    adata: AnnData object
        annotated data object
    keys: list(str), optional (default: `['n_counts', 'n_genes']`)
        keys in `adata.obs` or `adata.var` where the distibutions are stored
    bins: int; str, optional (default: `auto`)
        number of bins used for plotting or str from numpy.histogram
    max_bins: int, optional (default: `1000`)
        maximum number of bins possible
    groups: list(str), (default: `None`)
        keys in `adata.obs.obs_keys()`, groups by all possible combinations of values, e.g. for
        3 plates and 2 time points, we would create total of 6 groups
    fill_alpha: float[0.0, 1.0], (default: `0.4`)
        alpha channel of the fill color
    palette: list(str), optional (default: `None`)
        palette to use
    display_all: bool, optional (default: `True`)
        display the statistics for all data
    tools: str, optional (default: `'pan,reset, wheel_zoom, save'`)
        palette of interactive tools for the user
    legend_loc: str, (default: `'top_right'`)
        position of the legend
    legend_loc: str, default(`'top_left'`)
        position of the legend
    plot_width: int, optional (default: `None`)
        width of the plot
    plot_height: int, optional (default: `None`)
        height of the plot
    save: Union[os.PathLike, Str, NoneType], optional (default: `None`)
        path where to save the plot
    *args, **kwargs: arguments, keyword arguments
        addition argument to bokeh.models.figure

    Returns
    --------
    None
    """

    if max_bins < 1:
        raise ValueError(f'`max_bins` must >= 1')

    palette = Set1[9] + Set2[8] + Set3[12] if palette is None else palette

    # check the input
    for key in keys:
        if key not in adata.obs.keys() and \
           key not in adata.var.keys() and \
           key not in adata.var_names:
            raise ValueError(f'The key `{key}` does not exist in `adata.obs`, `adata.var` or `adata.var_names`.')

    def _create_adata_groups():
        if groups is None:
            return [adata], [('all',)]

        combs = list(product(*[set(adata.obs[g]) for g in groups]))
        adatas= [adata[reduce(lambda l, r: l & r,
                              (adata.obs[k] == v for k, v in zip(groups, vals)), True)]
                 for vals in combs] + [adata]

        if display_all:
            combs += [('all',)]
            adatas += [adata]

        return adatas, combs

    # group_v_combs contains the value combinations
    ad_gs = _create_adata_groups()
    
    cols = []
    for key in keys:
        callbacks = []
        fig = figure(*args, tools=tools, **kwargs)
        slider = Slider(start=1, end=max_bins, value=0, step=1,
                        title='Bins')

        plots = []
        for j, (ad, group_vs) in enumerate(filter(lambda ad_g: ad_g[0].n_obs > 0, zip(*ad_gs))):

            if key in ad.obs.keys():
                orig = ad.obs[key]
                hist, edges = np.histogram(orig, density=True, bins=bins)
            elif key in ad.var.keys():
                orig = ad.var[key]
                hist, edges = np.histogram(orig, density=True, bins=bins)
            else:
                orig = ad[:, key].X
                hist, edges = np.histogram(orig, density=True, bins=bins)

            slider.value = len(hist)
            # case when automatic bins
            max_bins = max(max_bins, slider.value)

            # original data, used for recalculation of histogram in JS code
            orig = ColumnDataSource(data=dict(values=orig))
            # data that we update in JS code
            source = ColumnDataSource(data=dict(hist=hist, l_edges=edges[:-1], r_edges=edges[1:]))

            legend = ', '.join(': '.join(map(str, gv)) for gv in zip(groups, group_vs)) \
                    if groups is not None else 'all'
            p = fig.quad(source=source, top='hist', bottom=0,
                         left='l_edges', right='r_edges',
                         fill_color=palette[j], legend_label=legend if legend_loc is not None else None,
                         muted_alpha=0,
                         line_color="#555555", fill_alpha=fill_alpha)

            # create callback and slider
            callback = CustomJS(args=dict(source=source, orig=orig), code=_inter_hist_js_code)
            callback.args['bins'] = slider
            callbacks.append(callback)

            # add the current plot so that we can set it
            # visible/invisible in JS code
            plots.append(p)

        slider.end = max_bins

        # slider now updates all values
        slider.js_on_change('value', *callbacks)

        button = Button(label='Toggle', button_type='primary')
        button.callback = CustomJS(
            args={'plots': plots},
            code='''
                 for (var i = 0; i < plots.length; i++) {
                     plots[i].muted = !plots[i].muted;
                 }
                 '''
        )

        if legend_loc is not None:
            fig.legend.location = legend_loc
            fig.legend.click_policy = 'mute'

        fig.xaxis.axis_label = key
        fig.yaxis.axis_label = 'normalized frequency'
        _set_plot_wh(fig, plot_width, plot_height)

        cols.append(column(slider, button, fig))

    if _bokeh_version > (1, 0, 4):
        from bokeh.layouts import grid
        plot = grid(children=cols, ncols=2)
    else:
        cols = list(map(list, np.array_split(cols, np.ceil(len(cols) / 2))))
        plot = layout(children=cols, sizing_mode='fixed', ncols=2)

    if save is not None:
        save = save if str(save).endswith('.html') else str(save) + '.html'
        bokeh_save(plot, save)
    else:
        show(plot)
示例#27
0
文件: main.py 项目: zebulon2/bokeh
    if len(signal) == len(signal_source.data['y']):
        signal_source.data['y'] = signal*gain.value
    else:
        t = np.linspace(0, TIMESLICE, len(signal))
        signal_source.data = dict(t=t, y=signal*gain.value)

    if len(spectrum) == len(spectrum_source.data['y']):
        spectrum_source.data['y'] = spectrum
    else:
        f = np.linspace(0, MAX_FREQ_KHZ, len(spectrum))
        spectrum_source.data = dict(f=f, y=spectrum)
    spectrum_plot.x_range.end = freq.value*0.001

    alphas = []
    for x in bins:
        a = np.zeros_like(eq_range)
        N = int(ceil(x))
        a[:N] = (1 - eq_range[:N]*0.05)
        alphas.append(a)
    eq_source.data['alpha'] = np.hstack(alphas)
curdoc().add_periodic_callback(update, 80)

controls = row(gain, freq)

plots = grid(column(waterfall_plot, row(column(signal_plot, spectrum_plot), eq)))

curdoc().add_root(desc)
curdoc().add_root(controls)
curdoc().add_root(plots)
示例#28
0
        d2['y'] = []
        d2['z'] = []
        d2['timestamp_str'] = []
        d2['timestamp'].push(d1['timestamp'][inds[0]])
        d2['timestamp_str'].push(d1['timestamp_str'][inds[0]])
        d2['x'].push(d1['x'][inds[0]])
        d2['y'].push(d1['y'][inds[0]])
        d2['z'].push(d1['z'][inds[0]])
        d2['timestamp'].push(d1['timestamp'][inds[inds.length-1]])
        d2['x'].push(d1['x'][inds[inds.length-1]])
        d2['y'].push(d1['y'][inds[inds.length-1]])
        d2['z'].push(d1['z'][inds[inds.length-1]])
        d2['timestamp_str'].push(d1['timestamp_str'][inds[inds.length-1]])
        s2.change.emit();
        table.change.emit();
    """,
    ),
)

### Layout

layout = grid(column(row(column(file_picker, p, select)),
                     row(column(selected_date_title, table)),
                     row(btn_chairstand, btn_3m_walk),
                     row(btn_clear_selection, btn_export)),
              sizing_mode='stretch_width')

bokeh_doc = curdoc()
bokeh_doc.add_root(layout)

bokeh_doc.title = "Visualize chair stands & 3M walks"
示例#29
0
    f.vbar(x='DATE', top='value', source = plot_CDS_be, fill_alpha = 0.5,\
       width=dt.timedelta(1), \
       line_color='black', color='color', legend_label="Be")

    f.vbar(x='DATE', top='value', source = plot_CDS_fr, fill_alpha = 0.5,\
       width=dt.timedelta(1), \
       line_color='black', color='color', y_range_name='France', legend_label="Fr")

    f.legend.location = "top_left"
    f.grid.grid_line_alpha = 0
    f.xaxis.axis_label = 'Date'
    f.ygrid.band_fill_color = "olive"
    f.ygrid.band_fill_alpha = 0.1

    return f


total = make_plot_compare(['hosp', 'TOTAL_IN'])
tab1 = Panel(child=total, title="Total")

icu = make_plot_compare(['rea', 'TOTAL_IN_ICU'])
tab2 = Panel(child=icu, title="ICU")

#deaths = make_plot_compare(['dc', 'DEATHS'])

tabs = Tabs(tabs=[tab1, tab2])

layout = grid([[cat_selection], [p], [tabs]])

curdoc().add_root(layout)
示例#30
0
def Interactive_Graph():
    print('Interactive Graph for Phase {} for {} on All Pairs at {}'.format(Phase,BotName,TimeFrame))
    dfp1 = pd.read_csv(
        'C:/Users/bryan/AppData/Roaming/MetaQuotes/Terminal/6C3C6A11D1C3791DD4DBF45421BF8028/reports/EA-B1v1/EURUSD/H4/WF_Report/OptiWFResults-EA-B1v1-EURUSD-H4-2007.1.1-2012.1.1-Complete.csv')
    dfp2 = pd.read_csv(
        'C:/Users/bryan/AppData/Roaming/MetaQuotes/Terminal/6C3C6A11D1C3791DD4DBF45421BF8028/reports/EA-B1v1/EURUSD/H4/WF_Report/OptiWFResults-EA-B1v1-EURUSD-H4-2007.1.1-2012.1.1-Complete.csv')
    dfp3 = pd.read_csv(
        'C:/Users/bryan/AppData/Roaming/MetaQuotes/Terminal/6C3C6A11D1C3791DD4DBF45421BF8028/reports/EA-B1v1/EURUSD/H4/WF_Report/OptiWFResults-EA-B1v1-EURUSD-H4-2007.1.1-2012.1.1-Complete.csv')

    dfp4 = pd.read_csv(
        'C:/Users/bryan/AppData/Roaming/MetaQuotes/Terminal/6C3C6A11D1C3791DD4DBF45421BF8028/reports/EA-B1v1/EURUSD/H4/WF_Report/OptiWFResults-EA-B1v1-EURUSD-H4-2007.1.1-2012.1.1-Complete.csv')

    dfp5 = pd.read_csv(
        'C:/Users/bryan/AppData/Roaming/MetaQuotes/Terminal/6C3C6A11D1C3791DD4DBF45421BF8028/reports/EA-B1v1/EURUSD/H4/WF_Report/OptiWFResults-EA-B1v1-EURUSD-H4-2007.1.1-2012.1.1-Complete.csv')

    columns = sorted(dfp1.columns)
    discrete = [x for x in columns if dfp1[x].dtype == object]
    continuous = [x for x in columns if x not in discrete]


    def create_figure1():
        xsp1 = dfp1[x.value].values
        ysp1 = dfp1[y.value].values
        x_titlep1 = x.value.title()
        y_titlep1 = y.value.title()

        kwp1 = dict()
        if x.value in discrete:
            kwp1['x_range'] = sorted(set(xsp1))
        if y.value in discrete:
            kwp1['y_range'] = sorted(set(ysp1))
        kwp1['title'] = "%s vs %s" % (x_titlep1, y_titlep1) + " for {} on {} and {}".format(BotName, EURUSD, TimeFrame)

        pp1 = figure(plot_height=400, plot_width=800, tools='pan,box_zoom,hover,reset,lasso_select', **kwp1)
        pp1.xaxis.axis_label = x_titlep1
        pp1.yaxis.axis_label = y_titlep1

        if x.value in discrete:
            pp1.xaxis.major_label_orientation = pd.np.pi / 4

        sz = 9
        if size.value != 'None':
            if len(set(dfp2[size.value])) > N_SIZES:
                groups = pd.qcut(dfp2[size.value].values, N_SIZES, duplicates='drop')
            else:
                groups = pd.Categorical(dfp2[size.value])
            sz = [SIZES[xx] for xx in groups.codes]

        c = "#31AADE"
        if color.value != 'None':
            if len(set(dfp2[color.value])) > N_COLORS:
                groups = pd.qcut(dfp2[color.value].values, N_COLORS, duplicates='drop')
            else:
                groups = pd.Categorical(dfp2[color.value])
            c = [COLORS[xx] for xx in groups.codes]

        # COLOR BAR NEXT TO GRAPHIC

        #PAIR 1
        try:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1['Profit']),high=max(dfp1['Profit']))  # arreglar Maximo y minimo para que agarren el valor
        except ValueError:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=0,high=1)
            print('This {} did not launch Phase {} on {}'.format(BotName,Phase,TimeFrame))

        #Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1[color.value]),high=max(dfp1[color.value]))  # arreglar Maximo y minimo para que agarren el valor
        GraphTicker = AdaptiveTicker(base=50,desired_num_ticks=10,num_minor_ticks=20,max_interval=1000)
        Color_legend = ColorBar(color_mapper=Var_color_mapper,ticker =GraphTicker,label_standoff=12, border_line_color=None,location=(0, 0)) #arreglar LogTicker para que muestre por al escala del color
        pp1.circle(x=xsp1, y=ysp1, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5)
        pp1.add_layout(Color_legend,'right')

        return pp1

    def create_figure2():
        xsp2 = dfp2[x.value].values
        ysp2 = dfp2[y.value].values
        x_titlep2 = x.value.title()
        y_titlep2 = y.value.title()

        kwp2 = dict()
        if x.value in discrete:
            kwp2['x_range'] = sorted(set(xsp2))
        if y.value in discrete:
            kwp2['y_range'] = sorted(set(ysp2))
        kwp2['title'] = "%s vs %s" % (x_titlep2, y_titlep2) + " for {} on {} and {}".format(BotName, GBPUSD, TimeFrame)

        pp2 = figure(plot_height=400, plot_width=800, tools='pan,box_zoom,hover,reset,lasso_select', **kwp2)
        pp2.xaxis.axis_label = x_titlep2
        pp2.yaxis.axis_label = y_titlep2

        if x.value in discrete:
            pp2.xaxis.major_label_orientation = pd.np.pi / 4

        sz = 9
        if size.value != 'None':
            if len(set(dfp2[size.value])) > N_SIZES:
                groups = pd.qcut(dfp2[size.value].values, N_SIZES, duplicates='drop')
            else:
                groups = pd.Categorical(dfp2[size.value])
            sz = [SIZES[xx] for xx in groups.codes]

        c = "#31AADE"
        if color.value != 'None':
            if len(set(dfp2[color.value])) > N_COLORS:
                groups = pd.qcut(dfp2[color.value].values, N_COLORS, duplicates='drop')
            else:
                groups = pd.Categorical(dfp2[color.value])
            c = [COLORS[xx] for xx in groups.codes]

        # COLOR BAR NEXT TO GRAPHIC
        #PAIR 2
        try:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1['Profit']),high=max(dfp1['Profit']))  # arreglar Maximo y minimo para que agarren el valor
        except ValueError:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=0,high=1)
            print('This {} did not launch Phase {} on {}'.format(BotName,Phase,TimeFrame))
        # Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1[color.value]),high=max(dfp1[color.value]))  # arreglar Maximo y minimo para que agarren el valor
        GraphTicker = AdaptiveTicker(base=50, desired_num_ticks=10, num_minor_ticks=20, max_interval=1000)
        Color_legend = ColorBar(color_mapper=Var_color_mapper, ticker=GraphTicker, label_standoff=12,border_line_color=None,location=(0, 0))  # arreglar LogTicker para que muestre por al escala del color
        pp2.circle(x=xsp2, y=ysp2, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white',hover_alpha=0.5)
        pp2.add_layout(Color_legend, 'right')
        return pp2

    def create_figure3():
        xsp3 = dfp3[x.value].values
        ysp3 = dfp3[y.value].values
        x_titlep3 = x.value.title()
        y_titlep3 = y.value.title()

        kwp3 = dict()
        if x.value in discrete:
            kwp3['x_range'] = sorted(set(xsp3))
        if y.value in discrete:
            kwp3['y_range'] = sorted(set(ysp3))
        kwp3['title'] = "%s vs %s" % (x_titlep3, y_titlep3) + " for {} on {} and {}".format(BotName, USDCAD, TimeFrame)

        pp3 = figure(plot_height=400, plot_width=800, tools='pan,box_zoom,hover,reset,lasso_select', **kwp3)
        pp3.xaxis.axis_label = x_titlep3
        pp3.yaxis.axis_label = y_titlep3

        if x.value in discrete:
            pp3.xaxis.major_label_orientation = pd.np.pi / 4

        sz = 9
        if size.value != 'None':
            if len(set(dfp3[size.value])) > N_SIZES:
                groups = pd.qcut(dfp3[size.value].values, N_SIZES, duplicates='drop')
            else:
                groups = pd.Categorical(dfp3[size.value])
            sz = [SIZES[xx] for xx in groups.codes]

        c = "#31AADE"
        if color.value != 'None':
            if len(set(dfp3[color.value])) > N_COLORS:
                groups = pd.qcut(dfp3[color.value].values, N_COLORS, duplicates='drop')
            else:
                groups = pd.Categorical(dfp3[color.value])
            c = [COLORS[xx] for xx in groups.codes]

        # COLOR BAR NEXT TO GRAPHIC
        #PAIR 3
        try:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1['Profit']),high=max(dfp1['Profit']))  # arreglar Maximo y minimo para que agarren el valor
        except ValueError:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=0,high=1)
            print('This {} did not launch Phase {} on {}'.format(BotName,Phase,TimeFrame))
        # Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1[color.value]),high=max(dfp1[color.value]))  # arreglar Maximo y minimo para que agarren el valor
        GraphTicker = AdaptiveTicker(base=50, desired_num_ticks=10, num_minor_ticks=20, max_interval=1000)
        Color_legend = ColorBar(color_mapper=Var_color_mapper, ticker=GraphTicker, label_standoff=12,border_line_color=None,location=(0, 0))
        pp3.circle(x=xsp3, y=ysp3, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white',hover_alpha=0.5)
        pp3.add_layout(Color_legend, 'right')
        return pp3

    def create_figure4():
        xsp4 = dfp4[x.value].values
        ysp4 = dfp4[y.value].values
        x_titlep4 = x.value.title()
        y_titlep4 = y.value.title()

        kwp4 = dict()
        if x.value in discrete:
            kwp4['x_range'] = sorted(set(xsp4))
        if y.value in discrete:
            kwp4['y_range'] = sorted(set(ysp4))
        kwp4['title'] = "%s vs %s" % (x_titlep4, y_titlep4) + " for {} on {} and {}".format(BotName, USDCHF, TimeFrame)

        pp4 = figure(plot_height=400, plot_width=800, tools='pan,box_zoom,hover,reset,lasso_select', **kwp4)
        pp4.xaxis.axis_label = x_titlep4
        pp4.yaxis.axis_label = y_titlep4

        if x.value in discrete:
            pp4.xaxis.major_label_orientation = pd.np.pi / 4

        sz = 9
        if size.value != 'None':
            if len(set(dfp4[size.value])) > N_SIZES:
                groups = pd.qcut(dfp4[size.value].values, N_SIZES, duplicates='drop')
            else:
                groups = pd.Categorical(dfp4[size.value])
            sz = [SIZES[xx] for xx in groups.codes]

        c = "#31AADE"
        if color.value != 'None':
            if len(set(dfp4[color.value])) > N_COLORS:
                groups = pd.qcut(dfp4[color.value].values, N_COLORS, duplicates='drop')
            else:
                groups = pd.Categorical(dfp4[color.value])
            c = [COLORS[xx] for xx in groups.codes]

        # COLOR BAR NEXT TO GRAPHIC
        #PAIR 4
        try:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1['Profit']),high=max(dfp1['Profit']))  # arreglar Maximo y minimo para que agarren el valor
        except ValueError:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=0,high=1)
            print('This {} did not launch Phase {} on {}'.format(BotName,Phase,TimeFrame))
        # Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1[color.value]),high=max(dfp1[color.value]))  # arreglar Maximo y minimo para que agarren el valor
        GraphTicker = AdaptiveTicker(base=50, desired_num_ticks=10, num_minor_ticks=20, max_interval=1000)
        Color_legend = ColorBar(color_mapper=Var_color_mapper, ticker=GraphTicker, label_standoff=12,border_line_color=None,location=(0, 0))
        pp4.circle(x=xsp4, y=ysp4, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white',hover_alpha=0.5)
        pp4.add_layout(Color_legend, 'right')
        return pp4

    def create_figure5():
        xsp5 = dfp5[x.value].values
        ysp5 = dfp5[y.value].values
        x_titlep5 = x.value.title()
        y_titlep5 = y.value.title()

        kwp5 = dict()
        if x.value in discrete:
            kwp5['x_range'] = sorted(set(xsp5))
        if y.value in discrete:
            kwp5['y_range'] = sorted(set(ysp5))
        kwp5['title'] = "%s vs %s" % (x_titlep5, y_titlep5) + " for {} on {} and {}".format(BotName, USDJPY, TimeFrame)

        pp5 = figure(plot_height=500, plot_width=800, tools='pan,box_zoom,hover,reset,lasso_select', **kwp5)
        pp5.xaxis.axis_label = x_titlep5
        pp5.yaxis.axis_label = y_titlep5

        if x.value in discrete:
            pp5.xaxis.major_label_orientation = pd.np.pi / 4

        sz = 9
        if size.value != 'None':
            if len(set(dfp5[size.value])) > N_SIZES:
                groups = pd.qcut(dfp5[size.value].values, N_SIZES, duplicates='drop')
            else:
                groups = pd.Categorical(dfp5[size.value])
            sz = [SIZES[xx] for xx in groups.codes]

        c = "#31AADE"
        if color.value != 'None':
            if len(set(dfp5[color.value])) > N_COLORS:
                groups = pd.qcut(dfp5[color.value].values, N_COLORS, duplicates='drop')
            else:
                groups = pd.Categorical(dfp5[color.value])
            c = [COLORS[xx] for xx in groups.codes]

        # COLOR BAR NEXT TO GRAPHIC
        #PAIR 5
        try:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1['Profit']),high=max(dfp1['Profit']))  # arreglar Maximo y minimo para que agarren el valor
        except ValueError:
            Var_color_mapper = LinearColorMapper(palette="Inferno256",low=0,high=1)
            print('This {} did not launch Phase {} on {}'.format(BotName,Phase,TimeFrame))
        # Var_color_mapper = LinearColorMapper(palette="Inferno256",low=min(dfp1[color.value]),high=max(dfp1[color.value]))  # arreglar Maximo y minimo para que agarren el valor
        GraphTicker = AdaptiveTicker(base=50, desired_num_ticks=10, num_minor_ticks=20, max_interval=1000)
        Color_legend = ColorBar(color_mapper=Var_color_mapper, ticker=GraphTicker, label_standoff=12,border_line_color=None,location=(0, 0))
        pp5.circle(x=xsp5, y=ysp5, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white',hover_alpha=0.5)
        pp5.add_layout(Color_legend, 'right')
        return pp5

    def callback(attr, old, new):

        layout.children[1] = grid([create_figure1(), create_figure2(), create_figure3(),create_figure4(),create_figure5()], ncols=2)

        callback = CustomJS(code="console.log('tap event occurred')")

    #source = ColumnDataSource(data=dict(x=dfp1['Pass'], y=dfp1['Profit']))
    x = Select(title='X-Axis', value='Pass', options=columns)
    x.on_change('value', callback)

    y = Select(title='Y-Axis', value='Profit', options=columns)
    y.on_change('value', callback)

    size = Select(title='Size', value='None', options=['None'] + continuous)
    size.on_change('value', callback)

    color = Select(title='Color', value='None', options=['None'] + continuous)
    color.on_change('value', callback)

    controls = column(y, x, color, size, width=200)
    #layout = row(controls, create_figure1(),create_figure2(),create_figure3()) # ESTE FUNCIONA GUARDAR POR AHORA
    #layoutgrid = gridplot([controls,create_figure1(),create_figure2(),create_figure3()],toolbar_location='left',sizing_mode='stretch_both',ncols=2) # ESTO NO ACTUALIZA RESULTADOS A PESAR DE QUE SI LOS UBICA CORRECTAMENTE
    #layout = row(controls, layoutgrid)
    layoutgrid = grid([create_figure1(), create_figure2(), create_figure3(),create_figure4(),create_figure5()], ncols=2) #ESTE SI FUNCIONA PERO AL ACTUALIZAR RESULTADOS DEJA SOLO FIGURA 1
    layout = row(controls,layoutgrid)
    curdoc().add_root(layout)
    output_notebook()
    curdoc().title = "Phase {} All Pairs on {}".format(Phase, TimeFrame),

    process = subprocess.call(['bokeh serve --show BokehINTERACTIVEALLPAIRS.py','bokeh serve --show BokehINTERACTIVE.py'])
示例#31
0
def test_grid() -> None:
    s0 = Spacer()
    s1 = Spacer()
    s2 = Spacer()
    s3 = Spacer()
    s4 = Spacer()
    s5 = Spacer()
    s6 = Spacer()

    g0 = grid([])
    assert g0.children == []

    g1 = grid(column(s0, row(column(s1, s2, s3, s4, s5), s6)))
    assert g1.children == [
        (s0, 0, 0, 1, 2),
        (s1, 1, 0, 1, 1),
        (s2, 2, 0, 1, 1),
        (s3, 3, 0, 1, 1),
        (s4, 4, 0, 1, 1),
        (s5, 5, 0, 1, 1),
        (s6, 1, 1, 5, 1),
    ]

    g2 = grid([s0, [[s1, s2, s3, s4, s5], s6]])
    assert g2.children == [
        (s0, 0, 0, 1, 2),
        (s1, 1, 0, 1, 1),
        (s2, 2, 0, 1, 1),
        (s3, 3, 0, 1, 1),
        (s4, 4, 0, 1, 1),
        (s5, 5, 0, 1, 1),
        (s6, 1, 1, 5, 1),
    ]

    g3 = grid([s0, s1, s2, s3, s4, s5, s6], ncols=2)
    assert g3.children == [
        (s0, 0, 0, 1, 1),
        (s1, 0, 1, 1, 1),
        (s2, 1, 0, 1, 1),
        (s3, 1, 1, 1, 1),
        (s4, 2, 0, 1, 1),
        (s5, 2, 1, 1, 1),
        (s6, 3, 0, 1, 2),
    ]

    g4 = grid([s0, s1, s2, s3, s4, s5, s6, None], ncols=2)
    assert g4.children == [
        (s0, 0, 0, 1, 1),
        (s1, 0, 1, 1, 1),
        (s2, 1, 0, 1, 1),
        (s3, 1, 1, 1, 1),
        (s4, 2, 0, 1, 1),
        (s5, 2, 1, 1, 1),
        (s6, 3, 0, 1, 1),
    ]

    with pytest.raises(NotImplementedError):
        grid("""
        +----+----+----+----+
        | s1 | s2 | s3 |    |
        +---------+----+ s4 |
        |    s5   | s5 |    |
        +---------+----+----+
        """)
示例#32
0
    def __init__(
        self,
        ydeg,
        npix,
        npts,
        nmaps,
        throttle_time,
        nosmooth,
        gp,
        sample_function,
    ):
        # Settings
        self.ydeg = ydeg
        self.npix = npix
        self.npts = npts
        self.throttle_time = throttle_time
        self.nosmooth = nosmooth
        self.nmaps = nmaps
        self.gp = gp

        # Design matrices
        self.A_I = get_intensity_design_matrix(ydeg, npix)
        self.A_F = get_flux_design_matrix(ydeg, npts)

        def sample_ylm(r, mu_l, sigma_l, c, n):
            # Avoid issues at the boundaries
            if mu_l == 0:
                mu_l = 1e-2
            elif mu_l == 90:
                mu_l = 90 - 1e-2
            a, b = gauss2beta(mu_l, sigma_l)
            return sample_function(r, a, b, c, n)

        self.sample_ylm = sample_ylm

        # Draw three samples from the default distr
        self.ylm = self.sample_ylm(
            params["size"]["r"]["value"],
            params["latitude"]["mu"]["value"],
            params["latitude"]["sigma"]["value"],
            params["contrast"]["c"]["value"],
            params["contrast"]["n"]["value"],
        )[0]

        # Plot the GP ylm samples
        self.color_mapper = LinearColorMapper(palette="Plasma256",
                                              nan_color="white",
                                              low=0.5,
                                              high=1.2)
        self.moll_plot = [None for i in range(self.nmaps)]
        self.moll_source = [
            ColumnDataSource(data=dict(image=[
                1.0 +
                (self.A_I @ self.ylm[i]).reshape(self.npix, 2 * self.npix)
            ])) for i in range(self.nmaps)
        ]
        eps = 0.1
        epsp = 0.02
        xe = np.linspace(-2, 2, 300)
        ye = 0.5 * np.sqrt(4 - xe**2)
        for i in range(self.nmaps):
            self.moll_plot[i] = figure(
                plot_width=280,
                plot_height=130,
                toolbar_location=None,
                x_range=(-2 - eps, 2 + eps),
                y_range=(-1 - eps / 2, 1 + eps / 2),
            )
            self.moll_plot[i].axis.visible = False
            self.moll_plot[i].grid.visible = False
            self.moll_plot[i].outline_line_color = None
            self.moll_plot[i].image(
                image="image",
                x=-2,
                y=-1,
                dw=4 + epsp,
                dh=2 + epsp / 2,
                color_mapper=self.color_mapper,
                source=self.moll_source[i],
            )
            self.moll_plot[i].toolbar.active_drag = None
            self.moll_plot[i].toolbar.active_scroll = None
            self.moll_plot[i].toolbar.active_tap = None

        # Plot lat/lon grid
        lat_lines = get_latitude_lines()
        lon_lines = get_longitude_lines()
        for i in range(self.nmaps):
            for x, y in lat_lines:
                self.moll_plot[i].line(x,
                                       y,
                                       line_width=1,
                                       color="black",
                                       alpha=0.25)
            for x, y in lon_lines:
                self.moll_plot[i].line(x,
                                       y,
                                       line_width=1,
                                       color="black",
                                       alpha=0.25)
            self.moll_plot[i].line(xe,
                                   ye,
                                   line_width=3,
                                   color="black",
                                   alpha=1)
            self.moll_plot[i].line(xe,
                                   -ye,
                                   line_width=3,
                                   color="black",
                                   alpha=1)

        # Colorbar slider
        self.slider = RangeSlider(
            start=0,
            end=1.5,
            step=0.01,
            value=(0.5, 1.2),
            orientation="horizontal",
            show_value=False,
            css_classes=["colorbar-slider"],
            direction="ltr",
            title="cmap",
        )
        self.slider.on_change("value", self.slider_callback)

        # Buttons
        self.seed_button = Button(
            label="re-seed",
            button_type="default",
            css_classes=["seed-button"],
            sizing_mode="fixed",
            height=30,
            width=75,
        )
        self.seed_button.on_click(self.seed_callback)

        self.smooth_button = Toggle(
            label="smooth",
            button_type="default",
            css_classes=["smooth-button"],
            sizing_mode="fixed",
            height=30,
            width=75,
            active=False,
        )
        self.smooth_button.disabled = bool(self.nosmooth)
        self.smooth_button.on_click(self.smooth_callback)

        self.auto_button = Toggle(
            label="auto",
            button_type="default",
            css_classes=["auto-button"],
            sizing_mode="fixed",
            height=30,
            width=75,
            active=True,
        )

        self.reset_button = Button(
            label="reset",
            button_type="default",
            css_classes=["reset-button"],
            sizing_mode="fixed",
            height=30,
            width=75,
        )
        self.reset_button.on_click(self.reset_callback)

        # Light curve samples
        self.flux_plot = [None for i in range(self.nmaps)]
        self.flux_source = [
            ColumnDataSource(data=dict(
                xs=[np.linspace(0, 2, npts) for j in range(6)],
                ys=[fluxnorm(self.A_F[j] @ self.ylm[i]) for j in range(6)],
                color=[Plasma6[5 - j] for j in range(6)],
                inc=[15, 30, 45, 60, 75, 90],
            )) for i in range(self.nmaps)
        ]
        for i in range(self.nmaps):
            self.flux_plot[i] = figure(
                toolbar_location=None,
                x_range=(0, 2),
                y_range=None,
                min_border_left=50,
                plot_height=400,
            )
            if i == 0:
                self.flux_plot[i].yaxis.axis_label = "flux [ppt]"
                self.flux_plot[i].yaxis.axis_label_text_font_style = "normal"
            self.flux_plot[i].xaxis.axis_label = "rotational phase"
            self.flux_plot[i].xaxis.axis_label_text_font_style = "normal"
            self.flux_plot[i].outline_line_color = None
            self.flux_plot[i].multi_line(
                xs="xs",
                ys="ys",
                line_color="color",
                source=self.flux_source[i],
            )
            self.flux_plot[i].toolbar.active_drag = None
            self.flux_plot[i].toolbar.active_scroll = None
            self.flux_plot[i].toolbar.active_tap = None
            self.flux_plot[i].yaxis.major_label_orientation = np.pi / 4
            self.flux_plot[i].xaxis.axis_label_text_font_size = "8pt"
            self.flux_plot[i].xaxis.major_label_text_font_size = "8pt"
            self.flux_plot[i].yaxis.axis_label_text_font_size = "8pt"
            self.flux_plot[i].yaxis.major_label_text_font_size = "8pt"

        # Javascript callback to update light curves & images
        self.A_F_source = ColumnDataSource(data=dict(A_F=self.A_F))
        self.A_I_source = ColumnDataSource(data=dict(A_I=self.A_I))
        self.ylm_source = ColumnDataSource(data=dict(ylm=self.ylm))
        callback = CustomJS(
            args=dict(
                A_F_source=self.A_F_source,
                A_I_source=self.A_I_source,
                ylm_source=self.ylm_source,
                flux_source=self.flux_source,
                moll_source=self.moll_source,
            ),
            code="""
            var A_F = A_F_source.data['A_F'];
            var A_I = A_I_source.data['A_I'];
            var ylm = ylm_source.data['ylm'];
            var i, j, k, l, m, n;
            for (n = 0; n < {nmax}; n++) {{

                // Update the light curves
                var flux = flux_source[n].data['ys'];
                for (l = 0; l < {lmax}; l++) {{
                    for (m = 0; m < {mmax}; m++) {{
                        flux[l][m] = 0.0;
                        for (k = 0; k < {kmax}; k++) {{
                            flux[l][m] += A_F[{kmax} * ({mmax} * l + m) + k] * ylm[{kmax} * n + k];
                        }}
                    }}
                    // Normalize
                    var mean = flux[l].reduce((previous, current) => current += previous) / {mmax};
                    for (m = 0; m < {mmax}; m++) {{
                        flux[l][m] = 1e3 * ((1 + flux[l][m]) / (1 + mean) - 1)
                    }}
                }}
                flux_source[n].change.emit();

                // Update the images
                var image = moll_source[n].data['image'][0];
                for (i = 0; i < {imax}; i++) {{
                    for (j = 0; j < {jmax}; j++) {{
                        image[{jmax} * i + j] = 1.0;
                        for (k = 0; k < {kmax}; k++) {{
                            image[{jmax} * i + j] += A_I[{kmax} * ({jmax} * i + j) + k] * ylm[{kmax} * n + k];
                        }}
                    }}
                }}
                moll_source[n].change.emit();

            }}
            """.format(
                imax=self.npix,
                jmax=2 * self.npix,
                kmax=(self.ydeg + 1)**2,
                nmax=self.nmaps,
                lmax=self.A_F.shape[0],
                mmax=self.npts,
            ),
        )
        self.js_dummy = self.flux_plot[0].circle(x=0, y=0, size=1, alpha=0)
        self.js_dummy.glyph.js_on_change("size", callback)

        # Full layout
        self.plots = row(
            *[
                column(m, f, sizing_mode="scale_both")
                for m, f in zip(self.moll_plot, self.flux_plot)
            ],
            margin=(10, 30, 10, 30),
            sizing_mode="scale_both",
            css_classes=["samples"],
        )
        self.layout = grid([[self.plots]])
示例#33
0
refresh_button_2.on_click(refresh_file_list)

run_cases_section = column(run_cases_div, run_cases_select_div,
                           run_cases_select,
                           row(run_cases_button,
                               refresh_button_2), run_cases_output)

###############################################################################
"""
Specify site layout
"""
###############################################################################

# Define layouts
layout_settings = grid(
    [[header_div], [sites_section], [path_input_section], [dates_section],
     [clm_settings_section], [fates_settings_section], [create_file_section]],
    sizing_mode=None)

layout_running = grid(
    [[run_header_div], [make_cases_section], [run_cases_section]],
    sizing_mode=None)

# Define tabs
tab_1 = Panel(child=layout_settings, title="Create settings")
tab_2 = Panel(child=layout_running, title="Build/run cases")

page_tabs = Tabs(tabs=[tab_1, tab_2])

# add the layout to curdoc
curdoc().add_root(page_tabs)
示例#34
0
    def __init__(
        self,
        params,
        gp_callback,
        limits=(-90, 90),
        xticks=[-90, -60, -30, 0, 30, 60, 90],
        funcs=[],
        labels=[],
        xlabel="",
        ylabel="",
        distribution=False,
        legend_location="bottom_right",
        npts=300,
    ):
        # Store
        self.params = params
        self.limits = limits
        self.funcs = funcs
        self.gp_callback = gp_callback
        self.last_run = 0.0
        self.throttle_time = 0.0
        self.distribution = distribution

        # Arrays
        if len(self.funcs):
            xmin, xmax = self.limits
            xs = [np.linspace(xmin, xmax, npts) for f in self.funcs]
            ys = [
                f(x, *[self.params[p]["value"] for p in self.params.keys()])
                for x, f in zip(xs, self.funcs)
            ]
            colors = Category10[10][:len(xs)]
            lws = np.append([3], np.ones(10))[:len(xs)]
            self.source = ColumnDataSource(
                data=dict(xs=xs, ys=ys, colors=colors, lws=lws))

            # Plot them
            dx = (xmax - xmin) * 0.01
            self.plot = figure(
                plot_width=400,
                plot_height=600,
                toolbar_location=None,
                x_range=(xmin - dx, xmax + dx),
                title=xlabel,
                sizing_mode="stretch_both",
            )
            self.plot.title.align = "center"
            self.plot.title.text_font_size = "14pt"
            self.plot.multi_line(
                xs="xs",
                ys="ys",
                line_color="colors",
                source=self.source,
                line_width="lws",
                line_alpha=0.6,
            )
            self.plot.xaxis.axis_label_text_font_style = "normal"
            self.plot.xaxis.axis_label_text_font_size = "12pt"
            self.plot.xaxis.ticker = FixedTicker(ticks=xticks)
            self.plot.yaxis[0].formatter = FuncTickFormatter(
                code="return '  ';")
            self.plot.yaxis.axis_label = ylabel
            self.plot.yaxis.axis_label_text_font_style = "normal"
            self.plot.yaxis.axis_label_text_font_size = "12pt"
            self.plot.outline_line_width = 1
            self.plot.outline_line_alpha = 1
            self.plot.outline_line_color = "black"
            self.plot.toolbar.active_drag = None
            self.plot.toolbar.active_scroll = None
            self.plot.toolbar.active_tap = None

            # Legend
            for j, label in enumerate(labels):
                self.plot.line(
                    [0, 0],
                    [0, 0],
                    legend_label=label,
                    line_color=Category10[10][j],
                )
            self.plot.legend.location = legend_location
            self.plot.legend.title_text_font_style = "bold"
            self.plot.legend.title_text_font_size = "8pt"
            self.plot.legend.label_text_font_size = "8pt"
            self.plot.legend.spacing = 0
            self.plot.legend.label_height = 5
            self.plot.legend.glyph_height = 15

        else:

            self.plot = None

        # Sliders
        self.sliders = []
        for p in self.params.keys():
            slider = Slider(
                start=self.params[p]["start"],
                end=self.params[p]["stop"],
                step=self.params[p]["step"],
                value=self.params[p]["value"],
                orientation="horizontal",
                format="0.3f",
                css_classes=["custom-slider"],
                sizing_mode="stretch_width",
                height=10,
                show_value=False,
                title=self.params[p]["label"],
            )
            slider.on_change("value_throttled", self.callback)
            slider.on_change("value", self.callback_throttled)
            self.sliders.append(slider)

        # HACK: Add a hidden slider to get the correct
        # amount of padding below the graph
        if len(self.params.keys()) < 2:
            slider = Slider(
                start=0,
                end=1,
                step=0.1,
                value=0.5,
                orientation="horizontal",
                css_classes=["custom-slider", "hidden-slider"],
                sizing_mode="stretch_width",
                height=10,
                show_value=False,
                title="s",
            )
            self.hidden_sliders = [slider]
        else:
            self.hidden_sliders = []

        # Show mean and std. dev.?
        if self.distribution:
            self.mean_vline = Span(
                location=self.sliders[0].value,
                dimension="height",
                line_color="black",
                line_width=1,
                line_dash="dashed",
            )
            self.std_vline1 = Span(
                location=self.sliders[0].value - self.sliders[1].value,
                dimension="height",
                line_color="black",
                line_width=1,
                line_dash="dotted",
            )
            self.std_vline2 = Span(
                location=self.sliders[0].value + self.sliders[1].value,
                dimension="height",
                line_color="black",
                line_width=1,
                line_dash="dotted",
            )
            self.plot.renderers.extend(
                [self.mean_vline, self.std_vline1, self.std_vline2])

        # Full layout
        if self.plot is not None:
            self.layout = grid([
                [self.plot],
                [
                    column(
                        *self.sliders,
                        *self.hidden_sliders,
                        sizing_mode="stretch_width",
                    )
                ],
            ])
        else:
            self.layout = grid([[
                column(
                    *self.sliders,
                    *self.hidden_sliders,
                    sizing_mode="stretch_width",
                )
            ]])