Exemplo n.º 1
0
def test_silence_with_bad_input_and_check_warn(mock_warn: MagicMock, mock_error: MagicMock) -> None:
    m = Mod(foo=-10)
    with pytest.raises(ValueError, match="Input to silence should be a warning object"):
        v.silence(cast(Any, "EXT:W"))
    issues = v.check_integrity([m])
    v.process_validation_issues(issues)
    assert not mock_error.called
    assert mock_warn.called
Exemplo n.º 2
0
def test_silence_with_bad_input_and_check_warn(mock_warn, mock_error):
    m = Mod(foo=-10)
    with pytest.raises(ValueError,
                       match=('Input to silence should be a '
                              'warning object')):
        v.silence('EXT:W')
    v.check_integrity([m])
    assert not mock_error.called
    assert mock_warn.called
Exemplo n.º 3
0
def silence_warnings(*warnings):
    """
    Context manager for silencing bokeh validation warnings.
    """
    for warning in warnings:
        silence(warning)
    try:
        yield
    finally:
        for warning in warnings:
            silence(warning, False)
Exemplo n.º 4
0
def silence_warnings(*warnings):
    """
    Context manager for silencing bokeh validation warnings.
    """
    for warning in warnings:
        silence(warning)
    try:
        yield
    finally:
        for warning in warnings:
            silence(warning, False)
Exemplo n.º 5
0
def test_silence_and_check_warn(mock_warn, mock_error):
    from bokeh.core.validation.warnings import EXT
    m = Mod(foo=-10)
    try:
        v.silence(EXT)  # turn the warning off
        v.check_integrity([m])
        assert not mock_error.called
        assert not mock_warn.called
    finally:
        v.silence(EXT, False)  # turn the warning back on
        v.check_integrity([m])
        assert not mock_error.called
        assert mock_warn.called
Exemplo n.º 6
0
def test_silence_and_check_warn(mock_warn, mock_error) -> None:
    from bokeh.core.validation.warnings import EXT
    m = Mod(foo=-10)
    try:
        v.silence(EXT)  # turn the warning off
        issues = v.check_integrity([m])
        v.process_validation_issues(issues)
        assert not mock_error.called
        assert not mock_warn.called
    finally:
        v.silence(EXT, False)  # turn the warning back on
        issues = v.check_integrity([m])
        v.process_validation_issues(issues)
        assert not mock_error.called
        assert mock_warn.called
Exemplo n.º 7
0
def test_silence_remove_warning_that_is_not_in_silencers_is_ok(
        mock_warn, mock_error):
    from bokeh.core.validation.warnings import EXT
    m = Mod(foo=-10)

    silencers0 = v.silence(EXT)  # turn the warning off
    assert len(silencers0) == 1

    silencers1 = v.silence(EXT, False)  # turn the warning back on
    silencers2 = v.silence(EXT, False)  # do it a second time - no-op
    assert len(silencers1) == 0
    assert silencers1 == silencers2

    v.check_integrity([m])
    assert not mock_error.called
    assert mock_warn.called
Exemplo n.º 8
0
def test_silence_warning_already_in_silencers_is_ok(mock_warn, mock_error):
    from bokeh.core.validation.warnings import EXT
    m = Mod(foo=-10)
    try:
        silencers0 = v.silence(EXT)  # turn the warning off
        silencers1 = v.silence(EXT)  # do it a second time - no-op
        assert len(silencers0) == 1
        assert silencers0 == silencers1  # silencers is same as before

        v.check_integrity([m])
        assert not mock_error.called
        assert not mock_warn.called
    finally:
        v.silence(EXT, False)  # turn the warning back on
        v.check_integrity([m])
        assert not mock_error.called
        assert mock_warn.called
Exemplo n.º 9
0
from bokeh.io import output_file, show, save
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.models import BoxAnnotation, Label, Range1d, WheelZoomTool, ResetTool, PanTool, LegendItem, Legend
from bokeh.core.validation.warnings import FIXED_SIZING_MODE
from bokeh.core.validation import silence

import easygui
from convert_fsa_to_csv import convert_folder

pd.set_option('display.max_columns', 20)
pd.set_option('display.width', 1000)
pd.set_option('display.max_rows', 50)

TOOLTIPS = [("(x,y)", "($x{1.1}, $y{int})")]
silence(FIXED_SIZING_MODE, True)

channels_of_interest = {
    'IGH-A_channel_1': 'blue',
    'IGH-B_channel_1': 'blue',
    'IGH-C_channel_2': 'green',
    'IGK-A_channel_1': 'blue',
    'IGK-B_channel_1': 'blue',
    'TCRB-A_channel_1': 'blue',
    'TCRB-A_channel_2': 'green',
    'TCRB-B_channel_1': 'blue',
    'TCRB-C_channel_1': 'blue',
    'TCRB-C_channel_2': 'green',
    'TCRB-C_channel_3': 'orange',
    'TCRG-A_channel_1': 'blue',
    'TCRG-A_channel_2': 'green',
# /usr/bin/env python3

from bokeh.plotting import figure
from bokeh.models import LinearColorMapper, HoverTool, Div, ColorBar
from bokeh.tile_providers import get_provider
from bokeh.layouts import layout
from bokeh.io import curdoc
from bokeh.core.validation import silence
from bokeh.core.validation.warnings import MISSING_RENDERERS
from coordinate_transformation.to_web_merc import toWebMerc
from helper_functions.helper_funcs import hour_inputs, slider_input, \
    source, update, button

# silence unnecessary warnings for color_bar_plot
silence(MISSING_RENDERERS, True)

# bokeh output HTML file
tile_provider = get_provider('CARTODBPOSITRON')

# base HTML web page for Bokeh visualization
homepage = Div(text=open('traffic_plot.html').read(), width=800)

# London longitude and latitude GPS coordinate range
london_x_range = (-0.25, 0.015)
london_y_range = (51.436, 51.568)
merc_lower_left = toWebMerc(london_x_range[0], london_y_range[0])
merc_upper_right = toWebMerc(london_x_range[1], london_y_range[1])

# tooltips on dats point hoverover
tooltips = [('Total traffic', '@sum_flux{0,0.00}'),
            ('Net flux', '@diff_flux{0,0.00}'),
Exemplo n.º 11
0
from bokeh.plotting import *
from bokeh.models import ColumnDataSource, CustomJS, Slider, Button, DataTable, TableColumn 
from bokeh.models import HoverTool, LinearColorMapper, NumberFormatter, RadioButtonGroup
from bokeh.models import Select, Spinner, RangeSlider, FileInput, MultiLine, PreText
from bokeh.models import Tabs, Panel, MultiSelect, RadioGroup, Div, LabelSet, Label
from bokeh import events
from bokeh.layouts import row, column, layout
from bokeh.io import curdoc, show
from bokeh.themes import Theme
from bokeh.core.validation import silence
from bokeh.core.validation.warnings import EMPTY_LAYOUT, MISSING_RENDERERS
from bokeh.palettes import Category20

# Ignore Warnings about Empty Plots on Initialization
silence(EMPTY_LAYOUT, True)
silence(MISSING_RENDERERS, True)
# Set the Output for the Bokeh Application
output_notebook()

### Define the Bokeh Application ###
# all code is inside this definition except for the call to show at the end #

def bkapp(doc):
    
### Functions ###

    # functions for user dialogs

    def open_file(ftype):
        root = Tk()
Exemplo n.º 12
0
    def setupBokeh(self, cbase=None, clevels=None, creverse=None):
        """-----------------------------------------------------------------------------------------
        SEt up four plot in 2 x 2 grid, but with differing sizes
            mainplot is the dotplot itself, upper right
            legend shows the colorbar legend
            scoreplot shows the window score distribution
            runploot shows the log of the run length distribution

        :param cbase: string, e.g. Greys, Blues, Reds, Viridis, etc
        :param clevels: int, usually 0-9 or 256
        :param creverse: boolean, if True highest color is dark
        :return: True
        -----------------------------------------------------------------------------------------"""

        # turn off MISSING_RENDERERS warning caused by plotting colorbars in empty plot
        silence(MISSING_RENDERERS, True)

        self.palette = self.setupPalette(cbase=cbase,
                                         clevels=clevels,
                                         creverse=creverse)

        if self.title:
            titlestr = self.title
        else:
            now = date.today()
            titlestr = 'Dotplot of {} and {} - {}'.format(
                self.s1.id, self.s2.id, now)

        xlabel = '\n'.join([self.s1.id, self.s1.doc])
        ylabel = '\n'.join([self.s2.doc, self.s2.id])

        # account for sequence length difference, ylen scaling affects main and legend panels
        xlen = 800
        ylen = xlen * self.l2 / self.l1

        # define each panel as a figure
        label = '({}, {}, score)'.format(self.s1.id, self.s2.id)
        TIPS = [(label, '($x{0}, $y{0}, @score)')]
        self.figure['main'] = figure(title=titlestr,
                                     x_axis_label=xlabel,
                                     y_axis_label=ylabel,
                                     height=int(ylen),
                                     width=int(xlen),
                                     align='center',
                                     tooltips=TIPS)

        self.figure['legend'] = figure(height=int(ylen), width=200)

        TIPS = [('score, number', '$x{0}, $y{0.00}')]
        self.figure['scoredist'] = figure(height=300, width=500, tooltips=TIPS)

        TIPS = [('length,count', '$x{0}, $y{0}')]
        self.figure['rundist'] = figure(height=300,
                                        width=500,
                                        y_axis_type='log',
                                        tooltips=TIPS)

        # grid layout
        self.grid = layout([[self.figure['main'], self.figure['legend']],
                            [self.figure['scoredist'],
                             self.figure['rundist']]])

        return True
Exemplo n.º 13
0
def bokeh_plot(histo, jup_url="http://127.0.0.1:8889"):
    if not isnotebook():
        raise NotImplementedError("Only usable in jupyter notebook")
    import bokeh.plotting.figure as bk_figure
    from bokeh.io import curdoc, show
    from bokeh import palettes
    from bokeh.layouts import row, widgetbox, column
    from bokeh.models import ColumnDataSource
    from bokeh.models.widgets import RadioButtonGroup, CheckboxButtonGroup
    from bokeh.models.widgets import RangeSlider, Div
    from bokeh.io import output_notebook  # enables plot interface in J notebook
    import numpy as np
    # init bokeh

    from bokeh.application import Application
    from bokeh.application.handlers import FunctionHandler

    from bokeh.core.validation import silence
    from bokeh.core.validation.warnings import EMPTY_LAYOUT
    silence(EMPTY_LAYOUT, True)

    output_notebook()

    # Set up widgets
    cfg_labels = ["Ghost"]
    wi_config = CheckboxButtonGroup(labels=cfg_labels, active=[0])
    wi_dense_select = RadioButtonGroup(
        labels=[ax.name for ax in histo.dense_axes()], active=0)
    wi_sparse_select = RadioButtonGroup(
        labels=[ax.name for ax in histo.sparse_axes()], active=0)

    # Dense widgets
    sliders = {}
    for ax in histo.dense_axes():
        edge_vals = (histo.axis(ax.name).edges()[0],
                     histo.axis(ax.name).edges()[-1])
        _smallest_bin = np.min(np.diff(histo.axis(ax.name).edges()))
        sliders[ax.name] = RangeSlider(title=ax.name,
                                       value=edge_vals,
                                       start=edge_vals[0],
                                       end=edge_vals[1],
                                       step=_smallest_bin,
                                       name=ax.name)

    # Cat widgets
    togglers = {}
    for ax in histo.sparse_axes():
        togglers[ax.name] = CheckboxButtonGroup(
            labels=[i.name for i in ax.identifiers()],
            active=[0],
            name=ax.name)

    # Toggles for all widgets
    configers = {}
    for ax in histo.sparse_axes():
        configers[ax.name] = CheckboxButtonGroup(labels=["Display", "Ghost"],
                                                 active=[0, 1],
                                                 name=ax.name)
    for ax in histo.dense_axes():
        configers[ax.name] = CheckboxButtonGroup(labels=["Display"],
                                                 active=[0],
                                                 name=ax.name)

    # Figure
    fig = bk_figure(title="1D Projection",
                    plot_width=500,
                    plot_height=500,
                    min_border=20,
                    toolbar_location=None)
    fig.yaxis.axis_label = "N"
    fig.xaxis.axis_label = "Quantity"

    # Iterate over possible overlays
    _max_idents = 0  # Max number of simultaneou histograms
    for ax in histo.sparse_axes():
        _max_idents = max(_max_idents, len([i.name for i in ax.identifiers()]))

    # Data source list
    sources = []
    sources_ghost = []
    for i in range(_max_idents):
        sources.append(
            ColumnDataSource(dict(left=[], top=[], right=[], bottom=[])))
        sources_ghost.append(
            ColumnDataSource(dict(left=[], top=[], right=[], bottom=[])))

    # Hist list
    hists = []
    hists_ghost = []
    for i in range(_max_idents):
        if _max_idents < 10:
            _color = palettes.Category10[min(max(3, _max_idents), 10)][i]
        else:
            _color = palettes.magma(_max_idents)[i]
        hists.append(
            fig.quad(left="left",
                     right="right",
                     top="top",
                     bottom="bottom",
                     source=sources[i],
                     alpha=0.9,
                     color=_color))
        hists_ghost.append(
            fig.quad(left="left",
                     right="right",
                     top="top",
                     bottom="bottom",
                     source=sources_ghost[i],
                     alpha=0.05,
                     color=_color))

    def update_data(attrname, old, new):
        sparse_active = wi_sparse_select.active
        sparse_name = [ax.name for ax in histo.sparse_axes()][sparse_active]
        sparse_other = [
            ax.name for ax in histo.sparse_axes() if ax.name != sparse_name
        ]

        dense_active = wi_dense_select.active
        dense_name = [ax.name for ax in histo.dense_axes()][dense_active]
        dense_other = [
            ax.name for ax in histo.dense_axes() if ax.name != dense_name
        ]

        # Apply cuts in projections
        _h = histo.copy()
        for proj_ax in sparse_other:
            _idents = histo.axis(proj_ax).identifiers()
            _labels = [ident.name for ident in _idents]
            if 0 in configers[proj_ax].active:
                _h = _h.integrate(
                    proj_ax, [_labels[i] for i in togglers[proj_ax].active])
            else:
                _h = _h.integrate(proj_ax)

        for proj_ax in dense_other:
            _h = _h.integrate(
                proj_ax,
                slice(sliders[proj_ax].value[0], sliders[proj_ax].value[1]))

        for cat_ix in range(_max_idents):
            # Update histo for each toggled overlay
            if cat_ix in togglers[sparse_name].active:
                cat_value = histo.axis(sparse_name).identifiers()[cat_ix]
                h1d = _h.integrate(sparse_name, cat_value)

                # Get shown histogram
                values = h1d.project(dense_name).values()
                if values != {}:
                    h = values[()]
                    bins = h1d.axis(dense_name).edges()

                    # Apply cuts on shown axis
                    bin_los = bins[:-1][
                        bins[:-1] > sliders[dense_name].value[0]]
                    bin_his = bins[1:][bins[1:] < sliders[dense_name].value[1]]
                    new_bins = np.intersect1d(bin_los, bin_his)
                    bin_ixs = np.searchsorted(bins, new_bins)[:-1]
                    h = h[bin_ixs]

                    sources[cat_ix].data = dict(left=new_bins[:-1],
                                                right=new_bins[1:],
                                                top=h,
                                                bottom=np.zeros_like(h))
                else:
                    sources[cat_ix].data = dict(left=[],
                                                right=[],
                                                top=[],
                                                bottom=[])

                # Add ghosts
                if 0 in wi_config.active:
                    h1d = histo.integrate(sparse_name, cat_value)
                    for proj_ax in sparse_other:
                        _idents = histo.axis(proj_ax).identifiers()
                        _labels = [ident.name for ident in _idents]
                        if 1 not in configers[proj_ax].active:
                            h1d = h1d.integrate(
                                proj_ax,
                                [_labels[i] for i in togglers[proj_ax].active])
                        else:
                            h1d = h1d.integrate(proj_ax)
                    values = h1d.project(dense_name).values()
                    if values != {}:
                        h = h1d.project(dense_name).values()[()]
                        bins = h1d.axis(dense_name).edges()
                        sources_ghost[cat_ix].data = dict(
                            left=bins[:-1],
                            right=bins[1:],
                            top=h,
                            bottom=np.zeros_like(h))
                    else:
                        sources_ghost[cat_ix].data = dict(left=[],
                                                          right=[],
                                                          top=[],
                                                          bottom=[])
            else:
                sources[cat_ix].data = dict(left=[],
                                            right=[],
                                            top=[],
                                            bottom=[])
                sources_ghost[cat_ix].data = dict(left=[],
                                                  right=[],
                                                  top=[],
                                                  bottom=[])

        # Cosmetics
        fig.xaxis.axis_label = dense_name

    for name, slider in sliders.items():
        slider.on_change('value', update_data)
    for name, toggler in togglers.items():
        toggler.on_change('active', update_data)
    for name, configer in configers.items():
        configer.on_change('active', update_data)
    # Button
    for w in [wi_dense_select, wi_sparse_select, wi_config]:
        w.on_change('active', update_data)

    from bokeh.models.widgets import Panel, Tabs
    from bokeh.io import output_file, show
    from bokeh.plotting import figure

    layout = row(
        fig,
        column(
            Div(text="<b>Overlay Axis:</b>",
                style={
                    'font-size': '100%',
                    'color': 'black'
                }), wi_sparse_select,
            Div(text="<b>Plot Axis:</b>",
                style={
                    'font-size': '100%',
                    'color': 'black'
                }), wi_dense_select,
            Div(text="<b>Categorical Cuts:</b>",
                style={
                    'font-size': '100%',
                    'color': 'black'
                }), *[toggler for name, toggler in togglers.items()],
            Div(text="<b>Dense Cuts:</b>",
                style={
                    'font-size': '100%',
                    'color': 'black'
                }), *[slider for name, slider in sliders.items()]))

    # Config prep
    incl_lists = [[], [], []]
    for i, key in enumerate(list(configers.keys())):
        incl_lists[i // max(5,
                            len(list(configers.keys())) / 3)].append(
                                Div(text="<b>{}:</b>".format(key),
                                    style={
                                        'font-size': '70%',
                                        'color': 'black'
                                    }))
        incl_lists[i // max(5,
                            len(list(configers.keys())) / 3)].append(
                                configers[key])

    layout_cfgs = column(
        row(
            column(
                Div(text="<b>Configs:</b>",
                    style={
                        'font-size': '100%',
                        'color': 'black'
                    }), wi_config)),
        Div(text="<b>Axis togglers:</b>",
            style={
                'font-size': '100%',
                'color': 'black'
            }),
        row(
            column(incl_lists[0]),
            column(incl_lists[1]),
            column(incl_lists[2]),
        ))

    # Update active buttons
    def update_layout(attrname, old, new):
        active_axes = [None]
        for name, wi in configers.items():
            if 0 in wi.active:
                active_axes.append(name)
        for child in layout.children[1].children:
            if child.name not in active_axes:
                child.visible = False
            else:
                child.visible = True

    for name, configer in configers.items():
        configer.on_change('active', update_layout)

    tab1 = Panel(child=layout, title="Projection")
    tab2 = Panel(child=layout_cfgs, title="Configs")
    tabs = Tabs(tabs=[tab1, tab2])

    def modify_doc(doc):
        doc.add_root(row(tabs, width=800))
        doc.title = "Sliders"

    handler = FunctionHandler(modify_doc)
    app = Application(handler)

    show(app, notebook_url=jup_url)
    update_data("", "", "")
Exemplo n.º 14
0
import argparse  # to easily parse arguments
import sys  # sys.argv[1:] -- to obtain possible file path

from bokeh.server.server import Server
from bokeh.core import validation

import layout_factory as lf

import pandas as pd

validation.silence(1002, True)  # silence the bokeh plot warnings


def hardwired_data():
    x_name = 'Year, 1956 = 0'
    y_name = 'Birds (sqrt)'
    data_frame = pd.DataFrame()
    data_frame[x_name] = [
        0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22,
        23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47
    ]
    data_frame[y_name] = [
        1.4142135623730951, 1.4142135623730951, 3.1622776601683795, 2.0,
        3.1622776601683795, 3.4641016151377544, 3.1622776601683795,
        2.8284271247461903, 4.123105625617661, 2.6457513110645907,
        6.6332495807108, 7.0710678118654755, 5.0990195135927845,
        3.1622776601683795, 2.6457513110645907, 1.0, 6.164414002968976,
        9.591663046625438, 10.63014581273465, 9.0, 8.888194417315589,
        8.48528137423857, 9.16515138991168, 8.18535277187245, 6.557438524302,
        7.211102550927978, 8.18535277187245, 7.416198487095663,
Exemplo n.º 15
0
# In[1]:

from bokeh.io import output_file, show, curdoc
from bokeh.plotting import figure
from bokeh.models import Div, Select, TextInput, BoxAnnotation, Toggle, ColumnDataSource, Label, LabelSet, Title
from bokeh.layouts import layout
from bokeh.resources import CDN
from bokeh.embed import file_html
from os.path import dirname, join
from bokeh.core.validation import silence
from bokeh.core.validation.warnings import EMPTY_LAYOUT
from bokeh.models.widgets import CheckboxGroup

# In[2]:

silence(EMPTY_LAYOUT, True)

# In[3]:

output_file("stacked.html", mode='inline')

# In[4]:

platform = [
    'Nintendo DS', 'Playstation 2', 'Playstation 3', 'Nintendo Wii',
    'Xbox 360', 'Playstation Portable', 'Playstation 1', 'PC',
    'Game Boy Advance', 'Xbox', 'GameCube', 'Nintendo 3DS', 'Playstation 4',
    'Playstation Vita', 'Nintendo 64', 'Super Nintendo', 'Xbox One',
    'Sega Saturn', 'Nintendo WiiU', 'Atari 2600',
    'Nintendo Entertainment System', 'Game Boy', 'Sega Dreamcast',
    'Sega Genesis'
Exemplo n.º 16
0
import sys
""" Class that imports TypeScript code for a custom tool: EnhanceTool
    This tool lets the user create a rectangular selection area that specifies
    a range of residue pairs to be displayed at a higher resolution.
    (In other words, it takes the range of residues and redisplays the plot so
    it shows only this range of residues at the given resolution. In this
    way, it "enhances" the region.)
"""


class EnhanceTool(Tool):
    __implementation__ = 'enhance_tool.ts'
    source = Instance(ColumnDataSource)


validation.silence(MISSING_RENDERERS, True)
source = ColumnDataSource(data=dict(x=[], y=[]))
plot = figure(x_range=(0, 1),
              y_range=(0, 1),
              tools=[EnhanceTool(source=source)])
show(plot)
validation.silence(MISSING_RENDERERS, False)
""" Class that initiates and loops the Bokeh server
    that houses a dashboard for the given plots
"""


class DashboardServer:
    """ Initialization function
    """
    def __init__(self,