Пример #1
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Circle(x='x', y='y', size=20))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    select = Select(options=["Option 1", "Option 2", "Option 3"], css_classes=["foo"])
    def cb(attr, old, new):
        source.data['val'] = [old, new]
    select.on_change('value', cb)
    doc.add_root(column(select, plot))
Пример #2
0
    def __init__(self, worker, **kwargs):
        with log_errors():
            self.worker = worker

            names = ['nbytes', 'duration', 'bandwidth', 'count', 'type',
                     'inout-color', 'type-color', 'key', 'key-color', 'start',
                     'stop']
            quantities = ['nbytes', 'duration', 'bandwidth', 'count',
                          'start', 'stop']
            colors = ['inout-color', 'type-color', 'key-color']

            # self.source = ColumnDataSource({name: [] for name in names})
            self.source = ColumnDataSource({
                'nbytes': [1, 2],
                'duration': [0.01, 0.02],
                'bandwidth': [0.01, 0.02],
                'count': [1, 2],
                'type': ['int', 'str'],
                'inout-color': ['blue', 'red'],
                'type-color': ['blue', 'red'],
                'key': ['add', 'inc'],
                'start': [1, 2],
                'stop': [1, 2]
                })

            self.x = Select(title='X-Axis', value='nbytes', options=quantities)
            self.x.on_change('value', self.update_figure)

            self.y = Select(title='Y-Axis', value='bandwidth', options=quantities)
            self.y.on_change('value', self.update_figure)

            self.size = Select(title='Size', value='None',
                               options=['None'] + quantities)
            self.size.on_change('value', self.update_figure)

            self.color = Select(title='Color', value='inout-color',
                                options=['black'] + colors)
            self.color.on_change('value', self.update_figure)

            if 'sizing_mode' in kwargs:
                kw = {'sizing_mode': kwargs['sizing_mode']}
            else:
                kw = {}

            self.control = widgetbox([self.x, self.y, self.size, self.color],
                                     width=200, **kw)

            self.last_outgoing = 0
            self.last_incoming = 0
            self.kwargs = kwargs

            self.layout = row(self.control, self.create_figure(**self.kwargs),
                              **kw)

            self.root = self.layout
Пример #3
0
def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'):    

    source = ColumnDataSource(data=initData)
    selectDOW = Select(title="Days:", value="Monday", options=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
    selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"])
    model = dict(source=source, select_dow = selectDOW, select_ut = selectUT)
    plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime")
    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
    
    callback = CustomJS(args=model, code="""
          var dayOfWeek = select_dow.get('value')
            var userType = select_ut.get('value')
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        var temp=[];
                        
                        for(var date in result.x) {
                            temp.push(new Date(result.x[date]));
                        }
                        
                        data['x'] = temp;
                        data['y'] = result.y;
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {dow:dayOfWeek, ut:userType};
        url = "/select?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    selectDOW.callback = callback
    selectUT.callback = callback
    layout = vform(selectDOW, selectUT, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
    
    
Пример #4
0
    def test_js_on_change_executes(self, bokeh_model_page):
        select = Select(options=["Option 1", "Option 2", "Option 3"], css_classes=["foo"])
        select.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(select)

        el = page.driver.find_element_by_css_selector('.foo select')
        el.click()

        el = page.driver.find_element_by_css_selector('.foo select option[value="Option 3"]')
        el.click()

        results = page.results
        assert results['value'] == 'Option 3'

        assert page.has_no_console_errors()
Пример #5
0
    def create_layout(self):

        # create figure
        self.x_range = Range1d(start=self.model.map_extent[0],
                               end=self.model.map_extent[2], bounds=None)
        self.y_range = Range1d(start=self.model.map_extent[1],
                               end=self.model.map_extent[3], bounds=None)

        self.fig = Figure(tools='box_zoom,wheel_zoom,pan', x_range=self.x_range,
                          y_range=self.y_range)
        self.fig.plot_height = 600 
        self.fig.plot_width = 1024
        self.fig.axis.visible = True

        # add datashader layer
        self.image_source = ImageSource(url=self.model.service_url,
                                        extra_url_vars=self.model.shader_url_vars)
        self.image_renderer = DynamicImageRenderer(image_source=self.image_source)
        self.fig.renderers.append(self.image_renderer)

        # add ui components
        axes_select = Select.create(name='Plot:',
                                    options=self.model.axes)
        
        axes_select.on_change('value', self.on_axes_change)
        field_select = Select.create(name='Summary:', options=self.model.fields)
        
        field_select.on_change('value', self.on_field_change)
        
        aggregate_select = Select.create(name='Aggregation:',
            options=self.model.aggregate_functions)
        aggregate_select.on_change('value', self.on_aggregate_change)

        transfer_select = Select.create(name='Scale:',
            options=self.model.transfer_functions)
        transfer_select.on_change('value', self.on_transfer_function_change)

        controls = [axes_select, field_select, aggregate_select,
                    transfer_select]

        self.controls = VBox(width=200, height=600, children=controls)
        self.map_area = VBox(width=self.fig.plot_width, children=[self.fig])
        self.layout = HBox(width=self.fig.plot_width, children=[self.controls, self.map_area])
Пример #6
0
def bball():
    os.chdir('C:\\Users\\weinfz18\\Documents\\NBA_current')  ##  switch to correct directory
    imgo = np.loadtxt('imgo.csv', delimiter=',')
    imgd = np.loadtxt('imgd.csv', delimiter=',')
    ##  court image 
    players = pd.read_csv('C:\\Users\\weinfz18\\Documents\\NBA_current\\all_players.csv', names=['players'],delimiter='$')
    oplayer = "Whiteside, Hassan"
    dplayer = "Whiteside, Hassan"
    dplayername = ''.join([x for x in dplayer.lower() if x in 'abcdefghijklmnopqrstuvwxyz'])
    oplayername = ''.join([x for x in oplayer.lower() if x in 'abcdefghijklmnopqrstuvwxyz'])
    odata = pd.read_csv('C:\\Users\\weinfz18\\Documents\\NBA_current\\player_shots\\{}\\odata.csv'.format(oplayername))
    ddata = pd.read_csv('C:\\Users\\weinfz18\\Documents\\NBA_current\\player_shots\\{}\\ddata.csv'.format(dplayername))
    odata = odata[odata['dense']!=0]
    ddata = ddata[ddata['dense']!=0]
    ddata = ddata.reset_index(drop=True)
    odata = odata.reset_index(drop=True)
    odata = odata.to_dict("list")
    ddata = ddata.to_dict("list")
    
    oplayer_select = Select(value="Rubio, Ricky", title='Offensive player', options=sorted(players['players'].tolist()))
    dplayer_select = Select(value="Rubio, Ricky", title='Defensive player', options=sorted(players['players'].tolist()))
    oplayer_select.on_change('value', update_plot)
    dplayer_select.on_change('value', update_plot)
    op, odata_table, dp, ddata_table = Make_Plot(ddata,odata,imgo,imgd,oplayer,dplayer)
    oscript, odiv = components(op)
    otscript, otdiv = components(odata_table)
    dscript, ddiv = components(dp)
    dtscript, dtdiv = components(ddata_table)
    script = [oscript, otscript, dscript, dtscript]
    div = [odiv, otdiv, ddiv, dtdiv]
    return render_template('index.html', script=script, div=div)
Пример #7
0
def create_layout():
    year_select = Select(title="Year:", value="2010", options=years)
    location_select = Select(title="Location:", value="World", options=locations)

    year_select.on_change('value', on_year_change)
    location_select.on_change('value', on_location_change)

    controls = row(children=[year_select, location_select])
    layout = column(children=[controls, pyramid(), population()])

    return layout
Пример #8
0
    def create_layout(self):
        years = list(map(str, sorted(self.df.Year.unique())))
        locations = sorted(self.df.Location.unique())

        year_select = Select(title="Year:", value="2010", options=years)
        location_select = Select(title="Location:", value="World", options=locations)

        year_select.on_change('value', self.on_year_change)
        location_select.on_change('value', self.on_location_change)

        controls = HBox(year_select, location_select)
        self.layout = VBox(controls, self.plot)
Пример #9
0
def create_layout():
    size_select = Select(
        value="Days Active", title="Marker Scaling:", options=["Days Active", "Days Remaining", "Power Output"]
    )
    size_select.on_change("value", on_size_change)

    location_select = Select(title="Power Plant Name:", value=location, options=locations)
    location_select.on_change("value", on_location_change)

    controls = HBox(children=[size_select, location_select])
    layout = VBox(children=[controls, map(), performance()])

    return layout
Пример #10
0
 def create_channel_widget(self):
     self.w_channel = Select(title="Channel:", value="", options=[])
     self.w_channel.on_change('value', self.on_channel_widget_change)
Пример #11
0
 def create_telid_widget(self):
     self.w_telid = Select(title="Telescope:", value="", options=[])
     self.w_telid.on_change('value', self.on_telid_widget_change)
Пример #12
0
class BokehFileViewer(Tool):
    name = "BokehFileViewer"
    description = ("Interactively explore an event file using the bokeh "
                   "visualisation package")

    port = Int(5006, help="Port to open bokeh server onto").tag(config=True)
    disable_server = Bool(False, help="Do not start the bokeh server "
                                      "(useful for testing)").tag(config=True)

    aliases = Dict(dict(
        port='BokehFileViewer.port',
        disable_server='BokehFileViewer.disable_server',
        r='EventSourceFactory.product',
        f='EventSourceFactory.input_url',
        max_events='EventSourceFactory.max_events',
        ped='CameraR1CalibratorFactory.pedestal_path',
        tf='CameraR1CalibratorFactory.tf_path',
        pe='CameraR1CalibratorFactory.pe_path',
        ff='CameraR1CalibratorFactory.ff_path',
        extractor='ChargeExtractorFactory.product',
        extractor_t0='ChargeExtractorFactory.t0',
        extractor_window_width='ChargeExtractorFactory.window_width',
        extractor_window_shift='ChargeExtractorFactory.window_shift',
        extractor_sig_amp_cut_HG='ChargeExtractorFactory.sig_amp_cut_HG',
        extractor_sig_amp_cut_LG='ChargeExtractorFactory.sig_amp_cut_LG',
        extractor_lwt='ChargeExtractorFactory.lwt',
        cleaner='WaveformCleanerFactory.product',
    ))

    classes = List([
        EventSourceFactory,
        ChargeExtractorFactory,
        CameraR1CalibratorFactory,
        CameraDL1Calibrator,
        WaveformCleanerFactory
    ])

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._event = None
        self._event_index = None
        self._event_id = None
        self._telid = None
        self._channel = None

        self.w_next_event = None
        self.w_previous_event = None
        self.w_event_index = None
        self.w_event_id = None
        self.w_goto_event_index = None
        self.w_goto_event_id = None
        self.w_telid = None
        self.w_channel = None
        self.w_dl1_dict = None
        self.wb_extractor = None
        self.layout = None

        self.reader = None
        self.seeker = None
        self.extractor = None
        self.cleaner = None
        self.r1 = None
        self.dl0 = None
        self.dl1 = None
        self.viewer = None

        self._updating_dl1 = False

    def setup(self):
        self.log_format = "%(levelname)s: %(message)s [%(name)s.%(funcName)s]"
        kwargs = dict(config=self.config, tool=self)

        default_url = get_dataset_path("gamma_test.simtel.gz")
        EventSourceFactory.input_url.default_value = default_url
        self.reader = EventSourceFactory.produce(**kwargs)
        self.seeker = EventSeeker(self.reader, **kwargs)

        self.extractor = ChargeExtractorFactory.produce(**kwargs)
        self.cleaner = WaveformCleanerFactory.produce(**kwargs)

        self.r1 = CameraR1CalibratorFactory.produce(
            eventsource=self.reader,
            **kwargs
        )
        self.dl0 = CameraDL0Reducer(**kwargs)
        self.dl1 = CameraDL1Calibrator(
            extractor=self.extractor,
            cleaner=self.cleaner,
            **kwargs
        )

        self.viewer = BokehEventViewer(**kwargs)

        # Setup widgets
        self.viewer.create()
        self.viewer.enable_automatic_index_increment()
        self.create_previous_event_widget()
        self.create_next_event_widget()
        self.create_event_index_widget()
        self.create_goto_event_index_widget()
        self.create_event_id_widget()
        self.create_goto_event_id_widget()
        self.create_telid_widget()
        self.create_channel_widget()
        self.create_dl1_widgets()
        self.update_dl1_widget_values()

        # Setup layout
        self.layout = layout([
            [self.viewer.layout],
            [
                self.w_previous_event,
                self.w_next_event,
                self.w_goto_event_index,
                self.w_goto_event_id
            ],
            [self.w_event_index, self.w_event_id],
            [self.w_telid, self.w_channel],
            [self.wb_extractor]
        ])

    def start(self):
        self.event_index = 0

    def finish(self):
        if not self.disable_server:
            def modify_doc(doc):
                doc.add_root(self.layout)
                doc.title = self.name

                directory = os.path.abspath(os.path.dirname(__file__))
                theme_path = os.path.join(directory, "theme.yaml")
                template_path = os.path.join(directory, "templates")
                doc.theme = Theme(filename=theme_path)
                env = jinja2.Environment(
                    loader=jinja2.FileSystemLoader(template_path)
                )
                doc.template = env.get_template('index.html')

            self.log.info('Opening Bokeh application on '
                          'http://localhost:{}/'.format(self.port))
            server = Server({'/': modify_doc}, num_procs=1, port=self.port)
            server.start()
            server.io_loop.add_callback(server.show, "/")
            server.io_loop.start()

    @property
    def event_index(self):
        return self._event_index

    @event_index.setter
    def event_index(self, val):
        try:
            self.event = self.seeker[val]
        except IndexError:
            self.log.warning("Event Index {} does not exist".format(val))

    @property
    def event_id(self):
        return self._event_id

    @event_id.setter
    def event_id(self, val):
        try:
            self.event = self.seeker[str(val)]
        except IndexError:
            self.log.warning("Event ID {} does not exist".format(val))

    @property
    def telid(self):
        return self._telid

    @telid.setter
    def telid(self, val):
        self.channel = 0
        tels = list(self.event.r0.tels_with_data)
        if val not in tels:
            val = tels[0]
        self._telid = val
        self.viewer.telid = val
        self.update_telid_widget()

    @property
    def channel(self):
        return self._channel

    @channel.setter
    def channel(self, val):
        self._channel = val
        self.viewer.channel = val
        self.update_channel_widget()

    @property
    def event(self):
        return self._event

    @event.setter
    def event(self, val):

        # Calibrate
        self.r1.calibrate(val)
        self.dl0.reduce(val)
        self.dl1.calibrate(val)

        self._event = val

        self.viewer.event = val

        self._event_index = val.count
        self._event_id = val.r0.event_id
        self.update_event_index_widget()
        self.update_event_id_widget()

        self._telid = self.viewer.telid
        self.update_telid_widget()

        self._channel = self.viewer.channel
        self.update_channel_widget()

    def update_dl1_calibrator(self, extractor=None, cleaner=None):
        """
        Recreate the dl1 calibrator with the specified extractor and cleaner

        Parameters
        ----------
        extractor : ctapipe.image.charge_extractors.ChargeExtractor
        cleaner : ctapipe.image.waveform_cleaning.WaveformCleaner
        """
        if extractor is None:
            extractor = self.dl1.extractor
        if cleaner is None:
            cleaner = self.dl1.cleaner

        self.extractor = extractor
        self.cleaner = cleaner

        kwargs = dict(config=self.config, tool=self)
        self.dl1 = CameraDL1Calibrator(
            extractor=self.extractor,
            cleaner=self.cleaner,
            **kwargs
        )
        self.dl1.calibrate(self.event)
        self.viewer.refresh()

    def create_next_event_widget(self):
        self.w_next_event = Button(label=">", button_type="default", width=50)
        self.w_next_event.on_click(self.on_next_event_widget_click)

    def on_next_event_widget_click(self):
        self.event_index += 1

    def create_previous_event_widget(self):
        self.w_previous_event = Button(
            label="<",
            button_type="default",
            width=50
        )
        self.w_previous_event.on_click(self.on_previous_event_widget_click)

    def on_previous_event_widget_click(self):
        self.event_index -= 1

    def create_event_index_widget(self):
        self.w_event_index = TextInput(title="Event Index:", value='')

    def update_event_index_widget(self):
        if self.w_event_index:
            self.w_event_index.value = str(self.event_index)

    def create_event_id_widget(self):
        self.w_event_id = TextInput(title="Event ID:", value='')

    def update_event_id_widget(self):
        if self.w_event_id:
            self.w_event_id.value = str(self.event_id)

    def create_goto_event_index_widget(self):
        self.w_goto_event_index = Button(
            label="GOTO Index",
            button_type="default",
            width=100
        )
        self.w_goto_event_index.on_click(self.on_goto_event_index_widget_click)

    def on_goto_event_index_widget_click(self):
        self.event_index = int(self.w_event_index.value)

    def create_goto_event_id_widget(self):
        self.w_goto_event_id = Button(
            label="GOTO ID",
            button_type="default",
            width=70
        )
        self.w_goto_event_id.on_click(self.on_goto_event_id_widget_click)

    def on_goto_event_id_widget_click(self):
        self.event_id = int(self.w_event_id.value)

    def create_telid_widget(self):
        self.w_telid = Select(title="Telescope:", value="", options=[])
        self.w_telid.on_change('value', self.on_telid_widget_change)

    def update_telid_widget(self):
        if self.w_telid:
            tels = [str(t) for t in self.event.r0.tels_with_data]
            self.w_telid.options = tels
            self.w_telid.value = str(self.telid)

    def on_telid_widget_change(self, _, __, ___):
        if self.telid != int(self.w_telid.value):
            self.telid = int(self.w_telid.value)

    def create_channel_widget(self):
        self.w_channel = Select(title="Channel:", value="", options=[])
        self.w_channel.on_change('value', self.on_channel_widget_change)

    def update_channel_widget(self):
        if self.w_channel:
            try:
                n_chan = self.event.r0.tel[self.telid].waveform.shape[0]
            except AttributeError:
                n_chan = 1
            channels = [str(c) for c in range(n_chan)]
            self.w_channel.options = channels
            self.w_channel.value = str(self.channel)

    def on_channel_widget_change(self, _, __, ___):
        if self.channel != int(self.w_channel.value):
            self.channel = int(self.w_channel.value)

    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            cleaner=Select(title="Cleaner:", value='', width=5,
                           options=WaveformCleanerFactory.subclass_names),
            extractor=Select(title="Extractor:", value='', width=5,
                             options=ChargeExtractorFactory.subclass_names),
            extractor_t0=TextInput(title="T0:", value=''),
            extractor_window_width=TextInput(title="Window Width:", value=''),
            extractor_window_shift=TextInput(title="Window Shift:", value=''),
            extractor_sig_amp_cut_HG=TextInput(title="Significant Amplitude "
                                                     "Cut (HG):", value=''),
            extractor_sig_amp_cut_LG=TextInput(title="Significant Amplitude "
                                                     "Cut (LG):", value=''),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=''))

        for val in self.w_dl1_dict.values():
            val.on_change('value', self.on_dl1_widget_change)

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict['cleaner'],
            self.w_dl1_dict['extractor'],
            self.w_dl1_dict['extractor_t0'],
            self.w_dl1_dict['extractor_window_width'],
            self.w_dl1_dict['extractor_window_shift'],
            self.w_dl1_dict['extractor_sig_amp_cut_HG'],
            self.w_dl1_dict['extractor_sig_amp_cut_LG'],
            self.w_dl1_dict['extractor_lwt'])

    def update_dl1_widget_values(self):
        if self.w_dl1_dict:
            for key, val in self.w_dl1_dict.items():
                if 'extractor' in key:
                    if key == 'extractor':
                        val.value = self.extractor.__class__.__name__
                    else:
                        key = key.replace("extractor_", "")
                        try:
                            val.value = str(getattr(self.extractor, key))
                        except AttributeError:
                            val.value = ''
                elif 'cleaner' in key:
                    if key == 'cleaner':
                        val.value = self.cleaner.__class__.__name__
                    else:
                        key = key.replace("cleaner_", "")
                        try:
                            val.value = str(getattr(self.cleaner, key))
                        except AttributeError:
                            val.value = ''

    def on_dl1_widget_change(self, _, __, ___):
        if self.event:
            if not self._updating_dl1:
                self._updating_dl1 = True
                cmdline = []
                for key, val in self.w_dl1_dict.items():
                    if val.value:
                        cmdline.append('--{}'.format(key))
                        cmdline.append(val.value)
                self.parse_command_line(cmdline)
                kwargs = dict(config=self.config, tool=self)
                extractor = ChargeExtractorFactory.produce(**kwargs)
                cleaner = WaveformCleanerFactory.produce(**kwargs)
                self.update_dl1_calibrator(extractor, cleaner)
                self.update_dl1_widget_values()
                self._updating_dl1 = False
Пример #13
0
    def create_layout(self):

        # create figure
        self.x_range = Range1d(start=self.model.map_extent[0],
                               end=self.model.map_extent[2], bounds=None)
        self.y_range = Range1d(start=self.model.map_extent[1],
                               end=self.model.map_extent[3], bounds=None)

        self.fig = Figure(tools='wheel_zoom,pan',
                          x_range=self.x_range,
                          lod_threshold=None,
                          plot_width=self.model.plot_width,
                          plot_height=self.model.plot_height,
                          y_range=self.y_range)

        self.fig.min_border_top = 0
        self.fig.min_border_bottom = 10
        self.fig.min_border_left = 0
        self.fig.min_border_right = 0
        self.fig.axis.visible = False

        self.fig.xgrid.grid_line_color = None
        self.fig.ygrid.grid_line_color = None
        
        # add tiled basemap
        self.tile_source = WMTSTileSource(url=self.model.basemap)
        self.tile_renderer = TileRenderer(tile_source=self.tile_source)
        self.fig.renderers.append(self.tile_renderer)

        # add datashader layer
        self.image_source = ImageSource(url=self.model.service_url,
                                        extra_url_vars=self.model.shader_url_vars)
        self.image_renderer = DynamicImageRenderer(image_source=self.image_source)
        self.fig.renderers.append(self.image_renderer)
        
        # add label layer
        self.label_source = WMTSTileSource(url=self.model.labels_url)
        self.label_renderer = TileRenderer(tile_source=self.label_source)
        self.fig.renderers.append(self.label_renderer)

        # Add a hover tool
        self.invisible_square = Square(x='x',
                                       y='y',
                                       fill_color=None,
                                       line_color=None, 
                                       size=self.model.hover_size)

        self.visible_square = Square(x='x',
                                     y='y', 
                                     fill_color='#79DCDE',
                                     fill_alpha=.5,
                                     line_color='#79DCDE', 
                                     line_alpha=1,
                                     size=self.model.hover_size)

        cr = self.fig.add_glyph(self.model.hover_source,
                                self.invisible_square,
                                selection_glyph=self.visible_square,
                                nonselection_glyph=self.invisible_square)

        code = "source.set('selected', cb_data['index']);"
        callback = CustomJS(args={'source': self.model.hover_source}, code=code)
        self.model.hover_tool = HoverTool(tooltips=[(self.model.fields.keys()[0], "@value")],
                                    callback=callback, 
                                    renderers=[cr], 
                                    mode='mouse')
        self.fig.add_tools(self.model.hover_tool)
        self.model.legend_side_vbox = VBox()
        self.model.legend_bottom_vbox = VBox()

        # add ui components
        controls = []
        axes_select = Select.create(name='Axes',
                                    options=self.model.axes)
        axes_select.on_change('value', self.on_axes_change)
        controls.append(axes_select)

        self.field_select = Select.create(name='Field', options=self.model.fields)
        self.field_select.on_change('value', self.on_field_change)
        controls.append(self.field_select)

        self.aggregate_select = Select.create(name='Aggregate',
                                         options=self.model.aggregate_functions)
        self.aggregate_select.on_change('value', self.on_aggregate_change)
        controls.append(self.aggregate_select)

        transfer_select = Select.create(name='Transfer Function',
                                        options=self.model.transfer_functions)
        transfer_select.on_change('value', self.on_transfer_function_change)
        controls.append(transfer_select)

        color_ramp_select = Select.create(name='Color Ramp', options=self.model.color_ramps)
        color_ramp_select.on_change('value', self.on_color_ramp_change)
        controls.append(color_ramp_select)

        spread_size_slider = Slider(title="Spread Size (px)", value=0, start=0,
                                        end=10, step=1)
        spread_size_slider.on_change('value', self.on_spread_size_change)
        controls.append(spread_size_slider)

        hover_size_slider = Slider(title="Hover Size (px)", value=8, start=4,
                                        end=30, step=1)
        hover_size_slider.on_change('value', self.on_hover_size_change)
        controls.append(hover_size_slider)

        controls.append(self.model.legend_side_vbox)

        # add map components
        basemap_select = Select.create(name='Basemap', value='Imagery',
                                       options=self.model.basemaps)
        basemap_select.on_change('value', self.on_basemap_change)

        image_opacity_slider = Slider(title="Opacity", value=100, start=0,
                                      end=100, step=1)
        image_opacity_slider.on_change('value', self.on_image_opacity_slider_change)

        basemap_opacity_slider = Slider(title="Basemap Opacity", value=100, start=0,
                                        end=100, step=1)
        basemap_opacity_slider.on_change('value', self.on_basemap_opacity_slider_change)


        show_labels_chk = CheckboxGroup(labels=["Show Labels"], active=[0])
        show_labels_chk.on_click(self.on_labels_change)

        map_controls = [basemap_select, basemap_opacity_slider,
                        image_opacity_slider, show_labels_chk]

        self.controls = VBox(width=200, height=600, children=controls)
        self.map_controls = HBox(width=self.fig.plot_width, children=map_controls)
        self.map_area = VBox(width=self.fig.plot_width, children=[self.map_controls,
                                                                  self.fig,
                                                                  self.model.legend_bottom_vbox])
        self.layout = HBox(width=1366, children=[self.controls, self.map_area])
Пример #14
0
          source=source2,
          level='overlay')

p2.select_one(HoverTool).tooltips = [("poisonous", "@poisonous"),
                                     ('prediction', '@pred{0.00}')]

# set up widgets
ml_models = [
    'Logistic Regression', 'KNN (N=1)', 'KNN (N=20)',
    'Decision Tree (max_depth=5)', 'Decision Tree (full depth)',
    'Random Forest', 'SVM (linear kernel)', 'SVM (rbf kernel)',
    'Gaussian Naive Bayes', 'MLP (3 hidden layers, relu activation)'
]

model_select = Select(value='Logistic Regression',
                      title='Select model:',
                      width=200,
                      options=ml_models)

test_split_button = Button(label="New Train/Test Split", width=200)

prediction_types = ['Probability', 'Decision']

prediction_select = Select(value='Probability',
                           title='Select boundary:',
                           width=200,
                           options=prediction_types)

inputs = column(widgetbox(test_split_button, model_select, prediction_select))


def update_predictions(attrname, old, new):
Пример #15
0
class BokehEventViewerCamera(CameraDisplay):
    def __init__(self, event_viewer, fig=None):
        """
        A `ctapipe.visualization.bokeh.CameraDisplay` modified to utilise a
        `ctapipe.core.container.DataContainer` directly.

        Parameters
        ----------
        event_viewer : BokehEventViewer
            The BokehEventViewer this object belongs to
        fig : bokeh.plotting.figure
            Figure to store the bokeh plot onto (optional)
        """
        self._event = None
        self._view = 'r0'
        self._telid = None
        self._channel = 0
        self._time = 0
        super().__init__(fig=fig)

        self._view_options = {
            'r0': lambda e, t, c, time: e.r0.tel[t].waveform[c, :, time],
            'r1': lambda e, t, c, time: e.r1.tel[t].waveform[c, :, time],
            'dl0': lambda e, t, c, time: e.dl0.tel[t].waveform[c, :, time],
            'dl1': lambda e, t, c, time: e.dl1.tel[t].image[c, :],
            'peakpos': lambda e, t, c, time: e.dl1.tel[t].peakpos[c, :],
            'cleaned': lambda e, t, c, time: e.dl1.tel[t].cleaned[c, :, time],
        }

        self.w_view = None
        self._geom_tel = None

        self.event_viewer = event_viewer

    def _reset(self):
        self.reset_pixels()
        self.event_viewer.change_time(0)

    def _set_image(self):
        e = self.event
        v = self.view
        t = self.telid
        c = self.channel
        time = self.time
        if not e:
            self.event_viewer.log.warning("No event has been provided")
            return

        tels = list(e.r0.tels_with_data)
        if t is None:
            t = tels[0]
        if t not in tels:
            raise KeyError(f"Telescope {t} has no data")

        try:
            self.image = self._view_options[v](e, t, c, time)
            self.fig.title.text = f'{v} (T = {time})'
        except TypeError:
            self.image = None

    def _update_geometry(self):
        e = self.event
        t = self.telid
        if e:
            # Check if geom actually needs to be changed
            if not t == self._geom_tel:
                self.geom = e.inst.subarray.tel[t].camera
                self._geom_tel = t
        else:
            self.event_viewer.log.warning("No event has been provided")

    def refresh(self):
        self._set_image()

    @property
    def event(self):
        return self._event

    @event.setter
    def event(self, val):
        self._event = val
        self._update_geometry()
        self._set_image()

    def change_event(self, event, telid):
        if self.event:  # Only reset when an event exists
            self._reset()
        self._telid = telid
        self.event = event

    @property
    def view(self):
        return self._view

    @view.setter
    def view(self, val):
        if val not in list(self._view_options.keys()):
            raise ValueError(f"View is not valid: {val}")
        self._view = val
        self._set_image()

    @property
    def telid(self):
        return self._telid

    @telid.setter
    def telid(self, val):
        if self.event:  # Only reset when an event exists
            self._reset()
        self._telid = val
        self._update_geometry()
        self._set_image()

    @property
    def channel(self):
        return self._channel

    @channel.setter
    def channel(self, val):
        self._channel = val
        self._set_image()

    @property
    def time(self):
        return self._time

    @time.setter
    def time(self, val):
        self._time = int(val)
        self._set_image()

    def _on_pixel_click(self, pix_id):
        super()._on_pixel_click(pix_id)
        ai = self.active_index
        self.event_viewer.waveforms[ai].pixel = pix_id

    def create_view_widget(self):
        self.w_view = Select(title="View:", value="", options=[], width=5)
        self.w_view.on_change('value', self.on_view_widget_change)
        self.layout = column([self.w_view, self.layout])

    def update_view_widget(self):
        self.w_view.options = list(self._view_options.keys())
        self.w_view.value = self.view

    def on_view_widget_change(self, _, __, ___):
        if self.view != self.w_view.value:
            self.view = self.w_view.value
Пример #16
0
class BokehEventViewerWaveform(WaveformDisplay):
    def __init__(self, event_viewer, fig=None):
        """
        A `ctapipe.visualization.bokeh.WaveformDisplay` modified to utilise a
        `ctapipe.core.container.DataContainer` directly.

        Parameters
        ----------
        event_viewer : BokehEventViewer
            The BokehEventViewer this object belongs to
        fig : bokeh.plotting.figure
            Figure to store the bokeh plot onto (optional)
        """
        self._event = None
        self._view = 'r0'
        self._telid = None
        self._channel = 0
        self._pixel = 0
        super().__init__(fig=fig)
        self._draw_integration_window()

        self._view_options = {
            'r0': lambda e, t, c, p: e.r0.tel[t].waveform[c, p],
            'r1': lambda e, t, c, p: e.r1.tel[t].waveform[c, p],
            'dl0': lambda e, t, c, p: e.dl0.tel[t].waveform[c, p],
            'cleaned': lambda e, t, c, p: e.dl1.tel[t].cleaned[c, p],
        }

        self.w_view = None

        self.event_viewer = event_viewer

    def _reset(self):
        for wav in self.event_viewer.waveforms:
            wav.pixel = 0

    def _set_waveform(self):
        e = self.event
        v = self.view
        t = self.telid
        c = self.channel
        p = self.pixel
        if not e:
            self.event_viewer.log.warning("No event has been provided")
            return

        tels = list(e.r0.tels_with_data)
        if t is None:
            t = tels[0]
        if t not in tels:
            raise KeyError(f"Telescope {t} has no data")

        try:
            self.waveform = self._view_options[v](e, t, c, p)
            self.fig.title.text = f'{v} (Pixel = {p})'
        except TypeError:
            self.waveform = None

    def _draw_integration_window(self):
        self.intwin1 = Span(location=0, dimension='height',
                            line_color='green', line_dash='dotted')
        self.intwin2 = Span(location=0, dimension='height',
                            line_color='green', line_dash='dotted')
        self.fig.add_layout(self.intwin1)
        self.fig.add_layout(self.intwin2)

    def _set_integration_window(self):
        e = self.event
        t = self.telid
        c = self.channel
        p = self.pixel
        if e:
            if e.dl1.tel[t].extracted_samples is not None:
                # Get Windows
                windows = e.dl1.tel[t].extracted_samples[c, p]
                length = np.sum(windows)
                start = np.argmax(windows)
                end = start + length - 1
                self.intwin1.location = start
                self.intwin2.location = end
        else:
            self.event_viewer.log.warning("No event has been provided")

    def refresh(self):
        self._set_waveform()
        self._set_integration_window()

    @property
    def event(self):
        return self._event

    @event.setter
    def event(self, val):
        self._event = val
        self._set_waveform()
        self._set_integration_window()

    def change_event(self, event, telid):
        if self.event:  # Only reset when an event exists
            self._reset()
        self._telid = telid
        self.event = event

    @property
    def view(self):
        return self._view

    @view.setter
    def view(self, val):
        if val not in list(self._view_options.keys()):
            raise ValueError(f"View is not valid: {val}")
        self._view = val
        self._set_waveform()
        self._set_integration_window()

    @property
    def telid(self):
        return self._telid

    @telid.setter
    def telid(self, val):
        if self.event:  # Only reset when an event exists
            self._reset()
        self._telid = val
        self._set_waveform()
        self._set_integration_window()

    @property
    def channel(self):
        return self._channel

    @channel.setter
    def channel(self, val):
        self._channel = val
        self._set_waveform()
        self._set_integration_window()

    @property
    def pixel(self):
        return self._pixel

    @pixel.setter
    def pixel(self, val):
        self._pixel = val
        self._set_waveform()
        self._set_integration_window()

    def _on_waveform_click(self, time):
        super()._on_waveform_click(time)
        self.event_viewer.change_time(time)

    def create_view_widget(self):
        self.w_view = Select(title="View:", value="", options=[], width=5)
        self.w_view.on_change('value', self.on_view_widget_change)
        self.layout = column([self.w_view, self.layout])

    def update_view_widget(self):
        self.w_view.options = list(self._view_options.keys())
        self.w_view.value = self.view

    def on_view_widget_change(self, _, __, ___):
        if self.view != self.w_view.value:
            self.view = self.w_view.value
Пример #17
0
cities = {
    'Austin': {
        'airport': 'AUS',
        'title': 'Austin, TX',
    },
    'Boston': {
        'airport': 'BOS',
        'title': 'Boston, MA',
    },
    'Seattle': {
        'airport': 'SEA',
        'title': 'Seattle, WA',
    }
}

city_select = Select(value=city, title='City', options=sorted(cities.keys()))
distribution_select = Select(value=distribution, title='Distribution', options=['Discrete', 'Smooth'])

df = pd.read_csv(join(dirname(__file__), 'data/2015_weather.csv'))
source = get_dataset(df, cities[city]['airport'], distribution)
plot = make_plot(source, cities[city]['title'])

city_select.on_change('value', update_plot)
distribution_select.on_change('value', update_plot)

controls = VBox(city_select, distribution_select)

# add to document
curdoc().add_root(HBox(controls, plot))
Пример #18
0
    def modify_doc_dummy(self, symbol):
        print("cmoing in modify_doc_dummy")

        df = self.optionUtility.getProcessedOptionChainData(symbol)
        self.latestData[symbol] = df
        allSources = {}

        def update(attr, old, new):
            selected_expiryDate = expiry_date_selector.value
            # selectedStrikePrice = allUniqueStrikePrice[strikePrice_selector.active];
            activeStrikePriceIndexes = strikePrice_selector.active
            # will take top of selected if number is greater
            activeStrikePriceIndexes.sort()
            # starting one will be selected
            index = 0
            selectedStrikeNumber = activeStrikePriceIndexes.__sizeof__()
            processed = []
            # print(activeStrikePriceIndexes)
            for source in allWorkingSources:
                if (index > (selectedStrikeNumber - 1)):
                    break
                    # in case less number of strike is selected don't through error
                strikeIndex = activeStrikePriceIndexes[index]
                selectedStrikePrice = allUniqueStrikePrice[strikeIndex]
                new_src = 0
                new_src = self.dashboard_tool.make_dataset(
                    int(selectedStrikePrice), selected_expiryDate, symbol,
                    self.isForTodayOnly)
                #
                # if((not (selectedStrikePrice in allSources.keys()))) :
                #     new_src = dashboard_tool.make_dataset(int(selectedStrikePrice), selected_expiryDate, symbol,
                #                                           isForTodayOnly)
                #     allSources[selectedStrikePrice]  = new_src; #save it once processed data base call is saved.. which also requires computing
                # else :
                #     new_src = allSources[selectedStrikePrice]
                source.data.update(new_src.data)
                index = index + 1
                processed.append(selectedStrikePrice)
                # print(selectedStrikePrice) # shown prices are these..
            # print(processed, activeStrikePriceIndexes);

        allUniqueStrikePrice = self.latestData[symbol]['strikePrice'].apply(
            str).unique().tolist()
        ATMStrikeindex = int(np.floor(len(allUniqueStrikePrice) / 2))
        expiry_date_selector = Select(value=self.nearestExpiryDate,
                                      options=self.expiryDates)
        strikePrice_selector = CheckboxButtonGroup(
            labels=allUniqueStrikePrice,
            active=[
                ATMStrikeindex - 2, ATMStrikeindex - 1, ATMStrikeindex,
                ATMStrikeindex + 1, ATMStrikeindex + 2
            ])  # in case multiple to be shown at once#
        # strikePrice_selector = RadioButtonGroup(
        #     labels=allUniqueStrikePrice, active=ATMStrikeindex);
        #
        strikePrice_selector.on_change('active', update)
        expiry_date_selector.on_change('value', update)

        selected_expiryDate = expiry_date_selector.value
        # selectedStrikePrice = allUniqueStrikePrice[strikePrice_selector.active];

        activeStrikePriceIndexes = strikePrice_selector.active
        allplots = []
        allWorkingSources = []
        for oneindex in activeStrikePriceIndexes:
            selectedStrikePrice = allUniqueStrikePrice[oneindex]
            src = self.dashboard_tool.make_dataset(int(selectedStrikePrice),
                                                   selected_expiryDate, symbol,
                                                   self.isForTodayOnly)
            allSources[selectedStrikePrice] = src
            allWorkingSources.append(src)
            p = self.dashboard_tool.make_plot(src, selectedStrikePrice)
            allplots.append(p)
        allplotslayout = column(allplots)
        layout = column(row(expiry_date_selector, strikePrice_selector),
                        allplotslayout)
        tab = Panel(child=layout, title=symbol)
        return tab
Пример #19
0
    ("atomic mass", "@mass"),
    ("electronic configuration", "@electronic"),
]



######### CREATES CROSSFILTER ##########################


# decide if all columns or crossfilter down to sub properties

# The crossfilter widgets

# first select code this crossfilters the available options to 
# available exchanges and elements 
code = Select(title='Code', value='vasp', options=codes)
code.on_change('value', update)


# second select exchange 

element = Select(title='Element', value='Cu', options=_elements)
element.on_change('value', update)

exchange = Select()


# The plotter widgets 

x = Select(title='X-Axis', value='k-point', options=plottables)
x.on_change('value', update)
Пример #20
0
plot_data = ColumnDataSource(dict(time_mid=[0], price_mean=[0], time_left=[0], time_right=[0], price_min=[0], price_max=[0]))

# create a plot and style its properties
fig = figure(width=plot_width, height=plot_height, x_axis_type="datetime", toolbar_location='above', tools="pan,box_zoom,xwheel_zoom,reset,save");
fig.quad(top='price_max', bottom='price_min', left='time_left', right='time_right', source=plot_data, color=Blues3[1])
fig.line(x='time_mid', y='price_mean', source=plot_data, color=Blues3[0]);

# add widgets
title=Div(text="<h1>Stock Price</h1>")
description=Paragraph(text='Type in a symbol or select one from Dow 30 \
and Nasdaq 100, and its price on 5/6/2010 will be plotted shortly. Due to its \
high frequency, the series plotted is downsampled, with the shaded area denoting \
the min/max prices at every time point. Details can be revealed by zoom in with \
tools above the plot.')
symbol_box=TextInput(value='', title='Type Symbol', width=100)
market_select = Select(value='', title='Select ', width=100, options=['', 'Dow 30', 'Nasdaq 100'])
symbol_select = Select(value='', title='Symbol ', width=100, options=[])
button = Button(label="GO", button_type='success', width=100)
progress_bar=PreText()

# add callbacks and interactions
button.callback=CustomJS(code=dims_jscode, args=dict(plot=fig, dims=dims))
button.on_click(button_click)
fig.x_range.on_change('start', update_plot)
#fig.x_range.on_change('end', update_plot)
fig.x_range.callback = CustomJS(code=dims_jscode, args=dict(plot=fig, dims=dims))
market_select.on_change('value', update_symbol_select)
symbol_select.on_change('value', update_symbol_box)

# put the button and plot in a layout and add to the document
doc=curdoc()
Пример #21
0
color = to_color(main_scatter_df)
r=main_scatter_plot.circle('x','y', source=main_scatter_source, radius=0.25, fill_alpha=0.8, color=color)

# calculate context
context_df = df.groupby(['attr_value']).agg({'id':'count'}).rename(columns={'id':'n'})

# setup attribute table
table_df = df[df.attr_name==selected_attribute].groupby(['attr_value']).agg({'id':'count'})
table_df = table_df.sort_values(by='id', ascending=False).rename(columns={'id':'n'})
joined_df = calculate_ratio(table_df)
table_source = ColumnDataSource(joined_df)
table_source_column = [TableColumn(field="attr_value", title="Attribute Value"),TableColumn(field="n", title="Counts"),TableColumn(field="ratio", title="Ratio"),]
table_data_table = DataTable(source=table_source, columns=table_source_column, width=400, height=800)

# setup dropdowns
main_dropdown = Select(title="Chart Attributes", options=attributes_name, value=selected_attribute)
table_dropdown = Select(title="Histogram Attributes", options=attributes_name, value=selected_attribute)

# setup text input
threshold_input = TextInput(value=str(threshold), title="Threshold:")

# setup layout
layout_left = VBox(main_scatter_plot, main_dropdown)
layout_right = VBox(HBox(table_dropdown,threshold_input), table_data_table)
layout = HBox(layout_left,layout_right)

def update_threshold_callback(attr_name, old, new):
    global threshold
    threshold=int(new)
    update_table()
Пример #22
0
# dividing data into gneeral discretes and continuous

columns = sorted(df_obs.columns) #+ sorted(df.columns)
discrete = [x for x in columns if df_obs[x].dtype == object] 

continuous = [x for x in columns if x not in discrete]

####################################################################

##divide data into plottables and non plottables (aggregates or 3D plottables) ,
#keep it to 2D plottables for now, this is known from the column names themselves

plottables =  ['k-point', 'value', 'perc_precisions']

x_select = Select(title='X-Axis', value='k-point', options=plottables)

y_select = Select(title='Y-Axis', value='value', options=plottables)

non_plottables = [ x for x in columns if x not in plottables ] # for aggregates

structures = list(np.unique(df_obs['structure']))
_elements = list(np.unique(df_obs['element']))
#print (_elements)
exchanges = list(np.unique(df_obs['exchange']))
properties = list(np.unique(df_obs['property']))
codes = list(np.unique(df_obs['code']))

# which sets of k-point and value to string together ? any unit transformations on the dataset values or k-point

## have another dataframe (mongo collection) for the reference standards to compute the accuracy (uniquely identified by the element SAME standard should apply to all codes/exchanges/elements.
# Create a new plot: plot
plot = figure()

# Add circles to the plot
plot.circle('x', 'y', source=source)

# Define a callback function: update_plot
def update_plot(attr, old, new):
    # If the new Selection is 'female_literacy', update 'y' to female_literacy
    if new == 'female_literacy': 
        source.data = {
            'x' : fertility,
            'y' : female_literacy
        }
    # Else, update 'y' to population
    else:
        source.data = {
            'x' : fertility,
            'y' : population
        }

# Create a dropdown Select widget: select    
select = Select(title="distribution", options=['female_literacy', 'population'], value='female_literacy')

# Attach the update_plot callback to the 'value' property of select
select.on_change('value', update_plot)

# Create layout and add to current document
layout = row(select, plot)
curdoc().add_root(layout)
    def create_layout(self):

        # create figure
        self.x_range = Range1d(start=self.model.map_extent[0],
                               end=self.model.map_extent[2], bounds=None)
        self.y_range = Range1d(start=self.model.map_extent[1],
                               end=self.model.map_extent[3], bounds=None)

        self.fig = Figure(tools='wheel_zoom,pan',
                          x_range=self.x_range,
                          lod_threshold=None,
                          plot_width=self.model.plot_width,
                          plot_height=self.model.plot_height,
                          y_range=self.y_range)

        self.fig.min_border_top = 0
        self.fig.min_border_bottom = 10
        self.fig.min_border_left = 0
        self.fig.min_border_right = 0
        self.fig.axis.visible = False

        self.fig.xgrid.grid_line_color = None
        self.fig.ygrid.grid_line_color = None

        # add tiled basemap
        self.tile_source = WMTSTileSource(url=self.model.basemap)
        self.tile_renderer = TileRenderer(tile_source=self.tile_source)
        self.fig.renderers.append(self.tile_renderer)

        # add datashader layer
        self.image_source = ImageSource(url=self.model.service_url,
                                        extra_url_vars=self.model.shader_url_vars)
        self.image_renderer = DynamicImageRenderer(image_source=self.image_source)
        self.fig.renderers.append(self.image_renderer)

        # add label layer
        self.label_source = WMTSTileSource(url=self.model.labels_url)
        self.label_renderer = TileRenderer(tile_source=self.label_source)
        self.fig.renderers.append(self.label_renderer)

        # Add a hover tool
        hover_layer = HoverLayer()
        hover_layer.field_name = self.model.field_title
        hover_layer.is_categorical = self.model.field in self.model.categorical_fields
        self.fig.renderers.append(hover_layer.renderer)
        self.fig.add_tools(hover_layer.tool)
        self.model.hover_layer = hover_layer

        self.model.legend_side_vbox = VBox()
        self.model.legend_bottom_vbox = VBox()

        # add ui components
        controls = []
        axes_select = Select.create(name='Axes',
                                    options=self.model.axes)
        axes_select.on_change('value', self.on_axes_change)
        controls.append(axes_select)

        self.field_select = Select.create(name='Field', options=self.model.fields)
        self.field_select.on_change('value', self.on_field_change)
        controls.append(self.field_select)

        self.aggregate_select = Select.create(name='Aggregate',
                                              options=self.model.aggregate_functions)
        self.aggregate_select.on_change('value', self.on_aggregate_change)
        controls.append(self.aggregate_select)

        transfer_select = Select.create(name='Transfer Function',
                                        options=self.model.transfer_functions)
        transfer_select.on_change('value', self.on_transfer_function_change)
        controls.append(transfer_select)

        color_ramp_select = Select.create(name='Color Ramp', options=self.model.color_ramps)
        color_ramp_select.on_change('value', self.on_color_ramp_change)
        controls.append(color_ramp_select)

        spread_size_slider = Slider(title="Spread Size (px)", value=0, start=0,
                                    end=10, step=1)
        spread_size_slider.on_change('value', self.on_spread_size_change)
        controls.append(spread_size_slider)

        hover_size_slider = Slider(title="Hover Size (px)", value=8, start=4,
                                   end=30, step=1)
        hover_size_slider.on_change('value', self.on_hover_size_change)
        controls.append(hover_size_slider)

        controls.append(self.model.legend_side_vbox)

        # add map components
        basemap_select = Select.create(name='Basemap', value='Imagery',
                                       options=self.model.basemaps)
        basemap_select.on_change('value', self.on_basemap_change)

        image_opacity_slider = Slider(title="Opacity", value=100, start=0,
                                      end=100, step=1)
        image_opacity_slider.on_change('value', self.on_image_opacity_slider_change)

        basemap_opacity_slider = Slider(title="Basemap Opacity", value=100, start=0,
                                        end=100, step=1)
        basemap_opacity_slider.on_change('value', self.on_basemap_opacity_slider_change)

        show_labels_chk = CheckboxGroup(labels=["Show Labels"], active=[0])
        show_labels_chk.on_click(self.on_labels_change)

        map_controls = [basemap_select, basemap_opacity_slider,
                        image_opacity_slider, show_labels_chk]

        self.controls = VBox(width=200, height=600, children=controls)
        self.map_controls = HBox(width=self.fig.plot_width, children=map_controls)
        self.map_area = VBox(width=self.fig.plot_width, children=[self.map_controls,
                                                                  self.fig,
                                                                  self.model.legend_bottom_vbox])
        self.layout = HBox(width=1366, children=[self.controls, self.map_area])
Пример #25
0
    new_data['image'] = [img.data]
    new_data['x'] = [x_range[0]]
    new_data['y'] = [y_range[0]]
    new_data['dh'] = [y_range[1] - y_range[0]]
    new_data['dw'] = [x_range[1] - x_range[0]]

    image_source.stream(new_data, 1)


time_select_options = OrderedDict()
time_select_options['1 Hour'] = 60
time_select_options['30 Minutes'] = 30
time_select_options['15 Minutes'] = 15
time_period = list(time_select_options.values())[0]

time_select = Select.create(name="Time Period", options=time_select_options)
time_select.on_change('value', on_time_select_change)

time_text = Paragraph(text='Time Period')

# load nyc taxi data
path = './data/nyc_taxi.csv'
datetime_field = 'tpep_dropoff_datetime'
cols = ['dropoff_x', 'dropoff_y', 'trip_distance', datetime_field]

df = pd.read_csv(path, usecols=cols, parse_dates=[datetime_field]).dropna(axis=0)
times = pd.DatetimeIndex(df[datetime_field])
group_count = grouped = groups = None
bin_data()

# manage client-side dimensions
Пример #26
0
 def create_view_widget(self):
     self.w_view = Select(title="View:", value="", options=[], width=5)
     self.w_view.on_change('value', self.on_view_widget_change)
     self.layout = column([self.w_view, self.layout])
Пример #27
0
                            },
                            line_color='black',
                            line_width=0.35,
                            fill_alpha=1,
                            hover_fill_color="#fec44f")


def handleSelectorChange(attrname, old, new):
    print(attrname, old, new)
    patch = generatePatchBasedOnSelect(selector.value)
    plot.add_tools(
        HoverTool(tooltips=[('Country', '@country'),
                            ('Total Cases', '@total_cases_formatted'),
                            ('Total Deaths', '@total_deaths_formatted')],
                  renderers=[patch]))
    plot.title.text = '%s Plot' % (selector.value)


selectOptions = [
    'Total Cases', 'Total Deaths', 'Total Cases Per Million',
    'Total Deaths Per Million'
]
selector = Select(value=selectOptions[0], options=selectOptions)
selector.on_change('value', handleSelectorChange)

# initialize the plot
init()

layout = column(selector, plot)
curdoc().add_root(layout)
Пример #28
0
    'SpectralClustering',
    'Ward',
    'AgglomerativeClustering',
    'DBSCAN',
    'Birch'
]

datasets_names = [
    'Noisy Circles',
    'Noisy Moons',
    'Blobs',
    'No Structure'
]

algorithm_select = Select(value='MiniBatchKMeans',
                          title='Select algorithm:',
                          options=clustering_algorithms)

dataset_select = Select(value='Noisy Circles',
                        title='Select dataset:',
                        options=datasets_names)

samples_slider = Slider(title="Number of samples",
                        value=1500.0,
                        start=1000.0,
                        end=3000.0,
                        step=100)

clusters_slider = Slider(title="Number of clusters",
                         value=2.0,
                         start=2.0,
Пример #29
0
class CrossFilter(DashboardComponent):
    def __init__(self, worker, **kwargs):
        with log_errors():
            self.worker = worker

            quantities = ['nbytes', 'duration', 'bandwidth', 'count',
                          'start', 'stop']
            colors = ['inout-color', 'type-color', 'key-color']

            # self.source = ColumnDataSource({name: [] for name in names})
            self.source = ColumnDataSource({
                'nbytes': [1, 2],
                'duration': [0.01, 0.02],
                'bandwidth': [0.01, 0.02],
                'count': [1, 2],
                'type': ['int', 'str'],
                'inout-color': ['blue', 'red'],
                'type-color': ['blue', 'red'],
                'key': ['add', 'inc'],
                'start': [1, 2],
                'stop': [1, 2]
            })

            self.x = Select(title='X-Axis', value='nbytes', options=quantities)
            self.x.on_change('value', self.update_figure)

            self.y = Select(title='Y-Axis', value='bandwidth', options=quantities)
            self.y.on_change('value', self.update_figure)

            self.size = Select(title='Size', value='None',
                               options=['None'] + quantities)
            self.size.on_change('value', self.update_figure)

            self.color = Select(title='Color', value='inout-color',
                                options=['black'] + colors)
            self.color.on_change('value', self.update_figure)

            if 'sizing_mode' in kwargs:
                kw = {'sizing_mode': kwargs['sizing_mode']}
            else:
                kw = {}

            self.control = widgetbox([self.x, self.y, self.size, self.color],
                                     width=200, **kw)

            self.last_outgoing = 0
            self.last_incoming = 0
            self.kwargs = kwargs

            self.layout = row(self.control, self.create_figure(**self.kwargs),
                              **kw)

            self.root = self.layout

    @without_property_validation
    def update(self):
        with log_errors():
            outgoing = self.worker.outgoing_transfer_log
            n = self.worker.outgoing_count - self.last_outgoing
            n = min(n, 1000)
            outgoing = [outgoing[-i].copy() for i in range(1, n)]
            self.last_outgoing = self.worker.outgoing_count

            incoming = self.worker.incoming_transfer_log
            n = self.worker.incoming_count - self.last_incoming
            n = min(n, 1000)
            incoming = [incoming[-i].copy() for i in range(1, n)]
            self.last_incoming = self.worker.incoming_count

            out = []

            for msg in incoming:
                if msg['keys']:
                    d = self.process_msg(msg)
                    d['inout-color'] = 'red'
                    out.append(d)

            for msg in outgoing:
                if msg['keys']:
                    d = self.process_msg(msg)
                    d['inout-color'] = 'blue'
                    out.append(d)

            if out:
                out = transpose(out)
                if (len(self.source.data['stop']) and
                        min(out['start']) > self.source.data['stop'][-1] + 10):
                    self.source.data.update(out)
                else:
                    self.source.stream(out, rollover=1000)

    def create_figure(self, **kwargs):
        with log_errors():
            fig = figure(title='', tools='', **kwargs)

            size = self.size.value
            if size == 'None':
                size = 1

            fig.circle(source=self.source, x=self.x.value, y=self.y.value,
                       color=self.color.value, size=10, alpha=0.5,
                       hover_alpha=1)
            fig.xaxis.axis_label = self.x.value
            fig.yaxis.axis_label = self.y.value

            fig.add_tools(
                # self.hover,
                ResetTool(),
                PanTool(),
                WheelZoomTool(),
                BoxZoomTool(),
            )
            return fig

    @without_property_validation
    def update_figure(self, attr, old, new):
        with log_errors():
            fig = self.create_figure(**self.kwargs)
            self.layout.children[1] = fig

    def process_msg(self, msg):
        try:
            def func(k):
                return msg['keys'].get(k, 0)
            main_key = max(msg['keys'], key=func)
            typ = self.worker.types.get(main_key, object).__name__
            keyname = key_split(main_key)
            d = {
                'nbytes': msg['total'],
                'duration': msg['duration'],
                'bandwidth': msg['bandwidth'],
                'count': len(msg['keys']),
                'type': typ,
                'type-color': color_of(typ),
                'key': keyname,
                'key-color': color_of(keyname),
                'start': msg['start'],
                'stop': msg['stop']
            }
            return d
        except Exception as e:
            logger.exception(e)
            raise
Пример #30
0
fs, f = 100, 5
offset, amplitude = 0, 2
phase = 0

# initialize bokeh figure objects for 'trig' data and 'psd' data
props = {'toolbar_location': 'right', 'tools': 'xbox_zoom, undo, redo, reset', 'logo': 'grey', 'width': 500, 'height': 250}
trig = figure(x_range=(0, 1), y_range=(-10, 10), x_axis_label='time, sec', **props)
psd = figure(title='power spectral density', y_axis_type='log', x_axis_label='frequency, Hz', **props)

# initialize glyphs on trig and psd figures as empty data sources
trig.circle('x', 'y', source=ColumnDataSource(data={'x': [], 'y': []}), size=1)
trig.line('x', 'y', source=ColumnDataSource(data={'x': [], 'y': []}), line_width=2)
psd.line('x', 'y', source=ColumnDataSource(data={'x': [], 'y': []}), line_width=3)

# create a Select widget controlling the trig function selection, start a list of widgets
select = Select(title='Trig Function', options=['sin', 'cos'])
select.on_change('value', callback_select)
widgets = [widgetbox(select, width=465)]

# initialize lists of sliders with inc / dec buttons to control trig attributes
controls = [
    [Button(label='-'), Slider(title='Sample Rate', value=fs, start=2, end=400, step=1), Button(label='+')],
    [Button(label='-'), Slider(title='Frequency', value=f, start=1, end=100, step=1), Button(label='+')],
    [Button(label='-'), Slider(title='Offset', value=offset, start=-10, end=10, step=1), Button(label='+')],
    [Button(label='-'), Slider(title='Amplitude', value=amplitude, start=0, end=10, step=1), Button(label='+')],
    [Button(label='-'), Slider(title='Phase', value=phase, start=0, end=6, step=1), Button(label='+')]]

# setup callbacks for controls, update the list of widgets
for control in controls:
    tmp = []
    for c in control:
Пример #31
0
def render_crossfilter(itmdt: Intermediate, plot_width: int, plot_height: int) -> column:
    """
    Render crossfilter scatter plot with a regression line.
    """

    # pylint: disable=too-many-locals, too-many-function-args
    df = itmdt["data"]
    df["__x__"] = df[df.columns[0]]
    df["__y__"] = df[df.columns[0]]
    source_scatter = ColumnDataSource(df)
    source_xy_value = ColumnDataSource({"x": [df.columns[0]], "y": [df.columns[0]]})
    var_list = list(df.columns[:-2])

    xcol = source_xy_value.data["x"][0]
    ycol = source_xy_value.data["y"][0]

    tooltips = [("X-Axis: ", "@__x__"), ("Y-Axis: ", "@__y__")]

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )
    scatter = fig.scatter("__x__", "__y__", source=source_scatter)

    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    fig.add_tools(hover)

    x_select = Select(title="X-Axis", value=xcol, options=var_list, width=150)
    y_select = Select(title="Y-Axis", value=ycol, options=var_list, width=150)

    x_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                x_axis=fig.xaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;

        xyValueData['x'][0] = currentSelect;
        scatterData['__x__'] = scatterData[currentSelect];

        x_axis.axis_label = currentSelect;
        scatter.change.emit();
        xy_value.change.emit();
        """,
        ),
    )
    y_select.js_on_change(
        "value",
        CustomJS(
            args=dict(
                scatter=source_scatter,
                xy_value=source_xy_value,
                y_axis=fig.yaxis[0],
            ),
            code="""
        let currentSelect = this.value;
        let xyValueData = xy_value.data;
        let scatterData = scatter.data;

        xyValueData['y'][0] = currentSelect;
        scatterData['__y__'] = scatterData[currentSelect];

        y_axis.axis_label = currentSelect;
        scatter.change.emit();
        xy_value.change.emit();
        """,
        ),
    )

    fig = column(row(x_select, y_select, align="center"), fig, sizing_mode="stretch_width")
    return fig
Пример #32
0
                    x_axis_label="Year",y_axis_label="Population")
population.line("x", "y", color="violet", line_width=2, source=known, legend="known")
population.line("x", "y", color="violet", line_width=2, line_dash="dashed", source=predicted, legend="predicted")

population.xaxis.major_label_orientation = pi/4
population.xgrid.grid_line_color = None
population.legend.location = "center_right"
population.x_range.end = 2150
population.yaxis.minor_tick_line_color = None
population.yaxis[0].formatter = FuncTickFormatter(code="""
    return (Math.abs(tick) / 1e9) + " B"
""")

# Controls and callbacks

year = Select(title="Year:", value="2010", options=years)
location = Select(title="Location:", value="World", options=locations)

def update():
    age =  df[(df.Location == location.value) & (df.Year == int(year.value))]
    ages.data = ColumnDataSource.from_df(age)

    pop = df[df.Location == location.value].groupby(df.Year).Value.sum()
    new_known = pop[pop.index <= 2010]
    new_predicted = pop[pop.index >= 2010]
    known.data = dict(x=new_known.index.map(str), y=new_known.values)
    predicted.data = dict(x=new_predicted.index.map(str), y=new_predicted.values)

year.on_change('value', lambda attr, old, new: update())
location.on_change('value', lambda attr, old, new: update())
Пример #33
0
#############
# Road Type
#menu_rt = [("Motorway", "motorway"), ("Trunk", "trunk"), 
#                  ("Primary", "primary"), ("Secondary", "secondary"), 
#                  ("Tertiary", "tertiary")]
#dropdown_min_road_type = Dropdown(label="Min Road Type", type="warning",
#                                  menu=menu_rt, default_action="secondary")
#def dropdown_handler_rt(action):
#    print("rt dropdown_handler: %s" % action)
#    global min_road_type
#    #min_road_type = 
#    #session.store_document(document)   
#dropdown_min_road_type.on_click(dropdown_handler_rt)  

select_rt = Select(title="Min Road Type:", value=min_road_type, 
                   options=['Motorway', 'Trunk', 'Primary', 'Secondary',
                            'Tertiary'])

def on_rt_change(obj, attr, old, new):
    print "Min Road:", new
    global min_road_type
    min_road_type = new

select_rt.on_change('value', on_rt_change)
##############

##############
# set max distance from gdelt to osm node
#select_dist = Select(title="Max Node Distance (km):", 
#                     value=str(max_node_dist_km), 
#                     options=['0','1','2','3','4','5','6','7','8','9','10'])
Пример #34
0
def create_figure():
    label = "%s vs %s" % (x.value.title(), y.value.title())
    kdims = [x.value, y.value]

    opts, style = {}, {}
    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)
Пример #35
0
transformer_class_list.remove("TransformerMixin")

transformer_dict = {}
transformers_name = []
for transformer_class in transformer_class_list:
    # Get class
    transformer = getattr(transformers, transformer_class)
    # Get an instance to have the name
    transformer_instance = transformer()
    transformers_name.append(transformer_instance.name)
    # Put the class object in dict
    transformer_dict[transformer_instance.name] = transformer

# Add widgets
select_processing = Select(title="Preprocessing:",
                           value=transformers_name[0],
                           options=transformers_name)
button_add = Button(label="Add", button_type="success")
button_remove = Button(label="Remove")
button_apply = Button(label="Apply")
multi_select = MultiSelect(title="Processing list:", value=[], options=[])
slider_window = Slider(start=3,
                       end=66,
                       value=7,
                       step=2,
                       title="Window Size Savitsky-Golay")
slider_polynomial = Slider(start=1,
                           end=4,
                           value=1,
                           step=1,
                           title="Polynomial Order Savitsky-Golay")