Beispiel #1
0
def test():
    p = figure(x_range=(-20, 20), y_range=(-20, 20), toolbar_location=None, webgl=False, plot_width=750, plot_height=750)
    p.border_fill_color = '#eeeeee'
    p.background_fill_color = 'white'
    p.outline_line_color = None
    p.grid.grid_line_color = None

    session = push_session(curdoc())
    curdoc().add_root(p)
    session.show()

    car = Car([1.0, 2.0], angle_to_vector(math.pi/2), wheels_angle=0.4, speed=1.0, width=1.0, length=2.0, fig=p, nrays=36)
    border = geom.Figure([[-10.0, -10.0], [-10.0, 10.0], [10.0, 10.0], [10.0, -10.0]],
            close=True, fig=p)
    obstacle = geom.Figure([[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]],
            close=True, fig=p)
    #obstacle = geom.Figure(close=True, fig=p)
    #print border.points
    #obstacle.set_points([[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]])
    env = geom.CompoundFigure([border, obstacle])
    env.draw()
    for i in xrange(10000):
        car.turn_wheels(random.random() - 0.5)
        car.save_pos()
        car.move(0.1)
        if car.path().intersect(env) != None:
            car.restore_pos()
            car.speed = -car.speed
        car.draw(env)
        time.sleep(0.01)
Beispiel #2
0
 def test_model_in_empty_document_context_manager_is_used(self):
     m = mock.MagicMock(name='_ModelInEmptyDocument')
     plot1 = figure()
     curdoc().add_root(plot1)
     with mock.patch('bokeh.embed._ModelInEmptyDocument', m):
         embed.notebook_div(plot1)
     m.assert_called_once_with(plot1)
Beispiel #3
0
def main(options, args):
    
    logger = log.get_logger("ginga", options=options)

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0,600], y_range=[0,600], plot_width=600, plot_height=600,
                 toolbar_location=None)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    def load_file(path):
        image = AstroImage(logger)
        image.load_file(path)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    # add a entry widget and configure with the call back
    dstdir = options.indir
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    if len(args) > 0:
        load_file(args[0])

    # put the path widget and viewer in a layout and add to the document
    curdoc().add_root(vplot(fig, path_w))
Beispiel #4
0
 def input_change(self, obj, attrname, old, new):
     if obj == self.ticker4_2_select:
         self.ticker4_2 = new
     if obj == self.ticker4_1_select:
         self.ticker4_1 = new
     if obj == self.ticker4_select:
         self.ticker4 = new
     if obj == self.ticker3_2_select:
         self.ticker3_2 = new
     if obj == self.ticker3_1_select:
         self.ticker3_1 = new
     if obj == self.ticker3_select:
         self.ticker3 = new
     if obj == self.ticker2p_select:
         self.ticker2p = new
     if obj == self.ticker2_select:
         self.ticker2 = new
     if obj == self.ticker1p_select:
         self.ticker1p = new
     if obj == self.ticker1_select:
         self.ticker1 = new
     if obj == self.button_select:
         self.button = new 
         if 'run' in self.button:
             self.make_source()
             self.make_plots()
             self.set_children()
             curdoc().add(self)
Beispiel #5
0
    def change_symbol(self, obj,attrname, old, new):
        self.selected_symbol = new
        Dashboard.recreate_all(self)

        if symbols_filtered:
            self.source_stocks_rank.data = symbols_filtered
        curdoc().add(self)
Beispiel #6
0
def render_plot():
    build_plot()
    session = push_session(curdoc())
    curdoc().add_periodic_callback(callback, 60000)
    session.show() # open the document in a browser
    session.loop_until_closed() # run forever
    return ""
Beispiel #7
0
 def set_plot(self):
     # print ("set_plot")
     """Makes and sets the plot based on the current configuration of app."""
     self.update_xy_ranges(source=self.df)
     plot = self.make_plot()
     self.plot = plot
     curdoc()._add_all()
Beispiel #8
0
    def exec_filter_symbol(self, obj,attrname, old, new):
        Dashboard.recreate_all(self)

        dat = Dashboard._pre_filtered_ranks[new]
        self.source_stocks_rank.data = dat
        self.symbol_filter.value = new
        curdoc().add(self)
Beispiel #9
0
def notebook_plot(x_key, y_key, **kwargs):
    r"""Live plot log entries in the current notebook.

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

    """
    subscriber, sequence, x, y = connect(x_key, y_key, **kwargs)
    session = push_session(curdoc())
    output_notebook()

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

    show(fig)

    def notebook_update():
        update(x_key, y_key, sequence, subscriber, plot)
        push_notebook()

    curdoc().add_periodic_callback(notebook_update, 50)

    session.loop_until_closed()
Beispiel #10
0
 def brand_change(self, obj, attrname, old, new):
     bdf = self.brand_df
     if self.selectr.value is None or self.selectr.value == 'Most Popular Brands':
         return
     self.update_selected_on_source(self.selectr.value)
     self.set_children()
     curdoc().add(self)
Beispiel #11
0
def render_table(sym):
    df = get_data(sym)

    text_input = TextInput(value=sym.upper(), title="Label:")
    mids = (df['open'] + df['close'])/2
    spans = abs(df['open'] - df['close'])
    inc = df['close'] > df['open']
    dec = df['close'] < df['open']
    w = 12*60*60*1000 # half day in ms

    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

    global p
    p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=750, plot_height=300, toolbar_location="left")

    p.title = sym.upper() + " Candlestick"
    p.xaxis.major_label_orientation = pi/4
    p.grid.grid_line_alpha=0.3

    p.segment(df.date, df.high, df.date, df.low, color="black")
    p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black")
    p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black")

    session = push_session(curdoc())

    curdoc().add_periodic_callback(update, 1000)

    session.show() # open the document in a browser

    session.loop_until_closed() # run forever
    output_file("candlestick.html", title="candlestick.py example")
Beispiel #12
0
    def on_slider_change(self, obj, attrname, old, new):
        if obj == self.min_excitation:
            self.min_excitation.value = new
            if self.min_excitation.value > self.max_excitation.value:
                self.min_excitation.value = old

        if obj == self.max_excitation:
            self.max_excitation.value = new
            if self.max_excitation.value < self.min_excitation.value:
                self.max_excitation.value = old

        if obj == self.min_emission:
            self.min_emission.value = new
            if self.min_emission.value > self.max_emission.value:
                self.min_emission.value = old

        if obj == self.max_emission:
            self.max_emission.value = new
            if self.max_emission.value < self.min_emission.value:
                self.max_emission.value = old

        self.set_sliders()
        self.make_source()
        self.set_children()
        curdoc().add(self)
Beispiel #13
0
 def inst_date_change(self, obj, attrname, old, new):
     logging.debug('Date change!')
     self.inst_date = new
     self.make_source()
     self.make_plots()
     self.set_children()
     curdoc().add(self)
Beispiel #14
0
 def star_change(self, obj, attrname, old, new):
     logging.debug('Star change!')
     self.star = new
     self.make_inst_date_input()
     self.make_source()
     self.make_plots()
     self.set_children()
     curdoc().add(self)
Beispiel #15
0
    def par_change(self, obj, attrname, old, new):
        # Update plots
        self.mainplot, highest = self.plot_Trun()
        name, T = highest.sort('ccf_max', ascending=False)[['name', 'T']].values[0]
        self.ccf_plot = self.plot_ccf(name, T)

        self.set_children()
        curdoc().add(self)
Beispiel #16
0
def button_group_click(new):
    global play
    if new == 0: # play
        play = True
        curdoc().add_periodic_callback(update, interval)
    else:
        play = False
        curdoc().remove_periodic_callback(update)
Beispiel #17
0
    def Trun_change(self, obj, attrname, old, new):

        idx = int(new['1d']['indices'][0])
        T = self.current_source.data['T'][idx]
        name = self.current_source.data['name'][idx]
        logging.debug('T = {}\nName = {}\n'.format(T, name))
        self.ccf_plot = self.plot_ccf(name, T)
        self.set_children()
        curdoc().add(self)
Beispiel #18
0
 def input_change(self, obj, attrname, old, new):
     if obj == self.ticker2_select:
         self.ticker2 = new
     if obj == self.ticker1_select:
         self.ticker1 = new
     self.make_source()
     self.make_plots()
     self.set_children()
     curdoc().add(self)
Beispiel #19
0
 def reschedule_redraw(self, time_sec):
     doc = curdoc()
     try:
         doc.remove_timeout_callback(self._defer_timer)
     except Exception:
         pass
     msec = int(time_sec * 1000.0)
     self._defer_timer = curdoc().add_timeout_callback(self.timer_cb,
                                                       msec)
def toggle_handler(active):
    if active:
        toggle.label = 'Stop'
        checkbox_group.disabled = True
        #t3.data_source.data["text"] = ['Running']
        curdoc().add_periodic_callback(update, periodic_callback_time_ms)
    else:
        toggle.label = 'Start'
        checkbox_group.disabled = False
        #t3.data_source.data["text"] = ['Stopped']
        curdoc().remove_periodic_callback(update)
Beispiel #21
0
 def selection_change(self, obj, attrname, old, new):
     #self.make_brand_plot
     #self.set_children()
     #curdoc().add(self)
     bdf = self.brand_df
     min_idx, max_idx = shoes_func.min_max_range(ranges, bdf['price'])
     self.configure_brand_source(min_idx, max_idx)
     self.make_brand_source()
     self.make_brand_plot(min_idx, max_idx)
     self.set_children()
     curdoc().add(self)
 def wrapper(*args, **kwargs):
     docname = prefix + str(uuid.uuid4())
     output_server(docname, url=url)
     curdoc().autoadd(False)
     app = func(*args, **kwargs)
     curdoc()._plotcontext.children = [app]
     curdoc().add_all()
     changed = push()
     logger.debug("stored: %s", str(changed))
     app.docname = docname
     return app
def toggle_handler(active):
    #t3.data_source.data["text"] = ['State = {}'.format(toggle.active)]
    if active:
        toggle.label = 'Stop'
        #toggle.type = 'danger'
        t3.data_source.data["text"] = ['Running']
        curdoc().add_periodic_callback(update, periodic_callback_time_ms)
    else:
        toggle.label = 'Start'
        #toggle.type = 'success'
        t3.data_source.data["text"] = ['Stopped']
        curdoc().remove_periodic_callback(update)
Beispiel #24
0
    def input_change(self, obj, attrname, old, new):
        self.make_source()
        self.make_county_source()
        print "source len: ", len(self.source.data['state'])
        print "county len: ", len(self.county_source.data['names'])
        if self.selectr.value is None or self.selectr.value == 'Choose A State':
            pass
        else:
            self.plot.title = self.selectr.value
        self.populate_glyphs()

        self.set_children()
        curdoc().add(self)
    def input_change(self, obj, attrname, old, new):
        """Executes whenever the input form changes.

        It is responsible for updating the plot, or anything else you want.

        Args:
            obj : the object that changed
            attrname : the attr that changed
            old : old value of attr
            new : new value of attr
        """
        self.update_data()
        self.make_plot()
        curdoc().add(self)
Beispiel #26
0
    def onscreen_message(self, text, delay=None):
        doc = curdoc()
        try:
            doc.remove_timeout_callback(self._msg_timer)
        except Exception:
            pass

        if text is not None:
            self.set_onscreen_message(text)

        msec = int(delay * 1000.0)
        if delay:
            self._msg_timer = curdoc().add_timeout_callback(
                self.onscreen_message_off, msec)
Beispiel #27
0
 def bokeh_local(self):
     p = figure()
     x, y = read_log()
     # print x, y
     self.r = p.line(x, y, color='navy', line_width=3)
     session = push_session(curdoc())
     session.show()
def main():
    session = push_session(curdoc(), session_id='labeler')
    document = session.document
    print document
    do_step(document)
    session.show()
    session.loop_until_closed()
Beispiel #29
0
    def test_replot_remove(self):
        self.assertIsNotNone(self.bokeh_server, "Server failed to start, cannot tests")
        ar_downsample._loadAR()
        output_server("Census")
        source = ServerDataSource(data_url="fn://bivariate", owner_username="******")
        plot = square('A', 'B', source=source)
        ar_downsample.replot(plot, remove_original=False)

        self.assertTrue(plot in curdoc().context.children, "Not retained")
        ar_downsample.replot(plot, remove_original=True)
        self.assertTrue(plot not in curdoc().context.children, "Not removed")

        try:
            ar_downsample.replot(plot, remove_original=True)
        except:
            self.assertTrue(False, "Error reploting plot not in curdoc")
Beispiel #30
0
    def check_change(self, obj, attrname, old, new):
        #Turn on/off the counties/hotel data
        print "what the heck ", obj, attrname, old, new
        if 0 in new:
            self._show_counties = True
        else:
            self._show_counties = False

        if 1 in new:
            self._show_hotels = True
        else:
            self._show_hotels = False

        self.populate_glyphs()
        self.set_children()
        curdoc().add(self)
Beispiel #31
0
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc, vplot

menu = [("Quaterly", "Quarterly"), ("Half Yearly", "Half Yearly"), None,
        ("Yearly", "Yearly")]
dropdown = Dropdown(label="Time Period", button_type="warning", menu=menu)


def function_to_call(attr, old, new):
    print dropdown.value


dropdown.on_change('value', function_to_call)

curdoc().add_root(dropdown)
Beispiel #32
0
    def __init__(self,
                 bokeh_doc_name,
                 monitor_channels=None,
                 open_browser=False,
                 server_url='http://localhost:5006/',
                 colors=colors):
        """
        Initialize a Bokeh plot!

        Parameters
        ----------
        bokeh_doc_name : str
            The name of the Bokeh document. Use a different name for each
            experiment if you are storing your plots.
        monitor_channels : list(MonitorsChannel or Monitor)
            The monitor channels and monitors that you want to plot. The
            monitors within a :class:`MonitorsChannel` will be plotted together in a single
            figure.
        open_browser : bool, optional
            Whether to try and open the plotting server in a browser window.
            Defaults to ``True``. Should probably be set to ``False`` when
            running experiments non-locally (e.g. on a cluster or through SSH).
        server_url : str, optional
            Url of the bokeh server. Ex: when starting the bokeh server with
            ``bokeh serve --ip 0.0.0.0`` at ``alice``, server_url should be
            ``http://alice:5006``. When not specified the default configured
            to ``http://localhost:5006/``.
        colors : list(str)
            The list of string hex codes for colors to cycle through when creating new lines on the same figure.
        """
        # Make sure Bokeh is available
        if BOKEH_AVAILABLE:
            monitor_channels = raise_to_list(monitor_channels)
            if monitor_channels is None:
                monitor_channels = []

            self.channels = monitor_channels
            self.colors = colors
            self.bokeh_doc_name = bokeh_doc_name
            self.server_url = server_url

            session = push_session(curdoc(),
                                   session_id=self.bokeh_doc_name,
                                   url=self.server_url)

            # Create figures for each group of channels
            self.data_sources = {}
            self.figures = []
            self.figure_indices = {}
            self.line_color_idx = 0

            for i, channel in enumerate(self.channels):
                idx = i
                assert isinstance(channel, MonitorsChannel) or isinstance(channel, Monitor), \
                    "Need channels to be type MonitorsChannel or Monitor. Found %s" % str(type(channel))

                # create the figure for this channel
                fig = figure(title='{} #{}'.format(bokeh_doc_name,
                                                   channel.name),
                             x_axis_label='epochs',
                             y_axis_label='value',
                             logo=None,
                             toolbar_location='right')
                # keep track of the line colors so we can rotate them around in the same manner across figures
                self.line_color_idx = 0

                # for each monitor in this channel, create the line (and train/valid/test variants if applicable)
                # If this is a MonitorsChannel of multiple Monitors to plot
                if isinstance(channel, MonitorsChannel):
                    for monitor in channel.monitors:
                        if monitor.train_flag:
                            name = COLLAPSE_SEPARATOR.join(
                                [channel.name, monitor.name, TRAIN_MARKER])
                            self._create_line(fig, name)

                        if monitor.valid_flag:
                            name = COLLAPSE_SEPARATOR.join(
                                [channel.name, monitor.name, VALID_MARKER])
                            self._create_line(fig, name)

                        if monitor.test_flag:
                            name = COLLAPSE_SEPARATOR.join(
                                [channel.name, monitor.name, TEST_MARKER])
                            self._create_line(fig, name)

                # otherwise it is a single Monitor
                else:
                    if channel.train_flag:
                        name = COLLAPSE_SEPARATOR.join(
                            [channel.name, TRAIN_MARKER])
                        self._create_line(fig, name)

                    if channel.valid_flag:
                        name = COLLAPSE_SEPARATOR.join(
                            [channel.name, VALID_MARKER])
                        self._create_line(fig, name)

                    if channel.test_flag:
                        name = COLLAPSE_SEPARATOR.join(
                            [channel.name, TEST_MARKER])
                        self._create_line(fig, name)

            if open_browser:
                session.show()
Beispiel #33
0
                            if (cb_obj.active.includes(12)){jline.visible = true;} 
                                // 1 index box is bline
                            if (cb_obj.active.includes(13)){kline.visible = true;} 
                             if (cb_obj.active.includes(14)){kkline.visible = true;} 
                                // 1 index box is bline
                            """,
                    args={
                        'aline': aline,
                        'bline': bline,
                        'cline': cline,
                        'ccline': ccline,
                        'dline': dline,
                        'ddline': ddline,
                        'eline': eline,
                        'fline': fline,
                        'gline': gline,
                        'ggline': ggline,
                        'hline': hline,
                        'iline': iline,
                        'jline': jline,
                        'kline': kline,
                        'kkline': kkline
                    })
checkboxes.js_on_click(callback)
layout = row(p1, checkboxes)
# output_file('BV2_DUT_sensors_134_sections.html')
# show(column(p1, p2, checkboxes))
curdoc().add_root(layout)
curdoc().title = "BV2"

show(layout)
Beispiel #34
0
        elif Gender == 'All':
            df = df
        if Race != 'All':
            df = df[df['RaceID'] == Race]
        elif Race == 'All':
            df = df
        df = df[df['Split'] == split]
        time = []
        for value in df['Duration']:
            if "-1 day" in value:
                value = "00:00:00"
            time.append(get_sec(value))
        avg = sum(time) / len(time)
        avges.append(avg)
    newdf = pd.DataFrame({'splits': Splits, 'AvgDuration': avges})
    newdf['AvgDuration'] = pd.to_datetime(newdf["AvgDuration"],
                                          unit='s').dt.time
    print(newdf)
    plot.data_source.data['x'] = newdf.splits
    plot.data_source.data['y'] = newdf.AvgDuration


Racetypes = Initialdf["RaceID"].unique().tolist()
Genders = ['All', 'M', 'F']
RaceSelect = Select(title="Select Race:", options=Racetypes)
GenderSelect = Select(title="Select Name:", options=Genders)
GenderSelect.on_change('value', update)
RaceSelect.on_change('value', update)
controls = column(GenderSelect, RaceSelect)
curdoc().add_root(row(p, controls))
Beispiel #35
0
from bokeh.models.tools import HoverTool, CrosshairTool, CustomAction
from bokeh.plotting import figure, curdoc
from bokeh.models.widgets import CheckboxGroup, RadioGroup, DataTable, TableColumn, Panel, Tabs
from bokeh.themes import Theme, built_in_themes
#
from itsdangerous import TimestampSigner
# from itsdangerous import BadSignature, SignatureExpired

import sys

sys.path.append("fontawesome")
from fontawesome.fontawesome_icon import FontAwesomeIcon

from nc_transform import get_plottable_variables, get_nc_data, get_tsp_data_dict

curdoc_element = curdoc()
args = curdoc_element.session_context.request.arguments

if not Path(os.environ['TSPLOT_DOWNLOAD']).exists():
    Path(os.environ['TSPLOT_DOWNLOAD']).mkdir(parents=True, exist_ok=True)


def get_variables(resource_url):
    plottable_variables = get_plottable_variables(resource_url)
    return plottable_variables


class metadict(dict):
    pass

Beispiel #36
0
date = DatePicker(value=str(D_MAX), min_date=str(D_MIN), max_date=str(D_MAX))
date.on_change("value", update_date)

reload_str = f"Dataset last loaded <i>{datetime.now().strftime('%Y-%m-%d %H:%M')}</i>"
last_refresh = Div(text=reload_str)

reload_btn = Button(label="Reload Counter", button_type="primary")
reload_btn.on_click(reload_counter)
_iframe = Div(text=IFRAME)
INFO_TEXT = f"""Dataset file: <pre>{DATASET}</pre>"""
#     <br>Remote file: <pre>{REMOTE_DATASET}</pre>
#     <br>Hashes: <pre>{HASH}<br>{REMOTE_HASH}</pre>
#     <br>If the hashes do not match the dataset has been updated on GitHub"""
dataset_info = Div(text=INFO_TEXT)

extras = row(column(_iframe), column(dataset_info), column(reload_btn))

drops = row(gyms, date, last_refresh)
plots = row(plot_line(), plot_heat())
plot2 = row(plot_week_line())

tabs = Tabs(tabs=[
    Panel(child=column(drops, plots, plot2), title="Historic Data"),
    Panel(child=extras, title="Extras"),
])

l = row(tabs)
curdoc().add_root(l)
curdoc().title = "Depot Climbing Gym Dashboard"
curdoc().add_periodic_callback(update, 300000)  # 5 minute update
Beispiel #37
0
    def update(attr, old, new):

        button.update(button_type='warning', label='Loading, please wait')

        def calculate():
            global home_to_plot, state_dict

            data_selector = data_type_selector.labels[
                data_type_selector.active]

            if data_selector == 'Net Load':
                data_to_plot = 'grid'
                plot1.yaxis.axis_label = 'Net Load [kWh]'

            if data_selector == 'Load + Battery(Charging)':
                data_to_plot = 'Load_+_Battery(Charging)'
                plot1.yaxis.axis_label = 'Load [kWh]'

            if data_selector == "Electric Vehicle Consumption":
                data_to_plot = 'car1'
                plot1.yaxis.axis_label = 'Consumption [kWh]'

            if data_selector == "PV Generation + Battery(Discharge)":
                data_to_plot = 'PV_+_Battery(Discharge)'
                plot1.yaxis.axis_label = 'Generation [kWh]'

            trainDays_to_plot = int(trainDays_input.value)

            new_home_to_plot = state_dict[community_selector.active]

            #new_home_to_plot = int(home_id_selector.value) ###

            plot1.title.text = f'{data_selector} forecasting of {new_home_to_plot} for date {date_slider.value}'

            if new_home_to_plot != home_to_plot:
                startDate = filterData[
                    filterData['state'] ==
                    new_home_to_plot]['time'].iloc[0].date()  ##change
                endDate = filterData[filterData['state'] ==
                                     new_home_to_plot]['time'].iloc[-1].date()
                middle = startDate + (endDate - startDate) / 1.5

                date_slider.start = startDate
                date_slider.end = endDate
                date_slider.value = middle
                date_to_plot = str(middle)

                print(startDate, endDate, middle)

            #daterange_raw = list(date_slider.value_as_datetime)
            #daterange_to_plot = [daterange_raw[0].strftime("%Y-%m-%d"), daterange_raw[1].strftime("%Y-%m-%d")]

            date_to_plot = date_slider.value

            new_src1, new_mape1 = arima(date=date_to_plot,
                                        state=new_home_to_plot,
                                        data=data_to_plot,
                                        trainDays=trainDays_to_plot)
            src1.data.update(new_src1.data)

            plot1.legend.title = f'Abs Error = {round(new_mape1,3)}%'

            button.update(button_type='success', label='Done')

            home_to_plot = new_home_to_plot

        curdoc().add_next_tick_callback(calculate)
Beispiel #38
0
    #             flag = 0
    #             break
    #         else:
    #             flag = 1
    #     if flag == 1:
    #         stopState[node.index] = 1
    #     elif flag == 0:
    #         stopState[node.index] = 0
    # if count > len(currentState)*100:
    #     infiniteFlag = True
    #     break
    
    new_data = dict()
    new_data['x'] = [i for i in range(len(currentState))]
    new_data['y'] = currentState
    ds.data = new_data
    
#for i in graphList:
# print(i.index, i.weight , i.adjVec, i.adjNum, i.weightPerNumPlusOne)
#print(currentState)

# for i,choose in enumerate(currentState):
#     if choose == 1:
#         MWIS.append(i)
#         totalWeight += graphList[i].weight
# print(MWIS)
# print(totalWeight)


curdoc().add_periodic_callback(compute, 500)
curdoc().add_root(p)
Beispiel #39
0
	def showGui(self):
		output_file(os.path.join("webpages","multiSignalSplicer.html"))

		logger.logData(source="Master splicer",priority="INFO",msgType="Show",msgData=())
		show(self.gui)
		curdoc().add_root(self.gui)
Beispiel #40
0
    x_axis_label='Petal_width',
    y_axis_label='Petal_length',
    height=500,
    width=500)
p1.circle(x="petal_length",
          y="sepal_length",
          color="color",
          fill_alpha=0.5,
          size=5,
          source=source)
p2.circle(x="petal_width",
          y="petal_length",
          color="color",
          fill_alpha=0.5,
          size=5,
          source=source)

button.on_click(click)

layout = row(column(select, button, div), column(p1), column(p2))

# # use curdoc to add your widgets to the document
curdoc().add_root(layout)
curdoc().title = "DVA_ex_3"

# # use on of the commands below to start your application
# # bokeh serve --show dva_ex3_skeleton_HS20.py
# # python -m bokeh serve --show dva_ex3_skeleton_HS20.py
# # bokeh serve --dev --show dva_ex3_skeleton_HS20.py
# # python -m bokeh serve --dev --show dva_ex3_skeleton_HS20.py
Beispiel #41
0
def click():
    div.text = f'{"The final cost is : calculating..."}'
    curdoc().add_next_tick_callback(start_clustering)
           source=surrogate_source,
           legend=label.lower())
p.yaxis.axis_label = 'Probability (%)'
plots.append([p])
p.add_tools(HoverTool(tooltips=[(label, "@" + label) for label in D.events]))
p.xaxis.axis_label = 'Time (sec.)'
p.legend.__setattr__('padding', 5)
p.legend.__setattr__('spacing', 0)
p.legend.__setattr__('label_height', 0)
p.legend.__setattr__('glyph_height', 10)
p.legend.__setattr__('background_fill_alpha', 0.5)
p.legend.__setattr__('label_text_alpha', 0.5)
x_range.follow = "end"
x_range.follow_interval = follow_interval
x_range.range_padding = 0

curdoc().add_root(
    column(header,
           gridplot(plots, toolbar_location="left", sizing_mode='scale_width'),
           row(surrogate_button,
               example_slider,
               filename_field,
               select_file_button,
               sizing_mode='scale_width'),
           sizing_mode='scale_width'))

controls = [example_slider]
for control in controls:
    control.on_change('value', lambda attr, old, new: update(new))
curdoc().title = filename
Beispiel #43
0
    source1.data = temp1.data
    source2.data = temp2.data
    # change title
    p1.title.text = sector_name +' electricity consumption for state: '+ state_name
    p2.title.text = sector_name +' electricity consumption for Region: '+ region
  
        
def callback_state(attr,old,new):
        
    global state_name, sector_name, region
    state_name = new
    temp1, temp2, region = get_source(sector_name,state_name)
    # change data
    source1.data = temp1.data
    source2.data = temp2.data
    # change title
    p1.title.text = sector_name +' electricity consumption for state: '+ state_name
    p2.title.text = sector_name +' electricity consumption for Region: '+ region
    
# make drop down menu
select_sector = Select(title='Sector:', value=[*sector_dict][0], options=[*sector_dict])
select_sector.on_change('value', callback_sector)
    
select_state = Select(title='State:', value=[*state_dict][0], options=[*state_dict])
select_state.on_change('value', callback_state)
    
layout = column(widgetbox(select_sector,select_state),p1,p2)

# put the button and plot in a layout and add to the document
curdoc().add_root(layout)
Beispiel #44
0
        new_figure.xaxis.axis_label = figure_data['xlabel']
        new_figure.yaxis.axis_label = figure_data['ylabel']
        # adding charts to figure
        for chart in figure_data['charts']:
            # adding both markers and line for chart
            marker = getattr(new_figure, chart['marker'])
            scatter = marker(x=[0], y=[0], color=chart['color'], size=10, legend=chart['legend'])
            line = new_figure.line(x=[0], y=[0], color=chart['color'], line_width=1, legend=chart['legend'])
            # adding data source for markers and line
            data_sources[state][chart['key']] = scatter.data_source = line.data_source
        figures.append(new_figure)

requests_key = config['requests_key']
url = config['url']

session = push_session(curdoc())


def update():
    try:
        resp = requests.get(url)
    except requests.RequestException:
        return
    resp_data = resp.json()
    data = resp_data['stats'][-1]  # Getting "Total" data from locust
    if resp_data['state'] in config['states']:
        for key, data_source in six.iteritems(data_sources[resp_data['state']]):
            # adding data from locust to data_source of our graphs
            data_source.data['x'].append(data[requests_key])
            data_source.data['y'].append(data[key])
            # trigger data source changes
Beispiel #45
0
                        top=result['Amount'],
                        color="#3498DB")


def update_VBarPlot(attr, old, new):
    year = Amountselect.value
    temp = result.copy()
    temp = temp[temp['Year'] == year]
    print(temp)
    VBar1.data_source.data['x'] = temp['RaceType']
    VBar1.data_source.data['top'] = temp['Amount']


types = Finishdf["RaceType"].unique().tolist()
Finishselect = Select(options=types)
Finishselect.on_change('value', updateFinish)
Avgdf.Year = Avgdf.Year.astype(str)
years = Avgdf.Year.unique().tolist()
Avgselect = Select(options=years)
Avgselect.on_change('value', UpdateAvgPlot)
Amountselect = Select(options=years)
Amountselect.on_change('value', update_VBarPlot)
Avgcontrols = column(Avgselect)
Amountcontrols = column(Amountselect)
FinishControls = column(Finishselect)
l = layout([
    [Finishp, FinishControls],
    [AvgPlot, Avgcontrols, AmountPlot, Amountcontrols],
])
curdoc().add_root(l)
Beispiel #46
0
    # selected_source = sorted(data_urls)[select.active]
    # data = pd.read_csv(data_urls[selected_source])
    data = pd.read_csv(data_urls[select.value])

    # Convert EPSG code
    p1 = Proj(init='epsg:4326')  # this is the EPSG code of the original
    p2 = Proj(init='epsg:3857')  # this is the EPSG code of the tiles
    transformed_coords = [
        transform(p1, p2, x1, y1) for x1, y1 in zip(data['X'], data['Y'])
    ]
    data['X'], data['Y'] = (zip(*transformed_coords))

    # Convert to coordinates
    new_data = {'X': data['X'], 'Y': data['Y']}
    src.data = new_data


# menu = [(k, k) for k in data_urls.keys()]
# select = RadioGroup(active=0,
#                     labels=sorted(data_urls.keys()))
# select.on_change('active', update)

menu = sorted(data_urls.keys())
select = Select(title='Dataset', value=menu[3], options=menu)
select.on_change('value', update_data)

r1 = row(select, make_plot())

curdoc().add_root(r1)
curdoc().title = "Boston Geo Data Explorer"
from bokeh.embed import file_html
from bokeh.plotting import curdoc
from bokeh.models.widgets import Button, Toggle, CheckboxGroup
from bokeh.models import Column


def show_pcur():
  show(p_cur)

def show_p14():
  show(p_14)

def show_p28():
  show(p_28)

button1 = Button(label = "current prediction")
button1.on_click(show_pcur)

button2 = Button(label = "14 days prediction")
button2.on_click(show_p14)

button3 = Button(label="28 days prediction")
button3.on_click(show_p28)

a = curdoc()


output_notebook()
show(Column(button1,button2,button3))

!bokeh serve --show
Beispiel #48
0
stacked_chart_positive_data = wrangle_pos_data_for_stacked_chart(user_inputs)
stacked_chart_negative_data = wrangle_neg_data_for_stacked_chart(user_inputs)
stacked_chart_positive_source = ColumnDataSource(
    data=stacked_chart_positive_data)
stacked_chart_negative_source = ColumnDataSource(
    data=stacked_chart_negative_data)
stacked_chart = create_stacked_chart(
    stacked_chart_positive_data,
    stacked_chart_negative_data,
    stacked_chart_positive_source,
    stacked_chart_negative_source,
)

pie_chart_data = wrangle_data_for_pie_chart(user_inputs)
pie_chart_source = ColumnDataSource(data=pie_chart_data)
pie_chart = create_pie_chart(pie_chart_source)

# layout of charts
bar_chart.margin = (0, 0, 15, 0)
stacked_chart.margin = (0, 0, 15, 0)

charts = column(
    bar_chart,
    stacked_chart,
    pie_chart,
    sizing_mode="stretch_width",
    margin=(0, 15, 0, 15),
)
# doc.theme = Theme(filename="main/static/main/ghg_bokeh_theme.yaml")
curdoc().add_root(layout([[inputs, charts]], css_classes=["center"]))
#
# Widgets
#

# data filters
filter_answered = checkbox_categorical_filter(src_ans, src_ans_orig)
filter_nanswered = checkbox_categorical_filter(src_nans, src_nans_orig)

# checkbox object
checkbox_group = CheckboxGroup(labels=LABELS_kmeans, active=[i for i in range(len(LABELS_kmeans))])

# event handlers
checkbox_group.js_on_change('active', filter_answered)
checkbox_group.js_on_change('active', filter_nanswered)

# output_file("color_scatter.html", title="color_scatter.py example")

# layout specificationns 
lay = layout(
        children = [
            [p_answered, p_nanswered],
            [checkbox_group],
        ]
)

tab = Panel(child=lay, title = 'Clusters')
tabs = Tabs(tabs=[tab])

curdoc().add_root(tabs)

# show(tabs)  # open a browser or notebook depending on configuration
    #DF TO DICT FOR GRAPHS
    graph1_dict = df1.to_dict('list')
    #print('graph1_dict ', graph1_dict)
    graph1_source.data = graph1_dict
    graph1.title.text = graph1_title
    graph1.add_tools(
        HoverTool(tooltips=[("Time", "@Time{%d-%m-%Y %H:%M}"),
                            (graph1_title, "@Metric{0,000.000}")],
                  formatters={'Time': 'datetime'}))

    graph2_dict = df2.to_dict('list')
    #print('graph1_dict ', graph1_dict)
    graph2_source.data = graph2_dict
    graph2.title.text = graph2_title
    graph2.add_tools(
        HoverTool(tooltips=[("Time", "@Time{%d-%m-%Y %H:%M}"),
                            (graph2_title, "@Metric{0,000.000}")],
                  formatters={'Time': 'datetime'}))


dropdown_coll1.on_change('value', refresh_graphs)
dropdown_coll2.on_change('value', refresh_graphs)

dropdown_days.on_change('value', refresh_graphs)
dropdown_hours.on_change('value', refresh_graphs)
dropdown_mins.on_change('value', refresh_graphs)

curdoc().add_root(
    layout([dropdown_days, dropdown_hours, dropdown_mins], dropdown_coll1,
           graph1, dropdown_coll2, graph2))
Beispiel #51
0
                      distortion_slider.value)
    pBox.children[0] = p


submit_button.on_click(submit_button_cb)
variation_selector.on_change('active', selector_cb)

save_button.on_click(save_button_cb)

#slider.on_change('value', cb)
# hack to throttle slider callback (https://stackoverflow.com/questions/38375961/throttling-in-bokeh-application/38379136#38379136)
distortion_slider.callback_policy = 'mouseup'  #call only on mouseup
#slider.callback_throttle = 50 #call max every x ms
source = ColumnDataSource(data=dict(value=[]))
source.on_change('data', slider_cb)
distortion_slider.callback = CustomJS(args=dict(source=source),
                                      code="""
    source.data = { value: [cb_obj.value] }
""")

# ## some CSS to center layout
# header = Div(text="""
#     <style>
#     body { width: 1150px; margin: 0 auto; }
#     </style>
# """)
# curdoc().add_root(header)

curdoc().add_root(layout)
curdoc().add_root(source)
Beispiel #52
0
            lic2bus[bus.Plaka].append(bus)

    new_data = {
        "lon": [[lon2wmlon(bus.Boylam) for bus in buses]
                for buses in lic2bus.values()],
        "lat": [[lat2wmlat(bus.Enlem) for bus in buses]
                for buses in lic2bus.values()],
        "license":
        list(lic2bus.keys()),
        "time": [buses[-1].Saat for buses in lic2bus.values()],
    }

    bus_line_renderer.data_source.data = new_data
    print(
        "Hi!",
        new_data["lon"][:3],
        new_data["lat"][:3],
        new_data["license"][:3],
        new_data["time"][:3],
    )

    new_data["lon"] = [vals[-1] for vals in new_data["lon"]]
    new_data["lat"] = [vals[-1] for vals in new_data["lat"]]
    bus_circle_renderer.data_source.data = new_data


update()
curdoc().add_root(p)
curdoc().add_root(explanation)
curdoc().add_periodic_callback(callback=update, period_milliseconds=60000)
Beispiel #53
0
        colorcycler = cycle(colors)
        legend_items = []
        for lib in subset:
            next_color = next(colorcycler)
            line = f.line(x=subset[lib].index, y=subset[lib], line_color=next_color)
            legend_items.append((lib, [line]))
        legend = Legend(items=legend_items, location=(0, -60))
        f.add_layout(legend, 'right')
        return f

    def app_layout(self):
        controls = widgetbox([self.experiments_combo], width=200)
        self._layout = row(self.make_plot(self.experiment_name), controls)
        return self._layout

    def update_experiment(self, attr, old, new):
        if self._layout is not None:
            self._layout.children[0] = self.make_plot()
        
if __name__ == '__main__':
    plot = main()
    if plot is not None:
        curdoc().add_root(plot.static_layout())
        #export_png(curdoc(), 'genesdetected.png')
        save(curdoc(), 'coverage_mean.html')
elif __name__.startswith('bk_script'):
    plot = main()
    if plot is not None:
        curdoc().add_root(plot.app_layout())

p4 = gridplot([[splom, dum_fig]], toolbar_location=None)
# [END] tab 4 - splom plot --------------------------------------------------------------------------------------------

# // TOOL GUI ===========================================================================================================================================================

# Spinner GUI
spinner = Spinner(title="Size", low=0, high=4, step=0.1, value=1, width=300)
# spinner.js_link('value', points.glyph, 'radius')

# Dropdown menu GUI
glyphs = [
    "Blood Categorie", "Blood Bas Analysis", "Enzym & Minerals & Proteine",
    "Other Tests"
]
select = Select(title="Select plot:", value="", options=[""] + glyphs)
curdoc().add_root(Row(select, name='root'))


def callback(attr, old, new):
    layouts = curdoc().get_model_by_name('root').children
    for glyph in glyphs:
        plot = curdoc().get_model_by_name(glyph)
        if plot:
            layouts.remove(plot)
    if new:
        p = figure(name=new)
        #exec(new + ' = p.' + new + '("x", "y", source = source)')
        layouts.append(p)


select.on_change('value', callback)
Beispiel #55
0
    opts['color_index'] = color.value if color.value != 'None' else None
    if size.value != 'None':
        opts['size_index'] = size.value
        opts['scaling_factor'] = (1. / df[size.value].max()) * 200
    points = hv.Points(df, kdims=kdims, label=label).opts(plot=opts,
                                                          style=style)
    return renderer.get_plot(points).state


def update(attr, old, new):
    layout.children[1] = create_figure()


x = Select(title='X-Axis', value='mpg', options=quantileable)
x.on_change('value', update)

y = Select(title='Y-Axis', value='hp', options=quantileable)
y.on_change('value', update)

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

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

controls = widgetbox([x, y, color, size], width=200)
layout = row(controls, create_figure())

curdoc().add_root(layout)
curdoc().title = "Crossfilter"
Beispiel #56
0
    
    # pick a date
    date_picker_i = DatePicker(value=date.today(),max_date=date.today(), title='Choose inital date:', width=150, disabled=False)
    mydate_i=date_picker_i.value
    date_picker_f = DatePicker(value=date.today(),max_date=date.today(), title='Choose final date:' , width=150, disabled=False)
    mydate_f=date_picker_f.value
    date_picker_i.on_change('value',initial_date)
    date_picker_f.on_change('value',final_date)
    
    hist_button = Button(label="Show History", button_type="default", width=310)
    hist_button.on_click(get_history)
    
    pre_head = PreText(text="N.B.: Readout every 10 seconds. Be patient!",width=500, height=50)
    pre_head2 = PreText(text="",width=400, height=25)
    pre_temp_top = PreText(text="",width=400, height=20)
    pre_temp_mid = PreText(text="",width=400, height=20)
    pre_temp_bot = PreText(text="",width=400, height=20)
    
    h_space = PreText(text="",width=50, height=1)
    v_space = PreText(text="",width=1, height=50)
    
#    curdoc().add_root(column(pre_head,row(div,column(pre_head2,pre_temp_top,pre_temp_mid,pre_temp_bot),column(plot['temperature'],plot['humidity'],plot['pressure']),)))
    curdoc().add_root(column(row(h_space,pre_head),row(h_space,live_hours_input, h_space, h_space, date_picker_i, date_picker_f), row(h_space,live_checkbox,h_space, h_space, hist_button),v_space,row(h_space,plot['temperature'],h_space,plot['humidity'],h_space,plot['pressure']), v_space,row(h_space,div)))
    
    readdata()
    main()
#    time.sleep ( 10 )
    periodic_callback_id = curdoc().add_periodic_callback(update, 10000)
else:
    pass    
Beispiel #57
0
    from cobras_ts.visualquerier import VisualQuerier
    from cobras_ts.cobras_kshape import COBRAS_kShape

import random
import numpy as np
import pandas as pd
import sys


def communicate_query_result(query_result):
    global querier
    querier.query_result = query_result
    querier.query_answered = True


curdoc().title = "COBRAS-TS"

loading = Div(text="""<h3>Loading...<h3>""", width=100, height=100)


def mustlink_callback():
    global query_answered
    global querier
    global layout
    global button_ml
    global button_cl

    button_ml.disabled = True
    button_cl.disabled = True

    layout.children[1].children[1].children[1] = loading
Beispiel #58
0
def main():
    ui = UI(_callback, UISpecs())
    # show(ui.layout)
    curdoc().add_root(ui.layout)
Beispiel #59
0
def demo_callback(*args, **kwargs):
    """
    This script takes a screenshot of quicktime. It assumes

    1. the window is in the upper left at (0, 0) of the main screen
    2. that it's taking a screenshot of an iPhone camera in iOS 12

    How to launch quicktime to record screen:

    * File > New Movie Recording
    * Click on red button and select "source: iPhone"

    """
    os.system(
        """osascript -e 'tell application "Keyboard Maestro Engine" to do script "3CF8CFB6-5A27-47FF-8DFF-F6CBA7FCE841"'"""
    )
    print("\n" + "picture taken" + "\n")
    with open("webcam.png", "rb") as f:
        callback(f)


# put the button and plot in a layout and add to the document
demo = Button(label="Take picture", button_type="success")
demo.on_click(demo_callback)

if True:
    button = upload
else:
    button = demo
curdoc().add_root(column(button, p))
Beispiel #60
0
#             # 'wellio': main_dir + "/docs/js/bundle.js",
#             # 'my_gist': "make_a_plot.js",
#             # 'my_test2': "./static/js/test_bokeh.js"
#         },
#         # css_file=main_dir + "../docs/css/main.css"
#     )

# def load_callback(event, value):
#     print('load this {}'.format(value))
code = '''
    plot_log(\"current_log\", source.value)
    target.text = \"done\"
'''

markdown = pn.pane.Markdown("<b>Markdown display</b>", width=400)
file_load_selector = pn.widgets.FileInput(accept='.LAS,.json,.las',
                                          name='File Input')
# file_load_selector.link(file_load_selector, callbacks={'value': load_callback})
file_load_selector.jslink(target=markdown, code={'value': code})
# file_load_selector.jscallback(value=code, args={'value': file_load_selector.value})
print('creating column')
main_column = pn.Column(width=900)
test_html = pn.panel('<h1> Hi select a log file! </h1>')
main_column.append(test_html)
main_column.append(file_load_selector)
main_column.append(pn.panel("<script> plot_log(\"current_log\") </script>"))
main_column.append(markdown)
print('trying to add to doc')
main_column.servable()
doc = curdoc()