Example #1
0
def update():
    current = df[(df['salary'] >= slider.value[0]) & (df['salary'] <= slider.value[1])].dropna()
    source.data = {
        'name'             : current.name,
        'salary'           : current.salary,
        'years_experience' : current.years_experience,
    }

slider = RangeSlider(title="Max Salary", start=10000, end=110000, value=(10000, 50000), step=1000, format="0,0")
slider.on_change('value', lambda attr, old, new: update())

button = Button(label="Download", button_type="success")
button.callback = CustomJS(args=dict(source=source),
                           code=open(join(dirname(__file__), "download.js")).read())

columns = [
    TableColumn(field="name", title="Employee Name"),
    TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")),
    TableColumn(field="years_experience", title="Experience (years)")
]

data_table = DataTable(source=source, columns=columns, width=800)

controls = widgetbox(slider, button)
table = widgetbox(data_table)

curdoc().add_root(row(controls, table))
curdoc().title = "Export CSV"

update()
    y_axis_label = "Correlation",
    x_range      = (0, len(corr)))

p.title.align = "center"
p.xaxis.visible = False
p.yaxis.minor_tick_line_color = None
p.circle(corr.index, "corr", source=s1)
p.select(HoverTool).tooltips = [
    ("A", "@a"),
    ("B", "@b"),
    ("Correlation", "@corr")
]

# Make Table
columns = [
    TableColumn(field="a",    title="a",    sortable=True),
    TableColumn(field="b",    title="b",    sortable=True),
    TableColumn(field="corr", title="corr", sortable=True, formatter=NumberFormatter(format="0.000"))]
dtable = DataTable(row_headers=False, source=s1, columns=columns)

# Input Controls
callback = CustomJS(args=dict(s1=s1, s2=s2, dtable=dtable), code="""
    var val = cb_obj.value;
    var d1  = s1.data;
    var d2  = s2.data;
    d1.a    = [];
    d1.b    = [];
    d1.corr = [];
    for (var i = 0; i < d2["a"].length; ++i) {
        if (val == "All" || val == d2["a"][i]) {
            d1.a.push(d2.a[i]);
def principal_window_words(inputs_file):
    output_file(filename="../dashboards/words_representations.html", title="Words representations")

    ###################################################
    # PREPARING DATA
    ###################################################
    sources = []
    sources_visible = []
    languages = []
    colors = viridis(len(inputs_file))
    for input_file in inputs_file:
        x = list()
        y = list()
        words = list()
        language = input_file[11:-5]
        languages.append(language)
        with open(input_file, 'r') as file:
            array = json.load(file)
            data = array['content']
            for translation in data:
                for word, vector in translation.items():
                    words.append(word)
                    x.append(vector[0])
                    y.append(vector[1])

            source_dict = {
                'x': x,
                'y': y,
                'words': words,
            }
            source = ColumnDataSource(source_dict)
            source_visible = ColumnDataSource({
                'x': x[:len(x) // 100 * 10],
                'y': y[:len(y) // 100 * 10],
                'words': words[:len(words) // 100 * 10],
            })
        sources.append(source)
        sources_visible.append(source_visible)

    ###################################################
    # SET UP MAIN FIGURE
    ###################################################

    tools = "hover, tap, box_zoom, box_select, reset, help"
    p = figure(tools=tools, title='Words intermediate representations\n', plot_width=1000, plot_height=650)

    for index in range(len(sources_visible)):
        p.circle('x', 'y',
                 size=4, alpha=0.4,
                 hover_color='red', hover_alpha=1.0,
                 selection_color='red',
                 nonselection_color='white',
                 source=sources_visible[index],
                 color=colors[index],
                 legend=languages[index],
                 name="data_{}".format(index))

    p.legend.click_policy = "hide"

    ###################################################
    # ADD LINKS IN HOVERTOOL
    ###################################################

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("words", "@words"),
    ]

    ###################################################
    # SET UP SLIDER
    ###################################################

    slider = Slider(title='Percentage of words',
                    value=10,
                    start=1,
                    end=100,
                    step=1)
    slider.callback = CustomJS(args=dict(sources_visible=sources_visible, sources=sources), code="""
            var percentage = cb_obj.value;
            // Get the data from the data sources
            for(var i=0; i < sources.length; i++) {
                var point_visible = sources_visible[i].data;
                var point_available = sources[i].data;
                var nbr_points = (point_available.x.length / 100) * percentage
    
                point_visible.x = []
                point_visible.y = []
    
                // Update the visible data
                for(var j = 0; j < nbr_points; j++) {  
                    point_visible.x.push(point_available.x[j]);
                    point_visible.y.push(point_available.y[j]);
                }  
                sources_visible[i].change.emit();
            }
            """)

    ###################################################
    # SET UP DATATABLE
    ###################################################

    columns0 = [TableColumn(field="words", title="Words in English")]
    columns1 = [TableColumn(field="words", title="Words in Spanish")]
    columns2 = [TableColumn(field="words", title="Words in French")]

    data_table0 = DataTable(source=sources_visible[0], columns=columns0, width=300, height=175)
    data_table1 = DataTable(source=sources_visible[1], columns=columns1, width=300, height=175)
    data_table2 = DataTable(source=sources_visible[2], columns=columns2, width=300, height=175)

    ###################################################
    # CREATION OF THE LAYOUT
    ###################################################

    window = layout([[p, column(slider, data_table0, data_table1, data_table2)]])
    # curdoc().add_root(window)
    show(window)
Example #4
0
d_freq_list = [None] * 20  # top 20
d_a_n = [None] * 20
for i in range(len(d_a_n)):
    d_freq_list[i] = get_event_freq(d_, d_[i]['term'])
    d_a_n[i] = d_[i]['term']
    #print d_a_n[i]
    #print d_freq_list[i]

#print 'd_freq_list: ' + str(d_freq_list)
data = dict(effects=d_a_n[0:20], probability=d_freq_list[0:20])

source = ColumnDataSource(data)

columns = [
    TableColumn(field="effects", title="Effect"),
    TableColumn(field="probability", title="probability"),
]
data_table = DataTable(source=source, columns=columns, width=720, height=510)

dt = data_table.source

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

p_ = Panel(child=data_table, title='20')

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

new_df_ROR = pd.DataFrame
new_df_ROR = pd.read_csv('data/PRR.csv')
print new_df_ROR
Example #5
0
            ra_avail.append(store_numbers[i])

    ra['store'] = 'Rite Aid'
    ra['state'] = 'CA'
    ra["status"] = np.where(ra["store_number"].isin(ra_avail), "Available",
                            "Fully Booked")
    return ra


df_cvs = refresh_cvs_data()
df_ra = refresh_ra_data()
df = df_cvs.append(df_ra)
df_avail = df[df.status == 'Available']
df_avail.sort_values(by=['city', 'store', 'address'])

Columns = [TableColumn(field=Ci, title=Ci.title())
           for Ci in df_avail.columns]  # bokeh columns
avail_vaccine_locations = DataTable(
    columns=Columns, source=ColumnDataSource(df_avail))  # bokeh table
now = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S UTC%z")
chart_info = f"""
<p><b>California Vaccine Appointment Availability as of {now}</b></p>
<p><a href="https://www.cvs.com/vaccine/intake/store/covid-screener/covid-qns">CVS signup site</a></p>
<p><a href="https://www.riteaid.com/covid-vaccine-apt">Rite Aid signup site</a></p>
"""

vaccinecharts = Panel(child=layout([[
    first_dose_admin, pop_vaccinated,
    Spacer(width=30, height=10, sizing_mode='fixed')
], [Div(text=chart_info)], [avail_vaccine_locations]],
                                   sizing_mode='stretch_width'),
def Table(n):
    data = dict(
        name=[n.name],
        source_key=[n.source_key],
        designation=[n.designation],
        RA=[n.ra],
        dec=[n.dec],
        discovery_reference=[n.discovery_reference],
        opt_type=[n.opt_type],
        opt_type_ref=[n.opt_type_ref],
        nir_type=[n.nir_type],
        nir_type_ref=[n.nir_type_ref],
        reduction_spextool_version=[n.reduction_spextool_version],
        reduction_person=[n.reduction_person],
        reduction_date=[n.reduction_date],
        quality_flag=[n.quality_flag],
        median_snr=[n.median_snr],
        spex_type=[n.spex_type],
        spex_gravity_classification=[n.spex_gravity_classification],
        published=[n.published],
        data_reference=[n.data_reference],
        note_sp=[n.note_sp],
    )

    source = ColumnDataSource(data)
    columns = [
        TableColumn(field='name', title='NAME'),
        TableColumn(field='source_key', title='SOURCE_KEY'),
        TableColumn(field='designation', title='DESIGNATION'),
        TableColumn(field='RA', title='RA'),
        TableColumn(field='dec', title='DEC'),
        TableColumn(field='discovery_reference', title='Discovery_reference'),
        TableColumn(field='opt_type', title='Opt_type'),
        TableColumn(field='opt_type_ref', title='opt_type_ref'),
        TableColumn(field='nir_type', title='nir_type'),
        TableColumn(field='nir_type_ref', title='nir_type_ref'),
        TableColumn(field='reduction_spextool_version',
                    title='Reduction_spextool_version'),
        TableColumn(field='reduction_person', title='Reduction_person'),
        TableColumn(field='reduction_date', title='Reduction_date'),
        TableColumn(field='quality_flag', title='Quality_flag'),
        TableColumn(field='median_snr', title='Median_snr'),
        TableColumn(field='spex_type', title='Spex_type'),
        TableColumn(field='spex_gravity_classification',
                    title='Spex_gravity_classification'),
        TableColumn(field='published', title='Published'),
        TableColumn(field='data_reference', title='Data_reference'),
        TableColumn(field='note_sp', title='Note_sp'),
    ]
    Table = DataTable(source=source, columns=columns, width=1200, height=50)
    return Table
    def create(self):
        print("running create...")
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        manufacturer_select = Select(title="Manufacturer:",
                                     value="All",
                                     options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:",
                              value="All",
                              options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:",
                                     value="All",
                                     options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:",
                              value="All",
                              options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:",
                              value="All",
                              options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        columns = [
            TableColumn(field="manufacturer",
                        title="Manufacturer",
                        editor=SelectEditor(options=manufacturers),
                        formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",
                        title="Model",
                        editor=StringEditor(completions=models)),
            TableColumn(field="displ",
                        title="Displacement",
                        editor=NumberEditor(step=0.1),
                        formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year", title="Year", editor=IntEditor()),
            TableColumn(field="cyl", title="Cylinders", editor=IntEditor()),
            TableColumn(field="trans",
                        title="Transmission",
                        editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",
                        title="Drive",
                        editor=SelectEditor(options=drives)),
            TableColumn(field="class",
                        title="Class",
                        editor=SelectEditor(options=classes)),
            TableColumn(field="cty", title="City MPG", editor=IntEditor()),
            TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()),
        ]
        data_table = DataTable(source=self.source,
                               columns=columns,
                               editable=True,
                               width=1300)

        plot = Plot(title=None,
                    x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    plot_width=1000,
                    plot_height=300)

        # Set up x & y axis
        plot.add_layout(LinearAxis(), 'below')
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        # Add Glyphs
        cty_glyph = Circle(x="index",
                           y="cty",
                           fill_color="#396285",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        hwy_glyph = Circle(x="index",
                           y="hwy",
                           fill_color="#CE603D",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        cty = plot.add_glyph(self.source, cty_glyph)
        hwy = plot.add_glyph(self.source, hwy_glyph)

        # Add the tools
        tooltips = [
            ("Manufacturer", "@manufacturer"),
            ("Model", "@model"),
            ("Displacement", "@displ"),
            ("Year", "@year"),
            ("Cylinders", "@cyl"),
            ("Transmission", "@trans"),
            ("Drive", "@drv"),
            ("Class", "@class"),
        ]
        cty_hover_tool = HoverTool(renderers=[cty],
                                   tooltips=tooltips + [("City MPG", "@cty")])
        hwy_hover_tool = HoverTool(renderers=[hwy],
                                   tooltips=tooltips +
                                   [("Highway MPG", "@hwy")])
        select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width')
        plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)

        controls = WidgetBox(manufacturer_select, model_select,
                             transmission_select, drive_select, class_select)
        top_panel = Row(controls, plot)
        layout = Column(top_panel, data_table)

        return layout
Example #8
0
              stack=cat(columns='medal', sort=False),
              color=color(columns='medal',
                          palette=['Green', 'Red'],
                          sort=False),
              legend='top_left',
              title="Respiration data quality of participant id " +
              str(ids[i]),
              width=800)

    output_file('Respiration_DataQuality_of_' + str(ids[i]) + ".html",
                title="RIP_BAR_Plot")

    source = ColumnDataSource(data)

    columns = [
        TableColumn(field="Date", title="Date"),
        TableColumn(field="ACCEPTABLE", title="ACCEPTABLE(Hours)"),
        TableColumn(field="UNACCEPTABLE", title="UNACCEPTABLE(Hours)"),
        TableColumn(field="Total", title="Total(Hours)")
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=500,
                           height=400)

    show(hplot(bar, vform(data_table)))
    dataf['ACCEPTABLE'] = dataf['ACCEPTABLE'] + data['ACCEPTABLE']
    dataf['UNACCEPTABLE'] = dataf['UNACCEPTABLE'] + data['UNACCEPTABLE']
    dataf['Date'] = dataf['Date'] + data['Date']
    dataf['Total'] = dataf['Total'] + data['Total']
    dataf['ParticipantID'] = dataf['ParticipantID'] + [
Example #9
0
    def create(self):
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        manufacturer_select = Select(title="Manufacturer:",
                                     value="All",
                                     options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:",
                              value="All",
                              options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:",
                                     value="All",
                                     options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:",
                              value="All",
                              options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:",
                              value="All",
                              options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        columns = [
            TableColumn(field="manufacturer",
                        title="Manufacturer",
                        editor=SelectEditor(options=manufacturers),
                        formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",
                        title="Model",
                        editor=StringEditor(completions=models)),
            TableColumn(field="displ",
                        title="Displacement",
                        editor=NumberEditor(step=0.1),
                        formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year", title="Year", editor=IntEditor()),
            TableColumn(field="cyl", title="Cylinders", editor=IntEditor()),
            TableColumn(field="trans",
                        title="Transmission",
                        editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",
                        title="Drive",
                        editor=SelectEditor(options=drives)),
            TableColumn(field="class",
                        title="Class",
                        editor=SelectEditor(options=classes)),
            TableColumn(field="cty", title="City MPG", editor=IntEditor()),
            TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()),
        ]
        data_table = DataTable(source=self.source,
                               columns=columns,
                               editable=True)

        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(title=None,
                    x_range=xdr,
                    y_range=ydr,
                    plot_width=800,
                    plot_height=300)
        xaxis = LinearAxis(plot=plot)
        plot.below.append(xaxis)
        yaxis = LinearAxis(plot=plot)
        ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker)
        plot.left.append(yaxis)
        cty_glyph = Circle(x="index",
                           y="cty",
                           fill_color="#396285",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        hwy_glyph = Circle(x="index",
                           y="hwy",
                           fill_color="#CE603D",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        cty = GlyphRenderer(data_source=self.source, glyph=cty_glyph)
        hwy = GlyphRenderer(data_source=self.source, glyph=hwy_glyph)
        tooltips = [
            ("Manufacturer", "@manufacturer"),
            ("Model", "@model"),
            ("Displacement", "@displ"),
            ("Year", "@year"),
            ("Cylinders", "@cyl"),
            ("Transmission", "@trans"),
            ("Drive", "@drv"),
            ("Class", "@class"),
        ]
        cty_hover_tool = HoverTool(plot=plot,
                                   renderers=[cty],
                                   tooltips=tooltips + [("City MPG", "@cty")])
        hwy_hover_tool = HoverTool(plot=plot,
                                   renderers=[hwy],
                                   tooltips=tooltips +
                                   [("Highway MPG", "@hwy")])
        select_tool = BoxSelectTool(plot=plot,
                                    renderers=[cty, hwy],
                                    dimensions=['width'])
        plot.tools.extend([cty_hover_tool, hwy_hover_tool, select_tool])
        plot.renderers.extend([cty, hwy, ygrid])

        controls = VBox(children=[
            manufacturer_select, model_select, transmission_select,
            drive_select, class_select
        ],
                        width=200)
        top_panel = HBox(children=[controls, plot])
        layout = VBox(children=[top_panel, data_table])

        return layout
Example #10
0
        'Injured': current.Injured,
        'Total_deaths': current.Total_deaths,
        'Total_damage': current["Total_damage ('000 US$)"]
    }


slider = RangeSlider(title="Year",
                     start=1985,
                     end=2017,
                     value=(1985, 2017),
                     step=1,
                     format="0")
slider.on_change('value', lambda attr, old, new: update())

columns = [
    TableColumn(field="year", title="Year"),
    TableColumn(field="disaster_type", title="Disaster type"),
    TableColumn(field="occurrences", title="Occurrence"),
    TableColumn(field="Injured", title="Injured"),
    TableColumn(field="Total_deaths", title="Total deaths"),
    TableColumn(field="Total_damage", title="Total damage ('000 US$)")
]

data_table = DataTable(source=source, columns=columns, width=1000)

controls = widgetbox(slider)
table = widgetbox(data_table)

curdoc().add_root(row(controls, table))
curdoc().title = "Disaster table"
from bokeh.embed import file_html
from bokeh.resources import INLINE
from bokeh.browserlib import view
from bokeh.sampledata.autompg2 import autompg2 as mpg

source = ColumnDataSource(mpg)

manufacturers = sorted(mpg["manufacturer"].unique())
models = sorted(mpg["model"].unique())
transmissions = sorted(mpg["trans"].unique())
drives = sorted(mpg["drv"].unique())
classes = sorted(mpg["class"].unique())

columns = [
    TableColumn(field="manufacturer",
                title="Manufacturer",
                editor=SelectEditor(options=manufacturers),
                formatter=StringFormatter(font_style="bold")),
    TableColumn(field="model",
                title="Model",
                editor=StringEditor(completions=models)),
    TableColumn(field="displ",
                title="Displacement",
                editor=NumberEditor(step=0.1),
                formatter=NumberFormatter(format="0.0")),
    TableColumn(field="year", title="Year", editor=IntEditor()),
    TableColumn(field="cyl", title="Cylinders", editor=IntEditor()),
    TableColumn(field="trans",
                title="Transmission",
                editor=SelectEditor(options=transmissions)),
    TableColumn(field="drv",
                title="Drive",
Example #12
0
                     color=None,
                     selection_color="orange")
plot_weighted.line('date',
                   'ts',
                   source=source_weighted,
                   line_width=3,
                   line_alpha=0.6)
plot_weighted.circle('date',
                     'ts',
                     size=1,
                     source=source_weighted,
                     color=None,
                     selection_color="orange")

columns = [
    TableColumn(field="word", title="word"),
    TableColumn(field="distance", title="distance")
]
data_table = DataTable(source=source_table,
                       columns=columns,
                       width=400,
                       height=300)


def update_title():
    plot_absolute.title.text = text.value + u"(绝对)= 周词频"
    plot.title.text = text.value + u"(相对)= 周词频 / 周所有词总词频"
    plot_weighted.title.text = text.value + u"(加权)= 周词频 * 词距离 / 周所有词总词频"


def update_data():
Example #13
0
evap = np.array(data['ActualET'])
q_rec = np.array(data['Qrec'])
snow = np.array(data['Snowfall'])
#%% Setup model (function)
q_sim = []
#set up data source
# all input data
ds_rec = ColumnDataSource(
    dict(q_rec=q_rec, ds_time=time_index, evap=evap, prec=prec, snow=snow))
# calculated discharge
ds_sim = ColumnDataSource(dict(q_sim=q_sim, ds_time=time_index))

# Create Data Table
columns_sug = [
    TableColumn(field='ds_time',
                title="Date",
                formatter=DateFormatter(format='ddMyy')),
    TableColumn(field="prec", title="Precipitation"),
    TableColumn(field="snow", title="Snowfall"),
    TableColumn(field="evap", title="Actual ET"),
    TableColumn(field="q_rec", title="Recorded Discharge"),
]

data_table = DataTable(source=ds_rec,
                       columns=columns_sug,
                       width=2 * 630,
                       height=340)

#%% plotting in sugawara tab
#widget dimensions for plotting
width = 620  # width of the input data graph in sugawara model tab
Example #14
0
    def __init__(self, scheduler, **kwargs):
        self.scheduler = scheduler
        self.names = [
            'disk-read', 'cores', 'cpu', 'disk-write', 'memory', 'last-seen',
            'memory_percent', 'host', 'network-send', 'network-recv'
        ]
        self.source = ColumnDataSource({k: [] for k in self.names})

        columns = {
            name: TableColumn(field=name, title=name.replace('_percent', ' %'))
            for name in self.names
        }

        cnames = [
            'host', 'cores', 'memory', 'cpu', 'memory_percent', 'network-send',
            'network-recv'
        ]

        formatters = {
            'cpu': NumberFormatter(format='0.0 %'),
            'memory_percent': NumberFormatter(format='0.0 %'),
            'memory': NumberFormatter(format='0 b'),
            'latency': NumberFormatter(format='0.00000'),
            'last-seen': NumberFormatter(format='0.000'),
            'disk-read': NumberFormatter(format='0 b'),
            'disk-write': NumberFormatter(format='0 b'),
            'network-send': NumberFormatter(format='0 b'),
            'network-recv': NumberFormatter(format='0 b')
        }

        table = DataTable(
            source=self.source,
            columns=[columns[n] for n in cnames],
        )

        for name in cnames:
            if name in formatters:
                table.columns[cnames.index(name)].formatter = formatters[name]

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@memory_percent</span>
                </div>
                """)

        mem_plot = figure(title='Memory Use (%)',
                          toolbar_location=None,
                          x_range=(0, 1),
                          y_range=(-0.1, 0.1),
                          height=80,
                          tools='',
                          **kwargs)
        mem_plot.circle(source=self.source,
                        x='memory_percent',
                        y=0,
                        size=10,
                        fill_alpha=0.5)
        mem_plot.ygrid.visible = False
        mem_plot.yaxis.minor_tick_line_alpha = 0
        mem_plot.yaxis.visible = False
        mem_plot.add_tools(hover, BoxSelectTool())

        hover = HoverTool(point_policy="follow_mouse",
                          tooltips="""
                <div>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@host: </span>
                  <span style="font-size: 10px; font-family: Monaco, monospace;">@cpu</span>
                </div>
                """)

        cpu_plot = figure(title='CPU Use (%)',
                          toolbar_location=None,
                          x_range=(0, 1),
                          y_range=(-0.1, 0.1),
                          height=80,
                          tools='',
                          **kwargs)
        cpu_plot.circle(source=self.source,
                        x='cpu',
                        y=0,
                        size=10,
                        fill_alpha=0.5)
        cpu_plot.ygrid.visible = False
        cpu_plot.yaxis.minor_tick_line_alpha = 0
        cpu_plot.yaxis.visible = False
        cpu_plot.add_tools(hover, BoxSelectTool())

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

        self.root = column(cpu_plot,
                           mem_plot,
                           table,
                           id='bk-worker-table',
                           **sizing_mode)
Example #15
0
    def __init__(self):
        note = Div(
            text="<b>NOTE</b>: Each plan may only have one protocol assigned. "
            "Updating database will overwrite any existing data.",
            width=700)
        self.update_checkbox = CheckboxGroup(
            labels=["Only update plans in table."], active=[0])

        self.toxicity = []  # Will be used to link to Toxicity tab

        self.source = ColumnDataSource(data=dict(mrn=['']))
        self.source.selected.on_change('indices', self.source_listener)

        self.clear_source_selection_button = Button(label='Clear Selection',
                                                    button_type='primary',
                                                    width=150)
        self.clear_source_selection_button.on_click(
            self.clear_source_selection)

        self.protocol = Select(value='', options=[''], title='Protocols:')
        self.physician = Select(value='',
                                options=[''],
                                title='Physician:',
                                width=150)

        self.date_filter_by = Select(
            value='None',
            options=['None', 'sim_study_date', 'import_time_stamp'],
            title='Date Filter Type:',
            width=150)
        self.date_filter_by.on_change('value', self.date_ticker)
        self.date_start = DatePicker(title='Start Date:', width=200)
        self.date_start.on_change('value', self.date_ticker)
        self.date_end = DatePicker(title='End Date:', width=200)
        self.date_end.on_change('value', self.date_ticker)

        self.update_protocol_options()
        self.update_physician_options()

        self.protocol_input = TextInput(value='',
                                        title='Protocol for MRN Input:')
        self.update_button = Button(label='Need MRNs to Update',
                                    button_type='default',
                                    width=150)
        self.update_button.on_click(self.update_db)

        self.mrn_input = TextAreaInput(value='',
                                       title='MRN Input:',
                                       rows=30,
                                       cols=25,
                                       max_length=2000)
        self.mrn_input.on_change('value', self.mrn_input_ticker)

        self.columns = [
            'mrn', 'protocol', 'physician', 'tx_site', 'sim_study_date',
            'import_time_stamp', 'toxicity_grades'
        ]
        relative_widths = [1, 0.8, 0.5, 1, 0.75, 1, 0.8]
        column_widths = [int(250. * rw) for rw in relative_widths]
        table_columns = [
            TableColumn(field=c, title=c, width=column_widths[i])
            for i, c in enumerate(self.columns)
        ]
        self.table = DataTable(source=self.source,
                               columns=table_columns,
                               width=800,
                               editable=True,
                               height=600)

        self.protocol.on_change('value', self.protocol_ticker)
        self.physician.on_change('value', self.physician_ticker)
        self.update_source()

        self.layout = column(
            row(self.protocol, self.physician),
            row(self.date_filter_by, Spacer(width=30), self.date_start,
                Spacer(width=30), self.date_end), note,
            row(
                self.table, Spacer(width=30),
                column(self.update_checkbox,
                       row(self.protocol_input, self.update_button),
                       self.clear_source_selection_button, self.mrn_input)))
def TablaKmResumen(df):
    """
        DATOS EN FORMA DE TABLA POR PARCIALES KILOMETRICOS
    """
    dfTramosKm = TablaParcialesKilometricos(df)
    dfTramosKm['Ritmo_STR'] = dfTramosKm.Ritmo.apply(
        lambda x: FormateoTiempos(x, 'R'))
    OrigenTramosKm = ColumnDataSource(dfTramosKm)
    TablaKmResumen = [
        TableColumn(field='TramoKm',
                    title='Km',
                    width=40,
                    default_sort='ascending',
                    sortable=False,
                    formatter=StringFormatter(font_style='normal',
                                              text_align='center',
                                              text_color='black')),
        TableColumn(field='Ritmo_STR',
                    title='Ritmo[min/Km]',
                    width=80,
                    default_sort='ascending',
                    sortable=False,
                    formatter=StringFormatter(font_style='normal',
                                              text_align='center',
                                              text_color='black')),
        TableColumn(field='FrecuenciaCardiaca',
                    title='FC[ppm]',
                    width=80,
                    default_sort='ascending',
                    sortable=False,
                    formatter=NumberFormatter(format='0,0',
                                              language='es',
                                              rounding='round',
                                              font_style='normal',
                                              text_align='center',
                                              text_color='black')),
        TableColumn(field='Cadencia',
                    title='Cadencia[ppm]',
                    width=80,
                    default_sort='ascending',
                    sortable=False,
                    formatter=NumberFormatter(format='0,0',
                                              language='es',
                                              rounding='round',
                                              font_style='normal',
                                              text_align='center',
                                              text_color='black')),
        TableColumn(field='DesnivelAcumulado',
                    title='Desnivel',
                    width=80,
                    default_sort='ascending',
                    sortable=False,
                    formatter=NumberFormatter(format='0,0',
                                              language='es',
                                              rounding='round',
                                              font_style='normal',
                                              text_align='center',
                                              text_color='black'))
    ]
    PLT_TablaKmResumen = DataTable(source=OrigenTramosKm,
                                   columns=TablaKmResumen,
                                   width=360,
                                   height=550,
                                   fit_columns=False,
                                   sortable=False,
                                   reorderable=False,
                                   selectable=True,
                                   editable=False,
                                   index_position=None,
                                   header_row=True,
                                   row_height=25)

    return PLT_TablaKmResumen
Example #17
0
#Defining Hover Tools
defaults = 'pan,box_zoom,box_select,lasso_select,reset,wheel_zoom,tap,undo,redo,save'
hover_userdefined = HoverTool(tooltips=[('CD-Drive','@cd_drive'),('Multiprocessor','@multi_process'),('PremiumCompany','@prem_comp')])
TOOLS = [defaults,hover_userdefined]

#Plots
p1 = figure(plot_height=600, plot_width=800, title="Generic Scatter plot", tools=TOOLS)
scatter1 = p1.circle(x='x',y='y',source=mainsource,size=7)
p2 = figure(plot_height=400, plot_width=600, title="Adverts vs Trends", tools=defaults)
p2.xaxis.axis_label="Number of Adverts"
p2.yaxis.axis_label="Trends"
lines = p2.line(x='ads',y='trends',source=mainsource,line_width=2)

#DataTable
columns=[
        TableColumn(field="price", title="Price"),
        TableColumn(field="speed", title="Speed"),
        TableColumn(field="hd", title="HardDisk"),
        TableColumn(field="ram", title="RAM"),
        TableColumn(field="screen",title="Screen"),
        TableColumn(field="cd",title="CD"),
        TableColumn(field="multi",title="MultiProcessor"),
        TableColumn(field="premium",title="Premium"),
        TableColumn(field="ads",title="Adverts"),
        TableColumn(field="trend", title="Trends"),
        ]
data_table = DataTable(source=sel_datasource, columns=columns, width=800, height=600)

#Filtering data
def filter_data():
    fdata = df[
def get_changed_parameters(ulog, plot_width):
    """
    get a bokeh column object with a table of the changed parameters
    :param initial_parameters: ulog.initial_parameters
    """
    param_names = []
    param_values = []
    param_defaults = []
    param_mins = []
    param_maxs = []
    param_descriptions = []
    param_colors = []
    default_params = get_default_parameters()
    initial_parameters = ulog.initial_parameters
    system_defaults = None
    airframe_defaults = None
    if ulog.has_default_parameters:
        system_defaults = ulog.get_default_parameters(0)
        airframe_defaults = ulog.get_default_parameters(1)

    for param_name in sorted(initial_parameters):
        param_value = initial_parameters[param_name]

        if param_name.startswith('RC') or param_name.startswith('CAL_'):
            continue

        system_default = None
        airframe_default = None
        is_airframe_default = True
        if system_defaults is not None:
            system_default = system_defaults.get(param_name, param_value)
        if airframe_defaults is not None:
            airframe_default = airframe_defaults.get(param_name, param_value)
            is_airframe_default = abs(float(airframe_default) - float(param_value)) < 0.00001

        try:
            if param_name in default_params:
                default_param = default_params[param_name]
                if system_default is None:
                    system_default = default_param['default']
                    airframe_default = default_param['default']
                if default_param['type'] == 'FLOAT':
                    is_default = abs(float(system_default) - float(param_value)) < 0.00001
                    if 'decimal' in default_param:
                        param_value = round(param_value, int(default_param['decimal']))
                        airframe_default = round(float(airframe_default), int(default_param['decimal'])) #pylint: disable=line-too-long
                else:
                    is_default = int(system_default) == int(param_value)
                if not is_default:
                    param_names.append(param_name)
                    param_values.append(param_value)
                    param_defaults.append(airframe_default)
                    param_mins.append(default_param.get('min', ''))
                    param_maxs.append(default_param.get('max', ''))
                    param_descriptions.append(default_param.get('short_desc', ''))
                    param_colors.append('black' if is_airframe_default else plot_color_red)
            else:
                # not found: add it as if it were changed
                param_names.append(param_name)
                param_values.append(param_value)
                param_defaults.append(airframe_default if airframe_default else '')
                param_mins.append('')
                param_maxs.append('')
                param_descriptions.append('(unknown)')
                param_colors.append('black' if is_airframe_default else plot_color_red)
        except Exception as error:
            print(type(error), error)
    param_data = dict(
        names=param_names,
        values=param_values,
        defaults=param_defaults,
        mins=param_mins,
        maxs=param_maxs,
        descriptions=param_descriptions,
        colors=param_colors)
    source = ColumnDataSource(param_data)
    formatter = HTMLTemplateFormatter(template='<font color="<%= colors %>"><%= value %></font>')
    columns = [
        TableColumn(field="names", title="Name",
                    width=int(plot_width*0.2), sortable=False),
        TableColumn(field="values", title="Value",
                    width=int(plot_width*0.15), sortable=False, formatter=formatter),
        TableColumn(field="defaults",
                    title="Frame Default" if airframe_defaults else "Default",
                    width=int(plot_width*0.1), sortable=False),
        TableColumn(field="mins", title="Min",
                    width=int(plot_width*0.075), sortable=False),
        TableColumn(field="maxs", title="Max",
                    width=int(plot_width*0.075), sortable=False),
        TableColumn(field="descriptions", title="Description",
                    width=int(plot_width*0.40), sortable=False),
        ]
    data_table = DataTable(source=source, columns=columns, width=plot_width,
                           height=300, sortable=False, selectable=False)
    div = Div(text="""<b>Non-default Parameters</b> (except RC and sensor calibration)""",
              width=int(plot_width/2))
    return column(div, data_table, width=plot_width)
#    var d2 = s2.get('data');
#    d2['Time'] = [];
#    d2['operating'] = [];
#    d2['maintenance'] = [];
#    d2['repair'] = [];
#    d2['total'] = [];
#    for (i = 0; i < inds.length; i++) {
#        d2['Time'].push(d1['Time'][inds[i]]);
#        d2['operating'].push(d1['operating'][inds[i]]);
#        d2['maintenance'].push(d1['maintenance'][inds[i]]);
#        d2['repair'].push(d1['repair'][inds[i]]);
#        d2['total'].push(d1['total'][inds[i]]);
#    }
#    s2.trigger('change');
#""")

#display N table
columns = [
	TableColumn(field='Time', title='Time: click to update table'),
	TableColumn(field='operating', title='operating'),
	TableColumn(field='maintenance', title='maintenance'),
	TableColumn(field='repair', title='repair'),
	TableColumn(field='total', title='total'),
]
N_table = DataTable(source=s2, columns=columns, width=1000, height=300)

#export plot to html and return
plot_grid = vplot(dec_fig, earn_fig, rev_fig, motor_fig, vform(N_table))
show(plot_grid, browser=None)

Example #20
0
from bokeh.models.widgets import DataTable, TableColumn
from bokeh.plotting import figure
from bokeh.layouts import row, column

source = ColumnDataSource(dict(time=[], low=[], high=[], open=[], last=[]))
source_1 = ColumnDataSource(
    dict(low=[], high=[], open=[], last=[], volume=[], value=[]))
source_2 = ColumnDataSource(dict(ask_bid_price=[], ask_bid_volume=[],
                                 index=[]))

fig = figure(x_axis_type='datetime', plot_width=1000, plot_height=500)
fig.line(x="time", y="last", color="navy", line_width=2, source=source)
# fig.background_fill_color = "black"

columns_1 = [
    TableColumn(field='open', title='开盘价'),
    TableColumn(field='last', title='最新价'),
    TableColumn(field='high', title='最高价'),
    TableColumn(field='low', title='最低价'),
    TableColumn(field='volume', title='成交量(手)'),
    TableColumn(field='value', title='成交金额(万元)')
]

columns_2 = [
    TableColumn(field='index', title='明细'),
    TableColumn(field='ask_bid_price', title='五档委托价'),
    TableColumn(field='ask_bid_volume', title='五档委托量')
]

data_table_1 = DataTable(source=source_1,
                         columns=columns_1,
Example #21
0
#     # TableColumn(field='volatility', title=u'波动率', formatter=NumberFormatter(format='0.00%')),
#     TableColumn(field='omega', title=u'Omega', formatter=NumberFormatter(format='0.00')),
#     TableColumn(field='max percentage', title=u'最好业绩排名', formatter=NumberFormatter(format='0.00%')),
#     TableColumn(field='max percentage date', title=u'获得最好业绩日期')
# ]
# data_table = DataTable(source=source_table, columns=columns, width=800)
# comp_columns = [
#     TableColumn(field='name', title=u'基金公司'),
#     TableColumn(field='ret', title=u'区间回报', formatter=NumberFormatter(format='0.00%')),
#     TableColumn(field='vol', title=u'波动率', formatter=NumberFormatter(format='0.00%')),
#     TableColumn(field='beta', title='Beta', formatter=NumberFormatter(format='0.00')),
#     TableColumn(field='pos', title=u'仓位变化', formatter=NumberFormatter(format='0.00%'))
# ]
# comp_data_table = DataTable(source=source_comp_table, columns=comp_columns, width=900)
stock_holding_columns = [
    TableColumn(field='ReportDate', title=u'日期'),
    TableColumn(field='FundCode', title=u'基金代码'),
    TableColumn(field='FundAbbr', title=u'基金名称'),
    # TableColumn(field='SecuCode', title=u'股票代码'),
    TableColumn(field='SecuAbbr', title=u'股票名称'),
    TableColumn(field='SharesHolding',
                title=u'当前持仓股数',
                formatter=NumberFormatter(format='0,0')),
    TableColumn(field='SDiff',
                title=u'持仓股数变动',
                formatter=NumberFormatter(format='0,0')),
    TableColumn(field='MarketValue',
                title=u'当前持仓市值',
                formatter=NumberFormatter(format='$0,0')),
    TableColumn(field='Diff',
                title=u'持仓市值变动',
Example #22
0
from datetime import date
from random import randint

from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.io import output_file, show, vform

output_file("data_table.html")

data = dict(
    dates=[date(2014, 3, i + 1) for i in range(10)],
    downloads=[randint(0, 100) for i in range(10)],
)
source = ColumnDataSource(data)

columns = [
    TableColumn(field="dates", title="Date", formatter=DateFormatter()),
    TableColumn(field="downloads", title="Downloads"),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

show(vform(data_table))
Example #23
0
 def data_column(title):
     return TableColumn(field=title,
                        title='<span class="header">' + title + "</span>",
                        formatter=large_text)
Example #24
0
    def _plot(self, runs):
        """Create table and plot that reacts to selection of cells by updating the plotted data to visualize correlation.

        Parameters
        ----------
        runs: List[ConfiguratorRun]
            list with runs (budgets) to be compared
        """
        df = self._get_table(runs)
        # Create CDS from pandas dataframe
        budget_names = list(df.columns.values)
        data = dict(df[budget_names])
        data["Budget"] = df.index.tolist()
        table_source = ColumnDataSource(data)
        # Create bokeh-datatable
        columns = [
            TableColumn(
                field='Budget', title="Budget", sortable=False, width=20)
        ] + [
            TableColumn(field=header,
                        title=header,
                        default_sort='descending',
                        width=10) for header in budget_names
        ]
        bokeh_table = DataTable(source=table_source,
                                columns=columns,
                                index_position=None,
                                sortable=False,
                                height=20 + 30 * len(data["Budget"]))

        # Create CDS for scatter-plot
        all_configs = set([
            a for b in
            [run.original_runhistory.get_all_configs() for run in runs]
            for a in b
        ])
        data = {
            os.path.basename(run.folder).replace('_', ' '): [
                run.original_runhistory.get_cost(c) if c in  # TODO
                run.original_runhistory.get_all_configs() else None
                for c in all_configs
            ]
            for run in runs
        }
        data['x'] = []
        data['y'] = []
        # Default scatter should be lowest vs highest:
        for x, y in zip(data[budget_names[0]], data[budget_names[-1]]):
            if x is not None and y is not None:
                data['x'].append(x)
                data['y'].append(y)

        with warnings.catch_warnings(record=True) as list_of_warnings:
            # Catch unmatching column lengths warning
            warnings.simplefilter('always')
            scatter_source = ColumnDataSource(data=data)
            for w in list_of_warnings:
                self.logger.debug(
                    "During budget correlation a %s was raised: %s",
                    str(w.category), w.message)

        # Create figure and dynamically updating plot (linked with table)
        min_val = min([
            min([v for v in val if v]) for val in data.values() if len(val) > 0
        ])
        max_val = max([
            max([v for v in val if v]) for val in data.values() if len(val) > 0
        ])
        padding = (
            max_val - min_val
        ) / 10  # Small padding to border (fraction of total intervall)
        min_val -= padding
        max_val += padding
        p = figure(plot_width=400,
                   plot_height=400,
                   match_aspect=True,
                   y_range=Range1d(start=min_val,
                                   end=max_val,
                                   bounds=(min_val, max_val)),
                   x_range=Range1d(start=min_val,
                                   end=max_val,
                                   bounds=(min_val, max_val)),
                   x_axis_label=budget_names[0],
                   y_axis_label=budget_names[-1])
        p.circle(
            x='x',
            y='y',
            #x=jitter('x', 0.1), y=jitter('y', 0.1),
            source=scatter_source,
            size=5,
            color="navy",
            alpha=0.5)

        code_budgets = 'var budgets = ' + str(
            budget_names) + '; console.log(budgets);'

        code_try = 'try {'
        code_get_selected_cell = """
            // This first part only extracts selected row and column!
            var grid = document.getElementsByClassName('grid-canvas')[0].children;
            var row = '';
            var col = '';
            for (var i=0,max=grid.length;i<max;i++){
                if (grid[i].outerHTML.includes('active')){
                    row=i;
                    for (var j=0,jmax=grid[i].children.length;j<jmax;j++){
                        if(grid[i].children[j].outerHTML.includes('active')){col=j}
                    }
                }
            }
            col = col - 1;
            console.log('row', row, budgets[row]);
            console.log('col', col, budgets[col]);
            table_source.selected.indices = [];  // Reset, so gets triggered again when clicked again
        """

        code_selected = """
        row = budgets.indexOf(select_x.value);
        col = budgets.indexOf(select_y.value);
        """

        code_update_selection_values = """
        select_x.value = budgets[row];
        select_y.value = budgets[col];
        """

        code_update_plot = """
            // This is the actual updating of the plot
            if (row =>  0 && col > 0) {
              // Copy relevant arrays
              var new_x = scatter_source.data[budgets[row]].slice();
              var new_y = scatter_source.data[budgets[col]].slice();
              // Remove all pairs where one value is null
              while ((next_null = new_x.indexOf(null)) > -1) {
                new_x.splice(next_null, 1);
                new_y.splice(next_null, 1);
              }
              while ((next_null = new_y.indexOf(null)) > -1) {
                new_x.splice(next_null, 1);
                new_y.splice(next_null, 1);
              }
              // Assign new data to the plotted columns
              scatter_source.data['x'] = new_x;
              scatter_source.data['y'] = new_y;
              scatter_source.change.emit();
              // Update axis-labels
              xaxis.attributes.axis_label = budgets[row];
              yaxis.attributes.axis_label = budgets[col];
              // Update ranges
              var min = Math.min(...[Math.min(...new_x), Math.min(...new_y)])
                  max = Math.max(...[Math.max(...new_x), Math.max(...new_y)]);
              var padding = (max - min) / 10;
              console.log(min, max, padding);
              xr.start = min - padding;
              yr.start = min - padding;
              xr.end = max + padding;
              yr.end = max + padding;
            }
        """

        code_catch = """
        } catch(err) {
            console.log(err.message);
        }
        """

        code_selected = code_budgets + code_try + code_selected + code_update_plot + code_catch
        select_x = Select(title="X-axis:",
                          value=budget_names[0],
                          options=budget_names)
        select_y = Select(title="Y-axis:",
                          value=budget_names[-1],
                          options=budget_names)
        callback_select = CustomJS(args=dict(
            scatter_source=scatter_source,
            select_x=select_x,
            select_y=select_y,
            xaxis=p.xaxis[0],
            yaxis=p.yaxis[0],
            xr=p.x_range,
            yr=p.y_range,
        ),
                                   code=code_selected)
        select_x.js_on_change('value', callback_select)
        select_y.js_on_change('value', callback_select)

        code_table_cell = code_budgets + code_try + code_get_selected_cell + code_update_selection_values + code_update_plot + code_catch
        callback_table_cell = CustomJS(args=dict(
            table_source=table_source,
            scatter_source=scatter_source,
            select_x=select_x,
            select_y=select_y,
            xaxis=p.xaxis[0],
            yaxis=p.yaxis[0],
            xr=p.x_range,
            yr=p.y_range,
        ),
                                       code=code_table_cell)
        table_source.selected.js_on_change('indices', callback_table_cell)

        layout = column(bokeh_table, row(p, column(select_x, select_y)))
        return layout
Example #25
0
        'k': kerrich_int
    })
    kerrich_df['mean'] = kerrich_df['k'].expanding().mean()

    chart = get_kerrich_chart(kerrich_df)

    # Kerrich 10,000 summary data
    table_explanation = Div(
        text="<p>The table shows the summary Kerrich data out to 10,000 "
        "tosses. </p>")

    kerrich_summary = get_kerrich_summary()
    data = dict(toss=kerrich_summary['No tosses'],
                mean=kerrich_summary['Mean'],
                ci=kerrich_summary['CI'])
    source = ColumnDataSource(data)
    columns = [
        TableColumn(field="toss", title="No tosses"),
        TableColumn(field="mean", title="Mean"),
        TableColumn(field='ci', title='Confidence interval (±)')
    ]
    data_table = DataTable(source=source, columns=columns)

    # Layout
    layout = column(
        title,
        row(column(chart_explanation, chart),
            column(table_explanation, data_table)))

    show(layout)
Example #26
0
    step=2,
    title="Measurement Uncertainty [%]",
)

toggle_button = Toggle(label="Simulate Measurement Error",
                       button_type="success")

ffa_info = Div(width=550,
               text="Mean of {} simulations for a sample size of {}.".format(
                   'x', 'y'))

error_info = Div(text="", style={'color': 'red'})

# Set up data table for summary statistics
datatable_columns = [
    TableColumn(field="parameter", title="Parameter"),
    TableColumn(field="value_all", title="All Data"),
    TableColumn(field="value_selection", title="Selected Data"),
]

data_table = DataTable(source=datatable_source,
                       columns=datatable_columns,
                       width=450,
                       height=125,
                       index_position=None)

# callback for updating the plot based on a changes to inputs
station_name_input.on_change('value', update_station)
simulation_number_input.on_change('value', update_n_simulations)
msmt_error_input.on_change('value_throttled', update_msmt_error)
sample_size_input.on_change('value', update_simulation_sample_size)
Example #27
0
		def coroutine(df):
			self.source.data = ColumnDataSource.from_df(df)
			if self.table is not None:
				self.table.columns = [TableColumn(field=c, title=c) for c in df.columns]
Example #28
0
def bokeh_plot(import_df):
    import pandas as pd
    import numpy as np
    from bokeh.plotting import figure, show
    from bokeh.layouts import layout, widgetbox, row, column, gridplot
    from bokeh.models import ColumnDataSource, HoverTool, BoxZoomTool, ResetTool, PanTool, CustomJS, PrintfTickFormatter, WheelZoomTool, SaveTool, LassoSelectTool, NumeralTickFormatter
    from bokeh.models.widgets import Slider, Select, TextInput, Div, Tabs, Panel, DataTable, DateFormatter, TableColumn, PreText, NumberFormatter, RangeSlider
    from bokeh.io import curdoc
    from functools import lru_cache
    from bokeh.transform import dodge
    from os.path import dirname, join
    from bokeh.core.properties import value

    #load plotting data here
    @lru_cache()
    def load_data():
        df = import_df
        df.dropna(how='all', axis=0)
        #Northest=['3229','3277','3276','3230','3259','All_Stores_NE']
        df.location_reference_id = df.location_reference_id.astype(str)
        #df['region'] = ['Northeast' if x in Northest else 'Midwest' for x in df['location_reference_id']]
        df['date'] = pd.to_datetime(df['date'])
        df[[
            'BOH_gt_Shelf_Capacity', 'OTL_gt_Shelf_Capacity',
            'Ideal_BOH_gt_Shelf_Capacity', 'BOH_lt_Ideal', 'BOH_eq_Ideal',
            'BOH_gt_Ideal', 'Demand_Fulfilled', 'Fill_Rate', 'Backroom_OH',
            'Total_OH', 'Prop_OH_in_Backroom', 'Never_Q98_gt_POG',
            'Never_Ideal_BOH_gt_POG', 'Sometimes_OTL_Casepack_1_gt_POG',
            'Always_OTL_Casepack_1_le_POG', 'Non_POG'
        ]] = df[[
            'BOH > Shelf Capacity', 'OTL > Shelf Capacity',
            'Ideal BOH > Shelf Capacity', 'BOH < Ideal', 'BOH = Ideal',
            'BOH > Ideal', 'Demand Fulfilled', 'Fill Rate', 'Backroom_OH',
            'Total OH', 'Prop OH in Backroom', 'Never: Q98 > POG',
            'Never: Ideal BOH > POG', 'Sometimes: OTL+Casepack-1 > POG',
            'Always: OTL+Casepack-1 <= POG', 'Non-POG'
        ]]
        df['date_bar'] = df['date']
        df['date_bar'] = df['date_bar'].astype(str)
        return df

    #Filter data source for "All" stores OR data agrregation on DC level
    df_agg = load_data().groupby(['location_reference_id'],
                                 as_index=False).sum()
    source1 = ColumnDataSource(data=df_agg)
    sdate = min(load_data()['date'])
    edate = max(load_data()['date'])
    nodes = len(list(load_data().location_reference_id.unique()))
    days = len(list(load_data().date.unique()))
    policy = "Prod"

    #list of dates for vbar charts
    x_range_list = list(load_data().date_bar.unique())
    #direct access to number of location_reference_idand region
    all_locations1 = list(load_data().location_reference_id.unique())
    #agg_value=['All']
    #all location_reference_idfrom csv file along with an option for agg data "All"
    #all_locations=all_locations1+agg_value
    #all_regions = ['Northeast', 'Midwest']
    all_regions = list(load_data().region.unique())

    desc = Div(text="All locations", width=230)
    pre = Div(text="_", width=230)
    location = Select(title="Location",
                      options=all_locations1,
                      value="All_Stores_NE")
    region = Select(title="Region", options=all_regions, value="NE")

    text_input = TextInput(value="default", title="Search Location:")
    #full data set from load_data(df=df_import)
    source = ColumnDataSource(data=load_data())
    original_source = ColumnDataSource(data=load_data())

    #plotting starts........... here are total 8 graphs for each Metric.

    #Back room on hand
    hover = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date", "@date_bar"), ("Backroom_OH", "@Backroom_OH{0,0.00}")])
    TOOLS = [
        hover,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    p = figure(x_range=x_range_list,
               plot_width=1000,
               plot_height=525,
               title="Backroom On hand by store",
               tools=TOOLS,
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Backroom OH")
    p.background_fill_color = "#e6e9ed"
    p.background_fill_alpha = 0.5
    p.vbar(x=dodge('date_bar', -0.25, range=p.x_range),
           top='Backroom_OH',
           hover_alpha=0.5,
           hover_line_color='black',
           width=0.8,
           source=source,
           color="#718dbf")
    p.xaxis.major_label_orientation = 1
    p.legend.border_line_width = 3
    p.legend.border_line_color = None
    p.legend.border_line_alpha = 0.5
    p.title.text_color = "olive"

    #inbound outbound
    hover_m = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date", "@date_bar"), (
                "Inbound",
                "@Inbound{0,0.00}"), ("Outbound", "@Outbound{0,0.00}")])
    TOOLS_m = [
        hover_m,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    m = figure(plot_height=525,
               plot_width=1000,
               x_range=x_range_list,
               title="Inbound/Outbound by store",
               tools=TOOLS_m,
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Units")
    m.background_fill_color = "#e6e9ed"
    m.background_fill_alpha = 0.5
    m.vbar(x=dodge('date_bar', -0.25, range=m.x_range),
           top='Inbound',
           hover_alpha=0.5,
           hover_line_color='black',
           width=0.4,
           source=source,
           color="#718dbf",
           legend=value("Inbound"))
    m.vbar(x=dodge('date_bar', 0.25, range=m.x_range),
           top='Outbound',
           hover_alpha=0.5,
           hover_line_color='black',
           width=0.4,
           source=source,
           color="#e84d60",
           legend=value("Outbound"))
    m.xaxis.major_label_orientation = 1
    m.legend.border_line_width = 3
    m.legend.border_line_color = None
    m.legend.border_line_alpha = 0.5
    m.title.text_color = "olive"

    #Stockout
    hover_s = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date", "@date_bar"), (
                "BOH_OOS",
                "@BOH_OOS{0,0.000}"), ("EOH_OOS", "@EOH_OOS{0,0.000}")])
    TOOLS_s = [
        hover_s,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    s = figure(plot_height=525,
               plot_width=1000,
               title="Stockouts by store",
               x_axis_type="datetime",
               toolbar_location='above',
               tools=TOOLS_s,
               x_axis_label="Date",
               y_axis_label="Prop Stockout")
    s.background_fill_color = "#e6e9ed"
    s.background_fill_alpha = 0.5
    s.circle(x='date',
             y='EOH_OOS',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    s.line(x='date',
           y='EOH_OOS',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color='navy',
           legend=value("EOH OOS"))
    s.circle(x='date',
             y='BOH_OOS',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    s.line(x='date',
           y='BOH_OOS',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color='red',
           legend=value("BOH OOS"))
    s.legend.border_line_width = 3
    s.legend.border_line_color = None
    s.legend.border_line_alpha = 0.5
    s.title.text_color = "olive"

    #Fill rate
    hover_t = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date", "@date_bar"), ("Fill Rate", "@Fill_Rate{0,0.00}")])
    TOOLS_t = [
        hover_t,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    t = figure(plot_height=525,
               x_range=x_range_list,
               plot_width=1000,
               title="Fill rates by store",
               tools=TOOLS_t,
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Fill rate")
    t.background_fill_color = "#e6e9ed"
    t.background_fill_alpha = 0.5
    t.vbar(x=dodge('date_bar', -0.25, range=t.x_range),
           top='Fill Rate',
           hover_alpha=0.5,
           hover_line_color='black',
           width=0.8,
           source=source,
           color="#718dbf")
    t.xaxis.major_label_orientation = 1
    t.legend.border_line_width = 3
    t.legend.border_line_color = None
    t.legend.border_line_alpha = 0.5
    t.title.text_color = "olive"

    # % Backroom spillover
    hover_w = HoverTool(
        tooltips=[("Location", "@location_reference_id"), ("Date",
                                                           "@date_bar"),
                  ("Prop OH in Backroom", "@Prop_OH_in_Backroom{0,0.00}")])
    TOOLS_w = [
        hover_w,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    w = figure(plot_height=525,
               plot_width=1000,
               title="Prop OH in Backroom by store",
               x_axis_type="datetime",
               tools=TOOLS_w,
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label=" % Backroom spillover")
    w.background_fill_color = "#e6e9ed"
    w.background_fill_alpha = 0.5
    w.circle(x='date',
             y='Prop OH in Backroom',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    w.line(x='date',
           y='Prop OH in Backroom',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color='navy')
    w.title.text_font_style = "bold"
    w.title.text_color = "olive"
    w.legend.click_policy = "hide"
    w.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    #BOH vs Ideal
    hover_f = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date",
            "@date_bar"), ('BOH < Ideal', "@BOH_lt_Ideal{0,0.00}"
                           ), ('BOH > Ideal', "@BOH_gt_Ideal{0,0.00}"
                               ), ('BOH = Ideal', "@BOH_eq_Ideal{0,0.00}")])
    TOOLS_f = [
        hover_f,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    colors = ["#c9d9d3", "#718dbf", "#e84d60"]
    BOH_vs_ideal = ['BOH < Ideal', 'BOH > Ideal', 'BOH = Ideal']
    f = figure(x_range=x_range_list,
               plot_height=525,
               plot_width=1000,
               title="BOH vs Ideal by store",
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Prop",
               tools=TOOLS_f)
    f.vbar_stack(BOH_vs_ideal,
                 x='date_bar',
                 width=0.9,
                 color=colors,
                 source=source,
                 legend=[value(x) for x in BOH_vs_ideal],
                 name=BOH_vs_ideal)
    f.xaxis.major_label_orientation = 1
    f.legend.border_line_width = 3
    f.legend.border_line_color = None
    f.legend.border_line_alpha = 0.5
    f.title.text_color = "olive"

    #Pog Fit
    hover_g = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date",
            "@date_bar"), ('Never: Q98 > POG', "@Never_Q98_gt_POG{0,0.00}"),
                  ("Never: Ideal BOH > POG",
                   "@Never_Ideal_BOH_gt_POG{0,0.00}"),
                  ("Sometimes: OTL+Casepack-1 > POG",
                   "@Sometimes_OTL_Casepack_1_gt_POG{0,0.00}"),
                  ("Always: OTL+Casepack-1 <= POG",
                   "@Always_OTL_Casepack_1_le_POG{0,0.00}"
                   ), ("Non-POG'", "@Non_POG{0,0.00}")])
    TOOLS_g = [
        hover_g,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    colors2 = ['#79D151', "#718dbf", '#29788E', '#fc8d59', '#d53e4f']
    pog_fit = [
        'Never: Q98 > POG', 'Never: Ideal BOH > POG',
        'Sometimes: OTL+Casepack-1 > POG', 'Always: OTL+Casepack-1 <= POG',
        'Non-POG'
    ]
    g = figure(x_range=x_range_list,
               plot_height=525,
               plot_width=1200,
               title="Pog Fit by store",
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Counts",
               tools=TOOLS_g)
    g.vbar_stack(pog_fit,
                 x='date_bar',
                 width=0.9,
                 color=colors2,
                 source=source,
                 legend=[value(x) for x in pog_fit],
                 name=pog_fit)
    g.xaxis.major_label_orientation = 1
    g.legend.border_line_width = 3
    g.legend.border_line_color = None
    g.legend.border_line_alpha = 0.5
    g.title.text_color = "olive"
    g.legend.location = "top_right"

    # BOH vs Pog
    colors3 = ["#c9d9d3", "#718dbf", "#e84d60"]
    shelf = [
        'BOH > Shelf Capacity', 'OTL > Shelf Capacity',
        'Ideal BOH > Shelf Capacity'
    ]
    hover_h = HoverTool(
        tooltips=[("Location", "@location_reference_id"), ("Date",
                                                           "@date_bar"),
                  ("OTL > Shelf Capacity", "@OTL_gt_Shelf_Capacity{0,0.00}"
                   ), ("BOH > Shelf Capacity",
                       "@BOH_gt_Shelf_Capacity{0,0.00}"),
                  ("Ideal BOH > Shelf Capacity",
                   "@Ideal_BOH_gt_Shelf_Capacity{0,0.00}")])
    TOOLS_h = [
        hover_h,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    h = figure(plot_height=525,
               plot_width=1000,
               title="BOH vs Pog by store",
               x_axis_type="datetime",
               toolbar_location='above',
               tools=TOOLS_h,
               x_axis_label="Date",
               y_axis_label="Prop")
    h.background_fill_color = "#e6e9ed"
    h.background_fill_alpha = 0.5
    h.circle(x='date',
             y='BOH > Shelf Capacity',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    h.line(x='date',
           y='BOH > Shelf Capacity',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color='navy',
           legend=value("BOH > Shelf Capacity"))
    h.circle(x='date',
             y='OTL > Shelf Capacity',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    h.line(x='date',
           y='OTL > Shelf Capacity',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color="green",
           legend=value("OTL > Shelf Capacity"))
    h.circle(x='date',
             y='Ideal BOH > Shelf Capacity',
             source=source,
             fill_color=None,
             line_color="#4375c6")
    h.line(x='date',
           y='Ideal BOH > Shelf Capacity',
           source=source,
           hover_alpha=0.5,
           hover_line_color='black',
           line_width=2,
           line_color="#e84d60",
           legend=value("Ideal BOH > Shelf Capacity"))
    h.legend.border_line_width = 3
    h.legend.border_line_color = None
    h.legend.border_line_alpha = 0.5
    h.title.text_color = "olive"
    h.legend.click_policy = "mute"

    # Inventory
    hover_j = HoverTool(
        tooltips=[("Location", "@location_reference_id"), (
            "Date", "@date_bar"), ("DFE_Q98", "@DFE_Q98{0,0.00}"),
                  ("OTL",
                   "@OTL{0,0.00}"), ("EOH",
                                     "@EOH{0,0.00}"), ("BOH", "@BOH{0,0.00}")])
    TOOLS_j = [
        hover_j,
        BoxZoomTool(),
        LassoSelectTool(),
        WheelZoomTool(),
        PanTool(),
        ResetTool(),
        SaveTool()
    ]
    j = figure(plot_height=525,
               plot_width=1200,
               x_range=x_range_list,
               title="Inbound/Outbound by store",
               tools=TOOLS_j,
               toolbar_location='above',
               x_axis_label="Date",
               y_axis_label="Units")
    j.background_fill_color = "#e6e9ed"
    j.background_fill_alpha = 0.5
    j.vbar(x=dodge('date_bar', -0.40, range=j.x_range),
           top='DFE_Q98',
           hover_alpha=0.3,
           hover_line_color='black',
           width=0.2,
           source=source,
           color="#FBA40A",
           legend=value("DFE_Q98"))
    j.vbar(x=dodge('date_bar', -0.20, range=j.x_range),
           top='OTL',
           hover_alpha=0.3,
           hover_line_color='black',
           width=0.2,
           source=source,
           color="#4292c6",
           legend=value("OTL"))
    j.vbar(x=dodge('date_bar', 0.00, range=j.x_range),
           top='EOH',
           hover_alpha=0.3,
           hover_line_color='black',
           width=0.2,
           source=source,
           color='#a1dab4',
           legend=value("EOH"))
    j.vbar(x=dodge('date_bar', 0.20, range=j.x_range),
           top='BOH',
           hover_alpha=0.3,
           hover_line_color='black',
           width=0.2,
           source=source,
           color="#DC5039",
           legend=value("BOH"))
    j.xaxis.major_label_orientation = 1
    j.legend.border_line_width = 3
    j.legend.border_line_color = None
    j.legend.border_line_alpha = 0.5
    j.title.text_color = "olive"
    j.legend.location = "top_left"
    j.legend.click_policy = "mute"

    #desc.text = " <br >  <b> Region:</b> <i>  </i> <br /> "
    pre.text = " <b>Start date:</b>  <i>{}</i> <br />  <b>End date:</b> <i>{}</i> <br /> <b>Time period:</b> <i>{}</i> days <br />  <b> Total Number of Nodes:</b> <i>{}</i> <br /> <b>Policy</b> = <i>{}</i><br /> ".format(
        sdate, edate, days, nodes, policy)

    #fuction to update data on selection
    callback = CustomJS(args=dict(source=source,
                                  original_source=original_source,
                                  location_select_obj=location,
                                  region_select_obj=region,
                                  div=desc,
                                  text_input=text_input),
                        code="""
    var data = source.get('data');
    var original_data = original_source.get('data');
    var loc = location_select_obj.get('value');
    var reg = region_select_obj.get('value');
    var line = " <br />  <b> Region:</b>"+ reg + "<br />  <b>Location:</b> " +   loc;
    var text_input =text_input.get('value');
    div.text=line;
    for (var key in original_data) {
    data[key] = [];
    for (var i = 0; i < original_data['location_reference_id'].length; ++i) {
    if ((original_data['location_reference_id'][i] === loc) && (original_data['region'][i] === reg) ) {
    data[key].push(original_data[key][i]);
    }   }   }
    source.trigger('change');
    """)

    #controls = [location, region]
    #for control in controls:
    #control.js_on_change("value", callback)
    #source.js_on_change("value", callback)
    desc.js_on_event('event', callback)
    location.js_on_change('value', callback)
    region.js_on_change('value', callback)
    text_input.js_on_change('value', callback)
    #inputs = widgetbox(*controls, sizing_mode="fixed")
    #inputs = widgetbox(*controls,width=220,height=500)
    inputs = widgetbox(location, region, desc, pre, width=220, height=500)
    # controls number of tabs
    tab1 = Panel(child=p, title='Backroom OH')
    tab2 = Panel(child=s, title='Stockouts')
    tab3 = Panel(child=f, title='BOH vs Ideal')
    tab4 = Panel(child=g, title='Pog Fit')
    tab5 = Panel(child=m, title='Inbound/Outbound')
    tab6 = Panel(child=h, title='BOH vs POG')
    tab7 = Panel(child=t, title='Fill Rate')
    tab8 = Panel(child=j, title='Inventory')
    tab9 = Panel(child=w, title='Prop OH in Backroom')

    #data table columns to summarize data
    columns = [
        TableColumn(field="location_reference_id", title="Location"),
        TableColumn(field="Backroom_OH",
                    title="Backroom_OH",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="Outbound",
                    title="Outbound",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="Inbound",
                    title="Inbound",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="OTL",
                    title="OTL",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="DFE_Q98",
                    title="DFE_Q98",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="BOH",
                    title="BOH",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="EOH",
                    title="EOH",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="BOH_OOS",
                    title="BOH_OOS",
                    formatter=NumberFormatter(format="0,0")),
        TableColumn(field="EOH_OOS",
                    title="EOH_OOS",
                    formatter=NumberFormatter(format="0,0"))
    ]
    data_table = DataTable(source=source1, columns=columns, width=1250)

    tab10 = Panel(child=data_table, title='Summary Table')
    view = Tabs(
        tabs=[tab1, tab2, tab5, tab8, tab6, tab3, tab7, tab4, tab9, tab10])

    layout_text = column(inputs)
    layout1 = row(layout_text, view)
    #laying out plot
    layout2 = layout(children=[[layout_text, view]],
                     sizing_mode='scale_height')
    #update plots
    return layout2
Example #29
0
    def summary(self):
        """Report summary

        This method will create tables to be presented in the report

        Parameters
        ----------

        Returns
        -------
        tabs : bokeh WidgetBox
            Bokeh WidgetBox with the summary table plot

        Example
        -------
        >>> rotor = rotor_example()
        >>> report = Report(rotor=rotor,
        ...                 minspeed=400,
        ...                 maxspeed=1000,
        ...                 speed_units="rad/s")
        >>> stability1 = report.stability_level_1(D=[0.35, 0.35],
        ...                          H=[0.08, 0.08],
        ...                          HP=[10000, 10000],
        ...                          RHO_ratio=[1.11, 1.14],
        ...                          RHOd=30.45,
        ...                          RHOs=37.65,
        ...                          oper_speed=1000.0)
        >>> stability2 = report.stability_level_2()
        >>> report.summary() # doctest: +ELLIPSIS
        Tabs...
        """
        stab_lvl1_data = dict(
            tags=[self.tag],
            machine_type=[self.machine_type],
            Q0=[self.Q0],
            Qa=[self.Qa],
            log_dec_a=[self.log_dec_a],
            Qratio=[self.Qratio],
            crti_speed=[self.crit_speed],
            MCS=[self.MCS],
            CSR=[self.CSR],
            RHO_gas=[self.RHO_gas],
        )
        stab_lvl2_data = dict(
            tags=self.df_logdec['tags'],
            logdec=self.df_logdec['log_dec'],
        )

        stab_lvl1_source = ColumnDataSource(stab_lvl1_data)
        stab_lvl2_source = ColumnDataSource(stab_lvl2_data)

        stab_lvl1_titles = [
            "Rotor Tag",
            "Machine Type",
            "$Q_0$ (N/m)",
            "$Q_A$ (N/m)",
            "log dec (δ)",
            "$Q_0 / Q_A$",
            "1st Critical Spped (RPM)",
            "MCS",
            "CSR",
            "Gas Density (kg/m³)",
        ]
        stab_lvl2_titles = ["Components", "Log. Dec."]

        stab_lvl1_formatters = [
            None,
            None,
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
            NumberFormatter(format="0.000"),
        ]
        stab_lvl2_formatters = [None, NumberFormatter(format="0.0000")]

        stab_lvl1_columns = [
            TableColumn(field=str(field), title=title, formatter=form)
            for field, title, form in zip(
                stab_lvl1_data.keys(), stab_lvl1_titles, stab_lvl1_formatters
            )
        ]
        stab_lvl2_columns = [
            TableColumn(field=str(field), title=title, formatter=form)
            for field, title, form in zip(
                stab_lvl2_data.keys(), stab_lvl2_titles, stab_lvl2_formatters
            )
        ]

        stab_lvl1_table = DataTable(
            source=stab_lvl1_source, columns=stab_lvl1_columns, width=1600
        )
        stab_lvl2_table = DataTable(
            source=stab_lvl2_source, columns=stab_lvl2_columns, width=1600
        )

        table1 = widgetbox(stab_lvl1_table)
        tab1 = Panel(child=table1, title="Stability Level 1")
        table2 = widgetbox(stab_lvl2_table)
        tab2 = Panel(child=table2, title="Stability Level 2")

        tabs = Tabs(tabs=[tab1, tab2])

        return tabs
Example #30
0
def cluster_gui(doc):
    global s2, s1, old_indices
    old_indices = []
    output_file("tile.html")
    tile_provider = get_provider(CARTODBPOSITRON)
    x = []
    y = []
    name = []
    global fig03
    fig03 = figure(
        plot_width=400,
        plot_height=400,
        tools=["box_zoom", "wheel_zoom", "reset", "save"],
        title="Waveforms from current selection",
    )
    for i, st in enumerate(stations):
        xm, ym = merc(st.lat, st.lon)
        x.append(xm)
        y.append(ym)
        name.append(st.nsl_string())

    # create first subplot
    plot_width = 400
    plot_height = 400
    d = num.ones_like(x)

    s1 = ColumnDataSource(data=dict(x=x, y=y, ind=d, name=name))
    # range bounds supplied in web mercator coordinates
    fig01 = figure(
        x_axis_type="mercator",
        y_axis_type="mercator",
        plot_width=plot_width,
        plot_height=plot_height,
        tools=[
            "lasso_select", "box_select", "reset", "save", "box_zoom",
            "wheel_zoom"
        ],
        title="Select",
    )
    fig01.add_tile(tile_provider)

    fig01.scatter("x", "y", source=s1, alpha=0.6, size=8)

    # create second subplot
    s2 = ColumnDataSource(data=dict(x=[], y=[], ind=[], name=[]))

    color_mapper = LinearColorMapper(palette='Magma256', low=1, high=100)

    fig02 = figure(
        x_axis_type="mercator",
        y_axis_type="mercator",
        plot_width=plot_width,
        plot_height=plot_height,
        x_range=(num.min(x), num.max(x)),
        y_range=(num.min(y), num.max(y)),
        tools=["box_zoom", "wheel_zoom", "reset", "save"],
        title="Stations selected for Array",
    )
    fig02.add_tile(tile_provider)

    fig02.scatter("x",
                  "y",
                  source=s2,
                  alpha=1,
                  color={
                      'field': 'ind',
                      'transform': color_mapper
                  },
                  size=8)

    x_event, y_event = merc(event.lat, event.lon)
    fig01.scatter(x_event, y_event, size=8, color="red")
    fig02.scatter(x_event, y_event, size=8, color="red")

    columns = [
        TableColumn(field="x", title="X axis"),
        TableColumn(field="y", title="Y axis"),
        TableColumn(field="ind", title="indices"),
        TableColumn(field="name", title="name"),
    ]

    table = DataTable(
        source=s2,
        columns=columns,
        width=400,
        height=600,
        sortable=True,
        selectable=True,
        editable=True,
    )

    source_count = 0
    callback_slider = CustomJS(code="""
        source_count = slider.value;
        """)
    global slider

    slider = Slider(start=1, end=100, value=1, step=1, title="Array number")
    slider.js_on_change('value', callback_slider)

    s1.selected.js_on_change(
        "indices",
        CustomJS(args=dict(s1=s1, s2=s2, s3=slider, table=table),
                 code="""
            var inds = cb_obj.indices;
            var d1 = s1.data;
            var d2 = s2.data;
            const A = s3.value;

            for (var i = 0; i < inds.length; i++) {
                d2['x'].push(d1['x'][inds[i]])
                d2['y'].push(d1['y'][inds[i]])
                d2['name'].push(d1['name'][inds[i]])
                d2['ind'].push(A)
            }
            s2.change.emit();
            table.change.emit();
    	    s2.data = s2.data;

            var inds = source_data.selected.indices;
            var data = source_data.data;
            var out = "name, x, y, ind\\n";
            for (i = 0; i < inds.length; i++) {
                out += data['name'][inds[i]] + "," + data['x'][inds[i]] + "," + data['y'][inds[i]] + "," + data['ind'][inds[i]]   + "\\n";
            }
            var file = new Blob([out], {type: 'text/plain'});

        """),
    ),

    savebutton = Button(label="Save", button_type="success")
    savebutton.callback = CustomJS(
        args=dict(source_data=s1),
        code="""
            var inds = source_data.selected.indices;
            var data = source_data.data;
            var out = "name, x, y, ind\\n";
            for (i = 0; i < inds.length; i++) {
                out += data['name'][inds[i]] + "," + data['x'][inds[i]] + "," + data['y'][inds[i]] + "," + data['ind'][inds[i]]   + "\\n";
            }
            var file = new Blob([out], {type: 'text/plain'});
            var elem = window.document.createElement('a');
            elem.href = window.URL.createObjectURL(file);
            elem.download = 'arrays.txt';
            document.body.appendChild(elem);
            elem.click();
            document.body.removeChild(elem);
            """,
    )

    tooltips = [
        ("X:", "@x"),
        ("Y:", "@y"),
        ("Array:", "@ind"),
        ("Station:", "@name"),
    ]

    fig01.add_tools(HoverTool(tooltips=tooltips))
    fig02.add_tools(HoverTool(tooltips=tooltips))
    fig03.add_tools(HoverTool(tooltips=tooltips))

    endbutton = Button(label="End and proceed", button_type="success")
    endbutton.on_click(button_callback)

    clearbutton = Button(label="Clear all", button_type="success")
    clearbutton.on_click(clearbuttonlast_callback)
    clearbuttonlast = Button(label="Clear last selection",
                             button_type="success")
    clearbuttonlast.on_click(clearbuttonlast_callback)
    clearbuttonone = Button(label="Remove one from list",
                            button_type="success")
    clearbuttonone.on_click(clearbuttonone_callback)

    b = Button(label="Reset all plots")
    b.js_on_click(
        CustomJS(code="""\
document.querySelectorAll('.bk-tool-icon-reset[title="Reset"]').forEach(d => d.click())
"""))
    #layout = grid([fig01, fig02, table, fig03, slider, clearbuttonlast, clearbutton, savebutton, endbutton], ncols=3, nrows=4)
    global text_input
    text_input = TextInput(value="1", title="Array number:")

    buttons = column(clearbuttonlast, clearbuttonone, clearbutton, savebutton,
                     endbutton)
    inputs = column(text_input, slider)

    layout_grid = layout([fig01, fig02, buttons], [fig03, inputs, table])

    #curdoc().add_root(layout)
    cluster_result = []
    doc.add_root(layout_grid)
    #global session
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 100)
    #session.show(layout)
    doc.add_periodic_callback(update, 900)
    curdoc().title = "Array selection"