Exemple #1
0
def load_data():
    curdoc().clear()
	
    button_1 = Button(label="Load data")
    button_1.on_click(load_data)



    curdoc().add_root(button_1)
	
    #datapath=filedialog.askopenfilename() 
    datapath=join(dirname(__file__), 'data/Analyte 2.txt'))
	
    global Dsource, Csource, Isource, Ssource, data_new_masked, data3, CX2, CY2, data, YY, XX,SelectedIon, mzlabs
    mz=pd.read_csv(datapath,sep='\t',skiprows=(0,1,2),header=None, nrows=1)
    mz=mz.drop(columns=[0,1,2])

    data = pd.read_csv(datapath,sep='\t',skiprows=(0,1,2,3),header=None)
    Xpixels=data[1].tolist()
    Ypixels=data[2].tolist()

    last=data.columns[-1]
    data = data.drop(data.columns[[0, 1, 2,last-1,last]], axis=1)

    ScanNum=data.index.tolist()

    TotalScan=len(ScanNum)


    mzlabs=mz.loc[0,:].values.tolist()

    data.columns=mzlabs



    data = data.reindex(sorted(data.columns), axis=1)
    mzlabs.sort()

    peakNum=len(mzlabs)

# Work out pixel dimensions- need to do try/ catch here 

    a=Xpixels[1]
    Ypix=Xpixels.count(a)

    Xpix=np.round(TotalScan/Ypix)

    print(Ypix)
    print(Xpix)

# Make sure Ypix * Xpix = total pix 

# Do sum normalisation.. this will have multiple options 

# This is not the real sum normalisation 

    data_new = data.div(data.sum(axis=1), axis=0)

# This is a crude method for clearing background pixels based on lipid vs non-lipid 


    D1=data.iloc[:,0:100]
    D2=data.iloc[:,500:1000]
    D1s = D1.sum(axis=1)
    D2s = D2.sum(axis=1)

    Ratio=D2s/D1s

    Ratio.tolist()


# This may be possible to do with only one copy of the data 


    data2=data
    data2.loc[Ratio<3,:]=0

    data3=data2.loc[~(data2==0).all(axis=1)]

    data_new_masked = data3.div(data3.sum(axis=1), axis=0)
    data_new_masked=data_new_masked.fillna(0)

# Do PCA data reduction 



#Data_reduced=PCA(n_components=10).fit_transform(data_new)
    Data_reduced=PCA(n_components=10).fit_transform(data_new_masked)

# Perform the UMAP - these paramaters will be adjustable


    reducer = umap.UMAP(n_neighbors=10,min_dist=0.1,n_components=2,metric='euclidean')

    embedding = reducer.fit_transform(Data_reduced)

# This can be replaced using the Xpix Ypix from above 


    YY=int(Ypix)
    XX=int(Xpix)

    CX=[]
    for y in range(YY):
        for x in range(XX):
            CX.append(x)
        
    CY=[]

    for y in range(YY):
        for x in range(XX):
            CY.append(y)
		
		
		
    idx=data3.index

    CX2 = [CX[i] for i in idx]
    CY2 = [CY[i] for i in idx]

# This defines the UMAP output as columns for the plotting tools 

    x2=embedding[:, 0]
    y2=embedding[:, 1]    


    x3=x2-np.min(x2)
    y3=y2-np.min(y2)

    scannum= np.arange(0,TotalScan).tolist()
    spectra=scannum

    spectra2 = [spectra[i] for i in idx]

    ColX=(x3/np.max(x3))*255
    ColY=(y3/np.max(y3))*255
    CV1 = ["#%02x%02x%02x" % (int(r), int(g), 0) for r, g in zip(ColX, ColY)]
    CV2 = ["#%02x%02x%02x" % (0, int(r), int(g)) for r, g in zip(ColX, ColY)]
    CV3 = ["#%02x%02x%02x" % (int(r), 0, int(g)) for r, g in zip(ColX, ColY)]


# Create the data sources required 

    Mean1=np.mean(data3) #.iloc[1,:] 

    Blank=[0]*len(CX2)
    BlankMap = ["#%02x%02x%02x" % (0, 0, 0) for r in(ColX)]

    CompData=Mean1/Mean1
    Ssource = ColumnDataSource(data=dict(x=mzlabs,y=Mean1))
    Dsource = ColumnDataSource(data=dict(x=x2, y=y2, cordsX=CX2,cordsY=CY2,CV=CV1,spectra=spectra2))
    Csource = ColumnDataSource(data=dict(x=mzlabs,Region1=Mean1,Region2=Mean1,y=CompData))
    Isource = ColumnDataSource(data=dict(cordsX=CX2,cordsY=CY2,Region1=Blank,Region2=Blank,Map=Blank))



# Set up the plot region (need to define min and max for right plot) 
    TOOLS="lasso_select, box_select,pan,wheel_zoom,box_zoom,reset"


    Right=figure(title="UMAP output",plot_width=500,plot_height=500,x_range=[-15,15], y_range=[-15,15],tools=TOOLS)

    Left=figure(plot_width=500,plot_height=500,title=None,x_range=[0,XX], y_range=[0,YY],tools=TOOLS)
    Left.axis.visible = False
    Results=figure(plot_width=500,plot_height=400,title=None,x_range=[0,1200],tools="pan,box_zoom,reset,tap",x_axis_label='m/z',y_axis_label='log2 fold change')
    Spectrum=figure(plot_width=500,plot_height=400,title=None,x_range=[0,1200],x_axis_label='m/z',y_axis_label='mean intensity')
    SelectedIon=figure(plot_width=300,plot_height=300,title="Selected ion image",title_location = "below",x_range=[0,XX], y_range=[0,YY])
    SelectedIon.axis.visible = False
    Regions=figure(plot_width=200,plot_height=200,title=None,x_range=[0,Xpix], y_range=[0,Ypix],align="center")
    Regions.axis.visible = False


    Results.add_tools(HoverTool(
        tooltips = [
            ("m/z", "@x"),
            ("fold change", "@y"),
        ],
        mode='mouse',
        point_policy='snap_to_data'
    ))

# Populate the initial plots 
    r=Right.scatter(x='x',y='y',fill_color='CV',line_color=None,source=Dsource,radius=0.1)
    Left.square(x='cordsX',y='cordsY',fill_color='CV',line_color=None,alpha=1,size=5, source=Dsource)
#Spectrum.line(x='x',y='y',source=Ssource)
#Results.line(x='x',y='y',source=Csource)
    Spectrum.vbar(x='x',top='y',source=Ssource,width=0.5)
    Results.vbar(x='x',top='y',source=Csource,width=0.5)
    Regions.square(x='cordsX',y='cordsY',fill_color='Map',line_color=None,alpha=1,size=5, source=Isource)

    callback = CustomJS(args=dict(renderer=r), code="""
        renderer.glyph.radius = cb_obj.value;
    """)


    slider1 = Slider(start=0.01, end=1, step=0.01, value=0.1,title='circle size')
    slider1.js_on_change('value', callback)

    #text = TextInput(title="title", value='Insert experiment name')

    button_group = RadioButtonGroup(labels=["Red Green", "Red Blue", "Blue Green"], active=0)
    select = Select(title="Option:", value="foo", options=["No normalisation", "Sum normalisation", "Mean normalisation", "Median normalisation"])
    button_1 = Button(label="Load data")
    button_2 = Button(label="Reset data")
    button_3 = Button(label="Select region 1")
    button_4 = Button(label="Select region 2")
    button_5 = Button(label="Compare")
    button_6 = Button(label="Output report")
	# These are the list of actions possible 

    #text.on_change('value', update_title) 
    button_1.on_click(load_data)
    button_3.on_click(Region_1)
    button_4.on_click(Region_2)
    button_5.on_click(Compare_data)
    Dsource.selected.on_change('indices', update_data)
#taptool = Results.select(type=TapTool)
    Csource.selected.on_change('indices',create_ion_map)


    
    p = gridplot([[Left,Right,column(slider1,select, button_3,button_4,Regions,button_5,button_6)],[Spectrum,Results,SelectedIon]])
    

    curdoc().add_root(p)
    ## draw temporal voltage trace
    s5 = temporalTrace(K_MATCH[I] - 1, TEMP_DT, plth, pltw)
    ## all spatial traces
    s6 = fullTrace(dtSource, plth, pltw, _con)

    output_file("test.html", title="example")
    p = gridplot([[s1, s2, s3], [s4, s5, s6]])
    #p = gridplot([[s1, s2, s3]])
    return p


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


unit = Select(title='Unit', value='0', options=OPT)
unit.on_change('value', update)

contrast = Select(title='Contrast',
                  value='energy',
                  options=['energy', 'accuracy'])
contrast.on_change('value', update)

#controls = widgetbox([x, y, color, size], width=200)
controls = widgetbox([unit, contrast], width=200)

layout = row(controls, create_figure())

curdoc().add_root(layout)
curdoc().title = "Electrode Array and Cells Geometry"
Exemple #3
0
#    src.change.emit();
#    p.change.emit();
#""")

callbackSelectHistParam = CustomJS(code="""
    let val = this.value;
    whichParam = Number(val.slice(-1));
""")

#layout
options = []
#will label as "a0", "a1", etc

select = Select(
    title="Select Model Parameter",
    options=options,
    value="",
)

callbackGenerateDropdown = CustomJS(args=dict(select=select),
                                    code="""
    let options = [];
    for (let m = 0; m < parameters.length - 2; m++){ //excluding slop
        options.push("a" + m.toString());
    }
    select.options = options;
""")

widgets = row(select)
layout = column(widgets, p)
Exemple #4
0
# set up plot (styling in theme.yaml)
plot = figure(toolbar_location=None, title=algorithm)
source = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], colors=colors))
plot.circle('x', 'y', fill_color='colors', line_color=None, source=source)

# set up widgets
clustering_algorithms = [
    'MiniBatchKMeans', 'AffinityPropagation', 'MeanShift',
    'SpectralClustering', 'Ward', 'AgglomerativeClustering', 'DBSCAN', 'Birch'
]

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

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

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

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

clusters_slider = Slider(title="Number of clusters",
    }


def reset():
    source.data = {'total_bsmt_SF': x, 'sale_price': y}


plot = figure(x_axis_label='Total Basement Area (In sqft)',
              y_axis_label='Sales Price')
source = ColumnDataSource(data={'total_bsmt_SF': x, 'sale_price': y})

# Create a slider: slider
slider = Slider(title='Sales Year', start=2006, end=2010, step=1, value=2006)
slider.on_change('value', changeArea)

select = Select(
    title="Sales Condition",
    options=['Normal', 'Abnorml', 'Partial', 'AdjLand', 'Alloca', 'Family'],
    value='Normal')
select.on_change('value', salesCondition)

button = Button(label='Reset Filters')
button.on_click(reset)

# Add a line to the plot
plot.circle('total_bsmt_SF', 'sale_price', source=source)

# Add slider1 and slider2 to a widgetbox
layout = column(widgetbox(slider, select, button), plot)
# Add the plot to the current document
curdoc().add_root(layout)
Exemple #6
0
    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)(plot=opts, style=style)
    plot = renderer.get_plot(points)
    plot.initialize_plot()
    return plot.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)
    plot.y_range.start = min(data[y])
    plot.y_range.end = max(data[y])

    # Add title to plot
    plot.title.text = 'Gapminder data for %d' % yr


# Create a dropdown slider widget: slider
slider = Slider(start=1970, end=2010, step=1, value=1970, title='Year')

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

# Create a dropdown Select widget for the x data: x_select
x_select = Select(options=['fertility', 'life', 'child_mortality', 'gdp'],
                  value='fertility',
                  title='x-axis data')

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

# Create a dropdown Select widget for the y data: y_select
y_select = Select(options=['fertility', 'life', 'child_mortality', 'gdp'],
                  value='life',
                  title='y-axis data')

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

# Create layout and add to current document
layout = row(widgetbox(slider, x_select, y_select), plot)
def create_analysis_chart(metadata, actuals, predictions):
    add_data_to_indexdb(actuals, predictions)
    
    ######################
    # create actuals plot
    actuals_source = ColumnDataSource(dict(id=[], start=[], target=[], ma=[])) # empty

    filtered_predictions = predictions.reset_index(level=1)
    predictions_source = ColumnDataSource(dict(id=[], start=[], **{q:[] for q in quantile_names}))

    # create the plot
    predictions_plot = figure(
        title='', 
        plot_width=800, plot_height=400, 
        x_axis_label='date/time', 
        y_axis_label='pm10 ',
        x_axis_type='datetime',
        y_range= [0, max(predictions['0.5'].max())],
        tools=''
    )

    # plot vertical areas for the quantiles
    predictions_plot.varea_stack(
        stackers=quantile_names, 
        x='start', 
        color= inferno(len(quantiles)), 
        legend_label=quantile_names, 
        source=predictions_source,
        alpha=1,
    )

    # plot actual values
    predictions_plot.line(
        x= "start", y= "target", 
        color= 'red', 
        source= actuals_source
    )
    
    # plot actual values
    predictions_plot.line(
        x= "start", y= "ma", 
        color= 'black', 
        source= actuals_source
    )

    # add a legend
    predictions_plot.legend.items.reverse()
    
    
    #############################
    # Create location selector
    options = metadata.reset_index()[['id', 'country', 'city', 'location']].astype('str').agg('-'.join, axis=1).tolist()
    location_select = Select(title='Select Location:', value=options[0], options=options)
    
    
    ################################
    # Create prediction start slider
    start_min = filtered_predictions.reset_index()['start'].min()
    start_slider = Slider(
        start=0, 
        end= predictions.index.get_level_values(1).unique().max(), 
        value=0, 
        step=1, 
        title=f'prediction time delta'
    )
    
    
    #############################
    # Create javascript callback
    # The javascript callback function connects all the plots and 
    # gui components together so changes will update the plots.
    callback_args=dict(
        actuals= actuals_source, 
        predictions= predictions_source, 
        location_select= location_select, 
        start_slider= start_slider
    )

    with open('javascript/plot_update_callback.js', 'r') as f:
        callback_code = f.read()    
        plot_update_callback = CustomJS(code=callback_code, args=callback_args)
        location_select.js_on_change('value', plot_update_callback)
        start_slider.js_on_change('value', plot_update_callback)
                                                                   
    return column(location_select, predictions_plot, start_slider) 
Exemple #9
0
    def __init__(self, server, doc=None, **kwargs):
        if doc is not None:
            self.doc = weakref.ref(doc)
            try:
                self.key = doc.session_context.request.arguments.get(
                    "key", None)
            except AttributeError:
                self.key = None
            if isinstance(self.key, list):
                self.key = self.key[0]
            if isinstance(self.key, bytes):
                self.key = self.key.decode()
            self.task_names = ["All", self.key]
        else:
            self.key = None
            self.task_names = ["All"]

        self.server = server
        self.start = None
        self.stop = None
        self.ts = {"count": [], "time": []}
        self.state = profile.create()
        data = profile.plot_data(self.state, profile_interval)
        self.states = data.pop("states")
        self.profile_plot, self.source = profile.plot_figure(data, **kwargs)

        changing = [False]  # avoid repeated changes from within callback

        @without_property_validation
        def cb(attr, old, new):
            if changing[0]:
                return
            with log_errors():
                if isinstance(new, list):  # bokeh >= 1.0
                    selected = new
                else:
                    selected = new["1d"]["indices"]
                try:
                    ind = selected[0]
                except IndexError:
                    return
                data = profile.plot_data(self.states[ind], profile_interval)
                del self.states[:]
                self.states.extend(data.pop("states"))
                changing[0] = True  # don't recursively trigger callback
                self.source.data.update(data)
                if isinstance(new, list):  # bokeh >= 1.0
                    self.source.selected.indices = old
                else:
                    self.source.selected = old
                changing[0] = False

        if BOKEH_VERSION >= "1.0.0":
            self.source.selected.on_change("indices", cb)
        else:
            self.source.on_change("selected", cb)

        self.ts_source = ColumnDataSource({"time": [], "count": []})
        self.ts_plot = figure(title="Activity over time",
                              height=100,
                              x_axis_type="datetime",
                              active_drag="xbox_select",
                              y_range=[0, 1 / profile_interval],
                              tools="xpan,xwheel_zoom,xbox_select,reset",
                              **kwargs)
        self.ts_plot.line("time", "count", source=self.ts_source)
        self.ts_plot.circle("time",
                            "count",
                            source=self.ts_source,
                            color=None,
                            selection_color="orange")
        self.ts_plot.yaxis.visible = False
        self.ts_plot.grid.visible = False

        def ts_change(attr, old, new):
            with log_errors():
                try:
                    selected = self.ts_source.selected.indices
                except AttributeError:
                    selected = self.ts_source.selected["1d"]["indices"]
                if selected:
                    start = self.ts_source.data["time"][min(selected)] / 1000
                    stop = self.ts_source.data["time"][max(selected)] / 1000
                    self.start, self.stop = min(start, stop), max(start, stop)
                else:
                    self.start = self.stop = None
                self.trigger_update(update_metadata=False)

        if BOKEH_VERSION >= "1.0.0":
            self.ts_source.selected.on_change("indices", ts_change)
        else:
            self.ts_source.on_change("selected", ts_change)

        self.reset_button = Button(label="Reset", button_type="success")
        self.reset_button.on_click(lambda: self.update(self.state))

        self.update_button = Button(label="Update", button_type="success")
        self.update_button.on_click(self.trigger_update)

        self.select = Select(value=self.task_names[-1],
                             options=self.task_names)

        def select_cb(attr, old, new):
            if new == "All":
                new = None
            self.key = new
            self.trigger_update(update_metadata=False)

        self.select.on_change("value", select_cb)

        self.root = column(
            row(
                self.select,
                self.reset_button,
                self.update_button,
                sizing_mode="scale_width",
            ), self.profile_plot, self.ts_plot, **kwargs)
Exemple #10
0
    def create_widget(self):
        # Button - Launch Cybathlon game in new window
        self.button_launch_game = Button(label='Launch Game',
                                         button_type='primary')
        self.button_launch_game.on_click(self.on_launch_game_start)

        # Toggle - Connect to LSL stream
        self.button_lsl = Toggle(label='Connect to LSL')
        self.button_lsl.on_click(self.on_lsl_connect_toggle)

        # Toggle - Start/stop LSL stream recording
        self.button_record = Toggle(label='Start Recording',
                                    button_type='primary')
        self.button_record.on_click(self.on_lsl_record_toggle)

        # Select - Choose pre-trained model
        self.select_model = Select(title="Select pre-trained model",
                                   value='AUTOPLAY',
                                   options=self.available_models)
        self.select_model.on_change('value', self.on_model_change)

        # Select - Choose port to send events to
        self.select_port = Select(title='Select port')
        self.select_port.options = self.available_ports
        self.select_port.on_change('value', self.on_select_port)

        # Checkbox - Choose player settings
        self.div_settings = Div(text='<b>Settings</b>', align='center')
        self.checkbox_settings = CheckboxButtonGroup(labels=['Show signal',
                                                             'Send events'])
        self.checkbox_settings.on_change('active', self.on_settings_change)

        # Select - Channel to visualize
        self.select_channel = Select(title='Select channel', value='1 - Fp1')
        self.select_channel.on_change('value', self.on_channel_change)

        # Plot - LSL EEG Stream
        self.plot_stream = figure(title='Temporal EEG signal',
                                  x_axis_label='Time [s]',
                                  y_axis_label='Amplitude',
                                  plot_height=500,
                                  plot_width=800,
                                  visible=False)
        self.plot_stream.line(x='ts', y='eeg', source=self.channel_source)

        # Plot - Chronogram prediction vs results
        self.plot_chronogram = figure(title='Chronogram',
                                      x_axis_label='Time [s]',
                                      y_axis_label='Action',
                                      plot_height=300,
                                      plot_width=800)
        self.plot_chronogram.line(x='ts', y='y_true', color='blue',
                                  source=self.chrono_source,
                                  legend_label='Groundtruth')
        self.plot_chronogram.cross(x='ts', y='y_pred', color='red',
                                   source=self.chrono_source,
                                   legend_label='Prediction')
        self.plot_chronogram.legend.background_fill_alpha = 0.6
        self.plot_chronogram.yaxis.ticker = list(self.pred_decoding.keys())
        self.plot_chronogram.yaxis.major_label_overrides = self.pred_decoding

        # Div - Display useful information
        self.model_info = Div(text=f'<b>Model:</b> AUTOPLAY')
        self.pred_info = Div()
        self.gd_info = Div()
        self.acc_info = Div()

        # Create layout
        column1 = column(self.button_launch_game, self.button_lsl,
                         self.button_record, self.select_model,
                         self.select_port, self.select_channel,
                         self.div_settings, self.checkbox_settings)
        column2 = column(self.plot_stream, self.plot_chronogram)
        column3 = column(self.model_info, self.gd_info,
                         self.pred_info, self.acc_info)
        return row(column1, column2, column3)
Exemple #11
0
btn_chairstand = Button(label="Mark Chairstand",
                        button_type="success",
                        width=50)
btn_clear_selection = Button(label="Clear Selection",
                             button_type="success",
                             width=50)

btn_3m_walk = Button(label="Mark 3 m walk", button_type="success", width=50)

btn_export = Button(label="Export annotations",
                    button_type="success",
                    width=50)

file_picker = Select(value=lst_fnames[0],
                     title='Select a file',
                     options=sorted(lst_fnames))

### Dashboard init

srs, colsource = get_filedata(lst_fnames[0])
p, select = make_plot(srs, colsource, file_picker.value)

range_tool = RangeTool(x_range=p.x_range)
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
select.add_tools(range_tool)
select.toolbar.active_multi = range_tool

### Callbacks
Exemple #12
0
            x_range=p.x_range,
            tools="xpan,xwheel_zoom,xbox_zoom,reset")
p2.line(x='time', y='macd', color='red', source=source)
p2.line(x='time', y='macd9', color='blue', source=source)
p2.segment(x0='time',
           y0=0,
           x1='time',
           y1='macdh',
           line_width=6,
           color='black',
           alpha=0.5,
           source=source)

mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001)
stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01)
mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26])

curdoc().add_root(
    VBox(HBox(mean, stddev, mavg, width=800), GridPlot(children=[[p], [p2]])))


def _create_prices(t):
    last_average = 100 if t == 0 else source.data['average'][-1]
    returns = asarray(lognormal(mean.value, stddev.value, 1))
    average = last_average * cumprod(returns)
    high = average * exp(abs(gamma(1, 0.03, size=1)))
    low = average / exp(abs(gamma(1, 0.03, size=1)))
    delta = high - low
    open = low + delta * uniform(0.05, 0.95, size=1)
    close = low + delta * uniform(0.05, 0.95, size=1)
    return open[0], high[0], low[0], close[0], average[0]
Exemple #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[3],
                               end=self.model.map_extent[1], bounds=None)
        self.fig = Figure(tools='wheel_zoom,pan,save,box_zoom', title='Color Magnitude Diagram',
                          x_range=self.x_range,
                          y_range=self.y_range,
                          lod_threshold=None,
                          plot_width=self.model.plot_width,
                          plot_height=self.model.plot_height,
                          background_fill_color='white')

        # Labeling will be used to deal with the fact that we cannot get the axes right 
        # this source can then be adjusted with sliders as necessary to reset axis. 
        label_source = ColumnDataSource(data={'x': [-5,-5,-5,-5,-5], 
                                        'y': [-10-0.2,-5-0.2,0-0.2,5-0.2,10-0.2], 'text':['10','5','0','-5','-10']}) 
        label1 = self.fig.text('x','y','text', source=label_source, text_font_size='8pt', text_color='deepskyblue') 

        # edit all the usual bokeh figure properties here 
        self.fig.xaxis.axis_label=self.model.xtitle 
        self.fig.yaxis.axis_label=self.model.ytitle 
        self.fig.yaxis.axis_label_text_font= 'PT Serif' 
        self.fig.yaxis.major_label_text_font = 'PT Serif' 
        self.fig.xaxis.axis_label_text_font= 'PT Serif' 
        self.fig.xaxis.major_label_text_font = 'PT Serif' 
        self.fig.min_border_top = 20
        self.fig.min_border_bottom = 10
        self.fig.min_border_left = 10
        self.fig.min_border_right = 10
        self.fig.axis.visible = False # use this to flip the axis labeling on and off 
        self.fig.xgrid.grid_line_color = '#aaaaaa' 
        self.fig.ygrid.grid_line_color = '#aaaaaa' 
        self.fig.ygrid.grid_line_alpha = 0.1  
        self.fig.xgrid.grid_line_alpha = 0.1  

        # add tiled basemap to class AppView 
        image_url    = 'http://server.arcgisonline.com/arcgis//rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.png' 
        self.tile_source = WMTSTileSource(url=image_url) 
        self.tile_renderer = TileRenderer(tile_source=self.tile_source)
        self.tile_renderer.alpha = 0.02 
        self.fig.renderers.append(self.tile_renderer) # comment this out and it takes the ds points with it! WHY? 

        # add datashader layer - these are the aggregated data points to class AppView 
        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.image_renderer.alpha = 1.00 
        self.fig.renderers.append(self.image_renderer)

        # add controls 
        controls = []            # empty list for astronomy controls 
        visual_controls = []     # empty list for visual controls 
        self.parameters = {}     # empty dict for astrophyscal pars 

        age_slider = Slider(title="Log Age [Gyr]", value=9.0, start=5.5, end=10.1, step=0.05)
        age_slider.on_change('value', self.on_age_change)
        controls.append(age_slider)
        self.parameters['age'] = age_slider.value 

        aperture_size_slider = Slider(title="Aperture [m]", value=10, start=2,end=20, step=1)
        aperture_size_slider.on_change('value', self.on_aperture_size_change)
        controls.append(aperture_size_slider)
        self.parameters['aperture'] = aperture_size_slider.value 

        exposure_time_slider = Slider(title="Exposure Time [hr]", value=0.1, start=1.0,end=10.0, step=0.1)
        exposure_time_slider.on_change('value', self.on_exposure_time_change)
        controls.append(exposure_time_slider)

        distance_slider = Slider(title="Distance [kpc]", value=100. , start=10.0,end=1000.0, step=100.)
        distance_slider.on_change('value', self.on_distance_change)
        controls.append(distance_slider)

        axes_select = Select(title='Variables', options=list(self.model.axes.keys()))
        axes_select.on_change('value', self.on_axes_change)
        controls.append(axes_select)

        self.field_select = Select(title='Field', options=list(self.model.fields.keys()))
        self.field_select.on_change('value', self.on_field_change)
        #controls.append(self.field_select) - chooses wich field to weight by in aggregation, temporarily omitted for devel 

        self.aggregate_select = Select(title='Aggregate', options=list(self.model.aggregate_functions.keys()))
        self.aggregate_select.on_change('value', self.on_aggregate_change)
        controls.append(self.aggregate_select)

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

        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)
        visual_controls.append(image_opacity_slider) 

        transfer_select = Select(title='Transfer Function', options=list(self.model.transfer_functions.keys()))
        transfer_select.on_change('value', self.on_transfer_function_change)
        visual_controls.append(transfer_select)

        color_ramp_select = Select(title='Colormap', name='Color Ramp', options=list(self.model.color_ramps.keys()))
        color_ramp_select.on_change('value', self.on_color_ramp_change)
        visual_controls.append(color_ramp_select)

        astro_tab = Panel(child=Column(children=controls), title='Stars') 
        visual_tab = Panel(child=Column(children=visual_controls), title='Visuals', width=450)

        self.controls = Tabs(tabs=[astro_tab, visual_tab], width=350)

        self.map_area = Column(width=900, height=600,children=[self.fig])
        self.layout = Row(width=1300, height=600,children=[self.controls, self.fig])
        self.model.fig = self.fig    # identify the fig defined here as the one that will be passed to AppView 
Exemple #14
0
    p.xaxis.formatter = DatetimeTickFormatter(
        hours=["%d %B %Y"],
        days=["%d %B %Y"],
        months=["%d %B %Y"],
        years=["%d %B %Y"],
    )
    p.xaxis.major_label_orientation = math.pi / 2
    p.yaxis.axis_label = '# Cases'
    return p


source = make_dataset(lenght_for_forecast=10, country='Germany')
p = make_plot(source)
show(p)

country_ = Select(title="Option:", value="Spain", options=country_list)
variable_ = Select(title="Option:", value="cases", options=variable_list)
lenght_for_forecast_ = Slider(start=1,
                              end=10,
                              value=3,
                              step=1,
                              title="# forecast periods")


# Update function takes three default parameters
def update(attrname, old, new):
    variable = variable_.value
    lenght_for_forecast = lenght_for_forecast_.value
    country = country_.value
    # Updating everythin for user
    data_ = data[data['countriesAndTerritories'] == country].copy()
from module_selection import COUNTRIES_INDEX
from datetime import datetime

### Valeur par défaut
country = "Belgium"
nbCluster = "3"
selected_cluster = "1"
nb_ind = "4"
type_date = "All"
metric_init = "DTW"
transf_init = "None"

### Widgets
# Panel 1
widget_country = Select(title="Country :",
                        value=country,
                        options=sorted(COUNTRIES_INDEX),
                        width=170)
div_part1 = Div(text="""
                <h2> Global visualization </h2>
                Select the country of your choice and the desired range on the bottom graph.""",
                width=900)

# Panel 2
# Plot 1
widget_country_2 = Select(title="Country",
                          value=country,
                          options=sorted(COUNTRIES_INDEX),
                          width=170)
widget_nb_clusters = Select(title="Number of clusters",
                            value=nbCluster,
                            options=["3", "4", "5"],
Exemple #16
0
       line_dash="4 4")

callback = CustomJS(args=dict(source=source, osds=osds),
                    code="""
    var data = source.data;
    var f = cb_obj.value
    var y = data['y']
    var x = data['x']
    for (var i = 0; i < x.length; i++) {
        y[i] = osds[f][x[i]]["total_ops"]
    }
    source.change.emit();
""")

menu = get_osdlist(osds)
select = Select(title="choose osd", value="osd.0", options=menu)
select.js_on_change("value", callback)

mid_ops = get_mid_ops(osds)
# To do, use javascript to calculate the mid value instead of python
callback_button = CustomJS(args=dict(source=source, mid_ops=mid_ops),
                           code="""
    var data = source.data;
    var y = data['y']
    var x = data['x']
    for (var i = 0; i < x.length; i++) {
        y[i] = mid_ops[i]
    }
    source.change.emit();

""")
Exemple #17
0
# Create a ColumnDataSource from df: source
company_list = ['AMCR', 'APD', 'AVY', 'ALB', 'BLL', 'CF']
n = len(company_list)


@lru_cache()
def get_data(company):
    dtf = data[data.Symbol == company].set_index('date')
    for name, color in zip(company_list, turbo(n)):
        if name == company:
            dtf['color'] = color
    return dtf


# set up widgets widgets
ticker = Select(value='AMCR', options=company_list, title="Company:")
range_slider = DateRangeSlider(start=startdate,
                               end=enddate,
                               value=(startdate, enddate),
                               step=1,
                               title='Date Range')

# Box selection
box = BoxAnnotation(fill_alpha=0.5,
                    line_alpha=0.5,
                    level='underlay',
                    left=startdate,
                    right=enddate)

# set up plots Main Figure
source = ColumnDataSource(data=dict(date=[],
Exemple #18
0
        fill_color={
            'field': 'color_type',
            'transform': color_mapper
        },
        source=geo_source,
    )

    # information to hover
    hover = HoverTool(tooltips=[('Zip Code', '@ZIP'), ('Has Data',
                                                       '@has_data')])
    p.add_tools(hover)

    # return the handler p to pass updated values to visualization
    return p

zipcode_selection = Select(options=zipcodes_sorted, value=initial_zipcodes)
num_selection = Select(options=['3', '4', '5'], value=str(initial_num))
period_selection = Select(options=['overnight',\
                                   'morning',\
                                   'midday',\
                                   'afternoon',\
                                   'night'], value = initial_period)
category_selection = CheckboxGroup(labels=[' category'], active=[])
# if active = [0], it means there are a total of 1 option, and it is checked;
# if active = [0,1], it means there are a total of 2 options, and they are both checked;

# webpage modules
div_title = Div(text=\
          """<h1><tt>hood2vec</tt> app</h1>"""+\
         "You can access <a href=\"https://github.com/xinliupitt/hood2vec\">source code</a> "+\
         "and <a href=\"https://arxiv.org/abs/1907.11951\">backend data generation</a> of this app. "+\
Exemple #19
0
def produce_graphs(doc, timetool_d, timetool_t, ipm2_d, ipm2_t, ipm3_d,
                   ipm3_t):

    switch_key = 'ipm2'

    b_scatter = Buffer(pd.DataFrame({'timetool_data': []}), length=40000)
    b_IpmAmp = Buffer(pd.DataFrame({'timetool': [], 'ipm': []}), length=1000)
    b_timehistory = Buffer(pd.DataFrame({
        'time': [],
        'correlation': []
    }),
                           length=40000)

    hvScatter = hv.DynamicMap(partial(hv.Points), streams=[b_scatter]).options(
        width=1000, finalize_hooks=[apply_formatter],
        xrotation=45).redim.label(index='Time in UTC')

    hvIpmAmp = hv.DynamicMap(
        partial(hv.Scatter, kdims=['timetool', 'ipm']),
        streams=[b_IpmAmp]).options(width=500).redim.label(time='Time in UTC')

    hvTimeHistory = hv.DynamicMap(
        partial(hv.Scatter, kdims=['time', 'correlation']),
        streams=[b_timehistory
                 ]).options(width=500,
                            finalize_hooks=[apply_formatter],
                            xrotation=45).redim.label(time='Time in UTC')

    layout = (hvIpmAmp + hvTimeHistory + hvScatter).cols(2)

    hvplot = renderer.get_plot(layout, doc)
    cb_id_scatter = None
    cb_id_amp_ipm = None
    cb_id_timehistory = None

    def push_data_scatter(timetool_d, timetool_t, buffer):

        timeStuff = list(timetool_t)
        # Convert time to seconds so bokeh formatter can get correct datetime
        times = [1000 * time for time in timeStuff]

        edgePos = []
        for array in timetool_d:
            edgePos.append(array[1])

        edgePos_data = pd.Series(edgePos, index=times)
        zipped = basic_event_builder(timetool_data=edgePos_data)
        buffer.send(zipped)

    def push_data_amp_ipm(timetool_d, timetool_t, ipm2_d, ipm2_t, ipm3_d,
                          ipm3_t, buffer):

        timeStuff = list(timetool_t)
        # Convert time to seconds so bokeh formatter can get correct datetime
        times = [1000 * time for time in timeStuff]

        tt_d = list(timetool_d)
        tt_t = list(timetool_t)
        i2_d = list(ipm2_d)
        i2_t = list(ipm2_t)
        i3_d = list(ipm3_d)
        i3_t = list(ipm3_t)

        ipmValue = i2_d
        ipmTime = i2_t

        if switch_key == 'ipm2':
            ipmValue = i2_d
            ipmTime = i2_t
        elif switch_key == 'ipm3':
            ipmValue = i3_d
            ipmTime = i3_t

        if len(tt_d) > len(ipmValue):
            tt_d = tt_d[:len(ipmValue)]
            tt_t = tt_t[:len(ipmValue)]
        elif len(tt_d) < len(ipmValue):
            ipmValue = ipmValue[:len(tt_d)]
            ipmTime = ipmTime[:len(tt_d)]

        edgeAmp = []

        for array in tt_d:
            edgeAmp.append(array[2])

        data = pd.DataFrame({'timetool': edgeAmp, 'ipm': ipmValue})

        buffer.send(data)

    def push_data_correlation_time_history(timetool_d, timetool_t, ipm2_d,
                                           ipm2_t, ipm3_d, ipm3_t, buffer):

        timeStuff = list(timetool_t)
        # Convert time to seconds so bokeh formatter can get correct datetime
        times = [1000 * time for time in timeStuff]

        tt_d = list(timetool_d)
        tt_t = list(timetool_t)
        i2_d = list(ipm2_d)
        i2_t = list(ipm2_t)
        i3_d = list(ipm3_d)
        i3_t = list(ipm3_t)

        ipmValue = i2_d
        ipmTime = i2_t

        if switch_key == 'ipm2':
            ipmValue = i2_d
            ipmTime = i2_t
        elif switch_key == 'ipm3':
            ipmValue = i3_d
            ipmTime = i3_t

        if len(tt_d) > len(ipmValue):
            tt_d = tt_d[:len(ipmValue)]
            tt_t = tt_t[:len(ipmValue)]
        elif len(tt_d) < len(ipmValue):
            ipmValue = ipmValue[:len(tt_d)]
            ipmTime = ipmTime[:len(tt_d)]

        edgeAmp = []

        for array in tt_d:
            edgeAmp.append(array[2])

        data = pd.DataFrame({'timetool': edgeAmp, 'ipm': ipmValue})

        data_list = data['timetool'].rolling(window=120).corr(
            other=data['ipm'])

        final_df = pd.DataFrame({
            'time': times[119:],
            'correlation': data_list[119:]
        })

        #print(final_df)

        buffer.send(final_df)

    def switch(attr, old, new):
        """
        Update drop down menu value
        
        """

        nonlocal switch_key, b_timehistory, b_IpmAmp
        switch_key = select.value
        b_timehistory.clear()
        b_IpmAmp.clear()
        print(switch_key)

    select = Select(title='ipm value:', value='ipm2', options=['ipm2', 'ipm3'])
    select.on_change('value', switch)

    cb_id_scatter = doc.add_periodic_callback(
        partial(push_data_scatter,
                timetool_d=timetool_d,
                timetool_t=timetool_t,
                buffer=b_scatter), 1000)

    cb_id_amp_ipm = doc.add_periodic_callback(
        partial(push_data_amp_ipm,
                timetool_d=timetool_d,
                timetool_t=timetool_t,
                ipm2_d=ipm2_d,
                ipm2_t=ipm2_t,
                ipm3_d=ipm3_d,
                ipm3_t=ipm3_t,
                buffer=b_IpmAmp), 1000)

    cb_id_timehistory = doc.add_periodic_callback(
        partial(push_data_correlation_time_history,
                timetool_d=timetool_d,
                timetool_t=timetool_t,
                ipm2_d=ipm2_d,
                ipm2_t=ipm2_t,
                ipm3_d=ipm3_d,
                ipm3_t=ipm3_t,
                buffer=b_timehistory), 1000)

    plot = column(select, hvplot.state)
    doc.add_root(plot)
Exemple #20
0
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)

# Create two dropdown Select widgets: select1, select2
select1 = Select(title='First', options=['A', 'B'], value='A')
select2 = Select(title='Second', options=['1', '2', '3'], value='1')


# Define a callback function: callback
    if new == "hide":
        hide_button.visible = False  # hides the button and adjusts the spacing of objects around it
        #hide_button.disabled = True  # this would still show the button but block it from being used
    if new == "show":
        hide_button.visible = True  # shows the button
        #hide_button.disabled = False # enables the button such that one can click on it again


# button to hide
hide_button = Button(label="now you see me", button_type="success", width=100)

# selection/dropdown whether to display the button or hide it
# value sets the initial choice
# options sets the list of available options
hide_selection = Select(title="display mode:",
                        value="show",
                        options=["show", "hide"])
hide_selection.on_change('value', change_display_mode)  # Python callback

#---------------------------------------------------------------------#

#################################
#          style example        #
#################################

# in very rare cases custom styles might be needed

# requires the folder /templates with /templates/styles.css and /templates/index.html


def change_background_color(attr, old, new):
Exemple #22
0
    def produce_hex(self, context, doc):
        """
        Create hextiles plot
        
        Parameters
        ----------
        
        context = zmq.Context()
            Creates zmq socket to receive data
            
        doc: bokeh.document (I think)
            Bokeh document to be displayed on webpage
        
        """

        # Port to connect to master
        port = 5000
        socket = context.socket(zmq.REQ)

        # MUST BE FROM SAME MACHINE, CHANGE IF NECESSARY!!!
        socket.connect("tcp://localhost:%d" % port)

        # Generate dynamic map
        plot = hv.DynamicMap(gen_hex, streams=[self.streamHex])

        # Use bokeh to render plot
        hvplot = renderer.get_plot(plot, doc)

        socket.send_string("First")
        print("Woof")
        data_dict = socket.recv_pyobj()

        peakDict = data_dict['peakDict']
        peakTSDict = data_dict['peakTSDict']

        self.ipm2_index = len(peakDict['peak_8'])
        self.ipm3_index = len(peakDict['peak_9'])
        self.ebeam_index = len(peakDict['peak_10'])
        self.ipm2TS_index = len(peakTSDict['peak_8_TS'])
        self.ipm3TS_index = len(peakTSDict['peak_9_TS'])
        self.ebeamTS_index = len(peakTSDict['peak_10_TS'])

        def clear():
            """
            "Clear" graphs and particular lists of server instance. Save current index
            and only plot points after that index.

            """
            self.ipm2_index = len(self.ipm2_plot)
            self.ipm3_index = len(self.ipm3_plot)
            self.ebeam_index = len(self.ebeam_plot)
            self.ipm2TS_index = len(self.ipm2TS_plot)
            self.ipm3TS_index = len(self.ipm3TS_plot)
            self.ebeamTS_index = len(self.ebeamTS_plot)

        def push_data():
            """
            Push data into stream to be ploted on hextiles plot

            """

            socket.send_string("Hello")
            print("Oof")

            data_dict = socket.recv_pyobj()

            peakDict = data_dict['peakDict']
            peakTSDict = data_dict['peakTSDict']

            self.ipm2_plot = list(peakDict['peak_8'])
            self.ipm3_plot = list(peakDict['peak_9'])
            self.ebeam_plot = list(peakDict['peak_10'])
            self.ipm2TS_plot = list(peakTSDict['peak_8_TS'])
            self.ipm3TS_plot = list(peakTSDict['peak_9_TS'])
            self.ebeamTS_plot = list(peakTSDict['peak_10_TS'])

            ipm2Data = pd.Series(self.ipm2_plot[self.ipm2_index:],
                                 index=self.ipm2TS_plot[self.ipm2TS_index:])

            ipm3Data = pd.Series(self.ipm3_plot[self.ipm3_index:],
                                 index=self.ipm3TS_plot[self.ipm3TS_index:])

            ebeamData = pd.Series(self.ebeam_plot[self.ebeam_index:],
                                  index=self.ebeamTS_plot[self.ebeamTS_index:])

            zipped = basic_event_builder(ipm2=ipm2Data,
                                         ipm3=ipm3Data,
                                         ebeam=ebeamData)
            data = zipped[['ebeam', self.switch_key]]
            self.paused_list = zipped
            self.streamHex.event(df=data)

        # Because of how the ZMQ pipe works, if you pause it, then the graph is delayed by however
        # long it's paused for (so instead of updating all the missed data at once, it'll try to read
        # each pipe send)
        def play_graph():
            """
            Provide play and pause functionality to the graph

            """

            if startButton.label == '► Play':
                startButton.label = '❚❚ Pause'
                self.callback_id_hex = doc.add_periodic_callback(
                    push_data, 1000)
            else:
                startButton.label = '► Play'
                doc.remove_periodic_callback(self.callback_id_hex)

        def saveFile():
            """
            Save current data plotted to csv file as a pandas.DataFrame

            """

            ipm2Data = pd.Series(self.ipm2_plot[self.ipm2_index:],
                                 index=self.ipm2TS_plot[self.ipm2TS_index:])

            ipm3Data = pd.Series(self.ipm3_plot[self.ipm3_index:],
                                 index=self.ipm3TS_plot[self.ipm3TS_index:])

            ebeamData = pd.Series(self.ebeam_plot[self.ebeam_index:],
                                  index=self.ebeamTS_plot[self.ebeamTS_index:])

            zipped = basic_event_builder(ipm2=ipm2Data,
                                         ipm3=ipm3Data,
                                         ebeam=ebeamData)
            zipped.to_csv('data_class.csv')

        # Need to add function to switch while paused as well

        def switch(attr, old, new):
            """
            Switch hextiles plot when drop down menu value is updated

            """

            self.switch_key = select.value

        def switch_on_pause(attr, old, new):
            """
            Switch hextiles plot even when live plotting is paused

            """

            if startButton.label == '► Play':
                self.streamHex.event(
                    df=self.paused_list[['ebeam', self.switch_key]])

        self.callback_id_hex = doc.add_periodic_callback(push_data, 1000)

        # Create widgets
        clearButton = Button(label='Clear')
        clearButton.on_click(clear)

        saveButton = Button(label='Save')
        saveButton.on_click(saveFile)

        select = Select(title="ipm value:",
                        value="ipm2",
                        options=["ipm2", "ipm3"])
        select.on_change('value', switch)
        select.on_change('value', switch_on_pause)

        startButton = Button(label='❚❚ Pause')
        startButton.on_click(play_graph)

        # Layout
        row_buttons = row([
            widgetbox([startButton, clearButton, saveButton],
                      sizing_mode='stretch_both')
        ])

        plot = layout([[hvplot.state],
                       widgetbox([startButton, clearButton, saveButton],
                                 sizing_mode='stretch_both'),
                       widgetbox([select])])

        doc.title = "Hextiles Graph"
        doc.add_root(plot)
Exemple #23
0
def geoplot(
    gdf_in,
    geometry_column="geometry",
    figure=None,
    figsize=None,
    title="",
    xlabel="Longitude",
    ylabel="Latitude",
    xlim=None,
    ylim=None,
    color="blue",
    colormap=None,
    colormap_uselog=False,
    colormap_range=None,
    category=None,
    dropdown=None,
    slider=None,
    slider_range=None,
    slider_name="",
    show_colorbar=True,
    colorbar_tick_format=None,
    xrange=None,
    yrange=None,
    hovertool=True,
    hovertool_columns=[],
    hovertool_string=None,
    simplify_shapes=None,
    tile_provider="CARTODBPOSITRON_RETINA",
    tile_provider_url=None,
    tile_attribution="",
    tile_alpha=1,
    panning=True,
    zooming=True,
    toolbar_location="right",
    show_figure=True,
    return_figure=True,
    return_html=False,
    legend=True,
    webgl=True,
    **kwargs,
):
    """Doc-String: TODO"""

    # Imports:
    import bokeh.plotting
    from bokeh.plotting import show
    from bokeh.models import (
        HoverTool,
        LogColorMapper,
        LinearColorMapper,
        GeoJSONDataSource,
        WheelZoomTool,
        ColorBar,
        BasicTicker,
        LogTicker,
        Select,
        Slider,
        ColumnDataSource,
    )
    from bokeh.models.callbacks import CustomJS
    from bokeh.models.widgets import Dropdown
    from bokeh.palettes import all_palettes
    from bokeh.layouts import row, column

    # Make a copy of the input geodataframe:
    gdf = gdf_in.copy()

    # Check layertypes:
    if type(gdf) != pd.DataFrame:
        layertypes = []
        if "Point" in str(gdf.geom_type.unique()):
            layertypes.append("Point")
        if "Line" in str(gdf.geom_type.unique()):
            layertypes.append("Line")
        if "Polygon" in str(gdf.geom_type.unique()):
            layertypes.append("Polygon")
        if len(layertypes) > 1:
            raise Exception(
                f"Can only plot GeoDataFrames/Series with single type of geometry (either Point, Line or Polygon). Provided is a GeoDataFrame/Series with types: {layertypes}"
            )
    else:
        layertypes = ["Point"]

    # Get and check provided parameters for geoplot:
    figure_options = {
        "title": title,
        "x_axis_label": xlabel,
        "y_axis_label": ylabel,
        "plot_width": 600,
        "plot_height": 400,
        "toolbar_location": toolbar_location,
        "active_scroll": "wheel_zoom",
        "x_axis_type": "mercator",
        "y_axis_type": "mercator",
    }
    if not figsize is None:
        width, height = figsize
        figure_options["plot_width"] = width
        figure_options["plot_height"] = height
    if webgl:
        figure_options["output_backend"] = "webgl"

    if type(gdf) != pd.DataFrame:
        # Convert GeoDataFrame to Web Mercator Projection:
        gdf.to_crs(epsg=3857, inplace=True)

        # Simplify shapes if wanted:
        if isinstance(simplify_shapes, numbers.Number):
            if layertypes[0] in ["Line", "Polygon"]:
                gdf[geometry_column] = gdf[geometry_column].simplify(simplify_shapes)
        elif not simplify_shapes is None:
            raise ValueError(
                "<simplify_shapes> parameter only accepts numbers or None."
            )

    # Check for category, dropdown or slider (choropleth map column):
    category_options = 0
    if not category is None:
        category_options += 1
        category_columns = [category]
    if not dropdown is None:
        category_options += 1
        category_columns = dropdown
    if not slider is None:
        category_options += 1
        category_columns = slider
    if category_options > 1:
        raise ValueError(
            "Only one of <category>, <dropdown> or <slider> parameters is allowed to be used at once."
        )

    # Check for category (single choropleth plot):
    if category is None:
        pass
    elif isinstance(category, (list, tuple)):
        raise ValueError(
            "For <category>, please provide an existing single column of the GeoDataFrame."
        )
    elif category in gdf.columns:
        pass
    else:
        raise ValueError(
            f"Could not find column '{category}' in GeoDataFrame. For <category>, please provide an existing single column of the GeoDataFrame."
        )

    # Check for dropdown (multiple choropleth plots via dropdown selection):
    if dropdown is None:
        pass
    elif not isinstance(dropdown, (list, tuple)):
        raise ValueError(
            "For <dropdown>, please provide a list/tuple of existing columns of the GeoDataFrame."
        )
    else:
        for col in dropdown:
            if col not in gdf.columns:
                raise ValueError(
                    f"Could not find column '{col}' for <dropdown> in GeoDataFrame. "
                )

    # Check for slider (multiple choropleth plots via slider selection):
    if slider is None:
        pass
    elif not isinstance(slider, (list, tuple)):
        raise ValueError(
            "For <slider>, please provide a list/tuple of existing columns of the GeoDataFrame."
        )
    else:
        for col in slider:
            if col not in gdf.columns:
                raise ValueError(
                    f"Could not find column '{col}' for <slider> in GeoDataFrame. "
                )

        if not slider_range is None:
            if not isinstance(slider_range, Iterable):
                raise ValueError(
                    "<slider_range> has to be a type that is iterable like list, tuple, range, ..."
                )
            else:
                slider_range = list(slider_range)
                if len(slider_range) != len(slider):
                    raise ValueError(
                        "The number of elements in <slider_range> has to be the same as in <slider>."
                    )
                steps = []
                for i in range(len(slider_range) - 1):
                    steps.append(slider_range[i + 1] - slider_range[i])

                if len(set(steps)) > 1:
                    raise ValueError(
                        "<slider_range> has to have equal step size between each elements (like a range-object)."
                    )
                else:
                    slider_step = steps[0]
                    slider_start = slider_range[0]
                    slider_end = slider_range[-1]

    # Check colormap if either <category>, <dropdown> or <slider> is choosen:
    if category_options == 1:
        if colormap is None:
            colormap = blue_colormap
        elif isinstance(colormap, (tuple, list)):
            if len(colormap) > 1:
                pass
            else:
                raise ValueError(
                    f"<colormap> only accepts a list/tuple of at least two colors or the name of one of the following predefined colormaps (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
                )
        elif isinstance(colormap, str):
            if colormap in all_palettes:
                colormap = all_palettes[colormap]
                colormap = colormap[max(colormap.keys())]
            else:
                raise ValueError(
                    f"Could not find <colormap> with name {colormap}. The following predefined colormaps are supported (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
                )
        else:
            raise ValueError(
                f"<colormap> only accepts a list/tuple of at least two colors or the name of one of the following predefined colormaps (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): {list(all_palettes.keys())}"
            )
    else:
        if isinstance(color, str):
            colormap = [color]
        elif color is None:
            colormap = ["blue"]
        else:
            raise ValueError(
                "<color> has to be a string specifying the fill_color of the map glyph."
            )

    # Check xlim & ylim:
    if xlim is not None:
        if isinstance(xlim, (tuple, list)):
            if len(xlim) == 2:
                xmin, xmax = xlim
                for _ in [xmin, xmax]:
                    if not -180 < _ <= 180:
                        raise ValueError(
                            "Limits for x-axis (=Longitude) have to be between -180 and 180."
                        )
                if not xmin < xmax:
                    raise ValueError("xmin has to be smaller than xmax.")

                from pyproj import Transformer

                transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
                xmin = transformer.transform(0, xmin)[0]
                xmax = transformer.transform(0, xmax)[0]
                figure_options["x_range"] = (xmin, xmax)
            else:
                raise ValueError(
                    "Limits for x-axis (=Longitude) have to be of form [xmin, xmax] with values between -180 and 180."
                )
        else:
            raise ValueError(
                "Limits for x-axis (=Longitude) have to be of form [xmin, xmax] with values between -180 and 180."
            )
    if ylim is not None:
        if isinstance(ylim, (tuple, list)):
            if len(ylim) == 2:
                ymin, ymax = ylim
                for _ in [ymin, ymax]:
                    if not -90 < _ <= 90:
                        raise ValueError(
                            "Limits for y-axis (=Latitude) have to be between -90 and 90."
                        )
                if not ymin < ymax:
                    raise ValueError("ymin has to be smaller than ymax.")

                from pyproj import Transformer

                transformer = Transformer.from_crs("epsg:4326", "epsg:3857")
                ymin = transformer.transform(ymin, 0)[1]
                ymax = transformer.transform(ymax, 0)[1]
                figure_options["y_range"] = (ymin, ymax)
            else:
                raise ValueError(
                    "Limits for y-axis (=Latitude) have to be of form [ymin, ymax] with values between -90 and 90."
                )
        else:
            raise ValueError(
                "Limits for y-axis (=Latitude) have to be of form [ymin, ymax] with values between -90 and 90."
            )

    # Create Figure to draw:
    old_layout = None
    if figure is None:
        p = bokeh.plotting.figure(**figure_options)

        # Add Tile Source as Background:
        p = _add_backgroundtile(
            p, tile_provider, tile_provider_url, tile_attribution, tile_alpha
        )

    elif isinstance(figure, type(bokeh.plotting.figure())):
        p = figure
    elif isinstance(figure, type(column())):
        old_layout = figure
        p = _get_figure(old_layout)
    else:
        raise ValueError(
            "Parameter <figure> has to be of type bokeh.plotting.figure or bokeh.layouts.column."
        )

    # Get ridd of zoom on axes:
    for t in p.tools:
        if type(t) == WheelZoomTool:
            t.zoom_on_axis = False

    # Hide legend if wanted:
    legend_input = legend
    if isinstance(legend, str):
        pass
    else:
        legend = "GeoLayer"

    # Define colormapper:
    if len(colormap) == 1:
        kwargs["fill_color"] = colormap[0]

    elif not category is None:
        # Check if category column is numerical:
        if not issubclass(gdf[category].dtype.type, np.number):
            raise NotImplementedError(
                f"<category> plot only yet implemented for numerical columns. Column '{category}' is not numerical."
            )

        field = category
        colormapper_options = {"palette": colormap}
        if not colormap_range is None:
            if not isinstance(colormap_range, (tuple, list)):
                raise ValueError(
                    "<colormap_range> can only be 'None' or a tuple/list of form (min, max)."
                )
            elif len(colormap_range) == 2:
                colormapper_options["low"] = colormap_range[0]
                colormapper_options["high"] = colormap_range[1]
        else:
            colormapper_options["low"] = gdf[field].min()
            colormapper_options["high"] = gdf[field].max()
        if colormap_uselog:
            colormapper = LogColorMapper(**colormapper_options)
        else:
            colormapper = LinearColorMapper(**colormapper_options)
        kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
        if not isinstance(legend, str):
            legend = str(field)

    elif not dropdown is None:
        # Check if all columns in dropdown selection are numerical:
        for col in dropdown:
            if not issubclass(gdf[col].dtype.type, np.number):
                raise NotImplementedError(
                    f"<dropdown> plot only yet implemented for numerical columns. Column '{col}' is not numerical."
                )

        field = dropdown[0]
        colormapper_options = {"palette": colormap}
        if not colormap_range is None:
            if not isinstance(colormap_range, (tuple, list)):
                raise ValueError(
                    "<colormap_range> can only be 'None' or a tuple/list of form (min, max)."
                )
            elif len(colormap_range) == 2:
                colormapper_options["low"] = colormap_range[0]
                colormapper_options["high"] = colormap_range[1]
        else:
            colormapper_options["low"] = gdf[dropdown].min().min()
            colormapper_options["high"] = gdf[dropdown].max().max()
        if colormap_uselog:
            colormapper = LogColorMapper(**colormapper_options)
        else:
            colormapper = LinearColorMapper(**colormapper_options)
        kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
        legend = " " + field

    elif not slider is None:
        # Check if all columns in dropdown selection are numerical:
        for col in slider:
            if not issubclass(gdf[col].dtype.type, np.number):
                raise NotImplementedError(
                    f"<slider> plot only yet implemented for numerical columns. Column '{col}' is not numerical."
                )

        field = slider[0]
        colormapper_options = {"palette": colormap}
        if not colormap_range is None:
            if not isinstance(colormap_range, (tuple, list)):
                raise ValueError(
                    "<colormap_range> can only be 'None' or a tuple/list of form (min, max)."
                )
            elif len(colormap_range) == 2:
                colormapper_options["low"] = colormap_range[0]
                colormapper_options["high"] = colormap_range[1]
        else:
            colormapper_options["low"] = gdf[slider].min().min()
            colormapper_options["high"] = gdf[slider].max().max()
        if colormap_uselog:
            colormapper = LogColorMapper(**colormapper_options)
        else:
            colormapper = LinearColorMapper(**colormapper_options)
        kwargs["fill_color"] = {"field": "Colormap", "transform": colormapper}
        if not isinstance(legend, str):
            legend = "Geolayer"

    # Check that only hovertool_columns or hovertool_string is used:
    if isinstance(hovertool_columns, (list, tuple, str)):
        if len(hovertool_columns) > 0 and hovertool_string is not None:
            raise ValueError(
                "Either <hovertool_columns> or <hovertool_string> can be used, but not both at the same time."
            )
    else:
        raise ValueError(
            "<hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
        )

    if hovertool_string is not None:
        hovertool_columns = "all"

    # Check for Hovertool columns:
    if hovertool:
        if not isinstance(hovertool_columns, (list, tuple)):
            if hovertool_columns == "all":
                hovertool_columns = list(
                    filter(lambda col: col != geometry_column, gdf.columns)
                )
            else:
                raise ValueError(
                    "<hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
                )
        elif len(hovertool_columns) == 0:
            if not category is None:
                hovertool_columns = [category]
            elif not dropdown is None:
                hovertool_columns = dropdown
            elif not slider is None:
                hovertool_columns = slider
            else:
                hovertool_columns = []
        else:
            for col in hovertool_columns:
                if col not in gdf.columns:
                    raise ValueError(
                        f"Could not find columns '{col}' in GeoDataFrame. <hovertool_columns> has to be a list of columns of the GeoDataFrame or the string 'all'."
                    )
    else:
        if category is None:
            hovertool_columns = []
        else:
            hovertool_columns = [category]

    # Reduce DataFrame to needed columns:
    if type(gdf) == pd.DataFrame:
        gdf["Geometry"] = 0
        additional_columns = ["x", "y"]
    else:
        additional_columns = [geometry_column]
    for kwarg, value in kwargs.items():
        if isinstance(value, Hashable):
            if value in gdf.columns:
                additional_columns.append(value)
    if category_options == 0:
        gdf = gdf[list(set(hovertool_columns) | set(additional_columns))]
    else:
        gdf = gdf[
            list(
                set(hovertool_columns) | set(category_columns) | set(additional_columns)
            )
        ]
        gdf["Colormap"] = gdf[field]
        field = "Colormap"

    # Create GeoJSON DataSource for Plot:
    if type(gdf) != pd.DataFrame:
        geo_source = GeoJSONDataSource(geojson=gdf.to_json())
    else:
        geo_source = gdf

    # Draw Glyph on Figure:
    layout = None
    if "Point" in layertypes:
        if "line_color" not in kwargs:
            kwargs["line_color"] = kwargs["fill_color"]
        glyph = p.scatter(
            x="x", y="y", source=geo_source, legend_label=legend, **kwargs
        )

    if "Line" in layertypes:
        if "line_color" not in kwargs:
            kwargs["line_color"] = kwargs["fill_color"]
            del kwargs["fill_color"]
        glyph = p.multi_line(
            xs="xs", ys="ys", source=geo_source, legend_label=legend, **kwargs
        )

    if "Polygon" in layertypes:

        if "line_color" not in kwargs:
            kwargs["line_color"] = "black"

        # Creates from a geoDataFrame with Polygons and Multipolygons a Pandas DataFrame
        # with x any y columns specifying the geometry of the Polygons:
        geo_source = ColumnDataSource(
            convert_geoDataFrame_to_patches(gdf, geometry_column)
        )

        # Plot polygons:
        glyph = p.multi_polygons(
            xs="__x__", ys="__y__", source=geo_source, legend_label=legend, **kwargs
        )

    # Add hovertool:
    if hovertool and (category_options == 1 or len(hovertool_columns) > 0):
        my_hover = HoverTool(renderers=[glyph])
        if hovertool_string is None:
            my_hover.tooltips = [(str(col), "@{%s}" % col) for col in hovertool_columns]
        else:
            my_hover.tooltips = hovertool_string
        p.add_tools(my_hover)

    # Add colorbar:
    if show_colorbar and category_options == 1:
        colorbar_options = {
            "color_mapper": colormapper,
            "label_standoff": 12,
            "border_line_color": None,
            "location": (0, 0),
        }
        if colormap_uselog:
            colorbar_options["ticker"] = LogTicker()

        if colorbar_tick_format:
            colorbar_options["formatter"] = get_tick_formatter(colorbar_tick_format)

        colorbar = ColorBar(**colorbar_options)

        p.add_layout(colorbar, "right")

    # Add Dropdown Widget:
    if not dropdown is None:
        # Define Dropdown widget:
        dropdown_widget = Select(
            title="Select Choropleth Layer", options=list(zip(dropdown, dropdown))
        )

        # Define Callback for Dropdown widget:
        callback = CustomJS(
            args=dict(
                dropdown_widget=dropdown_widget,
                geo_source=geo_source,
                legend=p.legend[0].items[0],
            ),
            code="""

                //Change selection of field for Colormapper for choropleth plot:
                geo_source.data["Colormap"] = geo_source.data[dropdown_widget.value];
                geo_source.change.emit();

                //Change label of Legend:
                legend.label["value"] = " " + dropdown_widget.value;

                            """,
        )
        dropdown_widget.js_on_change("value", callback)

        # Add Dropdown widget above the plot:
        if old_layout is None:
            layout = column(dropdown_widget, p)
        else:
            layout = column(dropdown_widget, old_layout)

    # Add Slider Widget:
    if not slider is None:

        if slider_range is None:
            slider_start = 0
            slider_end = len(slider) - 1
            slider_step = 1

        value2name = ColumnDataSource(
            {
                "Values": np.arange(
                    slider_start, slider_end + slider_step, slider_step
                ),
                "Names": slider,
            }
        )

        # Define Slider widget:
        slider_widget = Slider(
            start=slider_start,
            end=slider_end,
            value=slider_start,
            step=slider_step,
            title=slider_name,
        )

        # Define Callback for Slider widget:
        callback = CustomJS(
            args=dict(
                slider_widget=slider_widget,
                geo_source=geo_source,
                value2name=value2name,
            ),
            code="""

                //Change selection of field for Colormapper for choropleth plot:
                var slider_value = slider_widget.value;
                var i;
                for(i=0; i<value2name.data["Names"].length; i++)
                    {
                    if (value2name.data["Values"][i] == slider_value)
                        {
                         var name = value2name.data["Names"][i];
                         }

                    }
                geo_source.data["Colormap"] = geo_source.data[name];
                geo_source.change.emit();

                            """,
        )
        slider_widget.js_on_change("value", callback)

        # Add Slider widget above the plot:
        if old_layout is None:
            layout = column(slider_widget, p)
        else:
            layout = column(slider_widget, old_layout)

    # Hide legend if user wants:
    if legend_input is False:
        p.legend.visible = False

    # Set click policy for legend:
    p.legend.click_policy = "hide"

    # Set panning option:
    if panning is False:
        p.toolbar.active_drag = None

    # Set zooming option:
    if zooming is False:
        p.toolbar.active_scroll = None

    # Display plot and if wanted return plot:
    if layout is None:
        if old_layout is None:
            layout = p
        else:
            layout = old_layout

    # Display plot if wanted
    if show_figure:
        show(layout)

    # Return as (embeddable) HTML if wanted:
    if return_html:
        return embedded_html(layout)

    # Return plot:
    if return_figure:
        return layout
Exemple #24
0
def update_interactive_plot(attrname, old, new):
    params = params_select.value
    plot.title.text = "Forecast Results for SARIMA " + params
    src = prepare_data(results[params], test_ts)
    source.data.update(src.data)


# load data
file = load('data_clean.z')
test_ts = file['test']

# load models
models = load('Models/sarimas.z')

# create forecasts
f_steps = test_ts.shape[0]
results = {key: models[key].get_forecast(f_steps) for key in models.keys()}

# default plot varaibles
params = list(models.keys())[0]
params_select = Select(value=params,
                       title='SARIMA Type',
                       options=sorted(models.keys()))
source = prepare_data(results[params], test_ts)
plot = create_interactive_plot(source, "Forecast Results for SARIMA " + params)

# controls & dashboard setup
params_select.on_change('value', update_interactive_plot)
curdoc().add_root(row(plot, params_select))
curdoc().title = "SARIMA ANOMALY DETECTOR"
Exemple #25
0
        p.circle(x=xs, y=yd, color=f, size=sz, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5)
        p.line(x=xs, y=yd, color=f, line_width=2, legend = "Thermocouple 4 [degC]")   
    else:
        title = str(y_title)+" [mbar]"
        p.circle(x=xs, y=ys, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5)
        p.line(x=xs, y=ys, color =c, line_width=2, legend = title)
    p.legend.location = "top_left"
    return p


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


#x = Select(title='X-Axis', value='time', options=['time'])
x = Select(title='X-Axis', value="Last 24hrs", options=["Last 24hrs","Last 3 Days","Last Week","Last Month", "Last 3 Months","All Time"])
x.on_change('value', update)

y = Select(title='Y-Axis', value='Pressure Main and LoadLock', options=['Pressure Main','Pressure LoadLock', 'Pressure Main and LoadLock','RoomTemp and Humidity', 'Chamber Temperature'])
y.on_change('value', update)

size = Select(title='Size', value='None', options=['None','1','3','6','9','12','15','18'])
size.on_change('value', update)

color = Select(title='Color', value='None', options=['None','Spectral','RdYlBu','Plasma','Colorblind'])
color.on_change('value', update)

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

curdoc().add_root(layout)
def goals_overview_tab(events_df, match_list, bokeh_attack, bokeh_defence,
                       shirt_mapping):

    import metrica_to_bokeh as mtb
    from bokeh.models import ColumnDataSource, Select, TextInput, Panel, Paragraph
    from bokeh.layouts import row, column, WidgetBox

    def make_dataset(play, event_frame, tracking_attack, tracking_defence):
        if event_frame == "All":
            event = events_df.loc[[(play)]]
        else:
            event = events_df.loc[[(play, int(event_frame))]]

        tracking_frame = event['Start Frame'][0]

        att_frame = tracking_attack.loc[(play, tracking_frame)]
        att_player_frame = att_frame[att_frame['player'] != "ball"]
        att_player_frame['Shirt Number'] = att_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        def_frame = tracking_defence.loc[(play, tracking_frame)]
        def_player_frame = def_frame[def_frame['player'] != "ball"]
        def_player_frame['Shirt Number'] = def_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        ball_frame = att_frame[att_frame['player'] == "ball"]

        event_src = ColumnDataSource(event)
        att_src = ColumnDataSource(att_player_frame)
        def_src = ColumnDataSource(def_player_frame)
        ball_src = ColumnDataSource(ball_frame)

        return event_src, att_src, def_src, ball_src

    def make_plot(event_src, event_frame, att_src, def_src, ball_src):

        events = mtb.plot_bokeh_events(event_src)
        frame = mtb.plot_bokeh_frame(att_src, def_src, ball_src)
        frame = mtb.plot_bokeh_events(event_src, plot=frame)

        return events, frame

    def update(attr, old, new):
        match_selection = match_select.value
        event_selection = event_select.value

        new_event_src, new_att_src, new_def_src, new_ball_src = make_dataset(
            match_selection, event_selection, bokeh_attack, bokeh_defence)
        event_src.data.update(new_event_src.data)
        att_src.data.update(new_att_src.data)
        def_src.data.update(new_def_src.data)
        ball_src.data.update(new_ball_src.data)

    match_select = Select(title="Select Match:",
                          value=match_list[0],
                          options=match_list)
    match_select.on_change('value', update)

    event_select = TextInput(value="1", title="Event:")
    event_select.on_change('value', update)

    # Initial match to plot
    match = 'Liverpool [3] - 0 Bournemouth'
    event_frame = 1

    event_src, att_src, def_src, ball_src = make_dataset(
        match, event_frame, bokeh_attack, bokeh_defence)

    event, frame = make_plot(event_src, event_frame, att_src, def_src,
                             ball_src)
    event.title.text = 'Events'
    event.title.text_font_size = "20px"
    frame.title.text = "Tracking"
    frame.title.text_font_size = "20px"

    # Paragraph for instructions and disclaimers
    instructions = Paragraph(
        text=
        "Select a match from the dropdown list below. Then enter an event number or 'All' to see all events."
    )

    # Layout setup
    control = WidgetBox(row(match_select, event_select))
    plot_layout = row(event, frame)
    layout = column(instructions, column(control, plot_layout))

    tab1 = Panel(child=layout, title='Liverpool Goals')

    return tab1
Exemple #27
0
# Reverse color order so that dark blue is highest COVID-19 cases.
palette = palette[::-1]

# Add hover tool
hover = HoverTool(tooltips=[(
    'Neighborhood', '@Neighborhood'), (
        '# of Positive Cases',
        '@positive_cases'), ('# of Drivers Needed',
                             '@Drivers_Needed'), ('Hospital(s)', '@Hospital')])

# Call the plotting function
p = make_plot(input_field)

# Make a selection object: select
select = Select(title='Select Criteria:',
                value='Number of Positive COVID-19 Cases',
                options=['Number of Drivers Needed'])

select.on_change('value', update_plot)

# Make a column layout of widgetbox(slider) and plot, and add it to the current document
# Display the current document
#layout = column(p, widgetbox(select), widgetbox(slider))
#curdoc().add_root(layout)

# Use the following code to test in a notebook
# Interactive features will not show in notebook
#output_notebook()
#show(p)
Exemple #28
0
from bokeh.io import curdoc
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, Select
from bokeh.plotting import figure

app_dir = dirname(__file__)

if 'demo_data.hdf5' not in os.listdir(app_dir):
    import sys
    sys.path.append(app_dir)
    from create_hdf5 import generate_data
    generate_data(app_dir)


options = ['Gaussian', 'Exponential', 'Chi Square', 'Alpha', 'Beta']
data_select = Select(title="Distribution:", value=options[0],
                     options=options)

source = ColumnDataSource(data=dict(x=[], y=[]))

p = figure(height=600, width=800, title="", toolbar_location=None)
p.line(x="x", y="y", source=source, line_width=2)
p.background_fill_color = "#efefef"


def select_data():
    data_val = data_select.value
    with h5py.File(join(app_dir, 'demo_data.hdf5'), 'r') as f:
        return f[data_val]['x'][:], f[data_val]['pdf'][:]


def update():
Exemple #29
0
def bkapp_page():
   
    ###-----------------------------------------------------------------------###
    ###------------------------PREPARING DATA---------------------------------###
    ### This section contains getting and preparing data for this plot------  ###
    ###-----------------------------------------------------------------------###

    ### Load dataset rat interventions
    bait_interventions_to_save = pd.read_pickle('development/bait_interventions_to_save_pitch_night.pickle')
    ### Load indices of rows for each month for bait dataset
    indices_bait_df = pd.read_pickle('development/indices_bait_df_pitch_night.pickle')    #has 2 columns: 'from_index' and 'to_index'
    ### Load dataset rat sighting
    dataset_sightings_locations_to_save = pd.read_pickle('development/dataset_sightings_locations_to_save_pitch_night.pickle')
    ### Load indices of rows for each month for sightings dataset
    indices_sight_df = pd.read_pickle('development/indices_sight_df_pitch_night.pickle')    #has 2 columns: 'from_index' and 'to_index'

    ### Load dataset by zipcodes
    by_zipcodes_df = pd.read_pickle('development/dataset_by_zipcodes_pitch_night.pickle')
    
    ### PREDICTIONS datasets
    df = pd.read_pickle('development/locations_prediction_df_pitch_night.pickle')
    prophet_fit_all_nyc = pd.read_pickle('development/prophet_fit_all_nyc_pitch_night.pickle')    
    prophet_prediction_all_nyc = pd.read_pickle('development/prophet_prediction_all_nyc_pitch_night.pickle')    
        
    ### Read the nyc map data
    nyc_df = pd.read_pickle('development/nyc_converted_to_save.pickle')
    nyc_by_zips = pd.read_pickle('development/dataset_map_by_zipcodes_pitch_night.pickle')
    zip_hm = pd.read_pickle('development/zip_heatmaps_pitch_night.pickle')


    ### Read existing year-month strings in dataset
    with open('development/timepoints_pitch_night.pickle', "rb") as f:
        timepoints = pickle.load(f)
    timepoints = timepoints[:-1]
    
    ### list of zipcodes in dataset
    with open('development/all_zips.pickle', "rb") as f:
        all_zips = pickle.load(f)
    
    ### Read predicted months
    with open('development/predicted_months_pitch_night.pickle', "rb") as f:
        predicted_months = pickle.load(f)    
    
    ### prepare data for bokeh
    bait_source = ColumnDataSource(bait_interventions_to_save)
    indices_bait_source = ColumnDataSource(indices_bait_df)
    sight_source = ColumnDataSource(dataset_sightings_locations_to_save)
    indices_sight_source = ColumnDataSource(indices_sight_df)
    nyc_source = ColumnDataSource(nyc_df)
    timepoints_cds = ColumnDataSource(pd.DataFrame({'timepoints':timepoints}))
    predicted_months_cds = ColumnDataSource(pd.DataFrame({'predicted_months':predicted_months}))
    by_zipcodes_source = ColumnDataSource(by_zipcodes_df)
    nyc_by_zips_source = ColumnDataSource(nyc_by_zips)
    zip_hm_first = ColumnDataSource(zip_hm.loc[:,['ZIPCODE','x','y','sightings']])
    zip_hm_original = ColumnDataSource(zip_hm)

   
    ### bokeh data source for initial plot rendered:
    first_source_bait = ColumnDataSource(bait_interventions_to_save.iloc[indices_bait_df['from_index'][51]:indices_bait_df['to_index'][51],:])
    first_source_sight = ColumnDataSource(dataset_sightings_locations_to_save.iloc[indices_sight_df['from_index'][51]:indices_sight_df['to_index'][51],:])
    
    
    ###-----------------------------------------------------------------------###
    ###----------------------GRAPHICAL USER INTERFACE-------------------------###
    ### This code defines the Bokeh controls that are used for the user       ###
    ### interface. ---------------------------------------------------------- ### 
    ###-----------------------------------------------------------------------###
    
    ### Initialize plot figure
    p = figure(x_range=(-74.2, -73.7), y_range=(40.53, 40.915), tools= 'box_zoom,pan,save,reset', active_drag="box_zoom",
               min_border_right = 40, min_border_top = 5, min_border_bottom = 5, border_fill_color = "black",
               background_fill_color = "black", toolbar_location="left")
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.visible = False
    p.outline_line_color = "black"
 
    ###-----------------------------------------------------------------------###
    ###------------------------PREDICTED locations----------------------------###
    ###-------------------------heatmap---------------------------------------###
    ###-----------------------------------------------------------------------###
     
    
    colors = ['#000000'] + brewer["Reds"][9]
    binsize = 0.5/80
    hm_source = ColumnDataSource(pd.read_pickle('development/df_mock_pitch_practice.pickle'))    
#     hm_source = ColumnDataSource(df)
    hm_source_original = ColumnDataSource(df)
    ## not nomalized count
    mapper = LinearColorMapper(palette=colors, low=df.rat_count.min(), high=df.rat_count.max())
    prediction_location = p.rect(x="level_0", y="level_1", width=binsize, height=binsize,
           source=hm_source,
           fill_color={'field': 'start', 'transform': mapper},
           line_color=None) 

    ###-----------------------------------------------------------------------###
    ###---------------------------NYC map-------------------------------------###
    ###------------------------and events from data---------------------------###
    ###-----------------------------------------------------------------------###
       
    
    ### Add nyc map
    p.patches('x', 'y', source=nyc_source, color='black', line_width=1, fill_color={'field': 'colors'}, fill_alpha = 0.4)
    
    ### Add my bait points
    baits = p.circle('LONGITUDE', 'LATITUDE', source=first_source_bait, fill_color='#4dc6e0', line_color = '#4dc6e0', line_width=3, line_alpha=0.6, legend="Rat Interventions")
    ### Add my sights points
    sights = p.circle('LONGITUDE', 'LATITUDE', source=first_source_sight, fill_color = '#d96c82',line_color = '#d96c82',line_width=3, line_alpha=0.6, legend="Rat Sightings")
    
    p.legend.location = "top_left"
    p.legend.label_text_color = 'white'
    p.legend.border_line_color = "white"
    p.legend.background_fill_color = "black"
    
    ### Add slider
    date_slider = DateSlider(title="Date", start=dt.date(2010, 1, 1), end=dt.date(2018, 9, 1),value=dt.date(2014, 4, 1), step=1, format = "%B %Y")
        
    ### Add hovers
    bait_hover = HoverTool(tooltips = """
    <div>
        <div>
            <span style="font-size: 14px; font-weight:bold; color: #00BFFF">Location:</span> <span style="font-size: 15px; color: #000000">@HOUSE_NUMBER @STREET_NAME</span><br>
            <span style="font-size: 14px; font-weight:bold; color: #00BFFF;">Zip Code:</span> <span style="font-size: 15px; color: #000000"> @ZIP_CODE </span><br>
            <span style="font-size: 14px; font-weight:bold; color: #00BFFF;">Intervention Date: </span> <span style="font-size: 15px; color: #000000">@Inspection_Date</span><br>
            <span style="font-size: 14px; font-weight:bold; color: #00BFFF;">Intervention Type: </span> <span style="font-size: 15px; color: #000000">@RESULT</span>
        </div>
    </div>
    """, renderers=[baits]) 
    p.add_tools(bait_hover)
    
    sight_hover = HoverTool(tooltips = """
    <div>
        <div>
            <span style="font-size: 14px; font-weight:bold; color: #F08080">Location:</span> <span style="font-size: 15px; color: #000000">@ADDRESS</span><br>
            <span style="font-size: 14px; font-weight:bold; color: #F08080;">Zip Code:</span> <span style="font-size: 15px; color: #000000"> @ZIP_CODE </span><br>
            <span style="font-size: 14px; font-weight:bold; color: #F08080;">Rat Sighting Date: </span> <span style="font-size: 15px; color: #000000">@Sighting_Date</span>
        </div>
    </div>
    """, renderers=[sights])
    p.add_tools(sight_hover)
    
    
    prediction_hover = HoverTool(tooltips = """
    <div>
        <div>
            <span style="font-size: 14px; font-weight:bold; color: #F08080">Longitude:</span> <span style="font-size: 15px; color: #000000">@level_0</span><br>
            <span style="font-size: 14px; font-weight:bold; color: #F08080;">Latitude:</span> <span style="font-size: 15px; color: #000000"> @level_1 </span><br>
            <span style="font-size: 14px; font-weight:bold; color: #F08080;">Predicted monthly sightings: </span> <span style="font-size: 15px; color: #000000">@start</span>
        </div>
    </div>
    """, renderers=[prediction_location])
    p.add_tools(prediction_hover)
    
    
    ### Add a Zip Code selection option
    zip_select = Select(title="Selected Zipcode:", value="all zipcodes", options= all_zips)
    
    
    ###-----------------------------------------------------------------------###
    ###------------------------PLOT of whole----------------------------------###
    ###----------------------city sightings numbers---------------------------###
    ###-----------------------------------------------------------------------###
    
    fit_source = ColumnDataSource(prophet_fit_all_nyc)
    prediction_source = ColumnDataSource(prophet_prediction_all_nyc)

    p_right = figure(title = 'CITY-WIDE MONTHLY PREDICTIONS',tools= 'box_zoom,pan,save,reset', min_border_top = 250, min_border_left = 100, border_fill_color = "black",
               background_fill_color = "black", width = 600, height = 550, active_drag="box_zoom", x_axis_type="datetime")
    
    # interval shading glyph:
    lowerband = prophet_prediction_all_nyc['yhat_lower'].values
    upperband = prophet_prediction_all_nyc['yhat_upper'].values
    band_x = np.append(prophet_prediction_all_nyc['ds'].values, prophet_prediction_all_nyc['ds'].values[::-1])
    band_y = np.append(lowerband, upperband[::-1])
    p_right.patch(band_x, band_y, color='white', fill_alpha=0.5, alpha = 0.5)

    p_right.line(x = 'ds', y = 'y', source = fit_source, color = '#d96c82', line_width=2.6, legend = 'monthly rat sightings')
    p_right.circle(x = 'ds', y = 'y', source = fit_source, color = '#d96c82', size = 7, alpha = 0.5, legend = 'monthly rat sightings')

    p_right.line(x = 'ds', y = 'yhat', source = prophet_fit_all_nyc, line_width=2, color = 'white', legend = 'FBprophet fit/prediction')
    p_right.circle(x = 'ds', y = 'yhat', source = prophet_fit_all_nyc, color = 'white', size = 5, alpha = 0.5, legend = 'FBprophet fit/prediction')
    p_right.line(x = 'ds', y = 'yhat', source = prophet_prediction_all_nyc, line_width=2, color = 'white', line_dash="4 4")
    p_right.circle(x = 'ds', y = 'yhat', source = prophet_prediction_all_nyc, size = 5, color = 'white', alpha = 0.5, line_dash="4 4")

    p_right.line([prophet_fit_all_nyc.iloc[-1,0], prophet_prediction_all_nyc.iloc[0,0]], 
           [prophet_fit_all_nyc.iloc[-1,2], prophet_prediction_all_nyc.iloc[0,1]], line_dash="4 4", 
           line_width=2, color='white')

    p_right.legend.location = "top_left"
    p_right.xaxis.major_label_text_font_size = "14pt"
    p_right.yaxis.major_label_text_font_size = "14pt"
    p_right.title.text_font_size = '16pt'
    p_right.legend.label_text_font_size = '9pt'
    p_right.legend.location = "top_left"
    p_right.xaxis.axis_label = 'Date'
    p_right.yaxis.axis_label = 'monthly rat sightings'
    p_right.xaxis.axis_label_text_font_size = "14pt"
    p_right.yaxis.axis_label_text_font_size = "14pt"
    p_right.xaxis.axis_label_text_color = '#909090'
    p_right.xaxis.axis_line_color = '#909090'
    p_right.xaxis.major_label_text_color = '#909090'
    p_right.yaxis.axis_label_text_color = '#909090'
    p_right.yaxis.axis_line_color = '#909090'
    p_right.yaxis.major_label_text_color = '#909090'
    p_right.title.text_color = '#909090'
    p_right.legend.label_text_color = '#909090'
    p_right.legend.border_line_color = "#909090"
    p_right.outline_line_color = "#909090"
    p_right.legend.background_fill_color = "black"
       
     
    ###-----------------------------------------------------------------------###
    ###----------------------------CALLBACKS----------------------------------###
    ### This section defines the behavior of the GUI as the user interacts    ###
    ### with the controls.  --------------------------------------------------###
    ###-----------------------------------------------------------------------###

    
    ### Slider callback function       
    callback = CustomJS(args=dict(date_slider = date_slider, zip_select = zip_select, first_source_bait = first_source_bait, original_source_bait = bait_source, bait_indices = indices_bait_source, first_source_sight = first_source_sight, original_source_sight = sight_source, hm_source_original = hm_source_original, hm_source = hm_source, sight_indices = indices_sight_source, timepoints_cds = timepoints_cds, predicted_months_cds = predicted_months_cds), code="""
        var date_slider = new Date(date_slider.value);
        var timepoints_cds = timepoints_cds.data;
        var predicted_months_cds = predicted_months_cds.data;
        var zip_selected = parseFloat(zip_select.value);
        
        var data_bait = first_source_bait.data;
        var whole_data_bait = original_source_bait.data;
        var bait_indices = bait_indices.data;
        
        var data_sight = first_source_sight.data;
        var whole_data_sight = original_source_sight.data;
        var sight_indices = sight_indices.data;
        
        var data_hm = hm_source.data;
        var data_hm_original = hm_source_original.data;
                
        const monthNames = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        var year_month = (date_slider.getUTCFullYear()).toString() +'-'+ monthNames[date_slider.getUTCMonth()];
        console.log(year_month)       
        var g = timepoints_cds['timepoints'].indexOf(year_month)
        
        var test = 0;
        data_hm['start'] = [];
        data_hm['level_0'] = [];
        data_hm['level_1'] = [];
        if(predicted_months_cds['predicted_months'].indexOf(year_month) >= 0 ) {
            for (k = 0; k < 80*80; k++) {
                data_hm['start'].push(data_hm_original['predicted_'+ year_month][k])
                data_hm['level_0'].push(data_hm_original['level_0'][k])
                data_hm['level_1'].push(data_hm_original['level_1'][k])
                test = k;
            }                             
         }
        console.log(data_hm['start'][test]) 
         
        data_bait['LONGITUDE'] = []
        data_bait['LATITUDE'] = []
        data_bait['HOUSE_NUMBER'] = []
        data_bait['STREET_NAME'] = []
        data_bait['ZIP_CODE'] = []
        data_bait['Inspection_Date'] = []
        data_bait['RESULT'] = []
        for (i = bait_indices['from_index'][g]; i < bait_indices['to_index'][g] + 1; i++) {
            if(whole_data_bait['ZIP_CODE'][i] == zip_selected || zip_selected == "all zipcodes" || isNaN(zip_selected)) {
                data_bait['LONGITUDE'].push(whole_data_bait['LONGITUDE'][i])
                data_bait['LATITUDE'].push(whole_data_bait['LATITUDE'][i])
                data_bait['HOUSE_NUMBER'].push(whole_data_bait['HOUSE_NUMBER'][i])
                data_bait['STREET_NAME'].push(whole_data_bait['STREET_NAME'][i])
                data_bait['ZIP_CODE'].push(whole_data_bait['ZIP_CODE'][i])
                data_bait['Inspection_Date'].push(whole_data_bait['Inspection_Date'][i])
                data_bait['RESULT'].push(whole_data_bait['RESULT'][i])
            }
        }
        
        data_sight['LONGITUDE'] = []
        data_sight['LATITUDE'] = []
        data_sight['ADDRESS'] = []
        data_sight['ZIP_CODE'] = []
        data_sight['Sighting_Date'] = []
        for (j = sight_indices['from_index'][g]; j < sight_indices['to_index'][g] + 1; j++) {
            if(whole_data_sight['ZIP_CODE'][j] == zip_selected || zip_selected == "all zipcodes" || isNaN(zip_selected)) {
                data_sight['LONGITUDE'].push(whole_data_sight['LONGITUDE'][j])
                data_sight['LATITUDE'].push(whole_data_sight['LATITUDE'][j])
                data_sight['ADDRESS'].push(whole_data_sight['ADDRESS'][j])
                data_sight['ZIP_CODE'].push(whole_data_sight['ZIP_CODE'][j])
                data_sight['Sighting_Date'].push(whole_data_sight['Sighting_Date'][j])
            }
        }
        
        hm_source.change.emit();
        first_source_sight.change.emit();
        first_source_bait.change.emit();
    """)
    
    ### Zip code select callback function       
    zip_callback = CustomJS(args=dict(zip_select = zip_select, nyc_source = nyc_source, date_slider = date_slider, first_source_bait = first_source_bait, original_source_bait = bait_source, bait_indices = indices_bait_source, first_source_sight = first_source_sight, original_source_sight = sight_source, sight_indices = indices_sight_source, timepoints_cds = timepoints_cds), code="""
        var zip_selected = parseFloat(zip_select.value);
        var date_slider = new Date(date_slider.value);
        var timepoints_cds = timepoints_cds.data;
        
        var nyc_source_data = nyc_source.data;
        var zip_color_selected = "black";
        if (zip_selected == "all zipcodes" || isNaN(zip_selected)) {
            zip_color_selected = "white";
        }
        var zip_color_rest = "white";
        
        var data_bait = first_source_bait.data;
        var whole_data_bait = original_source_bait.data;
        var bait_indices = bait_indices.data;
        
        var data_sight = first_source_sight.data;
        var whole_data_sight = original_source_sight.data;
        var sight_indices = sight_indices.data;
        
        nyc_source_data['colors'] = []
        
        for (i = 0; i <nyc_source_data['ZIPCODE'].length; i++) {
            if (nyc_source_data['ZIPCODE'][i] == zip_selected || zip_selected == "all zipcodes" || isNaN(zip_selected)) {
                nyc_source_data['colors'].push(zip_color_selected);
            } else {
                nyc_source_data['colors'].push(zip_color_rest);
            }                                
        }   
                        
        const monthNames = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        var year_month = (date_slider.getUTCFullYear()).toString() +'-'+ monthNames[date_slider.getUTCMonth()];
        console.log(year_month)
        console.log(zip_selected)
        var g = timepoints_cds['timepoints'].indexOf(year_month)
            
        data_bait['LONGITUDE'] = []
        data_bait['LATITUDE'] = []
        data_bait['HOUSE_NUMBER'] = []
        data_bait['STREET_NAME'] = []
        data_bait['ZIP_CODE'] = []
        data_bait['Inspection_Date'] = []
        data_bait['RESULT'] = []
        for (i = bait_indices['from_index'][g]; i < bait_indices['to_index'][g] + 1; i++) {
            if(whole_data_bait['ZIP_CODE'][i] == zip_selected || zip_selected == "all zipcodes" || isNaN(zip_selected)) {
                data_bait['LONGITUDE'].push(whole_data_bait['LONGITUDE'][i])
                data_bait['LATITUDE'].push(whole_data_bait['LATITUDE'][i])
                data_bait['HOUSE_NUMBER'].push(whole_data_bait['HOUSE_NUMBER'][i])
                data_bait['STREET_NAME'].push(whole_data_bait['STREET_NAME'][i])
                data_bait['ZIP_CODE'].push(whole_data_bait['ZIP_CODE'][i])
                data_bait['Inspection_Date'].push(whole_data_bait['Inspection_Date'][i])
                data_bait['RESULT'].push(whole_data_bait['RESULT'][i])
            }
        }
        
        data_sight['LONGITUDE'] = []
        data_sight['LATITUDE'] = []
        data_sight['ADDRESS'] = []
        data_sight['ZIP_CODE'] = []
        data_sight['Sighting_Date'] = []
        for (j = sight_indices['from_index'][g]; j < sight_indices['to_index'][g] + 1; j++) {
            if(whole_data_sight['ZIP_CODE'][j] == zip_selected || zip_selected == "all zipcodes" || isNaN(zip_selected)) {
                data_sight['LONGITUDE'].push(whole_data_sight['LONGITUDE'][j])
                data_sight['LATITUDE'].push(whole_data_sight['LATITUDE'][j])
                data_sight['ADDRESS'].push(whole_data_sight['ADDRESS'][j])
                data_sight['ZIP_CODE'].push(whole_data_sight['ZIP_CODE'][j])
                data_sight['Sighting_Date'].push(whole_data_sight['Sighting_Date'][j])
            }
        }
        
        first_source_sight.change.emit();
        first_source_bait.change.emit();               
        nyc_source.change.emit();
    """)
    
    zip_select.js_on_change('value', zip_callback)
    date_slider.js_on_change('value', callback)
    
    layout = row(column(row(date_slider, zip_select), p), p_right)
#     layout = gridplot([[p, p_right]])
    
    the_script, the_div = components(layout)
    
    
    ###-----------------------------------------------------------------------###
    ###-----------------------------------------------------------------------###
    ###-----------------------BY ZIPCODES PLOT--------------------------------###
    ###-----------------------------------------------------------------------###
    ###-----------------------------------------------------------------------###
    
    
    colors = ['#f27991', '#f493a7', '#f7aebd', 
         '#fce4e9'] + ['#FFFFFF'] + ['#ddf8fd','#ccf4fd', '#bbf1fc','#aaedfc','#99eafb','#88e6fa', '#77e3fa',
                                     '#66dff9', '#56dcf9']
    mapper = LinearColorMapper(palette=colors, low=by_zipcodes_df.dev.min(), high=by_zipcodes_df.dev.max())
    color_bar = ColorBar(color_mapper=mapper, location=(0, 0), label_standoff=10, 
                         major_label_text_font_size='14pt', major_label_text_color = '#909090',
                        background_fill_color = 'black', scale_alpha = 0.7)

    mp = figure(x_range=(-74.2, -73.7), y_range=(40.53, 40.915), width = 600, height =630,
                tools= 'box_zoom,pan,save,reset', active_drag="box_zoom", background_fill_color = "black",
               min_border_right = 40, min_border_top = 5, min_border_bottom = 5, border_fill_color = "black")
    mp.xgrid.grid_line_color = None
    mp.ygrid.grid_line_color = None
    mp.axis.visible = False
    mp.outline_line_color = "black"
    
    zips = mp.patches('x', 'y', source=nyc_by_zips_source, color='black', line_width=1, 
               fill_color={'field': 'dev', 'transform': mapper}, alpha = 0.7)

    zips_hover = HoverTool(tooltips = """
        <div>
            <div>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Zip Code: </span> <span style="font-size: 15px; color: #000000">@ZIPCODE</span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000">Average number of rat sightings per year:</span> <span style="font-size: 15px; color: #000000">@sightings</span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Average number of interventions per year:</span> <span style="font-size: 15px; color: #000000"> @interventions </span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Number of interventions above expectation:</span> <span style="font-size: 15px; color: #000000"> @dev </span>
            </div>
        </div>
        """, renderers=[zips])
    mp.add_tools(zips_hover)


    p_zips = figure(title = 'Sightings and interventions by zipcode',tools= 'box_zoom,pan,save,reset', 
                active_drag="box_zoom", background_fill_color = "black",
                   min_border_right = 40, min_border_top = 5, min_border_bottom = 5, border_fill_color = "black")
    points = p_zips.circle(x = 'sightings', y = 'interventions', source = by_zipcodes_source, size=12, 
             fill_color={'field': 'dev', 'transform': mapper}, alpha = 0.7, line_color = 'black')

    p_zips.line(x = 'sightings', y = 'lin_fit', source = by_zipcodes_source, color = 'white')

    p_zips.add_layout(color_bar, 'left')

    points_hover = HoverTool(tooltips = """
        <div>
            <div>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Zip Code: </span> <span style="font-size: 15px; color: #000000">@ZIP_CODE</span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000">Average number of rat sightings per year:</span> <span style="font-size: 15px; color: #000000">@sightings</span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Average number of interventions per year:</span> <span style="font-size: 15px; color: #000000"> @interventions </span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Number of interventions above expectation:</span> <span style="font-size: 15px; color: #000000"> @dev </span>
            </div>
        </div>
        """, renderers=[points])
    p_zips.add_tools(points_hover)
    p_zips.xaxis.major_label_text_font_size = "14pt"
    p_zips.yaxis.major_label_text_font_size = "14pt"
    p_zips.title.text_font_size = '16pt'
    p_zips.xaxis.axis_label = 'average number of rat sightings per year'
    p_zips.yaxis.axis_label = 'average number of interventions per year'
    p_zips.xaxis.axis_label_text_font_size = "14pt"
    p_zips.yaxis.axis_label_text_font_size = "14pt"
    p_zips.xaxis.axis_label_text_color = '#909090'
    p_zips.xaxis.axis_line_color = '#909090'
    p_zips.xaxis.major_label_text_color = '#909090'
    p_zips.yaxis.axis_label_text_color = '#909090'
    p_zips.yaxis.axis_line_color = '#909090'
    p_zips.yaxis.major_label_text_color = '#909090'
    p_zips.title.text_color = '#909090'

    layout_zips = row(mp,p_zips)
    
    the_script_zips, the_div_zips = components(layout_zips)

       
    ###-----------------------------------------------------------------------###
    ###-----------------------------------------------------------------------###
    ###--------------------------HEATMAPS PLOT--------------------------------###
    ###-------------------------  BY ZIPCODE----------------------------------###
    ###-----------------------------------------------------------------------###
  

    colors_hm = ['#fdf1f4', '#fce4e9', '#fbd6de', '#f9c9d3', '#f8bcc8', 
              '#f7aebd', '#f5a1b2','#f493a7', '#f3869c', '#f27991'] 
    mapper_hm = LinearColorMapper(palette=colors_hm, low=0, high=50)
    hm_color_bar = ColorBar(color_mapper=mapper_hm, location=(0, 0), label_standoff=10, 
                         major_label_text_font_size='14pt', major_label_text_color = '#909090',
                           background_fill_color = 'black', scale_alpha = 0.7)

    heatmap = figure(x_range=(-74.2, -73.7), y_range=(40.53, 40.915), width = 500, height =500,
                tools= 'box_zoom,pan,save,reset', active_drag="box_zoom", background_fill_color = "black",
                     min_border_top = 5, min_border_bottom = 5, border_fill_color = "black",
                    toolbar_location="left")
    heatmap.xgrid.grid_line_color = None
    heatmap.ygrid.grid_line_color = None
    heatmap.axis.visible = False
    heatmap.outline_line_color = "black"

    zips_hm = heatmap.patches('x', 'y', source=zip_hm_first, color='black', line_width=1, 
               fill_color={'field': 'sightings', 'transform': mapper_hm}, alpha = 0.7)

    zips_hm_hover = HoverTool(tooltips = """
        <div>
            <div>
                <span style="font-size: 14px; font-weight:bold; color: #000000;">Zip Code: </span> <span style="font-size: 15px; color: #000000">@ZIPCODE</span><br>
                <span style="font-size: 14px; font-weight:bold; color: #000000">Number of sightings this month:</span> <span style="font-size: 15px; color: #000000">@sightings</span><br>
            </div>
        </div>
        """, renderers=[zips_hm])
    heatmap.add_tools(zips_hm_hover)

    dummy = figure(height=500, width=150, toolbar_location=None, min_border=0, outline_line_color=None,
                  background_fill_color = "black",
                     min_border_top = 5, min_border_bottom = 5, border_fill_color = "black")
    dummy.add_layout(hm_color_bar, 'right')

    ### Add slider
    date_slider_hm = DateSlider(title="Date", start=dt.date(2010, 1, 1), end=dt.date(2018, 4, 1),value=dt.date(2014, 7, 1), step=1, format = "%B %Y")

    ### Slider callback function       
    hm_callback = CustomJS(args=dict(date_slider = date_slider_hm,
                                  zip_hm_first = zip_hm_first, zip_hm_original = zip_hm_original), 
                        code="""
        var date_slider = new Date(date_slider.value);

        var data_hm = zip_hm_first.data;
        var data_hm_original = zip_hm_original.data;

        const monthNames = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        var year_month = (date_slider.getUTCFullYear()).toString() +'-'+ monthNames[date_slider.getUTCMonth()];
        console.log(year_month)       

        var test = 0;
        data_hm['sightings'] = [];
        for (k = 0; k < 263; k++) {
            data_hm['sightings'].push(data_hm_original[year_month][k])
        }                             

        zip_hm_first.change.emit();

    """)

    date_slider_hm.js_on_change('value', hm_callback)

    layout_hm = column(date_slider_hm,row(heatmap, dummy))
    
    the_script_hm, the_div_hm = components(layout_hm)


    
    return render_template('myindex-pitch-night.html', div = the_div, script=the_script, 
                           the_script_zips = the_script_zips, the_div_zips = the_div_zips,
                          the_script_hm = the_script_hm, the_div_hm = the_div_hm)   
Exemple #30
0
                        value=475000,
                        step=1)
min_cntr_area = Slider(title="Minimum country size (km2)",
                       start=0,
                       end=10375000,
                       value=0,
                       step=1)
max_cntr_area = Slider(title="Maximum country size (km2)",
                       start=0,
                       end=10375000,
                       value=10375000,
                       step=1)
continent = TextInput(title="Continent:")
income_group = TextInput(title="World Bank Income Group:")
x_axis = Select(title="X Axis",
                options=sorted(axis_map.keys()),
                value="log(Size Country/Total Edge Length)")
y_axis = Select(title="Y Axis",
                options=sorted(axis_map.keys()),
                value="Maximum 10% Isolated")

# Create Column Data Source that will be used by the plot
source = ColumnDataSource(
    data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[], alpha=[]))

TOOLTIPS = [("Country", "@title")]

p = figure(plot_height=300,
           plot_width=700,
           title="",
           toolbar_location=None,