Esempio n. 1
0
def hist_plot(ticker, alias, hsource, df, plot=None, selected_df=None):
    if selected_df is None:
        selected_df = df

    global_hist, global_bins = np.histogram(df[ticker + "_returns"], bins=50)
    hist, bins = np.histogram(selected_df[ticker + "_returns"], bins=50)

    top = hist.max()
    start = global_bins.min()
    end = global_bins.max()
    width = 0.7 * (bins[1] - bins[0])
    hdata = dict(
        width = [width] * len(hist),
        center = (bins[:-1] + bins[1:]) / 2,
        hist2 = hist / 2.0,
        hist = hist
    )
    hsource.data = hdata

    if plot is None:
        plot = Figure(
            plot_width=500, plot_height=200,
            tools="",
            title_text_font_size="10pt",
            x_range=[start, end],
            y_range=[0, top],
        )
        plot.rect('center', 'hist2', 'width', 'hist', source=hsource)

    plot.x_range.start = start
    plot.x_range.end = end
    plot.y_range.start = 0
    plot.y_range.end = top
    plot.title = "%s hist" % alias
    return plot
Esempio n. 2
0
def render_correlation_impact(itmdt: Intermediate, plot_width: int,
                              plot_height: int,
                              palette: Sequence[str]) -> Dict[str, Any]:
    """
    Render correlation heatmaps in to tabs
    """
    tabs: List[Panel] = []
    tooltips = [("x", "@x"), ("y", "@y"),
                ("correlation", "@correlation{1.11}")]
    axis_range = itmdt["axis_range"]

    for method, df in itmdt["data"].items():
        # in case of numerical column names
        df = df.copy()
        df["x"] = df["x"].apply(str)
        df["y"] = df["y"].apply(str)

        mapper, color_bar = create_color_mapper(palette)
        x_range = FactorRange(*axis_range)
        y_range = FactorRange(*reversed(axis_range))
        fig = Figure(
            x_range=x_range,
            y_range=y_range,
            plot_width=plot_width,
            plot_height=plot_height,
            x_axis_location="below",
            tools="hover",
            toolbar_location=None,
            tooltips=tooltips,
            background_fill_color="#fafafa",
            title=" ",
        )

        tweak_figure(fig)

        fig.rect(
            x="x",
            y="y",
            width=1,
            height=1,
            source=df,
            fill_color={
                "field": "correlation",
                "transform": mapper
            },
            line_color=None,
        )
        fig.frame_width = plot_width
        fig.add_layout(color_bar, "left")
        tab = Panel(child=fig, title=method)
        tabs.append(tab)

    return {
        "insights": itmdt["insights"],
        "tabledata": itmdt["tabledata"],
        "layout": [panel.child for panel in tabs],
        "meta": [panel.title for panel in tabs],
        "container_width": plot_width + 150,
    }
Esempio n. 3
0
def buildVendorsTab():
  defaultGfxVendors = [
    gfxVendors.index('NVIDIA Corporation'),
    gfxVendors.index('Advanced Micro Devices, Inc. [AMD/ATI]'),
    gfxVendors.index('Intel Corporation')
  ]

  gfxVendorCheckbox = CheckboxGroup(labels=gfxVendors, active=defaultGfxVendors)

  source_release = ColumnDataSource(data=dict(x=[], y=[], height=[]))
  source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[]))

  fig = Figure(title="GFX Vendors",
               x_range=[],
               y_range=[0, 0],
               plot_width=1000, plot_height=650)

  hover = HoverTool(tooltips=[
    ('Users', '@height %')
  ])

  fig.add_tools(hover)

  fig.rect(x='x', y='y', height='height', source=source_release,
           width=0.4, color='orange', legend='Release')

  fig.rect(x='x', y='y', height='height', source=source_beta,
           width=0.4, color='blue', legend='Beta')

  fig.xaxis.major_label_orientation = np.pi / 3

  def update(selected):
    vendors = [gfxVendors[i] for i in range(len(gfxVendors)) if i in selected]

    releaseUsers = 100 * getUsersForVendors('release', vendors) / gfxTotalReleaseUsers
    betaUsers = 100 * getUsersForVendors('beta', vendors) / gfxTotalBetaUsers

    fig.x_range.factors = vendors
    fig.y_range.end = max([releaseUsers.max(), betaUsers.max()])

    source_release.data = dict(
      x=[c + ':0.3' for c in vendors],
      y=releaseUsers / 2,
      height=releaseUsers,
    )

    source_beta.data = dict(
      x=[c + ':0.7' for c in vendors],
      y=betaUsers / 2,
      height=betaUsers,
    )

  gfxVendorCheckbox.on_click(update)

  update(gfxVendorCheckbox.active)

  vendorComparison = HBox(HBox(VBoxForm(*[gfxVendorCheckbox]), width=300), fig, width=1100)

  return Panel(child=vendorComparison, title="GFX Vendor Comparison")
Esempio n. 4
0
def render_heatmaps_tab(itmdt: Intermediate, plot_width: int, plot_height: int,
                        palette: Sequence[str]) -> Figure:
    """
    Render missing heatmaps in to tabs
    """
    tooltips = [("x", "@x"), ("y", "@y"),
                ("correlation", "@correlation{1.11}")]
    axis_range = itmdt["axis_range"]
    df = itmdt["data_heatmap"]
    df = df.where(
        np.triu(np.ones(df.shape)).astype(np.bool)  # pylint: disable=no-member
    ).T
    df = df.unstack().reset_index(name="correlation")
    df = df.rename(columns={"level_0": "x", "level_1": "y"})
    df = df[df["x"] != df["y"]]
    df = df.dropna()
    # in case of numerical column names
    df["x"] = df["x"].apply(str)
    df["y"] = df["y"].apply(str)
    mapper, color_bar = create_color_mapper_heatmap(palette)
    x_range = FactorRange(*axis_range)
    y_range = FactorRange(*reversed(axis_range))
    fig = Figure(
        x_range=x_range,
        y_range=y_range,
        plot_width=plot_width,
        plot_height=plot_height,
        x_axis_location="below",
        tools="hover",
        toolbar_location=None,
        tooltips=tooltips,
        background_fill_color="#fafafa",
    )

    tweak_figure(fig)
    fig.grid.grid_line_color = None
    fig.axis.axis_line_color = None
    fig.rect(
        x="x",
        y="y",
        width=1,
        height=1,
        source=df,
        fill_color={
            "field": "correlation",
            "transform": mapper
        },
        line_color=None,
    )

    fig.add_layout(color_bar, "right")

    return fig
Esempio n. 5
0
def buildOSesTab():
  osesCheckbox = CheckboxGroup(labels=oses, active=[i for i in range(len(oses))])

  source_release = ColumnDataSource(data=dict(x=[], y=[], height=[]))
  source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[]))

  fig = Figure(title='OS', x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650)

  hover = HoverTool(tooltips=[
    ('Users', '@height %')
  ])

  fig.add_tools(hover)

  fig.rect(x='x', y='y', height='height', source=source_release,
           width=0.4, color='orange', legend='Release')

  fig.rect(x='x', y='y', height='height', source=source_beta,
           width=0.4, color='blue', legend='Beta')

  fig.xaxis.major_label_orientation = np.pi / 3

  def update(selected):
    cur_oses = [oses[i] for i in range(len(oses)) if i in selected]

    releaseUsers = 100 * getUsersForOses('release', cur_oses) / osTotalReleaseUsers
    betaUsers = 100 * getUsersForOses('beta', cur_oses) / osTotalBetaUsers

    fig.x_range.factors = cur_oses
    fig.y_range.end = max([releaseUsers.max(), betaUsers.max()])

    source_release.data = dict(
      x=[c + ':0.3' for c in cur_oses],
      y=releaseUsers / 2,
      height=releaseUsers,
    )

    source_beta.data = dict(
      x=[c + ':0.7' for c in cur_oses],
      y=betaUsers / 2,
      height=betaUsers,
    )

  osesCheckbox.on_click(update)

  update(osesCheckbox.active)

  osesComparison = HBox(HBox(VBoxForm(*[osesCheckbox]), width=300), fig, width=1100)

  return Panel(child=osesComparison, title="OS Comparison")
Esempio n. 6
0
def render_correlation_heatmaps(itmdt: Intermediate, plot_width: int, plot_height: int) -> Tabs:
    """
    Render correlation heatmaps in to tabs
    """
    tabs: List[Panel] = []
    tooltips = [("x", "@x"), ("y", "@y"), ("correlation", "@correlation{1.11}")]
    axis_range = itmdt["axis_range"]

    for method, df in itmdt["data"].items():
        # in case of numerical column names
        df = df.copy()
        df["x"] = df["x"].apply(str)
        df["y"] = df["y"].apply(str)

        mapper, color_bar = create_color_mapper(RDBU)
        x_range = FactorRange(*axis_range)
        y_range = FactorRange(*reversed(axis_range))
        fig = Figure(
            x_range=x_range,
            y_range=y_range,
            plot_width=plot_width,
            plot_height=plot_height,
            x_axis_location="below",
            tools="hover",
            toolbar_location=None,
            tooltips=tooltips,
            background_fill_color="#fafafa",
        )

        tweak_figure(fig)

        fig.rect(
            x="x",
            y="y",
            width=1,
            height=1,
            source=df,
            fill_color={"field": "correlation", "transform": mapper},
            line_color=None,
        )

        fig.add_layout(color_bar, "right")
        tab = Panel(child=fig, title=method)
        tabs.append(tab)

    tabs = Tabs(tabs=tabs)
    return tabs
Esempio n. 7
0
    def empty_figure() -> Figure:
        # If no data to render in the heatmap, i.e. no missing values
        # we render a blank heatmap
        fig = Figure(
            x_range=[],
            y_range=[],
            plot_width=plot_width,
            plot_height=plot_height,
            x_axis_location="below",
            tools="hover",
            toolbar_location=None,
            background_fill_color="#fafafa",
        )

        # Add at least one renderer to fig, otherwise bokeh
        # gives us error -1000 (MISSING_RENDERERS): Plot has no renderers
        fig.rect(x=0, y=0, width=0, height=0)
        return fig
Esempio n. 8
0
        color=selected["color"].astype(object)
    ))
    source.data.update(src.data)
    p.x_range.update(factors=list(set(source.data.get("x"))))
    p.y_range.update(factors=list(set(source.data.get("y"))))

selected = select_facts()
source = ColumnDataSource(data=dict(x=[], y=[], color=[]))
source.data.update(ColumnDataSource(dict(
    x=selected["x"].astype(object),
    y=selected["y"].astype(object),
    color=selected["color"].astype(object)
    )).data)

p = Figure(plot_height=900, plot_width=900, title="", toolbar_location=None,
           x_range=list(set(source.data.get("x"))), y_range=list(set(source.data.get("y"))))
p.rect(x="x", y="y", source=source, color="color", width=1, height=1)
p.xaxis.major_label_orientation = pi/4
p.yaxis.major_label_orientation = pi/4

controls = [top_n, x_axis, y_axis]
for control in controls:
    control.on_change('value', update)

inputs = HBox(VBoxForm(*controls), width=300)

update(None, None, None) # initial load of the data

layout = HBox(inputs, p)
curdoc().add_root(layout)
Esempio n. 9
0
# initialise a white block for the first plot
hex_color = rgb_to_hex((255, 255, 255))

# 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);
Esempio n. 10
0
def render_heatmaps(df: Optional[pd.DataFrame], plot_width: int, plot_height: int) -> Figure:
    """
    Render missing heatmaps in to tabs
    """
    tooltips = [("x", "@x"), ("y", "@y"), ("correlation", "@correlation{1.11}")]
    mapper, color_bar = create_color_mapper_heatmap(RDBU)

    def empty_figure() -> Figure:
        # If no data to render in the heatmap, i.e. no missing values
        # we render a blank heatmap
        fig = Figure(
            x_range=[],
            y_range=[],
            plot_width=plot_width,
            plot_height=plot_height,
            x_axis_location="below",
            tools="hover",
            toolbar_location=None,
            background_fill_color="#fafafa",
        )

        # Add at least one renderer to fig, otherwise bokeh
        # gives us error -1000 (MISSING_RENDERERS): Plot has no renderers
        fig.rect(x=0, y=0, width=0, height=0)
        return fig

    if df is not None:

        df = df.where(np.triu(np.ones(df.shape)).astype(np.bool)).T  # pylint: disable=no-member

        if df.size != 0:
            x_range = FactorRange(*df.columns)
            y_range = FactorRange(*reversed(df.columns))

            df = df.unstack().reset_index(name="correlation")
            df = df.rename(columns={"level_0": "x", "level_1": "y"})
            df = df[df["x"] != df["y"]]
            df = drop_null(df)

            # in case of numerical column names
            df["x"] = df["x"].apply(str)
            df["y"] = df["y"].apply(str)

            fig = Figure(
                x_range=x_range,
                y_range=y_range,
                plot_width=plot_width,
                plot_height=plot_height,
                x_axis_location="below",
                tools="hover",
                toolbar_location=None,
                tooltips=tooltips,
                background_fill_color="#fafafa",
                title=" ",
            )

            fig.rect(
                x="x",
                y="y",
                width=1,
                height=1,
                source=df,
                fill_color={"field": "correlation", "transform": mapper},
                line_color=None,
            )
        else:
            fig = empty_figure()
    else:
        fig = empty_figure()

    tweak_figure(fig)
    fig.grid.grid_line_color = None
    fig.axis.axis_line_color = None
    fig.add_layout(color_bar, "left")
    fig.frame_width = plot_width
    return fig
Esempio n. 11
0
    ('months after IP', '@counts'),
    ('percentage', '@percents%'),
])

# customize plot
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "10pt"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi / 3

p.rect('counts',
       'epoch',
       1,
       1,
       source=source,
       color='colors',
       alpha='percents',
       line_color=None)


def get_cohorts_now():
    c = counts.value
    sm = start_mon.value
    em = end_mon.value
    r = relativedelta.relativedelta(pd.to_datetime(em), pd.to_datetime(sm))
    nmons = r.years * 12 + r.months + 1
    c = min(c, nmons)
    pro = product.value
    #cohorts_now = b_cohorts[b_cohorts['y_m'].isin(pd.date_range(sm,em,freq='MS'))]
    cohorts_now = b_cohorts[b_cohorts['pname'] == pro]
Esempio n. 12
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. 13
0
def hist_viz(
    hist: List[Tuple[np.ndarray, np.ndarray]],
    nrows: List[int],
    col: str,
    yscale: str,
    plot_width: int,
    plot_height: int,
    show_yticks: bool,
    orig: List[str],
    df_labels: List[str],
) -> Figure:
    """
    Render a histogram
    """
    # pylint: disable=too-many-arguments,too-many-locals

    tooltips = [
        ("Bin", "@intvl"),
        ("Frequency", "@freq"),
        ("Percent", "@pct{0.2f}%"),
        ("Source", "@orig"),
    ]
    fig = Figure(
        plot_height=plot_height,
        plot_width=plot_width,
        title=col,
        toolbar_location=None,
        y_axis_type=yscale,
    )

    for i, hst in enumerate(hist):
        counts, bins = hst
        if sum(counts) == 0:
            fig.rect(x=0, y=0, width=0, height=0)
            continue
        intvls = _format_bin_intervals(bins)
        df = pd.DataFrame({
            "intvl": intvls,
            "left": bins[:-1],
            "right": bins[1:],
            "freq": counts,
            "pct": counts / nrows[i] * 100,
            "orig": orig[i],
        })
        bottom = 0 if yscale == "linear" or df.empty else counts.min() / 2
        fig.quad(
            source=df,
            left="left",
            right="right",
            bottom=bottom,
            alpha=0.5,
            top="freq",
            fill_color=CATEGORY10[i],
            line_color=CATEGORY10[i],
        )
    hover = HoverTool(tooltips=tooltips, attachment="vertical", mode="vline")
    fig.add_tools(hover)

    tweak_figure(fig, "hist", show_yticks)
    fig.yaxis.axis_label = "Frequency"

    _format_axis(fig, df.iloc[0]["left"], df.iloc[-1]["right"], "x")

    x_axis_label = ""
    if show_yticks:
        x_axis_label += col
        if yscale == "linear":
            _format_axis(fig, 0, df["freq"].max(), "y")

    if orig != df_labels:
        if x_axis_label:
            x_axis_label += f", this vairable is only in {','.join(orig)}"
        else:
            x_axis_label += f"This vairable is only in {','.join(orig)}"
    fig.xaxis.axis_label = x_axis_label
    fig.xaxis.axis_label_standoff = 0

    return fig
Esempio n. 14
0
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={
           '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')
Esempio n. 15
0
def buildDevicesTab():
  gfxVendorSelect = Select(title='Vendor', options=gfxVendors, value=gfxVendors[0])
  gfxDeviceCheckbox = CheckboxGroup()

  source_release = ColumnDataSource(data=dict(x=[], y=[], height=[]))
  source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[]))

  fig = Figure(title="GFX Devices",
               x_range=[],
               y_range=[0, 0],
               plot_width=1000, plot_height=650)

  hover = HoverTool(tooltips=[
    ('Users', '@height %')
  ])

  fig.add_tools(hover)

  fig.rect(x='x', y='y', height='height', source=source_release,
           width=0.4, color='orange', legend='Release')

  fig.rect(x='x', y='y', height='height', source=source_beta,
           width=0.4, color='blue', legend='Beta')

  fig.xaxis.major_label_orientation = np.pi / 3

  def update_view():
    vendor = gfxVendorSelect.value
    deviceNames = getDeviceNames('release', vendor, True)

    gfxDeviceCheckbox.labels = deviceNames

    devices = [deviceNames[i] for i in range(len(deviceNames)) if i in gfxDeviceCheckbox.active]

    releaseUsers = 100 * getUsersForDevices('release', vendor, devices) / gfxTotalReleaseUsers
    betaUsers = 100 * getUsersForDevices('beta', vendor, devices) / gfxTotalBetaUsers

    fig.x_range.factors = devices
    fig.y_range.end = max([releaseUsers.max(), betaUsers.max()])

    source_release.data = dict(
      x=[c + ':0.3' for c in devices],
      y=releaseUsers / 2,
      height=releaseUsers,
    )

    source_beta.data = dict(
      x=[c + ':0.7' for c in devices],
      y=betaUsers / 2,
      height=betaUsers,
    )

  def update(attrname, old, new):
    gfxDeviceCheckbox.active = [i for i in range(5)]
    update_view()

  def click(selected):
    update_view()

  gfxVendorSelect.on_change('value', update)
  gfxDeviceCheckbox.on_click(click)

  update('value', '', gfxVendorSelect.value)

  deviceComparison = HBox(HBox(VBoxForm(*[gfxVendorSelect, gfxDeviceCheckbox]), width=300), fig, width=1100)

  return Panel(child=deviceComparison, title="GFX Device Comparison")
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)
Esempio n. 17
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. 18
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. 19
0

selected = select_facts()
source = ColumnDataSource(data=dict(x=[], y=[], color=[]))
source.data.update(
    ColumnDataSource(
        dict(x=selected["x"].astype(object),
             y=selected["y"].astype(object),
             color=selected["color"].astype(object))).data)

p = Figure(plot_height=900,
           plot_width=900,
           title="",
           toolbar_location=None,
           x_range=list(set(source.data.get("x"))),
           y_range=list(set(source.data.get("y"))))
p.rect(x="x", y="y", source=source, color="color", width=1, height=1)
p.xaxis.major_label_orientation = pi / 4
p.yaxis.major_label_orientation = pi / 4

controls = [top_n, x_axis, y_axis]
for control in controls:
    control.on_change('value', update)

inputs = HBox(VBoxForm(*controls), width=300)

update(None, None, None)  # initial load of the data

layout = HBox(inputs, p)
curdoc().add_root(layout)
Esempio n. 20
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. 21
0
def plotTracks(preds,tag,n=3,title=None,width=820,height=None,
                seqdepot=None,bcell=None,exp=None):
    """Plot epitopes as parallel tracks"""

    from bokeh.models import Range1d,HoverTool,FactorRange,Grid,GridPlot,ColumnDataSource
    from bokeh.plotting import Figure

    alls=1
    if title == None:
        title=tag
    for m in preds:
        alls += len(preds[m].data.groupby('allele'))
    if height==None:
        height = 130+10*alls
    yrange = Range1d(start=0, end=alls+3)
    plot = Figure(title=title,title_text_font_size="11pt",plot_width=width,
                  plot_height=height, y_range=yrange,
                y_axis_label='allele',
                tools="xpan, xwheel_zoom, resize, hover, reset, save",
                background_fill="#FAFAFA",
                toolbar_location="below")
    h=3
    if bcell != None:
        plotBCell(plot, bcell, alls)
    if seqdepot != None:
        plotAnnotations(plot,seqdepot)
    if exp is not None:
        plotExp(plot, exp)

    #plotRegions(plot)

    #lists for hover data
    #we plot all rects at once
    x=[];y=[];allele=[];widths=[];clrs=[];peptide=[]
    predictor=[];position=[];score=[];leg=[]
    l=80
    for m in preds:
        pred = preds[m]
        cmap = mpl.cm.get_cmap(colormaps[m])
        df = pred.data
        sckey = pred.scorekey
        pb = pred.getPromiscuousBinders(data=df,n=n)
        if len(pb) == 0:
            continue
        l = pred.getLength()
        grps = df.groupby('allele')
        alleles = grps.groups.keys()
        if len(pb)==0:
            continue
        c=colors[m]
        leg.append(m)

        for a,g in grps:
            b = pred.getBinders(data=g)
            b = b[b.pos.isin(pb.pos)] #only promiscuous
            b.sort('pos',inplace=True)
            scores = b[sckey].values
            score.extend(scores)
            pos = b['pos'].values
            position.extend(pos)
            x.extend(pos+(l/2.0)) #offset as coords are rect centers
            widths.extend([l for i in scores])
            clrs.extend([c for i in scores])
            y.extend([h+0.5 for i in scores])
            alls = [a for i in scores]
            allele.extend(alls)
            peptide.extend(list(b.peptide.values))
            predictor.extend([m for i in scores])
            h+=1

    source = ColumnDataSource(data=dict(x=x,y=y,allele=allele,peptide=peptide,
                                    predictor=predictor,position=position,score=score))
    plot.rect(x,y, width=widths, height=0.8,
         #x_range=Range1d(start=1, end=seqlen+l),
         color=clrs,line_color='gray',alpha=0.7,source=source)

    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("allele", "@allele"),
        ("position", "@position"),
        ("peptide", "@peptide"),
        ("score", "@score"),
        ("predictor", "@predictor"),
    ])

    seqlen = pred.data.pos.max()+l
    plot.set(x_range=Range1d(start=0, end=seqlen+1))
    plot.xaxis.major_label_text_font_size = "8pt"
    plot.xaxis.major_label_text_font_style = "bold"
    plot.ygrid.grid_line_color = None
    plot.yaxis.major_label_text_font_size = '0pt'
    plot.xaxis.major_label_orientation = np.pi/4

    #js,html = embedPlot(plot)
    script, div = embedPlot(plot)
    return script, div
Esempio n. 22
0
# 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
Esempio n. 23
0
TOOLS="tap, reset"

hover = HoverTool(names = ["glyphs"],
                  tooltips=[("Cooccurring", "@x, @y"),
                            ("Counts", "@counts"),
                            ("wikidataID for this item (x-axis)", "@wikidataID")])

fig = Figure(plot_height=700, plot_width=700, title="",
           tools=TOOLS, toolbar_location="above",
           x_range=new_x_factors[:top_n.value],  y_range=new_y_factors[:top_n.value])

fig.add_tools(hover)

update(None, None, None) # initial load of the data
rects = fig.rect(x="x", y="y", source=source, color="color", width=0.95, height=0.95, name="glyphs")
fig.xaxis.major_label_orientation = np.pi/4
fig.yaxis.major_label_orientation = np.pi/4
fig.xgrid.visible = False
fig.ygrid.visible = False

url = "https://www.wikidata.org/wiki/@wikidataID"
taptool = fig.select(type=TapTool)
taptool.callback = OpenURL(url=url)

renderer = fig.select(name="glyphs")[0]
renderer.selection_glyph = renderer.glyph
renderer.nonselection_glyph = renderer.glyph
renderer.hover_glyph = renderer.glyph

# table_columns = [TableColumn(field="x", title="X-axis facts"),