Esempio n. 1
0
def layout_padding(plots):
    """
    Temporary workaround to allow empty plots in a
    row of a bokeh GridPlot type. Should be removed
    when https://github.com/bokeh/bokeh/issues/2891
    is resolved.
    """
    widths, heights = defaultdict(int), defaultdict(int)
    for r, row in enumerate(plots):
        for c, p in enumerate(row):
            if p is not None:
                width = p.plot_width if isinstance(p, Plot) else p.width
                height = p.plot_height if isinstance(p, Plot) else p.height
                widths[c] = max(widths[c], width)
                heights[r] = max(heights[r], height)

    expanded_plots = []
    for r, row in enumerate(plots):
        expanded_plots.append([])
        for c, p in enumerate(row):
            if p is None:
                p = Figure(plot_width=widths[c],
                           plot_height=heights[r])
                p.text(x=0, y=0, text=[' '])
                p.xaxis.visible = False
                p.yaxis.visible = False
                p.outline_line_color = None
                p.xgrid.grid_line_color = None
                p.ygrid.grid_line_color = None
            expanded_plots[r].append(p)
    return expanded_plots
Esempio n. 2
0
def layout_padding(plots):
    """
    Temporary workaround to allow empty plots in a
    row of a bokeh GridPlot type. Should be removed
    when https://github.com/bokeh/bokeh/issues/2891
    is resolved.
    """
    widths, heights = defaultdict(int), defaultdict(int)
    for r, row in enumerate(plots):
        for c, p in enumerate(row):
            if p is not None:
                width = p.plot_width if isinstance(p, Plot) else p.width
                height = p.plot_height if isinstance(p, Plot) else p.height
                widths[c] = max(widths[c], width)
                heights[r] = max(heights[r], height)

    expanded_plots = []
    for r, row in enumerate(plots):
        expanded_plots.append([])
        for c, p in enumerate(row):
            if p is None:
                p = Figure(plot_width=widths[c], plot_height=heights[r])
                p.text(x=0, y=0, text=[' '])
                p.xaxis.visible = False
                p.yaxis.visible = False
                p.outline_line_color = None
                p.xgrid.grid_line_color = None
                p.ygrid.grid_line_color = None
            expanded_plots[r].append(p)
    return expanded_plots
Esempio n. 3
0
def make_plots(linesources, pointsources):
    plots = []
    i=0
    for linesource, pointsource in zip(linesources, pointsources):
        fig = Figure(title=None, toolbar_location=None, tools=[],
                   x_axis_type="datetime",
                   width=300, height=70)

        fig.xaxis.visible = False
        if i in [0, 9] :
            fig.xaxis.visible = True
            fig.height = 90
        fig.yaxis.visible = False
        fig.xgrid.visible = True
        fig.ygrid.visible = False
        fig.min_border_left = 10
        fig.min_border_right = 10
        fig.min_border_top = 5
        fig.min_border_bottom = 5
        if not i in [0, 9]:
            fig.xaxis.major_label_text_font_size = "0pt"
        #fig.yaxis.major_label_text_font_size = "0pt"
        fig.xaxis.major_tick_line_color = None
        fig.yaxis.major_tick_line_color = None
        fig.xaxis.minor_tick_line_color = None
        fig.yaxis.minor_tick_line_color = None
        fig.background_fill_color = "whitesmoke"

        fig.line(x='date', y="y", source=linesource)
        fig.circle(x='date', y='y', size=5, source=pointsource)
        fig.text(x='date', y='y', text='text', x_offset=5, y_offset=10, text_font_size='7pt', source=pointsource)

        fig.title.align = 'left'
        fig.title.text_font_style = 'normal'

        plots.append(fig)
        i+=1
    return plots
def plot_dispersion_bokeh(filename, period_array, curve_data_array, boundary_data, style_parameter):
    '''
    Plot dispersion maps and curves using bokeh
    
    Input:
        filename is the filename of the resulting html file
        period_array is a list of period
        curve_data_array is a list of dispersion curves
        boundary_data is a list of boundaries
        style_parameter contains plotting parameters 
    
    Output:
        None
        
    '''
    xlabel_fontsize = style_parameter['xlabel_fontsize']
    # ==============================
    # prepare data
    map_data_all_slices_velocity = []
    map_data_all_slices_period = []
    map_data_all_slices_color = []
    colorbar_data_all_left = []
    colorbar_data_all_right = []
    nperiod = len(period_array)
    ncurve = len(curve_data_array)
    ncolor = len(palette)
    palette_r = palette[::-1]
    colorbar_top = [0.1 for i in range(ncolor)]
    colorbar_bottom = [0 for i in range(ncolor)]
    for iperiod in range(nperiod):
        one_slice_lat_list = []
        one_slice_lon_list = []
        one_slice_vel_list = []
        
        map_period = period_array[iperiod]
        for icurve in range(ncurve):
            acurve = curve_data_array[icurve]
            curve_lat = acurve['latitude']
            curve_lon = acurve['longitude']
            curve_vel = acurve['velocity']
            curve_period = acurve['period']
            one_slice_lat_list.append(curve_lat)
            one_slice_lon_list.append(curve_lon)
            if map_period in curve_period:
                curve_period_index = curve_period.index(map_period)
                one_slice_vel_list.append(curve_vel[curve_period_index])
            else:
                one_slice_vel_list.append(style_parameter['nan_value'])
        # get color for dispersion values
        one_slice_vel_mean = np.nanmean(one_slice_vel_list)
        one_slice_vel_std = np.nanstd(one_slice_vel_list)
        
        color_min = one_slice_vel_mean - one_slice_vel_std * style_parameter['spread_factor']
        color_max = one_slice_vel_mean + one_slice_vel_std * style_parameter['spread_factor']
        color_step = (color_max - color_min)*1./ncolor
        one_slice_color_list = get_color_list(one_slice_vel_list,color_min,color_max,palette_r,\
                                             style_parameter['nan_value'],style_parameter['nan_color'])
        colorbar_left = np.linspace(color_min,color_max-color_step,ncolor)
        colorbar_right = np.linspace(color_min+color_step,color_max,ncolor)
        if one_slice_lat_list:
            map_data_all_slices_velocity.append(one_slice_vel_list)
            map_data_all_slices_period.append('Period: {0:6.1f} s'.format(map_period))
            map_data_all_slices_color.append(one_slice_color_list)
            colorbar_data_all_left.append(colorbar_left)
            colorbar_data_all_right.append(colorbar_right)
    # get location for all points
    map_lat_list, map_lon_list = [], []
    map_lat_label_list, map_lon_label_list = [], []
    for i in range(ncurve):
        acurve = curve_data_array[i]
        map_lat_list.append(acurve['latitude'])
        map_lon_list.append(acurve['longitude'])
        map_lat_label_list.append('Lat: {0:12.3f}'.format(acurve['latitude']))
        map_lon_label_list.append('Lon: {0:12.3f}'.format(acurve['longitude']))
    # data for the map view plot
    map_view_label_lon = style_parameter['map_view_period_label_lon']
    map_view_label_lat = style_parameter['map_view_period_label_lat']

    map_data_one_slice = map_data_all_slices_color[style_parameter['map_view_default_index']]
    map_data_one_slice_period = map_data_all_slices_period[style_parameter['map_view_default_index']]
    map_data_one_slice_bokeh = ColumnDataSource(data=dict(map_lat_list=map_lat_list,\
                                                          map_lon_list=map_lon_list,\
                                                          map_data_one_slice=map_data_one_slice))
    map_data_one_slice_period_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon],
                                                       map_period=[map_data_one_slice_period]))
    map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices_color=map_data_all_slices_color,\
                                                          map_data_all_slices_period=map_data_all_slices_period))

    # data for the colorbar
    colorbar_data_one_slice = {}
    colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']]
    colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']]
    colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,
                                                               colorbar_left=colorbar_data_one_slice['colorbar_left'],\
                                                               colorbar_right=colorbar_data_one_slice['colorbar_right'],\
                                                               palette_r=palette_r))
    colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\
                                                                colorbar_data_all_right=colorbar_data_all_right))
    # data for dispersion curves
    curve_default_index = style_parameter['curve_default_index']
    selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[map_lat_list[curve_default_index]],\
                                                     lon=[map_lon_list[curve_default_index]],\
                                                     color=[map_data_one_slice[curve_default_index]],\
                                                     index=[curve_default_index]))
    selected_curve_data = curve_data_array[curve_default_index]
    selected_curve_data_bokeh = ColumnDataSource(data=dict(curve_period=selected_curve_data['period'],\
                                                          curve_velocity=selected_curve_data['velocity']))

    period_all = []
    velocity_all = []
    for acurve in curve_data_array:
        period_all.append(acurve['period'])
        velocity_all.append(acurve['velocity'])
    curve_data_all_bokeh = ColumnDataSource(data=dict(period_all=period_all, velocity_all=velocity_all))
    
    selected_curve_lat_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lat_label_x']], \
                                                                y=[style_parameter['curve_lat_label_y']],\
                                                                lat_label=[map_lat_label_list[curve_default_index]]))
    selected_curve_lon_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lon_label_x']], \
                                                                y=[style_parameter['curve_lon_label_y']],\
                                                                lon_label=[map_lon_label_list[curve_default_index]]))
    all_curve_lat_label_bokeh = ColumnDataSource(data=dict(map_lat_label_list=map_lat_label_list))
    all_curve_lon_label_bokeh = ColumnDataSource(data=dict(map_lon_label_list=map_lon_label_list))
    # ==============================
    map_view = Figure(plot_width=style_parameter['map_view_plot_width'], \
                      plot_height=style_parameter['map_view_plot_height'], \
                      y_range=[style_parameter['map_view_lat_min'],\
                    style_parameter['map_view_lat_max']], x_range=[style_parameter['map_view_lon_min'],\
                    style_parameter['map_view_lon_max']], tools=style_parameter['map_view_tools'],\
                    title=style_parameter['map_view_title'])
    # ------------------------------
    # add boundaries to map view
    # country boundaries
    map_view.multi_line(boundary_data['country']['longitude'],\
                        boundary_data['country']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # marine boundaries
    map_view.multi_line(boundary_data['marine']['longitude'],\
                        boundary_data['marine']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # shoreline boundaries
    map_view.multi_line(boundary_data['shoreline']['longitude'],\
                        boundary_data['shoreline']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # state boundaries
    map_view.multi_line(boundary_data['state']['longitude'],\
                        boundary_data['state']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # ------------------------------
    # add period label
    map_view.rect(style_parameter['map_view_period_box_lon'], style_parameter['map_view_period_box_lat'], \
                  width=style_parameter['map_view_period_box_width'], height=style_parameter['map_view_period_box_height'], \
                  width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay')
    map_view.text('lon', 'lat', 'map_period', source=map_data_one_slice_period_bokeh,\
                  text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay')
    # ------------------------------
    # plot dots
    map_view.circle('map_lon_list', 'map_lat_list', color='map_data_one_slice', \
                    source=map_data_one_slice_bokeh, size=style_parameter['marker_size'],\
                    line_width=0.2, line_color='black', alpha=1.0,\
                    selection_color='map_data_one_slice', selection_line_color='black',\
                    selection_fill_alpha=1.0,\
                    nonselection_fill_alpha=1.0, nonselection_fill_color='map_data_one_slice',\
                    nonselection_line_color='black', nonselection_line_alpha=1.0)
    map_view.circle('lon', 'lat', color='color', source=selected_dot_on_map_bokeh, \
                    line_color='#00ff00', line_width=4.0, alpha=1.0, \
                    size=style_parameter['selected_marker_size'])
    # ------------------------------
    # change style
    map_view.title.text_font_size = style_parameter['title_font_size']
    map_view.title.align = 'center'
    map_view.title.text_font_style = 'normal'
    map_view.xaxis.axis_label = style_parameter['map_view_xlabel']
    map_view.xaxis.axis_label_text_font_style = 'normal'
    map_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.xaxis.major_label_text_font_size = xlabel_fontsize
    map_view.yaxis.axis_label = style_parameter['map_view_ylabel']
    map_view.yaxis.axis_label_text_font_style = 'normal'
    map_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.yaxis.major_label_text_font_size = xlabel_fontsize
    map_view.xgrid.grid_line_color = None
    map_view.ygrid.grid_line_color = None
    map_view.toolbar.logo = None
    map_view.toolbar_location = 'above'
    map_view.toolbar_sticky = False
    # ==============================
    # plot colorbar
    colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \
                          plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title'])
    colorbar_fig.toolbar_location=None
    colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\
                      fill_color='palette_r',source=colorbar_data_one_slice_bokeh)
    colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[])
    colorbar_fig.xgrid.grid_line_color = None
    colorbar_fig.ygrid.grid_line_color = None
    colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f")
    colorbar_fig.title.text_font_size = xlabel_fontsize
    colorbar_fig.title.align = 'center'
    colorbar_fig.title.text_font_style = 'normal'
    # ==============================
    curve_fig = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \
                       y_range=(style_parameter['curve_y_min'],style_parameter['curve_y_max']), \
                       x_range=(style_parameter['curve_x_min'],style_parameter['curve_x_max']),x_axis_type='log',\
                        tools=['save','box_zoom','wheel_zoom','reset','crosshair','pan'],
                        title=style_parameter['curve_title'])
    # ------------------------------
    curve_fig.rect([style_parameter['curve_label_box_x']], [style_parameter['curve_label_box_y']], \
                   width=style_parameter['curve_label_box_width'], height=style_parameter['curve_label_box_height'], \
                   width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay')
    curve_fig.text('x', 'y', \
                   'lat_label', source=selected_curve_lat_label_bokeh)
    curve_fig.text('x', 'y', \
                   'lon_label', source=selected_curve_lon_label_bokeh)
    # ------------------------------
    curve_fig.line('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, color='black')
    curve_fig.circle('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, size=5, color='black')
    # ------------------------------
    curve_fig.title.text_font_size = style_parameter['title_font_size']
    curve_fig.title.align = 'center'
    curve_fig.title.text_font_style = 'normal'
    curve_fig.xaxis.axis_label = style_parameter['curve_xlabel']
    curve_fig.xaxis.axis_label_text_font_style = 'normal'
    curve_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig.yaxis.axis_label = style_parameter['curve_ylabel']
    curve_fig.yaxis.axis_label_text_font_style = 'normal'
    curve_fig.yaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig.yaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig.xgrid.grid_line_dash = [4, 2]
    curve_fig.ygrid.grid_line_dash = [4, 2]
    curve_fig.xaxis[0].formatter = PrintfTickFormatter(format="%4.0f")
    curve_fig.toolbar.logo = None
    curve_fig.toolbar_location = 'above'
    curve_fig.toolbar_sticky = False
    # ==============================
    map_data_one_slice_bokeh.callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                                          map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                                          selected_curve_data_bokeh=selected_curve_data_bokeh,\
                                                          curve_data_all_bokeh=curve_data_all_bokeh,\
                                                          selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\
                                                          selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\
                                                          all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\
                                                          all_curve_lon_label_bokeh=all_curve_lon_label_bokeh), code="""
    
    var inds = Math.round(cb_obj.selected['1d'].indices)
    
    selected_dot_on_map_bokeh.data['index'] = [inds]
    
    var new_slice = map_data_one_slice_bokeh.data
    
    selected_dot_on_map_bokeh.data['lat'] = [new_slice['map_lat_list'][inds]]
    selected_dot_on_map_bokeh.data['lon'] = [new_slice['map_lon_list'][inds]]
    selected_dot_on_map_bokeh.data['color'] = [new_slice['map_data_one_slice'][inds]]
    
    selected_dot_on_map_bokeh.change.emit()
    
    selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][inds]
    selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][inds]
    
    selected_curve_data_bokeh.change.emit()
    
    var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list']
    var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list']
    
    selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[inds]]
    selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[inds]]
    
    selected_curve_lat_label_bokeh.change.emit()
    selected_curve_lon_label_bokeh.change.emit()
    """)
    # ==============================
    period_slider_callback = CustomJS(args=dict(map_data_all_slices_bokeh=map_data_all_slices_bokeh,\
                                  map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                  colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh, \
                                  colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\
                                  selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                  map_data_one_slice_period_bokeh=map_data_one_slice_period_bokeh),\
                       code="""
    var p_index = Math.round(cb_obj.value)
    var map_data_all_slices = map_data_all_slices_bokeh.data
    
    
    var map_data_new_slice = map_data_all_slices['map_data_all_slices_color'][p_index]
    map_data_one_slice_bokeh.data['map_data_one_slice'] = map_data_new_slice
    map_data_one_slice_bokeh.change.emit()
    
    var color_data_all_slices = colorbar_data_all_slices_bokeh.data
    colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][p_index]
    colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][p_index]
    colorbar_data_one_slice_bokeh.change.emit()
    
    var selected_index = selected_dot_on_map_bokeh.data['index']
    selected_dot_on_map_bokeh.data['color'] = [map_data_new_slice[selected_index]]
    selected_dot_on_map_bokeh.change.emit()
    
    map_data_one_slice_period_bokeh.data['map_period'] = [map_data_all_slices['map_data_all_slices_period'][p_index]]
    map_data_one_slice_period_bokeh.change.emit()
    """)
    period_slider = Slider(start=0, end=nperiod-1, value=style_parameter['map_view_default_index'], \
                           step=1, title=style_parameter['period_slider_title'], \
                           width=style_parameter['period_slider_plot_width'],\
                           height=50, callback=period_slider_callback)
    
    # ==============================
    curve_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                              map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                              selected_curve_data_bokeh=selected_curve_data_bokeh,\
                                              curve_data_all_bokeh=curve_data_all_bokeh,\
                                              selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\
                                              selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\
                                              all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\
                                              all_curve_lon_label_bokeh=all_curve_lon_label_bokeh),\
                                    code="""
    var c_index = Math.round(cb_obj.value)
    
    var one_slice = map_data_one_slice_bokeh.data
    
    selected_dot_on_map_bokeh.data['index'] = [c_index]
    selected_dot_on_map_bokeh.data['lat'] = [one_slice['map_lat_list'][c_index]]
    selected_dot_on_map_bokeh.data['lon'] = [one_slice['map_lon_list'][c_index]]
    selected_dot_on_map_bokeh.data['color'] = [one_slice['map_data_one_slice'][c_index]]
    
    selected_dot_on_map_bokeh.change.emit()
    
    selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][c_index]
    selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][c_index]
    
    selected_curve_data_bokeh.change.emit()
    
    var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list']
    var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list']
    
    selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[c_index]]
    selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[c_index]]
    
    selected_curve_lat_label_bokeh.change.emit()
    selected_curve_lon_label_bokeh.change.emit()
    """)
    curve_slider = Slider(start=0, end=ncurve-1, value=style_parameter['curve_default_index'], \
                          step=1, title=style_parameter['curve_slider_title'], width=style_parameter['curve_plot_width'],\
                          height=50, callback=curve_slider_callback)
    
    # ==============================
    # annotating text
    annotating_fig01 = Div(text=style_parameter['annotating_html01'], \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    annotating_fig02 = Div(text=style_parameter['annotating_html02'],\
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    # ==============================
    output_file(filename,title=style_parameter['html_title'],mode=style_parameter['library_source'])
    left_fig = Column(period_slider, map_view, colorbar_fig, annotating_fig01,\
                    width=style_parameter['left_column_width'] )
    right_fig = Column(curve_slider, curve_fig, annotating_fig02, \
                    width=style_parameter['right_column_width'] )
    layout = Row(left_fig, right_fig)
    save(layout)
def create_pie_chart(dataframe, title, palette):

    radio_tarta = 0.4

    df_pie_plot = dataframe.groupby("origen").size().sort_values(
        ascending=False).reset_index()
    df_pie_plot.columns = ["origen", "conteo"]

    df_pie_plot["porcentaje"] = df_pie_plot["conteo"] / df_pie_plot[
        "conteo"].sum() * 100
    df_pie_plot["porcentaje"] = df_pie_plot["porcentaje"].apply(
        lambda x: "{0:.2f}%".format(x))
    df_pie_plot["porcentaje_texto"] = df_pie_plot[
        "origen"] + "\n" + df_pie_plot["porcentaje"]

    df_pie_plot["angulo"] = df_pie_plot["conteo"] / df_pie_plot["conteo"].sum(
    ) * 2 * np.pi
    df_pie_plot["angulo_acumulado"] = df_pie_plot["angulo"].cumsum()
    df_pie_plot["angulo_bisectriz"] = df_pie_plot[
        "angulo_acumulado"] - df_pie_plot["angulo"] / 2.0
    df_pie_plot["posicion_x_texto"] = radio_tarta * 0.7 * np.cos(
        df_pie_plot["angulo_bisectriz"])
    df_pie_plot["posicion_y_texto"] = radio_tarta * 0.7 * np.sin(
        df_pie_plot["angulo_bisectriz"])

    df_pie_plot["color"] = palette[:len(df_pie_plot)]

    df_pie_plot_source = ColumnDataSource(data=df_pie_plot)

    pie_plot_bokeh = Figure(title=title,
                            x_range=(-0.45, 0.45),
                            y_range=(-0.45, 0.45))

    sectores = pie_plot_bokeh.annular_wedge(
        x=0,
        y=0,
        inner_radius=radio_tarta / 3.0,
        outer_radius=radio_tarta,
        start_angle=bokeh_cumsum("angulo", include_zero=True),
        end_angle=bokeh_cumsum('angulo'),
        line_color="white",
        line_width=3,
        fill_color='color',
        #legend_field="origen",
        alpha=0.8,
        hover_color="color",
        hover_alpha=1.0,
        source=df_pie_plot_source)

    textos = pie_plot_bokeh.text(x='posicion_x_texto',
                                 y='posicion_y_texto',
                                 text="porcentaje_texto",
                                 text_color="white",
                                 text_font_style="bold",
                                 text_align="center",
                                 text_baseline="middle",
                                 source=df_pie_plot_source)

    # Old hover:
    #hover_pie = HoverTool(tooltips="@{origen}: @{conteo}",
    #                      renderers=[sectores])

    # New hover:
    hover_pie = HoverTool(tooltips=[("Origen", "@{origen}"),
                                    ("Clientes", "@{conteo}"),
                                    ("Porcentaje", "@{porcentaje}")],
                          renderers=[sectores])

    pie_plot_bokeh.add_tools(hover_pie)

    pie_plot_bokeh.axis.axis_label = None
    pie_plot_bokeh.axis.visible = False
    pie_plot_bokeh.grid.grid_line_color = None

    return pie_plot_bokeh, df_pie_plot_source
Esempio n. 6
0
    def create_figure(self):

        analog_glyphs = {}
        binary_glyphs = {}
        multistates_glyphs = {}
        multistates_labels = {}
        virtuals_glyphs = {}

        self._log.debug("Creating figure")

        TOOLS = "pan,box_zoom,wheel_zoom,save,reset"
        p = Figure(
            x_axis_type="datetime",
            x_axis_label="Time",
            y_axis_label="Value",
            title="Live trends",
            tools=TOOLS,
            plot_width=1200,
            plot_height=800,
            toolbar_location="right",
        )

        p.title.text_font_size = "24pt"
        p.xaxis.axis_label_text_font_size = "18pt"
        p.yaxis.axis_label_text_font_size = "18pt"
        p.xaxis.axis_label_text_font_style = "normal"
        p.yaxis.axis_label_text_font_style = "normal"
        p.xaxis.major_label_text_font_size = "12pt"
        p.yaxis.major_label_text_font_size = "12pt"

        p.background_fill_color = "#f4f3ef"
        p.border_fill_color = "#f4f3ef"
        p.extra_y_ranges = {
            "bool": Range1d(start=0, end=1.1),
            "enum": Range1d(start=0, end=10),
        }
        p.add_layout(
            LinearAxis(y_range_name="bool", axis_label="Binary",
                       visible=False), "left")
        p.add_layout(
            LinearAxis(
                y_range_name="enum",
                axis_label="Enumerated",
                visible=False,
                # ticker=list(range(11)),
            ),
            "right",
        )

        hover_common = HoverTool(
            tooltips=[
                ("name", "$name"),
                ("value", "$data_y"),
                # ('state', "@$name_state"),
                # ("units", "$tags"),
                ("time", "@time_s"),
            ],
            renderers=[],
            toggleable=False,
            formatters={"@time_s": "datetime"},
            mode="mouse",
        )
        hover_multi = {}

        p.add_tools(hover_common)

        for name in self._binary_name:
            binary_glyphs[name] = p.step(
                x="index",
                y=name,
                source=self.cds,
                name=name,
                color=self.color_mappers["binary"][name],
                y_range_name="bool",
                mode="after",
                line_width=8,
                visible=False,
                tags=["unit", "description"],
            )
            # binary_glyphs[name].add_tool(hover_common)
            hover_common.renderers.append(binary_glyphs[name])

        for name in self._multistates_name:
            multistates_glyphs[name] = p.step(
                x="index",
                y=name,
                source=self.cds,
                name=name,
                color=self.color_mappers["multistates"][name],
                y_range_name="enum",
                line_dash="dashed",
                line_width=7,
                visible=False,
                tags=["unit", "description"],
                mode="after",
            )

        #        for name in self._multistates_labels:
        #            multistates_labels[name] = LabelSet(x="index", y=name.split('_')[0], text=name, level='glyph',
        #              x_offset=0, y_offset=1, source=self.cds, render_mode='canvas', visible=False)
        #            p.add_layout(multistates_labels[name])
        #        for name in self._multistates_labels:
        #            _msname = name.split("_")[0]
        #            multistates_labels[name] = p.circle(
        #                x="index",
        #                y=_msname,
        #                source=self.cds,
        #                color=self.color_mappers["multistates"][_msname],
        #                size=10,
        #                alpha=0.1,
        #                y_range_name="enum",
        #                visible=False,
        #            )
        #            hover_multi[name] = HoverTool(
        #                tooltips=[
        #                    ("name", "$name"),
        #                    ("value", "@" + name),
        #                    ("time", "@time_s"),
        #                ],
        #                mode="mouse",
        #                renderers=[multistates_labels[name]],
        #                toggleable=False,
        #            )
        #            p.add_tools(hover_multi[name])

        for name in self._multistates_labels:
            _msname = name.split("_")[0]
            multistates_labels[name] = p.text(
                x="index",
                y=_msname,
                text=name,
                source=self.cds,
                text_color=self.color_mappers["multistates"][_msname],
                angle=0.7835,
                # size=10,
                # alpha=0.1,
                y_range_name="enum",
                visible=False,
            )
            hover_multi[name] = HoverTool(
                tooltips=[
                    ("name", "$name"),
                    ("value", "@" + name),
                    ("time", "@time_s"),
                ],
                mode="mouse",
                renderers=[multistates_labels[name]],
                toggleable=False,
            )
            p.add_tools(hover_multi[name])

        for name in self._analog_name:
            analog_glyphs[name] = p.line(
                x="index",
                y=name,
                source=self.cds,
                name=name,
                color=self.color_mappers["analog"][name],
                line_width=2,
                visible=False,
                tags=["unit", "description"],
            )
            # analog_glyphs[name].add_tool(hover_common)
            hover_common.renderers.append(analog_glyphs[name])

        for name in self._virtuals_name:
            virtuals_glyphs[name] = p.line(
                x="index",
                y=name,
                source=self.cds,
                name=name,
                color=self.color_mappers["virtual"][name],
                line_width=2,
                visible=False,
                tags=["unit", "description"],
            )
            # virtuals_glyphs[name].add_tool(hover_common)
            hover_common.renderers.append(virtuals_glyphs[name])

        self.glyphs = {
            "analog": analog_glyphs,
            "binary": binary_glyphs,
            "multistates": multistates_glyphs,
            "multistates_labels": multistates_labels,
            "virtual": virtuals_glyphs,
        }
        legend = Legend(items=[])
        legend.click_policy = "hide"
        p.add_layout(legend, "below")
        return p
Esempio n. 7
0
# initialise the text color as black. This will be switched to white if the block color gets dark enough
text_color = '#000000'

# create a data source to enable refreshing of fill & text color
source = ColumnDataSource(data=dict(color=[hex_color], text_color=[text_color]))

# create first plot, as a rect() glyph and centered text label, with fill and text color taken from source
p1 = Figure(x_range=(-8, 8), y_range=(-4, 4),
            plot_width=600, plot_height=300,
            title='move sliders to change', tools='')

p1.rect(0, 0, width=18, height=10, fill_color='color',
        line_color = 'black', source=source)

p1.text(0, 0, text='color', text_color='text_color',
        alpha=0.6667, text_font_size='36pt', text_baseline='middle',
        text_align='center', source=source)

# the callback function to update the color of the block and associated label text
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = CustomJS(args=dict(source=source), code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }
    var data = source.get('data');
    color = data['color'];
Esempio n. 8
0
plot1.yaxis.axis_line_width = 0
plot1.xaxis.axis_line_color = 'black'
plot1.yaxis.axis_line_color = 'black'
plot1.border_fill_color = "black"
plot1.min_border_left = 80

# main glyphs for planet circles
star_syms = plot1.circle('x', 'y', source=star_points, name="star_points_to_hover", \
      fill_color='color', line_color='color', radius=0.5, line_alpha=0.5, fill_alpha=0.7)
star_syms.selection_glyph = Circle(fill_alpha=0.8,
                                   fill_color="purple",
                                   radius=1.5,
                                   line_color='purple',
                                   line_width=3)

plot1.text(0.95*0.707*np.array([10., 20., 30., 40.]), 0.707*np.array([10., 20., 30., 40.]), \
     text=['10 pc', '20 pc', '30 pc', '40 pc'], text_color="white", text_font_style='bold', text_font_size='12pt', text_alpha=0.8)
plot1.text([48.5], [47], ['Chance Of Detecting'],
           text_color="white",
           text_align="right",
           text_alpha=1.0)
plot1.text([48.5], [44.5], ['an Earth Twin if Present'],
           text_color="white",
           text_align="right",
           text_alpha=1.0)
plot1.text([48.5], [44.5], ['___________________'],
           text_color="white",
           text_align="right",
           text_alpha=1.0)
plot1.text(np.array([48.5]),
           np.array([41.5]), ["80-100%"],
           text_color='lightgreen',
Esempio n. 9
0
def periodic_plot(cds, title="Periodic Table", width=PLOT_WIDTH,
                  height=PLOT_HEIGHT, cmap="viridis",
                  showfblock=True, long_version=False,
                  color_mapper=None):
    """
    Create the periodic plot

    Args:
      df : DataFrame
        Pandas DataFrame with the data on elements
      tile : str
        Title to appear above the periodic table
      colorby : str
        Name of the column containig the colors
      width : int
        Width of the figure in pixels
      height : int
        Height of the figure in pixels
      cmap : str
        Colormap to use, see matplotlib colormaps
      long_version : bool
        Show the long version of the periodic table with the f block between
        the s and d blocks
      showfblock : bool
        Show the elements from the f block

    .. note::

        `property` attribute holds the current property to be displayed

    """

    fig = Figure(title=title,
                 x_axis_location="above",
                 x_range=(0.5, 18.5),
                 y_range=(10.0, 0.5),
                 plot_width=width,
                 plot_height=height,
                 tools="box_zoom,pan,resize,save,reset",
                 toolbar_location="above",
                 toolbar_sticky=False,
                 )

    if color_mapper is None:
        color_dict = "#1F77B4"
    else:
        color_dict = {"field": "value", "transform": color_mapper}

    fig.rect("x", "y", 0.9, 0.9, source=cds, fill_alpha=0.6,
             fill_color=color_dict, line_color=color_dict)

    # adjust the ticks and axis bounds
    fig.yaxis.bounds = (1, 7)
    fig.axis[1].ticker.num_minor_ticks = 0
    fig.axis[0].ticker = FixedTicker(ticks=list(range(1, 19)))

    text_props = {
        "source": cds,
        "angle": 0,
        "color": "black",
        "text_align": "center",
        "text_baseline": "middle"
    }

    fig.text(x="x", y="y_symbol", text="symbol",
             text_font_style="bold", text_font_size="15pt", **text_props)

    fig.text(x="x", y="y_anumber", text="atomic_number",
             text_font_size="9pt", **text_props)

    fig.text(x="x", y="y_name", text="name",
             text_font_size="7pt", **text_props)

    fig.text(x="x", y="y_prop", text="value_str",
             text_font_size="8pt", **text_props)

    fig.grid.grid_line_color = None

    hover = HoverTool(tooltips=HOVER_TOOLTIPS)

    fig.add_tools(hover)

    return fig
Esempio n. 10
0
def plot_cross_section_bokeh(filename, map_data_all_slices, map_depth_all_slices, \
                             color_range_all_slices, cross_data, boundary_data, \
                             style_parameter):
    '''
    Plot shear velocity maps and cross-sections using bokeh

    Input:
        filename is the filename of the resulting html file
        map_data_all_slices contains the velocity model parameters saved for map view plots
        map_depth_all_slices is a list of depths
        color_range_all_slices is a list of color ranges
        profile_data_all is a list of velocity profiles
        cross_lat_data_all is a list of cross-sections along latitude
        lat_value_all is a list of corresponding latitudes for these cross-sections
        cross_lon_data_all is a list of cross-sections along longitude
        lon_value_all is a list of corresponding longitudes for these cross-sections
        boundary_data is a list of boundaries
        style_parameter contains parameters to customize the plots

    Output:
        None
    
    '''
    xlabel_fontsize = style_parameter['xlabel_fontsize']
    #
    colorbar_data_all_left = []
    colorbar_data_all_right = []
    map_view_ndepth = style_parameter['map_view_ndepth']
    palette_r = palette[::-1]
    ncolor = len(palette_r)
    colorbar_top = [0.1 for i in range(ncolor)]
    colorbar_bottom = [0 for i in range(ncolor)]
    map_data_all_slices_depth = []
    for idepth in range(map_view_ndepth): 
        color_min = color_range_all_slices[idepth][0]
        color_max = color_range_all_slices[idepth][1]
        color_step = (color_max - color_min)*1./ncolor
        colorbar_left = np.linspace(color_min,color_max-color_step,ncolor)
        colorbar_right = np.linspace(color_min+color_step,color_max,ncolor)
        colorbar_data_all_left.append(colorbar_left)
        colorbar_data_all_right.append(colorbar_right)
        map_depth = map_depth_all_slices[idepth]
        map_data_all_slices_depth.append('Depth: {0:8.0f} km'.format(map_depth))
    # data for the colorbar
    colorbar_data_one_slice = {}
    colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']]
    colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']]
    colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\
                                                               colorbar_left=colorbar_data_one_slice['colorbar_left'],\
                                                               colorbar_right=colorbar_data_one_slice['colorbar_right'],\
                                                               palette_r=palette_r))
    colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\
                                                                colorbar_data_all_right=colorbar_data_all_right))
    #
    map_view_label_lon = style_parameter['map_view_depth_label_lon']
    map_view_label_lat = style_parameter['map_view_depth_label_lat']
    map_data_one_slice_depth = map_data_all_slices_depth[style_parameter['map_view_default_index']]
    map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon],
                                                           map_depth=[map_data_one_slice_depth]))
    
    #
    map_view_default_index = style_parameter['map_view_default_index']
    #map_data_one_slice = map_data_all_slices[map_view_default_index]
    map_color_all_slices = []
    for i in range(len(map_data_all_slices)):
        vmin, vmax = color_range_all_slices[i]
        map_color = val_to_rgb(map_data_all_slices[i], palette_r, vmin, vmax)
        map_color_all_slices.append(map_color)
    map_color_one_slice = map_color_all_slices[map_view_default_index]
    #
    map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\
                   y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']],\
                   dh=[style_parameter['nlat']],map_data_one_slice=[map_color_one_slice]))
    map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_color_all_slices,\
                                                           map_data_all_slices_depth=map_data_all_slices_depth))
    #
    
    plot_depth = np.shape(cross_data)[0] * style_parameter['cross_ddepth']
    plot_lon = great_arc_distance(style_parameter['cross_default_lat0'], style_parameter['cross_default_lon0'],\
                                  style_parameter['cross_default_lat1'], style_parameter['cross_default_lon1'])
    
    vs_min = style_parameter['cross_view_vs_min']
    vs_max = style_parameter['cross_view_vs_max']
    cross_color = val_to_rgb(cross_data, palette_r, vmin, vmax)
    cross_data_bokeh = ColumnDataSource(data=dict(x=[0],\
                   y=[plot_depth],dw=[plot_lon],\
                   dh=[plot_depth],cross_data=[cross_color]))
    
    map_line_bokeh = ColumnDataSource(data=dict(lat=[style_parameter['cross_default_lat0'], style_parameter['cross_default_lat1']],\
                                                    lon=[style_parameter['cross_default_lon0'], style_parameter['cross_default_lon1']]))
    #
    ncolor_cross = len(my_palette)
    colorbar_top_cross = [0.1 for i in range(ncolor_cross)]
    colorbar_bottom_cross = [0 for i in range(ncolor_cross)]
    color_min_cross = style_parameter['cross_view_vs_min']
    color_max_cross = style_parameter['cross_view_vs_max']
    color_step_cross = (color_max_cross - color_min_cross)*1./ncolor_cross
    colorbar_left_cross = np.linspace(color_min_cross, color_max_cross-color_step_cross, ncolor_cross)
    colorbar_right_cross = np.linspace(color_min_cross+color_step_cross, color_max_cross, ncolor_cross)
    # ==============================
    map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \
                      tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \
                      y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\
                      x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']])
    #
    map_view.image_rgba('map_data_one_slice',x='x',\
                   y='y',dw='dw',dh='dh',\
                   source=map_data_one_slice_bokeh, level='image')

    depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                               map_data_all_slices_bokeh=map_data_all_slices_bokeh,\
                                               colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\
                                               colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\
                                               map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code="""

        var d_index = Math.round(cb_obj.value)
        
        var map_data_all_slices = map_data_all_slices_bokeh.data
        
        map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]]
        map_data_one_slice_bokeh.change.emit()
        
        var color_data_all_slices = colorbar_data_all_slices_bokeh.data
        colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index]
        colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index]
        colorbar_data_one_slice_bokeh.change.emit()
        
        map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]]
        map_data_one_slice_depth_bokeh.change.emit()
        
    """) 
    depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \
                          value=map_view_default_index, step=1, \
                          width=style_parameter['map_view_plot_width'],\
                          title=style_parameter['depth_slider_title'], height=50, \
                          callback=depth_slider_callback)
    # ------------------------------
    # add boundaries to map view
    # country boundaries
    map_view.multi_line(boundary_data['country']['longitude'],\
                        boundary_data['country']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # marine boundaries
    map_view.multi_line(boundary_data['marine']['longitude'],\
                        boundary_data['marine']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # shoreline boundaries
    map_view.multi_line(boundary_data['shoreline']['longitude'],\
                        boundary_data['shoreline']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # state boundaries
    map_view.multi_line(boundary_data['state']['longitude'],\
                        boundary_data['state']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
     # ------------------------------
    # add depth label
    map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \
                  width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \
                  width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay')
    map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\
                  text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay')
    # ------------------------------
    map_view.line('lon', 'lat', source=map_line_bokeh, line_dash=[8,2,8,2], line_color='#00ff00',\
                        nonselection_line_alpha=1.0, line_width=5.,\
                        nonselection_line_color='black')
    map_view.text([style_parameter['cross_default_lon0']],[style_parameter['cross_default_lat0']], ['A'], \
            text_font_size=style_parameter['title_font_size'],text_align='left')
    map_view.text([style_parameter['cross_default_lon1']],[style_parameter['cross_default_lat1']], ['B'], \
            text_font_size=style_parameter['title_font_size'],text_align='left')
    # ------------------------------
    # change style
    map_view.title.text_font_size = style_parameter['title_font_size']
    map_view.title.align = 'center'
    map_view.title.text_font_style = 'normal'
    map_view.xaxis.axis_label = style_parameter['map_view_xlabel']
    map_view.xaxis.axis_label_text_font_style = 'normal'
    map_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.xaxis.major_label_text_font_size = xlabel_fontsize
    map_view.yaxis.axis_label = style_parameter['map_view_ylabel']
    map_view.yaxis.axis_label_text_font_style = 'normal'
    map_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.yaxis.major_label_text_font_size = xlabel_fontsize
    map_view.xgrid.grid_line_color = None
    map_view.ygrid.grid_line_color = None
    map_view.toolbar.logo = None
    map_view.toolbar_location = 'above'
    map_view.toolbar_sticky = False
    # ==============================
    # plot colorbar
    
    colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \
                      plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title'])
    colorbar_fig.toolbar_location=None
    colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\
                  color='palette_r',source=colorbar_data_one_slice_bokeh)
    colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[])
    colorbar_fig.xgrid.grid_line_color = None
    colorbar_fig.ygrid.grid_line_color = None
    colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f")
    colorbar_fig.title.text_font_size = xlabel_fontsize
    colorbar_fig.title.align = 'center'
    colorbar_fig.title.text_font_style = 'normal'
     # ==============================
    # annotating text
    annotating_fig01 = Div(text=style_parameter['annotating_html01'], \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    annotating_fig02 = Div(text="""<p style="font-size:16px">""", \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    # ==============================
    # plot cross-section along latitude
    cross_section_plot_width = int(style_parameter['cross_plot_height']*1.0/plot_depth*plot_lon/10.)
    cross_view = Figure(plot_width=cross_section_plot_width, plot_height=style_parameter['cross_plot_height'], \
                      tools=style_parameter['cross_view_tools'], title=style_parameter['cross_view_title'], \
                      y_range=[plot_depth, -30],\
                      x_range=[0, plot_lon])
    cross_view.image_rgba('cross_data',x='x',\
                   y='y',dw='dw',dh='dh',\
                   source=cross_data_bokeh, level='image')
    cross_view.text([plot_lon*0.1], [-10], ['A'], \
                text_font_size=style_parameter['title_font_size'],text_align='left',level='underlay')
    cross_view.text([plot_lon*0.9], [-10], ['B'], \
                text_font_size=style_parameter['title_font_size'],text_align='left',level='underlay')
    # ------------------------------
    # change style
    cross_view.title.text_font_size = style_parameter['title_font_size']
    cross_view.title.align = 'center'
    cross_view.title.text_font_style = 'normal'
    cross_view.xaxis.axis_label = style_parameter['cross_view_xlabel']
    cross_view.xaxis.axis_label_text_font_style = 'normal'
    cross_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    cross_view.xaxis.major_label_text_font_size = xlabel_fontsize
    cross_view.yaxis.axis_label = style_parameter['cross_view_ylabel']
    cross_view.yaxis.axis_label_text_font_style = 'normal'
    cross_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    cross_view.yaxis.major_label_text_font_size = xlabel_fontsize
    cross_view.xgrid.grid_line_color = None
    cross_view.ygrid.grid_line_color = None
    cross_view.toolbar.logo = None
    cross_view.toolbar_location = 'right'
    cross_view.toolbar_sticky = False
    # ==============================
    colorbar_fig_right = Figure(tools=[], y_range=(0,0.1),plot_width=cross_section_plot_width, \
                      plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title'])
    colorbar_fig_right.toolbar_location=None
    
    colorbar_fig_right.quad(top=colorbar_top_cross,bottom=colorbar_bottom_cross,\
                            left=colorbar_left_cross,right=colorbar_right_cross,\
                            color=my_palette)
    colorbar_fig_right.yaxis[0].ticker=FixedTicker(ticks=[])
    colorbar_fig_right.xgrid.grid_line_color = None
    colorbar_fig_right.ygrid.grid_line_color = None
    colorbar_fig_right.xaxis.axis_label_text_font_size = xlabel_fontsize
    colorbar_fig_right.xaxis.major_label_text_font_size = xlabel_fontsize
    colorbar_fig_right.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f")
    colorbar_fig_right.title.text_font_size = xlabel_fontsize
    colorbar_fig_right.title.align = 'center'
    colorbar_fig_right.title.text_font_style = 'normal'
    # ==============================
    output_file(filename,title=style_parameter['html_title'], mode=style_parameter['library_source'])
    left_column = Column(depth_slider, map_view, colorbar_fig, annotating_fig01, width=style_parameter['left_column_width'])
    
    right_column = Column(annotating_fig02, cross_view, colorbar_fig_right, width=cross_section_plot_width)
    layout = Row(left_column, right_column, height=800)
    save(layout)
Esempio n. 11
0
def plot_3DModel_bokeh(filename, map_data_all_slices, map_depth_all_slices, \
                       color_range_all_slices, profile_data_all, boundary_data, \
                       style_parameter):
    '''
    Plot shear velocity maps and velocity profiles using bokeh

    Input:
        filename is the filename of the resulting html file
        map_data_all_slices contains the velocity model parameters saved for map view plots
        map_depth_all_slices is a list of depths
        color_range_all_slices is a list of color ranges
        profile_data_all constains the velocity model parameters saved for profile plots
        boundary_data is a list of boundaries
        style_parameter contains plotting parameters

    Output:
        None
    
    '''
    xlabel_fontsize = style_parameter['xlabel_fontsize']
    #
    colorbar_data_all_left = []
    colorbar_data_all_right = []
    map_view_ndepth = style_parameter['map_view_ndepth']
    ncolor = len(palette)
    colorbar_top = [0.1 for i in range(ncolor)]
    colorbar_bottom = [0 for i in range(ncolor)]
    map_data_all_slices_depth = []
    for idepth in range(map_view_ndepth):
        color_min = color_range_all_slices[idepth][0]
        color_max = color_range_all_slices[idepth][1]
        color_step = (color_max - color_min) * 1. / ncolor
        colorbar_left = np.linspace(color_min, color_max - color_step, ncolor)
        colorbar_right = np.linspace(color_min + color_step, color_max, ncolor)
        colorbar_data_all_left.append(colorbar_left)
        colorbar_data_all_right.append(colorbar_right)
        map_depth = map_depth_all_slices[idepth]
        map_data_all_slices_depth.append(
            'Depth: {0:8.1f} km'.format(map_depth))
    #
    palette_r = palette[::-1]
    # data for the colorbar
    colorbar_data_one_slice = {}
    colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[
        style_parameter['map_view_default_index']]
    colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[
        style_parameter['map_view_default_index']]
    colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\
                                                               colorbar_left=colorbar_data_one_slice['colorbar_left'],\
                                                               colorbar_right=colorbar_data_one_slice['colorbar_right'],\
                                                               palette_r=palette_r))
    colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\
                                                                colorbar_data_all_right=colorbar_data_all_right))
    #
    map_view_label_lon = style_parameter['map_view_depth_label_lon']
    map_view_label_lat = style_parameter['map_view_depth_label_lat']
    map_data_one_slice_depth = map_data_all_slices_depth[
        style_parameter['map_view_default_index']]
    map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon],
                                                           map_depth=[map_data_one_slice_depth],
                                                           left=[style_parameter['profile_plot_xmin']], \
                                                           right=[style_parameter['profile_plot_xmax']]))

    #
    map_view_default_index = style_parameter['map_view_default_index']
    #map_data_one_slice = map_data_all_slices[map_view_default_index]
    #
    map_color_all_slices = []
    for i in range(len(map_data_all_slices)):
        vmin, vmax = color_range_all_slices[i]
        map_color = val_to_rgb(map_data_all_slices[i], palette_r, vmin, vmax)
        map_color_2d = map_color.view('uint32').reshape(map_color.shape[:2])
        map_color_all_slices.append(map_color_2d)
    map_color_one_slice = map_color_all_slices[map_view_default_index]
    #
    map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\
                   y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']*style_parameter['dlon']],\
                   dh=[style_parameter['nlat']*style_parameter['dlat']],map_data_one_slice=[map_color_one_slice]))
    map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_color_all_slices,\
                                                           map_data_all_slices_depth=map_data_all_slices_depth))
    # ------------------------------
    nprofile = len(profile_data_all)
    grid_lat_list = []
    grid_lon_list = []
    width_list = []
    height_list = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        grid_lat_list.append(aprofile['lat'])
        grid_lon_list.append(aprofile['lon'])
        width_list.append(style_parameter['map_view_grid_width'])
        height_list.append(style_parameter['map_view_grid_height'])
    grid_data_bokeh = ColumnDataSource(data=dict(lon=grid_lon_list,lat=grid_lat_list,\
                                            width=width_list, height=height_list))
    profile_default_index = style_parameter['profile_default_index']
    selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[grid_lat_list[profile_default_index]], \
                                                           lon=[grid_lon_list[profile_default_index]], \
                                                           width=[style_parameter['map_view_grid_width']],\
                                                           height=[style_parameter['map_view_grid_height']],\
                                                           index=[profile_default_index]))
    # ------------------------------
    profile_vs_all = []
    profile_depth_all = []
    profile_ndepth = style_parameter['profile_ndepth']
    profile_lat_label_list = []
    profile_lon_label_list = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        vs_raw = aprofile['vs']
        top_raw = aprofile['top']
        profile_lat_label_list.append('Lat: {0:12.1f}'.format(aprofile['lat']))
        profile_lon_label_list.append('Lon: {0:12.1f}'.format(aprofile['lon']))
        vs_plot = []
        depth_plot = []
        for idepth in range(profile_ndepth):
            vs_plot.append(vs_raw[idepth])
            depth_plot.append(top_raw[idepth])
            vs_plot.append(vs_raw[idepth])
            depth_plot.append(top_raw[idepth + 1])
        profile_vs_all.append(vs_plot)
        profile_depth_all.append(depth_plot)
    profile_data_all_bokeh = ColumnDataSource(data=dict(profile_vs_all=profile_vs_all, \
                                                        profile_depth_all=profile_depth_all))
    selected_profile_data_bokeh = ColumnDataSource(data=dict(vs=profile_vs_all[profile_default_index],\
                                                             depth=profile_depth_all[profile_default_index]))
    selected_profile_lat_label_bokeh = ColumnDataSource(data=\
                                dict(x=[style_parameter['profile_lat_label_x']], y=[style_parameter['profile_lat_label_y']],\
                                    lat_label=[profile_lat_label_list[profile_default_index]]))
    selected_profile_lon_label_bokeh = ColumnDataSource(data=\
                                dict(x=[style_parameter['profile_lon_label_x']], y=[style_parameter['profile_lon_label_y']],\
                                    lon_label=[profile_lon_label_list[profile_default_index]]))
    all_profile_lat_label_bokeh = ColumnDataSource(data=dict(
        profile_lat_label_list=profile_lat_label_list))
    all_profile_lon_label_bokeh = ColumnDataSource(data=dict(
        profile_lon_label_list=profile_lon_label_list))
    #
    button_ndepth = style_parameter['button_ndepth']
    button_data_all_vs = []
    button_data_all_vp = []
    button_data_all_rho = []
    button_data_all_top = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        button_data_all_vs.append(aprofile['vs'][:button_ndepth])
        button_data_all_vp.append(aprofile['vp'][:button_ndepth])
        button_data_all_rho.append(aprofile['rho'][:button_ndepth])
        button_data_all_top.append(aprofile['top'][:button_ndepth])
    button_data_all_bokeh = ColumnDataSource(data=dict(button_data_all_vs=button_data_all_vs,\
                                                       button_data_all_vp=button_data_all_vp,\
                                                       button_data_all_rho=button_data_all_rho,\
                                                       button_data_all_top=button_data_all_top))
    # ==============================
    map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \
                      tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \
                      y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\
                      x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']])
    #
    map_view.image_rgba('map_data_one_slice',x='x',\
                   y='y',dw='dw',dh='dh',
                   source=map_data_one_slice_bokeh, level='image')

    depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                               map_data_all_slices_bokeh=map_data_all_slices_bokeh,\
                                               colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\
                                               colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\
                                               map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code="""

        var d_index = Math.round(cb_obj.value)
        
        var map_data_all_slices = map_data_all_slices_bokeh.data
        
        map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]]
        map_data_one_slice_bokeh.change.emit()
        
        var color_data_all_slices = colorbar_data_all_slices_bokeh.data
        colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index]
        colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index]
        colorbar_data_one_slice_bokeh.change.emit()
        
        map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]]
        map_data_one_slice_depth_bokeh.change.emit()
        
    """)
    depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \
                          value=map_view_default_index, step=1, \
                          width=style_parameter['map_view_plot_width'],\
                          title=style_parameter['depth_slider_title'], height=50)
    depth_slider.js_on_change('value', depth_slider_callback)
    depth_slider_callback.args["depth_index"] = depth_slider
    # ------------------------------
    # add boundaries to map view
    # country boundaries
    map_view.multi_line(boundary_data['country']['longitude'],\
                        boundary_data['country']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # marine boundaries
    map_view.multi_line(boundary_data['marine']['longitude'],\
                        boundary_data['marine']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # shoreline boundaries
    map_view.multi_line(boundary_data['shoreline']['longitude'],\
                        boundary_data['shoreline']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # state boundaries
    map_view.multi_line(boundary_data['state']['longitude'],\
                        boundary_data['state']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # ------------------------------
    # add depth label
    map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \
                  width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \
                  width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay')
    map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\
                  text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay')
    # ------------------------------
    map_view.rect('lon', 'lat', width='width', \
                  width_units='screen', height='height', \
                  height_units='screen', line_color='gray', line_alpha=0.5, \
                  selection_line_color='gray', selection_line_alpha=0.5, selection_fill_color=None,\
                  nonselection_line_color='gray',nonselection_line_alpha=0.5, nonselection_fill_color=None,\
                  source=grid_data_bokeh, color=None, line_width=1, level='glyph')
    map_view.rect('lon', 'lat',width='width', \
                  width_units='screen', height='height', \
                  height_units='screen', line_color='#00ff00', line_alpha=1.0, \
                  source=selected_dot_on_map_bokeh, fill_color=None, line_width=3.,level='glyph')
    # ------------------------------
    grid_data_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh, \
                                                  grid_data_bokeh=grid_data_bokeh,\
                                                  profile_data_all_bokeh=profile_data_all_bokeh,\
                                                  selected_profile_data_bokeh=selected_profile_data_bokeh,\
                                                  selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\
                                                  selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \
                                                  all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \
                                                  all_profile_lon_label_bokeh=all_profile_lon_label_bokeh, \
                                                 ), code="""
        
        var inds = cb_obj.indices
        
        var grid_data = grid_data_bokeh.data
        selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][inds]]
        selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][inds]]
        selected_dot_on_map_bokeh.data['index'] = [inds]
        selected_dot_on_map_bokeh.change.emit()
        
        var profile_data_all = profile_data_all_bokeh.data
        selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][inds]
        selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][inds]
        selected_profile_data_bokeh.change.emit()
        
        var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list']
        var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list']
        selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[inds]]
        selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[inds]]
        selected_profile_lat_label_bokeh.change.emit()
        selected_profile_lon_label_bokeh.change.emit()
    """)
    grid_data_bokeh.selected.js_on_change('indices', grid_data_js)
    # ------------------------------
    # change style
    map_view.title.text_font_size = style_parameter['title_font_size']
    map_view.title.align = 'center'
    map_view.title.text_font_style = 'normal'
    map_view.xaxis.axis_label = style_parameter['map_view_xlabel']
    map_view.xaxis.axis_label_text_font_style = 'normal'
    map_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.xaxis.major_label_text_font_size = xlabel_fontsize
    map_view.yaxis.axis_label = style_parameter['map_view_ylabel']
    map_view.yaxis.axis_label_text_font_style = 'normal'
    map_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.yaxis.major_label_text_font_size = xlabel_fontsize
    map_view.xgrid.grid_line_color = None
    map_view.ygrid.grid_line_color = None
    map_view.toolbar.logo = None
    map_view.toolbar_location = 'above'
    map_view.toolbar_sticky = False
    # ==============================
    # plot colorbar
    colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \
                      plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title'])
    colorbar_fig.toolbar_location = None
    colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\
                  color='palette_r',source=colorbar_data_one_slice_bokeh)
    colorbar_fig.yaxis[0].ticker = FixedTicker(ticks=[])
    colorbar_fig.xgrid.grid_line_color = None
    colorbar_fig.ygrid.grid_line_color = None
    colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f")
    colorbar_fig.title.text_font_size = xlabel_fontsize
    colorbar_fig.title.align = 'center'
    colorbar_fig.title.text_font_style = 'normal'
    # ==============================
    profile_xrange = Range1d(start=style_parameter['profile_plot_xmin'],
                             end=style_parameter['profile_plot_xmax'])
    profile_yrange = Range1d(start=style_parameter['profile_plot_ymax'],
                             end=style_parameter['profile_plot_ymin'])
    profile_fig = Figure(plot_width=style_parameter['profile_plot_width'], plot_height=style_parameter['profile_plot_height'],\
                         x_range=profile_xrange, y_range=profile_yrange, tools=style_parameter['profile_tools'],\
                         title=style_parameter['profile_title'])
    profile_fig.line('vs',
                     'depth',
                     source=selected_profile_data_bokeh,
                     line_width=2,
                     line_color='black')
    # ------------------------------
    # add lat, lon
    profile_fig.rect([style_parameter['profile_label_box_x']], [style_parameter['profile_label_box_y']],\
                     width=style_parameter['profile_label_box_width'], height=style_parameter['profile_label_box_height'],\
                     width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black',\
                     level='underlay')
    profile_fig.text('x',
                     'y',
                     'lat_label',
                     source=selected_profile_lat_label_bokeh)
    profile_fig.text('x',
                     'y',
                     'lon_label',
                     source=selected_profile_lon_label_bokeh)
    # ------------------------------
    # change style
    profile_fig.xaxis.axis_label = style_parameter['profile_xlabel']
    profile_fig.xaxis.axis_label_text_font_style = 'normal'
    profile_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    profile_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    profile_fig.yaxis.axis_label = style_parameter['profile_ylabel']
    profile_fig.yaxis.axis_label_text_font_style = 'normal'
    profile_fig.yaxis.axis_label_text_font_size = xlabel_fontsize
    profile_fig.yaxis.major_label_text_font_size = xlabel_fontsize
    profile_fig.xgrid.grid_line_dash = [4, 2]
    profile_fig.ygrid.grid_line_dash = [4, 2]
    profile_fig.title.text_font_size = style_parameter['title_font_size']
    profile_fig.title.align = 'center'
    profile_fig.title.text_font_style = 'normal'
    profile_fig.toolbar_location = 'above'
    profile_fig.toolbar_sticky = False
    profile_fig.toolbar.logo = None
    # ==============================
    profile_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                                 grid_data_bokeh=grid_data_bokeh, \
                                                 profile_data_all_bokeh=profile_data_all_bokeh, \
                                                 selected_profile_data_bokeh=selected_profile_data_bokeh,\
                                                 selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\
                                                 selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \
                                                 all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \
                                                 all_profile_lon_label_bokeh=all_profile_lon_label_bokeh), code="""
        var p_index = Math.round(cb_obj.value)
        
        var grid_data = grid_data_bokeh.data
        selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][p_index]]
        selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][p_index]]
        selected_dot_on_map_bokeh.data['index'] = [p_index]
        selected_dot_on_map_bokeh.change.emit()
        
        var profile_data_all = profile_data_all_bokeh.data
        selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][p_index]
        selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][p_index]
        selected_profile_data_bokeh.change.emit()
        
        var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list']
        var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list']
        selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[p_index]]
        selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[p_index]]
        selected_profile_lat_label_bokeh.change.emit()
        selected_profile_lon_label_bokeh.change.emit()
        
    """)
    profile_slider = Slider(start=0, end=nprofile-1, value=style_parameter['profile_default_index'], \
                           step=1, title=style_parameter['profile_slider_title'], \
                           width=style_parameter['profile_plot_width'], height=50)
    profile_slider_callback.args['profile_index'] = profile_slider
    profile_slider.js_on_change('value', profile_slider_callback)
    # ==============================
    simple_text_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\
                                                    selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \
                                           code="""
        var index = selected_dot_on_map_bokeh.data['index']
        
        var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index]
        var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index]
        var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index]
        var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index]
        
        var csvContent = ""
        var i = 0
        var temp = csvContent
        temp += "# Layer Top (km)      Vs(km/s)    Vp(km/s)    Rho(g/cm^3) \\n"
        while(button_data_vp[i]) {
            temp+=button_data_top[i].toPrecision(6) + "    " + button_data_vs[i].toPrecision(4) + "   " + \
                    button_data_vp[i].toPrecision(4) + "   " + button_data_rho[i].toPrecision(4) + "\\n"
            i = i + 1
        }
        const blob = new Blob([temp], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'vel_model.txt';
        link.target = '_blank'
        link.style.visibility = 'hidden'
        link.dispatchEvent(new MouseEvent('click'))
        
    """)

    simple_text_button = Button(
        label=style_parameter['simple_text_button_label'],
        button_type='default',
        width=style_parameter['button_width'])
    simple_text_button.js_on_click(simple_text_button_callback)
    # ------------------------------
    model96_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\
                                                    selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \
                                           code="""
        var index = selected_dot_on_map_bokeh.data['index']
        var lat = selected_dot_on_map_bokeh.data['lat']
        var lon = selected_dot_on_map_bokeh.data['lon']
        
        var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index]
        var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index]
        var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index]
        var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index]
        
        var csvContent = ""
        var i = 0
        var temp = csvContent
        temp +=  "MODEL." + index + " \\n"
        temp +=  "ShearVelocityModel Lat: "+ lat +"  Lon: " + lon + "\\n"
        temp +=  "ISOTROPIC \\n"
        temp +=  "KGS \\n"
        temp +=  "SPHERICAL EARTH \\n"
        temp +=  "1-D \\n"
        temp +=  "CONSTANT VELOCITY \\n"
        temp +=  "LINE08 \\n"
        temp +=  "LINE09 \\n"
        temp +=  "LINE10 \\n"
        temp +=  "LINE11 \\n"
        temp +=  "      H(KM)   VP(KM/S)   VS(KM/S) RHO(GM/CC)     QP         QS       ETAP       ETAS      FREFP      FREFS \\n"
        while(button_data_vp[i+1]) {
            var thickness = button_data_top[i+1] - button_data_top[i]
            temp+="      " +thickness.toPrecision(6) + "    " + button_data_vp[i].toPrecision(4) + "      " + button_data_vs[i].toPrecision(4) \
                 + "      " + button_data_rho[i].toPrecision(4) + "     0.00       0.00       0.00       0.00       1.00       1.00" + "\\n"
            i = i + 1
        }
        const blob = new Blob([temp], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'vel_model96.txt';
        link.target = '_blank'
        link.style.visibility = 'hidden'
        link.dispatchEvent(new MouseEvent('click'))
    """)
    model96_button = Button(label=style_parameter['model96_button_label'],
                            button_type='default',
                            width=style_parameter['button_width'])
    model96_button.js_on_click(model96_button_callback)
    # ==============================
    # annotating text
    annotating_fig01 = Div(text=style_parameter['annotating_html01'], \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    annotating_fig02 = Div(text=style_parameter['annotating_html02'],\
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    # ==============================
    output_file(filename,
                title=style_parameter['html_title'],
                mode=style_parameter['library_source'])
    left_column = Column(depth_slider,
                         map_view,
                         colorbar_fig,
                         annotating_fig01,
                         width=style_parameter['left_column_width'])
    button_pannel = Row(simple_text_button, model96_button)
    right_column = Column(profile_slider,
                          profile_fig,
                          button_pannel,
                          annotating_fig02,
                          width=style_parameter['right_column_width'])
    layout = Row(left_column, right_column)
    save(layout)
Esempio n. 12
0
                         size=8)

# imaging
ulens = Table.read(
    '/Users/tumlinson/Dropbox/LUVOIR_STDT/luvoir_simtools/planetspace/imaging.dat',
    format='ascii',
    names=['name', 'msini', 'semi', 'mstar'])
a_rad = 2.7 * ulens['mstar']
ulens_syms = p1.square(ulens['semi'] / a_rad,
                       ulens['msini'] * mjup,
                       fill_alpha=0.4,
                       line_alpha=0.9,
                       color='purple',
                       size=8)

p1.text([5.2 / 2.7], [317.8], ['J'], text_color="red", text_align="center")

#xyouts, 5.2/2.7, 317.8, 'J', align=0.5
#xyouts, 9.6/2.7,  95.2, 'S', align=0.5
#xyouts, 19.2/2.7,  14.5, 'U', align=0.5
#xyouts, 30.1/2.7,  17.1, 'N', align=0.5
#xyouts, 1.0/2.7,   1.0, 'E', align=0.5
#xyouts, 0.72/2.7,   0.8, 'V', align=0.5
#xyouts, 1.5/2.7,   0.1, 'M', align=0.5
#xyouts, 0.39/2.7,   0.055, 'M', align=0.5


def update_image(active):
    print 'wHAT?'
    print active
    print active.__contains__(1)
Esempio n. 13
0
sample_curve_input = Dropdown(label="choose a sample function pair or enter one below",
                              menu=leibnitz_settings.sample_curve_names)
sample_curve_input.on_click(sample_curve_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Leibnitz sector formula",
              x_range=[leibnitz_settings.x_min_view, leibnitz_settings.x_max_view],
              y_range=[leibnitz_settings.y_min_view, leibnitz_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend='curve')
plot.scatter('x', 'y', source=source_point, color='blue', legend='point at t')
plot.scatter([0], [0], color='black', marker='x')
pat = plot.patch('x', 'y', source=source_sector, fill_color='blue', fill_alpha=.2, legend='area')
plot.line('x_start', 'y_start', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.line('x_end', 'y_end', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.text('x', 'y', text='text', text_color='text_color', source=source_text)

# calculate data
update_curve()
update_point()

# lists all the controls in our app
controls = widgetbox(t_value_input, sample_curve_input, x_component_input, y_component_input)

# make layout
curdoc().add_root(row(plot, controls))
Esempio n. 14
0
    str(int(np.sum(yields['complete9'][:]))),
    str(int(np.sum(yields['complete10'][:]))),
    str(int(np.sum(yields['complete11'][:]))),
    str(int(np.sum(yields['complete12'][:]))),
    str(int(np.sum(yields['complete13'][:]))),
    str(int(np.sum(yields['complete14'][:])))
]

hist_plot.quad(top='yields', bottom=0., left='left', right='right', source=total_yield_label, \
                color='color', fill_alpha=0.9, line_alpha=1., name='total_yield_label_hover')

hist_plot.text('xlabels',
               'yields',
               'labels',
               0.,
               20,
               -3,
               text_align='center',
               source=total_yield_label,
               text_color='black')

yield_hover = HoverTool(names=["total_yield_label_hover"],
                        mode='mouse',
                        tooltips=""" 
            <div>
                <span style="font-size: 20px; font-weight: bold; color:@color">N = </span>
                <span style="font-size: 20px; font-weight: bold; color:@color">@yields</span>
            </div>
            <div>
                <span style="font-size: 20px; font-weight: bold; color:@color">@temp </span>
            </div>
Esempio n. 15
0
p.rect("x",
       "y",
       .98,
       .98,
       0,
       source=source,
       fill_color={
           'field': 'z',
           'transform': mapper
       },
       fill_alpha=0.9)  #, color="color")
p.axis.minor_tick_line_color = None

p.text(x="x",
       y="y_offset2",
       text="ztext",
       text_font_style="bold",
       text_font_size="20pt",
       **text_props)
p.text(x="x", y="y_offset1", text="amp", text_font_size="18pt", **text_props)
formatter = PrintfTickFormatter(format='%2.1e')
color_bar = ColorBar(color_mapper=mapper,
                     major_label_text_align='left',
                     major_label_text_font_size='10pt',
                     label_standoff=2,
                     location=(0, 0),
                     formatter=formatter,
                     title="(ADU)",
                     title_text_baseline="alphabetic")

p.add_layout(color_bar, 'right')
Esempio n. 16
0
            plot_width=600,
            plot_height=300,
            title=None,
            tools=tools1)
color_block = p1.rect(x='x',
                      y='y',
                      width=18,
                      height=10,
                      fill_color='color',
                      line_color='black',
                      source=source)
hex_code_text = p1.text('x',
                        'y',
                        text='color',
                        text_color='text_color',
                        alpha=0.6667,
                        text_font_size='36pt',
                        text_baseline='middle',
                        text_align='center',
                        source=source)

# the callback function to update the color of the block and associated label text
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = CustomJS(args=dict(source=source),
                    code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
Esempio n. 17
0
                              menu=leibnitz_settings.sample_curve_names)
sample_curve_input.on_change('value', sample_curve_change)

# initialize plot
toolset = "crosshair,pan,reset,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Leibnitz sector formula",
              x_range=[leibnitz_settings.x_min_view, leibnitz_settings.x_max_view],
              y_range=[leibnitz_settings.y_min_view, leibnitz_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_curve, line_width=3, line_alpha=1, color='black', legend_label='curve')
plot.scatter('x', 'y', source=source_point, color='blue', legend_label='point at t')
plot.scatter([0], [0], color='black', marker='x')
pat = plot.patch('x', 'y', source=source_sector, fill_color='blue', fill_alpha=.2, legend_label='area')
plot.line('x_start', 'y_start', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.line('x_end', 'y_end', source=source_lines, line_width=1, line_alpha=1, color='blue')
plot.text('x', 'y', text='text', text_color='text_color', source=source_text)

# calculate data
update_curve()
update_point()

# lists all the controls in our app
controls = widgetbox(t_value_input, sample_curve_input, x_component_input, y_component_input)

# make layout
curdoc().add_root(row(plot, controls))
curdoc().title = split(dirname(__file__))[-1].replace('_',' ').replace('-',' ')  # get path of parent directory and only use the name of the Parent Directory for the tab name. Replace underscores '_' and minuses '-' with blanks ' '
Esempio n. 18
0
class pf_graph:
    def end_date(self):
        now = date.today() + timedelta(hours=4)
        return now.strftime("%Y%m%d")

    def get_quotes(self):
        self.data_slice = slice(-self.data_length, None)
        self.pf.asset_ticker = self.ticker
        quote = fn.get_quotes_finam(self.ticker,
                                    start_date=self.from_date,
                                    end_date=self.end_date(),
                                    period=self.quote_period,
                                    verbose=False,
                                    timeout=30)
        self.quote = quote[self.data_slice]
        #print(self.quote.tail())
        #self.quote.to_csv('/home/jupyter/bokeh/pf/quotes_{}'.format(self.quote_period))

    def update_quotes(self):
        quote = self.quote
        last_day = quote.ix[-1].name
        last_day_begin = datetime(last_day.year, last_day.month, last_day.day)
        quote_base = quote.ix[:last_day_begin + timedelta(seconds=-1)]
        last_day_str = last_day_begin.strftime('%Y%m%d')
        #while True:
        #print('get quotes')
        try:
            quote = fn.get_quotes_finam(self.ticker,
                                        start_date=last_day_str,
                                        end_date=self.end_date(),
                                        period=self.quote_period,
                                        verbose=False,
                                        timeout=5)
        except timeout as e:
            print('get quotes: timeout, period={}!'.format(self.quote_period))
            self.text.value = 'timeout!'
            return
        except:
            self.text.value = 'get quote error!'
            return
        #print('obtain quotes')
        self.quote = quote_base.append(quote)[self.data_slice]
        time_str = quote.ix[-1].name.strftime('%Y-%m-%d %H:%M')
        if self.text_marker == len(markers) - 1:
            self.text_marker = 0
        else:
            self.text_marker += 1
        self.text.value = '{} [{}] {}'.format(
            markers[self.text_marker], time_str,
            quote.ix[-1][self.ticker + '_Close'])
        #time.sleep(1)

    def __init__(self, quote_period, box_size, graph_name, candles=30):
        # Set up data
        self.graph_counter = 0
        self.data_length = candles
        self.data_slice = slice(-self.data_length, None)
        self.quote_period = quote_period
        self.ticker = 'SPFB.RTS'
        self.box_size_divider = 1.

        self.pf = point_and_figure.Point_and_Figure()

        #print(quote_period)
        if (quote_period == 'daily' or quote_period == 'hour'):
            self.from_date = (date.today() - timedelta(
                days=days_look_back_min_candles * 5)).strftime('%Y%m%d')
        else:
            self.from_date = (
                date.today() -
                timedelta(days=days_look_back_min_candles)).strftime('%Y%m%d')

        self.get_quotes()
        self.last_quote_date = None

        self.pf.box_size = box_size
        self.pf.process_df(self.quote)
        self.pf.prepare_datasource()

        self.plot = Figure(
            plot_height=400,
            plot_width=600,
            title=graph_name,
            tools="crosshair,pan,reset,resize,wheel_zoom,save",
        )
        self.yticker = bokeh.models.FixedTicker()
        #print pf.yticks
        self.yticker.ticks = list(self.pf.yticks)
        self.xticker = bokeh.models.FixedTicker()
        self.xticker.ticks = list(self.pf.xticks)
        # ticker.interval = 1
        #p.xaxis.ticker = ticker
        self.plot.ygrid.ticker = self.yticker
        self.plot.xgrid.ticker = self.xticker
        self.plot.yaxis.formatter = bokeh.models.NumeralTickFormatter(
            format=self.pf.bokeh_ticks_format)
        self.plot.yaxis.ticker = self.yticker
        #self.plot.ygrid.band_fill_alpha = 0.05
        #self.plot.ygrid.band_fill_color = "navy"
        #self.glyphs_size = 100.
        #self.glyphs_size = self.pf.box_size / 1. / len(self.pf.yticks) * self.pf.scale_factor

        self.scale = Slider(title="scale",
                            value=300,
                            start=300,
                            end=3000,
                            step=1)
        self.scale.on_change('value', self.scale_change)

        self.recalc_glyphs_size = True
        self.calc_glyphs()
        self.source_x = ColumnDataSource(
            data=dict(x=self.pf.x_x, y=self.pf.x_y, size=self.glyphs_size_x))
        self.source_o = ColumnDataSource(
            data=dict(x=self.pf.o_x, y=self.pf.o_y, size=self.glyphs_size_o))
        self.source_digits = ColumnDataSource(
            data=dict(x=self.pf.digits_x,
                      y=self.pf.digits_y,
                      text=self.pf.digits_text,
                      size=self.font_size))
        self.graph_o = self.plot.circle('x',
                                        'y',
                                        source=self.source_o,
                                        alpha=0.5,
                                        size='size',
                                        color="navy")
        self.graph_x = self.plot.cross('x',
                                       'y',
                                       source=self.source_x,
                                       alpha=0.5,
                                       size='size',
                                       color="navy",
                                       angle=np.pi / 4)
        self.graph_digits = self.plot.text(
            'x',
            'y',
            source=self.source_digits,
            alpha=0.5,
            text='text',
            color="navy",
            text_font_size='size')  #text_font_size

        self.box = Slider(title="box",
                          value=self.pf.box_size,
                          start=10,
                          end=500,
                          step=1)
        self.box.on_change('value', self.box_change)

        self.text = TextInput()
        self.text_marker = 0

    def calc_glyphs(self):
        #self.glyphs_size = self.pf.box_size / 4. / len(self.pf.yticks) * self.pf.scale_factor
        #print self.glyphs_size
        if self.recalc_glyphs_size:
            self.glyphs_size = min(
                self.plot.plot_height / 1.2 / (len(self.pf.yticks) + 3),
                self.plot.plot_width / 1.2 / (len(self.pf.xticks) + 3))
            self.scale.value = int(self.glyphs_size * 100)
        self.recalc_glyphs_size = False
        if self.glyphs_size < 3:
            self.glyphs_size = 3
        self.glyphs_size_x = [self.glyphs_size for _ in self.pf.x_x]
        self.glyphs_size_o = [self.glyphs_size for _ in self.pf.o_x]
        self.font_size = [
            '{}px'.format(self.glyphs_size) for _ in self.pf.digits_x
        ]
        #print(self.glyphs_size_x)

    def scale_change(self, attrname, old, new):
        self.glyphs_size = self.scale.value / 100.
        #print(self.glyphs_size)

    def box_change(self, attrname, old, new):
        self.pf.box_size = self.box.value / self.box_size_divider
        self.recalc_glyphs_size = True

    def update_data(self, attrname, old, new):
        #print('box')
        # Get the current slider values

        # Generate the new curve
        self.pf.process_df(self.quote)
        self.pf.prepare_datasource()
        self.yticker.ticks = list(self.pf.yticks)
        self.xticker.ticks = list(self.pf.xticks)
        self.calc_glyphs()
        #self.graph_o.glyph.size = self.glyphs_size
        #self.graph_x.glyph.size = self.glyphs_size
        #self.shuffle(x=self.pf.x_x, y=self.pf.x_y)
        data = dict(x=self.pf.x_x, y=self.pf.x_y, size=self.glyphs_size_x)
        self.source_x.data = data
        #self.shuffle(x=self.pf.o_x, y=self.pf.o_y)
        data = dict(x=self.pf.o_x, y=self.pf.o_y, size=self.glyphs_size_o)
        self.source_o.data = data
        data = dict(x=self.pf.digits_x,
                    y=self.pf.digits_y,
                    text=self.pf.digits_text,
                    size=self.font_size)
        self.source_digits.data = data
Esempio n. 19
0
            title='move sliders to change',
            tools='')

p1.rect(0,
        0,
        width=18,
        height=10,
        fill_color='color',
        line_color='black',
        source=source)

p1.text(0,
        0,
        text='color',
        text_color='text_color',
        alpha=0.6667,
        text_font_size='36pt',
        text_baseline='middle',
        text_align='center',
        source=source)

# the callback function to update the color of the block and associated label text
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = CustomJS(args=dict(source=source),
                    code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
Esempio n. 20
0
    def plot_amp(self,
                 dz,
                 refexp,
                 name="",
                 font_size="1.2vw",
                 description="",
                 nrg=[],
                 wrg=[],
                 status_plot=False):
        ''' Initializing AMP plot
        '''
        ztext, cbarformat = self.set_amp(dz)
        dx = [0, 1, 0, 1]
        dy = [1, 1, 0, 0]

        zvalid = np.array([x if x > -999 else np.nan for x in dz])
        data_source = dict(
            x=dx,
            y=dy,
            z=dz,
            zvalid=zvalid,
            ref=["{:.2f}".format(x) for x in refexp],
            zdiff=zvalid - np.array(refexp),
            y_offset1=[i + 0.15 for i in dy],
            y_offset2=[i - 0.10 for i in dy],
            amp=['AMP %s' % i for i in range(1, 5)],
            amp_number=['%s' % i for i in range(1, 5)],
            ztext=ztext,
        )

        if status_plot:
            text_val = 'status'
            color_status = ['green', 'darkgrey', 'yellow', 'red']
            color = {
                'NaN': 'darkgrey',
                'NORMAL': 'green',
                'WARNING': 'yellow',
                'ALARM': 'red',
            }
            status = [
                self.val_status(x, nrg=nrg, wrg=wrg)
                for x in zvalid - np.array(refexp)
            ]
            color_status = [
                color[self.val_status(x, nrg=nrg, wrg=wrg)]
                for x in zvalid - np.array(refexp)
            ]
            fill_color = "color_status"
            data_source.update({
                'status': status,
                'color_status': color_status,
            })
            fill_alpha = 0.8

        if not status_plot:
            text_val = 'ztext'
            cmap = get_palette("RdBu_r")
            mapper = LinearColorMapper(palette=cmap,
                                       low=wrg[0],
                                       high=wrg[1],
                                       nan_color="darkgrey")
            formatter = PrintfTickFormatter(format=cbarformat)
            color_bar = ColorBar(color_mapper=mapper,
                                 major_label_text_align='left',
                                 major_label_text_font_size='10pt',
                                 label_standoff=2,
                                 location=(0, 0),
                                 formatter=formatter,
                                 title="(Val-Ref)",
                                 title_standoff=15,
                                 title_text_baseline="alphabetic")
            fill_color = {'field': 'zdiff', 'transform': mapper}
            fill_alpha = 0.9

        cmap_tooltip = """
            <div>

                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">AMP: </span>
                    <span style="font-size: 1vw; color: #515151;">@amp_number</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">counts: </span>
                    <span style="font-size: 1vw; color: #515151">@text_val</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Reference: </span>
                    <span style="font-size: 1vw; color: #515151;">@ref</span>
                </div>
            </div>
        """.replace("counts:",
                    name.replace("_AMP", "") + ":").replace(
                        "text_val", text_val)

        hover = HoverTool(tooltips=cmap_tooltip)

        p = Figure(title=name,
                   tools=[hover],
                   x_range=list([-0.5, 1.5]),
                   y_range=list([-0.5, 1.5]),
                   plot_width=450,
                   plot_height=400)

        source = ColumnDataSource(data=data_source)

        text_props = {
            "source": source,
            "angle": 0,
            "color": "black",
            "text_color": "black",
            "text_align": "center",
            "text_baseline": "middle"
        }

        p.rect("x",
               "y",
               .98,
               .98,
               0,
               source=source,
               fill_color=fill_color,
               fill_alpha=fill_alpha)
        p.text(x="x",
               y="y_offset1",
               text="amp",
               text_font_size="2vw",
               **text_props)
        p.text(x="x",
               y="y_offset2",
               text="ztext",
               text_font_style="bold",
               text_font_size="2.5vw",
               **text_props)

        if not status_plot:
            p.add_layout(color_bar, 'right')

        # Format:
        p.xaxis.axis_label_text_font_size = font_size
        p.legend.label_text_font_size = font_size
        p.title.text_font_size = font_size
        p.xaxis.axis_label = description

        # Clear Axis:
        p.grid.grid_line_color = None
        p.outline_line_color = None
        p.axis.minor_tick_line_color = None
        p.axis.major_label_text_font_size = '0pt'
        p.yaxis.major_label_text_font_size = '0pt'
        p.xaxis.major_tick_line_color = None
        p.xaxis.minor_tick_line_color = None
        p.yaxis.major_tick_line_color = None
        p.yaxis.minor_tick_line_color = None
        p.yaxis.visible = False
        p.xaxis.visible = True
        p.axis.clear

        return p
Esempio n. 21
0
        """)

# Set up plot
snr_plot = Figure(plot_height=400,
                  plot_width=800,
                  tools="crosshair,pan,reset,resize,save,box_zoom,wheel_zoom",
                  x_range=[120, 2300],
                  y_range=[0, 40],
                  toolbar_location='right')
snr_plot.x_range = Range1d(120, 2300, bounds=(120, 2300))
snr_plot.add_tools(hover)
snr_plot.background_fill_color = "beige"
snr_plot.background_fill_alpha = 0.5
snr_plot.yaxis.axis_label = 'SNR'
snr_plot.xaxis.axis_label = 'Wavelength (nm)'
snr_plot.text(5500, 20, text=['V'], text_align='center', text_color='red')

snr_plot.line('x', 'y', source=source, line_width=3, line_alpha=1.0)
snr_plot.circle('x',
                'y',
                source=source,
                fill_color='white',
                line_color='blue',
                size=10)

snr_plot.line('x',
              'y',
              source=source2,
              line_width=3,
              line_color='orange',
              line_alpha=1.0)
def plot_waveform_bokeh(filename,waveform_list,metadata_list,station_lat_list,\
                       station_lon_list, event_lat, event_lon, boundary_data, style_parameter):
    xlabel_fontsize = style_parameter['xlabel_fontsize']
    #
    map_station_location_bokeh = ColumnDataSource(data=dict(map_lat_list=station_lat_list,\
                                                            map_lon_list=station_lon_list))
    dot_default_index = 0
    selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[station_lat_list[dot_default_index]],\
                                                           lon=[station_lon_list[dot_default_index]],\
                                                           index=[dot_default_index]))
    map_view = Figure(plot_width=style_parameter['map_view_plot_width'], \
                      plot_height=style_parameter['map_view_plot_height'], \
                      y_range=[style_parameter['map_view_lat_min'],\
                    style_parameter['map_view_lat_max']], x_range=[style_parameter['map_view_lon_min'],\
                    style_parameter['map_view_lon_max']], tools=style_parameter['map_view_tools'],\
                    title=style_parameter['map_view_title'])
    # ------------------------------
    # add boundaries to map view
    # country boundaries
    map_view.multi_line(boundary_data['country']['longitude'],\
                        boundary_data['country']['latitude'],color='gray',\
                        line_width=2, level='underlay', nonselection_line_alpha=1.0,\
                        nonselection_line_color='gray')
    # marine boundaries
    map_view.multi_line(boundary_data['marine']['longitude'],\
                        boundary_data['marine']['latitude'],color='gray',\
                        level='underlay', nonselection_line_alpha=1.0,\
                        nonselection_line_color='gray')
    # shoreline boundaries
    map_view.multi_line(boundary_data['shoreline']['longitude'],\
                        boundary_data['shoreline']['latitude'],color='gray',\
                        line_width=2, nonselection_line_alpha=1.0, level='underlay',
                        nonselection_line_color='gray')
    # state boundaries
    map_view.multi_line(boundary_data['state']['longitude'],\
                        boundary_data['state']['latitude'],color='gray',\
                        level='underlay', nonselection_line_alpha=1.0,\
                        nonselection_line_color='gray')
    #
    map_view.triangle('map_lon_list', 'map_lat_list', source=map_station_location_bokeh, \
                      line_color='gray', size=style_parameter['marker_size'], fill_color='black',\
                      selection_color='black', selection_line_color='gray',\
                      selection_fill_alpha=1.0,\
                      nonselection_fill_alpha=1.0, nonselection_fill_color='black',\
                      nonselection_line_color='gray', nonselection_line_alpha=1.0)
    map_view.triangle('lon','lat', source=selected_dot_on_map_bokeh,\
                      size=style_parameter['selected_marker_size'], line_color='black',fill_color='red')
    map_view.asterisk([event_lon], [event_lat], size=style_parameter['event_marker_size'], line_width=3, line_color='red', \
                      fill_color='red')
    # change style
    map_view.title.text_font_size = style_parameter['title_font_size']
    map_view.title.align = 'center'
    map_view.title.text_font_style = 'normal'
    map_view.xaxis.axis_label = style_parameter['map_view_xlabel']
    map_view.xaxis.axis_label_text_font_style = 'normal'
    map_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.xaxis.major_label_text_font_size = xlabel_fontsize
    map_view.yaxis.axis_label = style_parameter['map_view_ylabel']
    map_view.yaxis.axis_label_text_font_style = 'normal'
    map_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.yaxis.major_label_text_font_size = xlabel_fontsize
    map_view.xgrid.grid_line_color = None
    map_view.ygrid.grid_line_color = None
    map_view.toolbar.logo = None
    map_view.toolbar_location = 'above'
    map_view.toolbar_sticky = False
    # --------------------------------------------------------
    max_waveform_length = 0
    max_waveform_amp = 0
    ncurve = len(waveform_list)
    for a_sta in waveform_list:
        for a_trace in a_sta:
            if len(a_trace) > max_waveform_length:
                max_waveform_length = len(a_trace)
            if np.max(np.abs(a_trace)) > max_waveform_amp:
                max_waveform_amp = np.max(np.abs(a_trace))
    #
    plotting_list = []
    for a_sta in waveform_list:
        temp = []
        for a_trace in a_sta:
            if len(a_trace) < max_waveform_length:
                a_trace = np.append(a_trace,np.zeros([(max_waveform_length-len(a_trace)),1]))
            temp.append(list(a_trace))
        plotting_list.append(temp)
    #
    time_list = []
    for ista in range(len(plotting_list)):
        a_sta = plotting_list[ista]
        temp = []
        for itr in range(len(a_sta)):
            a_trace = a_sta[itr]
            delta = metadata_list[ista][itr]['delta']
            time = list(np.arange(len(a_trace))*delta)
            temp.append(time)
        #
        time_list.append(temp)
    #
    reftime_label_list = []
    channel_label_list = []
    for ista in range(len(metadata_list)):
        temp_ref = []
        temp_channel = []
        a_sta = metadata_list[ista]
        for a_trace in a_sta:
            temp_ref.append('Starting from '+a_trace['starttime'])
            temp_channel.append(a_trace['network']+'_'+a_trace['station']+'_'+a_trace['channel'])
        reftime_label_list.append(temp_ref)
        channel_label_list.append(temp_channel)
    # --------------------------------------------------------
    curve_fig01 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \
                       y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \
                       x_range=(0,max_waveform_length),\
                    tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) 
    #
    curve_index = 0
    select_curve_data = plotting_list[dot_default_index][curve_index]
    select_curve_time = time_list[dot_default_index][curve_index]
    
    selected_curve_data_bokeh01 = ColumnDataSource(data=dict(time=select_curve_time,amp=select_curve_data))
    select_reftime_label = reftime_label_list[dot_default_index][curve_index]
    selected_reftime_label_bokeh01 = ColumnDataSource(data=dict(x=[style_parameter['curve_reftime_label_x']],\
                                                                y=[style_parameter['curve_reftime_label_y']],\
                                                                label=[select_reftime_label]))
    select_channel_label = channel_label_list[dot_default_index][curve_index]
    selected_channel_label_bokeh01 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\
                                                                y=[style_parameter['curve_channel_label_y']],\
                                                                label=[select_channel_label]))
    all_curve_data_bokeh = ColumnDataSource(data=dict(t=time_list, amp=plotting_list))
    all_reftime_label_bokeh = ColumnDataSource(data=dict(label=reftime_label_list))
    all_channel_label_bokeh = ColumnDataSource(data=dict(label=channel_label_list))
    # plot waveform
    curve_fig01.line('time','amp', source=selected_curve_data_bokeh01,\
                   line_color='black')
    # add refference time as a label
    curve_fig01.text('x', 'y', 'label', source=selected_reftime_label_bokeh01)
    # add channel label
    curve_fig01.text('x', 'y', 'label', source=selected_channel_label_bokeh01)
    # change style
    curve_fig01.title.text_font_size = style_parameter['title_font_size']
    curve_fig01.title.align = 'center'
    curve_fig01.title.text_font_style = 'normal'
    curve_fig01.xaxis.axis_label = style_parameter['curve_xlabel']
    curve_fig01.xaxis.axis_label_text_font_style = 'normal'
    curve_fig01.xaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig01.xaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig01.yaxis.axis_label = style_parameter['curve_ylabel']
    curve_fig01.yaxis.axis_label_text_font_style = 'normal'
    curve_fig01.yaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig01.yaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig01.toolbar.logo = None
    curve_fig01.toolbar_location = 'above'
    curve_fig01.toolbar_sticky = False
    # --------------------------------------------------------
    curve_fig02 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \
                       y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \
                       x_range=(0,max_waveform_length),\
                    tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) 
    #
    curve_index = 1
    select_curve_data = plotting_list[dot_default_index][curve_index]
    select_curve_time = time_list[dot_default_index][curve_index]
    selected_curve_data_bokeh02 = ColumnDataSource(data=dict(time=select_curve_time,amp=select_curve_data))
    select_channel_label = channel_label_list[dot_default_index][curve_index]
    selected_channel_label_bokeh02 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\
                                                                y=[style_parameter['curve_channel_label_y']],\
                                                                label=[select_channel_label]))
    # plot waveform
    curve_fig02.line('time','amp', source=selected_curve_data_bokeh02,\
                   line_color='black')
    # add channel label
    curve_fig02.text('x', 'y', 'label', source=selected_channel_label_bokeh02)
    # change style
    curve_fig02.title.text_font_size = style_parameter['title_font_size']
    curve_fig02.title.align = 'center'
    curve_fig02.title.text_font_style = 'normal'
    curve_fig02.xaxis.axis_label = style_parameter['curve_xlabel']
    curve_fig02.xaxis.axis_label_text_font_style = 'normal'
    curve_fig02.xaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig02.xaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig02.yaxis.axis_label = style_parameter['curve_ylabel']
    curve_fig02.yaxis.axis_label_text_font_style = 'normal'
    curve_fig02.yaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig02.yaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig02.toolbar.logo = None
    curve_fig02.toolbar_location = 'above'
    curve_fig02.toolbar_sticky = False
    # --------------------------------------------------------
    curve_fig03 = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \
                       y_range=(-max_waveform_amp*1.05,max_waveform_amp*1.05), \
                       x_range=(0,max_waveform_length),\
                    tools=['save','box_zoom','ywheel_zoom','xwheel_zoom','reset','crosshair','pan']) 
    #
    curve_index = 2
    select_curve_data = plotting_list[dot_default_index][curve_index]
    select_curve_time = time_list[dot_default_index][curve_index]
    selected_curve_data_bokeh03 = ColumnDataSource(data=dict(time=select_curve_time,amp=select_curve_data))
    select_channel_label = channel_label_list[dot_default_index][curve_index]
    selected_channel_label_bokeh03 = ColumnDataSource(data=dict(x=[style_parameter['curve_channel_label_x']],\
                                                                y=[style_parameter['curve_channel_label_y']],\
                                                                label=[select_channel_label]))
    # plot waveform
    curve_fig03.line('time','amp', source=selected_curve_data_bokeh03,\
                   line_color='black')
    # add channel label
    curve_fig03.text('x', 'y', 'label', source=selected_channel_label_bokeh03)
    # change style
    curve_fig03.title.text_font_size = style_parameter['title_font_size']
    curve_fig03.title.align = 'center'
    curve_fig03.title.text_font_style = 'normal'
    curve_fig03.xaxis.axis_label = style_parameter['curve_xlabel']
    curve_fig03.xaxis.axis_label_text_font_style = 'normal'
    curve_fig03.xaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig03.xaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig03.yaxis.axis_label = style_parameter['curve_ylabel']
    curve_fig03.yaxis.axis_label_text_font_style = 'normal'
    curve_fig03.yaxis.axis_label_text_font_size = xlabel_fontsize
    curve_fig03.yaxis.major_label_text_font_size = xlabel_fontsize
    curve_fig03.toolbar.logo = None
    curve_fig03.toolbar_location = 'above'
    curve_fig03.toolbar_sticky = False
    # --------------------------------------------------------
    map_station_location_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                                            map_station_location_bokeh=map_station_location_bokeh,\
                                                            selected_curve_data_bokeh01=selected_curve_data_bokeh01,\
                                                            selected_curve_data_bokeh02=selected_curve_data_bokeh02,\
                                                            selected_curve_data_bokeh03=selected_curve_data_bokeh03,\
                                                            selected_channel_label_bokeh01=selected_channel_label_bokeh01,\
                                                            selected_channel_label_bokeh02=selected_channel_label_bokeh02,\
                                                            selected_channel_label_bokeh03=selected_channel_label_bokeh03,\
                                                            selected_reftime_label_bokeh01=selected_reftime_label_bokeh01,\
                                                            all_reftime_label_bokeh=all_reftime_label_bokeh,\
                                                            all_channel_label_bokeh=all_channel_label_bokeh,\
                                                            all_curve_data_bokeh=all_curve_data_bokeh), code="""
    var inds = cb_obj.indices
    
    selected_dot_on_map_bokeh.data['index'] = [inds]
    var new_loc = map_station_location_bokeh.data
    
    selected_dot_on_map_bokeh.data['lat'] = [new_loc['map_lat_list'][inds]]
    selected_dot_on_map_bokeh.data['lon'] = [new_loc['map_lon_list'][inds]]
    
    selected_dot_on_map_bokeh.change.emit()
    
    selected_curve_data_bokeh01.data['t'] = all_curve_data_bokeh.data['t'][inds][0]
    selected_curve_data_bokeh01.data['amp'] = all_curve_data_bokeh.data['amp'][inds][0]

    selected_curve_data_bokeh01.change.emit()
    
    selected_curve_data_bokeh02.data['t'] = all_curve_data_bokeh.data['t'][inds][1]
    selected_curve_data_bokeh02.data['amp'] = all_curve_data_bokeh.data['amp'][inds][1]

    selected_curve_data_bokeh02.change.emit()
    
    selected_curve_data_bokeh03.data['t'] = all_curve_data_bokeh.data['t'][inds][2]
    selected_curve_data_bokeh03.data['amp'] = all_curve_data_bokeh.data['amp'][inds][2]

    selected_curve_data_bokeh03.change.emit()
    
    selected_reftime_label_bokeh01.data['label'] = [all_reftime_label_bokeh.data['label'][inds][0]]
    
    selected_reftime_label_bokeh01.change.emit()
    
    selected_channel_label_bokeh01.data['label'] = [all_channel_label_bokeh.data['label'][inds][0]]
    
    selected_channel_label_bokeh01.change.emit()
    
    selected_channel_label_bokeh02.data['label'] = [all_channel_label_bokeh.data['label'][inds][1]]
    
    selected_channel_label_bokeh02.change.emit()
    
    selected_channel_label_bokeh03.data['label'] = [all_channel_label_bokeh.data['label'][inds][2]]
    
    selected_channel_label_bokeh03.change.emit()
    """)
    #
    map_station_location_bokeh.selected.js_on_change('indices', map_station_location_js)
    #
    curve_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                                map_station_location_bokeh=map_station_location_bokeh,\
                                                selected_curve_data_bokeh01=selected_curve_data_bokeh01,\
                                                selected_curve_data_bokeh02=selected_curve_data_bokeh02,\
                                                selected_curve_data_bokeh03=selected_curve_data_bokeh03,\
                                                selected_channel_label_bokeh01=selected_channel_label_bokeh01,\
                                                selected_channel_label_bokeh02=selected_channel_label_bokeh02,\
                                                selected_channel_label_bokeh03=selected_channel_label_bokeh03,\
                                                selected_reftime_label_bokeh01=selected_reftime_label_bokeh01,\
                                                all_reftime_label_bokeh=all_reftime_label_bokeh,\
                                                all_channel_label_bokeh=all_channel_label_bokeh,\
                                                all_curve_data_bokeh=all_curve_data_bokeh),code="""
    var inds = Math.round(cb_obj.value)
    
    selected_dot_on_map_bokeh.data['index'] = [inds]
    var new_loc = map_station_location_bokeh.data
    
    selected_dot_on_map_bokeh.data['lat'] = [new_loc['map_lat_list'][inds]]
    selected_dot_on_map_bokeh.data['lon'] = [new_loc['map_lon_list'][inds]]
    
    selected_dot_on_map_bokeh.change.emit()
    
    selected_curve_data_bokeh01.data['t'] = all_curve_data_bokeh.data['t'][inds][0]
    selected_curve_data_bokeh01.data['amp'] = all_curve_data_bokeh.data['amp'][inds][0]

    selected_curve_data_bokeh01.change.emit()
    
    selected_curve_data_bokeh02.data['t'] = all_curve_data_bokeh.data['t'][inds][1]
    selected_curve_data_bokeh02.data['amp'] = all_curve_data_bokeh.data['amp'][inds][1]

    selected_curve_data_bokeh02.change.emit()
    
    selected_curve_data_bokeh03.data['t'] = all_curve_data_bokeh.data['t'][inds][2]
    selected_curve_data_bokeh03.data['amp'] = all_curve_data_bokeh.data['amp'][inds][2]

    selected_curve_data_bokeh03.change.emit()
    
    selected_reftime_label_bokeh01.data['label'] = [all_reftime_label_bokeh.data['label'][inds][0]]
    
    selected_reftime_label_bokeh01.change.emit()
    
    selected_channel_label_bokeh01.data['label'] = [all_channel_label_bokeh.data['label'][inds][0]]
    
    selected_channel_label_bokeh01.change.emit()
    
    selected_channel_label_bokeh02.data['label'] = [all_channel_label_bokeh.data['label'][inds][1]]
    
    selected_channel_label_bokeh02.change.emit()
    
    selected_channel_label_bokeh03.data['label'] = [all_channel_label_bokeh.data['label'][inds][2]]
    
    selected_channel_label_bokeh03.change.emit()
    """)
    curve_slider = Slider(start=0, end=ncurve-1, value=style_parameter['curve_default_index'], \
                          step=1, title=style_parameter['curve_slider_title'], width=style_parameter['map_view_plot_width'],\
                          height=50, callback=curve_slider_callback)
    
    # ==============================
    # annotating text
    annotating_fig01 = Div(text=style_parameter['annotating_html01'], \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    annotating_fig02 = Div(text=style_parameter['annotating_html02'],\
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    # ==============================
    output_file(filename,title=style_parameter['html_title'],mode=style_parameter['library_source'])
    #
    left_fig = Column(curve_slider, map_view, annotating_fig01, width=style_parameter['left_column_width'] )
    
    right_fig = Column(curve_fig01, curve_fig02, curve_fig03, annotating_fig02, width=style_parameter['right_column_width'])
    layout = Row(left_fig, right_fig)
    save(layout)
Esempio n. 23
0
# initialise the text color as black. This will be switched to white if the block color gets dark enough
text_color = '#000000'

# create a data source to enable refreshing of fill & text color
source = ColumnDataSource(data=dict(x = x, y = y, color = [hex_color], text_color = [text_color]))

tools1 = 'reset, save'

# create first plot, as a rect() glyph and centered text label, with fill and text color taken from source
p1 = Figure(x_range=(-8, 8), y_range=(-4, 4), plot_width=600, plot_height=300,
            title=None, tools=tools1)
color_block = p1.rect(x='x', y='y', width=18, height=10, fill_color='color',
                      line_color = 'black', source=source)
hex_code_text = p1.text('x', 'y', text='color', text_color='text_color',
                        alpha=0.6667, text_font_size='36pt', text_baseline='middle',
                        text_align='center', source=source)

# the callback function to update the color of the block and associated label text
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = CustomJS(args=dict(source=source), code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }
    var data = source.get('data');
    var RS = red_slider;
Esempio n. 24
0
class AppView(object):

    def __init__(self, app_model):
        self.model = app_model
        self.create_layout()

    def create_layout(self):
        # create figure
        self.x_range = Range1d(start=self.model.map_extent[0],
                               end=self.model.map_extent[2], bounds=None)
        self.y_range = Range1d(start=self.model.map_extent[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 

    def update_image(self):
        self.model.shader_url_vars['cachebust'] = str(uuid.uuid4())
        self.image_renderer.image_source = ImageSource(url=self.model.service_url, extra_url_vars=self.model.shader_url_vars)
        self.fig.xaxis.axis_label=self.model.active_axes['xtitle']  
        self.fig.yaxis.axis_label=self.model.active_axes['ytitle'] 

    def on_field_change(self, attr, old, new):
        self.model.field_title = new
        self.model.field = self.model.fields[new]

        self.update_image()

        if not self.model.field:
            self.aggregate_select.options = [("No Aggregates Available", "")]
        elif self.model.field in self.model.categorical_fields:
            self.aggregate_select.options = [("Categorical", "count_cat")]
        else:
            opts = [(k, k) for k in self.model.aggregate_functions.keys()]
            self.aggregate_select.options = opts

    def on_spread_size_change(self, attr, old, new):
        self.model.spread_size = int(new)
        self.update_image()

    def on_aperture_size_change(self, attr, old, new):
        self.model.aperture = int(new)
        self.update_image()

    def on_age_change(self, attr, old, new):
        self.model.age = new
        self.update_image()

    def on_exposure_time_change(self, attr, old, new):
        self.model.exposure_time = int(new)
        self.update_image()

    def on_distance_change(self, attr, old, new):
        self.model.distance = int(new)
        self.update_image()

    def on_axes_change(self, attr, old, new):
        print("self.model.axes ", self.model.axes) 
        self.model.active_axes = self.model.axes[new]
        self.update_image()

    def on_aggregate_change(self, attr, old, new):
        self.model.agg_function_name = new
        self.update_image()

    def on_transfer_function_change(self, attr, old, new):
        self.model.transfer_function = self.model.transfer_functions[new]
        self.update_image()

    def on_color_ramp_change(self, attr, old, new):
        self.model.color_ramp = self.model.color_ramps[new]
        self.update_image()

    def on_image_opacity_slider_change(self, attr, old, new):
        self.image_renderer.alpha = new / 100
    def _segment_plot(self, source):
        """Plot showing the mirror segments.

        The plot shows the 91 segment positions with their position number. The colour of the segments indicates how
        long ago they have been recoated.

        Params:
        -------
        source: pandas.DataFrame
            Data source.

        Returns:
        --------
        bokeh.plotting.Figure
            Plot showing the mirror segments.
        """

        def segment_color(date):
            """Fill colour of a mirror segment."""
            days = (datetime.datetime.now().date() - date).days
            days = min(days, self.RECOATING_PERIOD)
            days = max(days, 0)

            def hex_value(v):
                """Convert integer into a hexadecimal string suitable for specifying an RGB value in a css rule."""
                s = format(int(round(255 * v)), 'x')
                if len(s) < 2:
                    s = '0' + s
                return s

            # The colour ranges from dark green for recently recoated segments to white for segments which need to be
            # recoated.
            h = 99
            s = 100
            l = 33 + 67 * days / self.RECOATING_PERIOD
            rgb = colorsys.hls_to_rgb(h / 360, l / 100, s / 100)

            return '#{r}{g}{b}'.format(r=hex_value(rgb[0]),
                                       g=hex_value(rgb[1]),
                                       b=hex_value(rgb[2]))

        plot = Figure(tools='tap', toolbar_location=None)
        colors = [segment_color(d) for d in source.data['ReplacementDate']]
        plot.patches(xs='SegmentPositionCornerXs',
                     ys='SegmentPositionCornerYs',
                     source=source,
                     color=colors,
                     line_color='#dddddd')
        plot.text(x='SegmentPositionX',
                  y='SegmentPositionY',
                  text='SegmentPosition',
                  source=source,
                  text_color='black',
                  text_align='center',
                  text_baseline='middle')

        plot.grid.grid_line_color = None
        plot.axis.visible = False

        plot.min_border_top = 20
        plot.min_border_bottom = 30

        plot.outline_line_color = None

        return plot