Esempio n. 1
0
def bkapp(doc):
    def update_plot(attrname, old_value, new_value):
        disease = disease_selector.value
        smooth = int(smooth_selector.value)
        src = models.get_disease_totals_by_name(disease, smooth)
        source.data.update(src.data)
        chart.title.text = disease
        disease_selector.label = disease
        smooth_selector.label = str(smooth)
        doc.title = "Epidemic - {}".format(disease)

    # request
    args = doc.session_context.request.arguments
    get_param = lambda param, default: args.get(
        param, [bytes(str(default), encoding='utf')])[0].decode('utf-8')
    disease = get_param('disease', DEFAULT_DISEASE)
    smooth = get_param('smooth', 2)
    ## Components

    # Widgets
    disease_selector = Dropdown(label=disease,
                                value=disease,
                                menu=list(zip(DISEASES, DISEASES)))
    smooth_selector = Dropdown(label=smooth,
                               value=smooth,
                               menu=[(str(i), str(i)) for i in range(1, 9)])
    picker = RadioButtonGroup(labels=['Total Cases', 'Cases by Region'],
                              width=300)

    # Sources

    source = ColumnDataSource(
    )  # models.get_disease_data_by_name(disease,smooth)
    # Events
    disease_selector.on_change('value', update_plot)
    smooth_selector.on_change('value', update_plot)

    # Figures
    chart = make_plot(source, disease)
    ranger = make_range_tool(chart)
    chart_range = make_range_plot(source, ranger)

    #
    controls = column(widgetbox(disease_selector, smooth_selector, picker),
                      height=280)
    charts_col = column(chart, chart_range, width=1024)

    doc.add_root(row(charts_col, controls))
    doc.title = "Epidemic - {}".format(disease)
    update_plot(None, None, None)
Esempio n. 2
0
def getDropdown():
    menu = [("Clustering 1", "item_1"), ("Clustering 2", "item_2"), None,
            ("Clustering 3", "item_3")]
    dropdown = Dropdown(label="Choose clustering to explore",
                        type="warning",
                        menu=menu)
    return dropdown
Esempio n. 3
0
def _timeseries_widgets(col_1, col_2, col_max, col_min, n_bins, aggregate,
                        callback):
    col_1_time = pd.to_datetime(col_1)
    if col_max is None:
        col_max = col_1_time.max()
    if col_min is None:
        col_min = col_1_time.min()

    slider = Slider(start=1, end=100, value=n_bins, step=1, title="Bins")
    slider.on_change('value', callback)

    range_select = DateRangeSlider(start=col_1_time.min(),
                                   end=col_1_time.max(),
                                   value=(col_min, col_max),
                                   step=1,
                                   title='Range',
                                   format='%R %F')
    range_select.on_change('value', callback)
    dropdown = Dropdown(value=aggregate,
                        label=aggregate,
                        button_type="default",
                        menu=[('mean', 'mean'), ('count', 'count'),
                              ('sum', 'sum'), ('max', 'max'), ('min', 'min')])
    dropdown.on_change('value', callback)
    return slider, range_select, dropdown
Esempio n. 4
0
def ddownexample_tab():

    from bokeh.models.widgets import Dropdown
    from bokeh.layouts import widgetbox
    from bokeh.layouts import layout
    from bokeh.models.widgets import Panel

    # menu = [(x, x) for x in df["opp_type"].unique()]
    menu = [("chris", "Chris"), ("marie", "Marie"), ("david", "David"),
            ("michael", "Michael")]

    # button_type: default, primary, success, warning, danger, link
    dropdown = Dropdown(label="Select sibling",
                        button_type="success",
                        menu=menu)

    def printddval(attr, old, new):
        print(dropdown.value)

    dropdown.on_change('value', printddval)

    mylayout = [widgetbox(dropdown)]
    tab = Panel(child=layout([mylayout]), title="Dropdown example")

    return tab
Esempio n. 5
0
def _scatter_widgets(col_1, col_2, aggregate, callback):
    dropdown = Dropdown(value=aggregate,
                        label=aggregate,
                        button_type="default",
                        menu=[('mean', 'mean'), ('last', 'last'),
                              ('sum', 'sum'), ('max', 'max'), ('min', 'min')])
    dropdown.on_change('value', callback)
    return dropdown
Esempio n. 6
0
def dropdown_example():
    output_file('dropdown.html')

    menu = [('Item 1', 'item_1'), ('Item 2', 'item_2'), None,
            ('Item 3', 'item_3')]
    dropdown = Dropdown(label='Dropdown button',
                        button_type='warning',
                        menu=menu)

    show(widgetbox(dropdown))
Esempio n. 7
0
    def __init__(self):

        super().__init__()

        self.state = "New York"
        self.menu = STATES

        self.state_selection = Dropdown(menu=self.menu,
                                        label=self.state,
                                        sizing_mode="stretch_width")
Esempio n. 8
0
def trend_tab(data, ticker):

    #pg_title = Paragraph()
    #pg_title.text = '[ '+ticker+' ] PRICE TREND'

    def make_plot(data_src):

        p = figure(x_axis_type="datetime",
                   title=ticker + ' Closing Price Trend',
                   plot_width=800,
                   plot_height=400)
        p.grid.grid_line_alpha = 0.3
        p.xaxis.axis_label = 'Trading Date'
        p.yaxis.axis_label = '[ ' + ticker + ' ] Close Price'

        p.line(data_src['Date'],
               data_src['Close'],
               line_width=2,
               legend_label=ticker)

        p.legend.location = "top_left"

        return p

    def update(attr, old, new):
        # ticker
        ticker = dropdown.value  #'SCOM'
        ticker_file = ticker + '.csv'

        # Read data into dataframes
        data_df = pd.read_csv(join(dirname(__file__), 'data', ticker_file),
                              parse_dates=True).dropna()

        data_df['Date'] = pd.to_datetime(data_df['Date'])

        src.data.update(data_df.data)

    # Set dropdown
    stocks_list = [("Safaricom Plc", "SCOM"),
                   ("Nation Media Group Plc", "NMG"), None,
                   ("Kenya Power & Lighting Company", "KPLC")]
    dropdown = Dropdown(label="NSE Stocks List", menu=stocks_list)

    dropdown.on_change('value', update)
    dropdown.on_click(update)

    p = make_plot(data)

    # Create a row layout
    layout = row(widgetbox(dropdown, align='center'), p)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Stock Price Trend')

    return tab
Esempio n. 9
0
    def __init__(self, renderer):
        self.file_input = Dropdown(label="Select dataset", menu=[])
        for dataset_name in SQLDBInformer(DbConn({})).get_all_schemas():
            if dataset_name in set(["information_schema", "performance_schema", "sys", "defaultDB", "mysql"]):
                continue
            if dataset_name[:3] == "pg_":
                continue
            self.file_input.menu.append(dataset_name)
        self.run_id_dropdown = Dropdown(label="select run id here", menu=[])
        self.ground_truth_id_dropdown = Dropdown(label="select ground truth id here", menu=[])
        self.score_slider = RangeSlider(start=0, end=1, value=(0, 1), step=.1, callback_policy='mouseup',
                                        title="score range")
        self.max_elements_slider = Slider(start=1000, end=100000, value=10000, step=1000,
                                          callback_policy='mouseup', title="max render")
        self.range_link_radio = RadioGroup(labels=["Link read plot to x-range", "Link read plot to y-range"],
                                           active=0, orientation="horizontal")
        self.full_render_button = Button(label="render without limit")
        self.render_mems_button = Button(label="render MEMs")
        self.delete_button = Button(label="Delete Dataset")
        self.force_read_id = TextInput(value="", title="Render reads with ids (comma seperated list):")

        self.file_input.on_change("value", lambda x,y,z: self.file_input_change(renderer))
        self.run_id_dropdown.on_change("value", lambda x,y,z: self.run_id_change(renderer))
        self.ground_truth_id_dropdown.on_change("value", lambda x,y,z: self.ground_id_change(renderer))
        self.score_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))
        self.max_elements_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))

        self.full_render_button.on_event(ButtonClick, lambda x: self.full_render(renderer))
        self.render_mems_button.on_event(ButtonClick, lambda x: self.render_mems_button_event(renderer))
        self.delete_button.on_event(ButtonClick, lambda x: self.delete_button_event(renderer))
        self.force_read_id.on_change("value", lambda x,y,z: self.forced_read_ids_change(renderer))

        self.spinner_div = Div(text=html_file("spinner"), sizing_mode="scale_both", visible=False)
        self.condition = threading.Condition()

        self.subset_buttons = CheckboxButtonGroup(labels=["Render false-positives", "Render false-negatives",
                                                          "Render true-positives", "Compute Stats"],
                                                          active=[0, 1, 2])
        self.subset_buttons.on_click(lambda x: self.forced_read_ids_change(renderer))
        self.blur_slider = Slider(start=0, end=500, value=100, step=1, callback_policy='mouseup',
                                        title="Blur")
        self.blur_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))
Esempio n. 10
0
    def init_dropdown_widget(cls, update_value_callback, update_options_callback,
                             on_change_callback, value=None, options=None):

        if not value:
            value = cls.get_value_or_none(update_value_callback)
        if not options:
            options = cls.get_value_or_none(update_options_callback)

        dropdown_button = Dropdown(label=value, menu=options)
        #on_change is set after the object is created due to dependencies
        return DropdownWidget(dropdown_button, update_value_callback,
                              update_options_callback, on_change_callback)
Esempio n. 11
0
    def assemble_global_widgets(self):
        model_menu = [(self.rf_clf_name, self.rf_clf_name), None,
                      (self.xgb_clf_name, self.xgb_clf_name)]

        model_dropdown = Dropdown(label="Model",
                                  button_type="warning",
                                  menu=model_menu,
                                  value=self.xgb_clf_name)

        threshold_slider = Slider(start=0,
                                  end=1,
                                  value=0.5,
                                  step=.01,
                                  title="Threshold value")

        return model_dropdown, threshold_slider
Esempio n. 12
0
    def __init__(self, main):

        self.row = pn.Row(pn.pane.Str("loading"))

        plot_options = [
            "Basic Plot",
            "Selected Source Info",
        ] + list(extension_plots.get_plot_dict().keys())

        self._plot_selection = Dropdown(label="Choose plot type:",
                                        menu=plot_options)

        self._plot_selection.on_click(
            partial(
                self._update_main_contents,
                main=main,
            ), )
Esempio n. 13
0
    def __init__(self):

        super().__init__()

        self.state = "New York, Washington"
        self.menu = COUNTIES

        self.state_selection = Dropdown(menu=self.menu,
                                        label=self.state,
                                        sizing_mode="stretch_width")

        self.data_getter = RadioGroup(
            labels=[
                "Cases",
                "Deaths",
            ],
            active=0,
            sizing_mode="stretch_width",
        )
Esempio n. 14
0
    def assemble_global_widgets(self):
        model_menu = [(self.rf_clf.__name__, self.rf_clf.__name__), None,
                      (self.xgb_clf.__name__, self.xgb_clf.__name__)]

        model_dropdown = Dropdown(label="Model",
                                  button_type="warning",
                                  menu=model_menu,
                                  value=self.xgb_clf.__name__)

        vis_x_axis = self.test
        min_date, max_date = vis_x_axis.index.min(), vis_x_axis.index.max()

        time_period_slider = DateRangeSlider(title="Time Period",
                                             value=(min_date, max_date),
                                             start=min_date,
                                             end=max_date,
                                             step=1)

        return model_dropdown, time_period_slider
Esempio n. 15
0
def initialize():
    text_output = Paragraph(text='Status', width=300, height=100)
    DATA_STORE.update({'text_output': text_output})

    retrieve_data(initial=True)
    df = DATA_STORE['data']

    symbols = sorted(list(set(df.index.get_level_values(level=0))))

    if DATA_STORE['valid_symbols'] is None:
        DATA_STORE.update({'valid_symbols': symbols})

    set_data_symbol()

    menu = [*zip(symbols, symbols)]
    dropdown = Dropdown(label='Select Symbol',
                        button_type='primary',
                        menu=menu)
    dropdown.on_change('value', dropdown_callback)

    bucket_input = TextInput(value='mlsl-mle-ws', title='S3 Bucket:')
    key_input = TextInput(value='training-data/crypto_test_preds.csv',
                          title='S3 Key:')
    profile_input = TextInput(value='kyle_general', title='Boto Profile:')
    text_button = Button(label='Pull Data')
    text_button.on_event(ButtonClick, text_button_callback)
    default_button = Button(label='Reset Defaults')
    default_button.on_event(ButtonClick, default_button_callback)

    DATA_STORE.update({
        'dropdown': dropdown,
        's3_bucket_input': bucket_input,
        's3_key_input': key_input,
        'text_button': text_button,
        'boto_profile_input': profile_input,
        'default_button': default_button
    })
Esempio n. 16
0
File: view.py Progetto: msalasj/oma
def create_panel(controller):
    # im logo
    logo = figure()
    logo = config_fig_logo(logo, controller.cfg.app_name)
    logo.css_classes = ['panel_logo']
    # title
    title = Div(text='Optimización y Mantenimiento de la Agenda',
                css_classes=['panel_title'],
                width=680)
    # modules selection
    menu = get_user_modules(controller.user.profile)
    panel_menu = Dropdown(
        label='Módulos',
        button_type="primary",
        menu=menu,
        css_classes=['panel_menu'],
        name='panel_menu',
        width=150,
    )
    panel_menu.on_click(controller.module_selection)
    # widget
    widget = layout([[logo, title, panel_menu]], sizing_mode='fixed')
    widget.name = 'header'
    return widget
Esempio n. 17
0
        "console.log('toggle(inactive): active=' + this.active, this.toString())"
    ))

toggle_active = Toggle(label="Toggle button (initially active)",
                       button_type="success",
                       active=True)
toggle_active.js_on_click(
    CustomJS(
        code=
        "console.log('toggle(active): active=' + this.active, this.toString())"
    ))

menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None,
        ("Item 3", "item_3_value")]

dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.js_on_click(
    CustomJS(code="console.log('dropdown: click ' + this.toString())"))
dropdown.js_on_event(
    "menu_item_click",
    CustomJS(code="console.log('dropdown: ' + this.item, this.toString())"))

dropdown_disabled = Dropdown(label="Dropdown button (disabled)",
                             button_type="warning",
                             disabled=True,
                             menu=menu)
dropdown_disabled.js_on_click(
    CustomJS(
        code="console.log('dropdown(disabled): click ' + this.toString())"))
dropdown_disabled.js_on_event(
    "menu_item_click",
Esempio n. 18
0

def radio_button_group_handler(active):
    print("radio_button_group_handler: %s" % active)


button = Button(label="Push button",
                icon=Icon(icon_name="check"),
                type="primary")
button.on_click(button_handler)

toggle = Toggle(label="Toggle button", type="success")
toggle.on_click(toggle_handler)

menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button",
                 type="danger",
                 menu=menu,
                 default_value="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)
Esempio n. 19
0

  # Then set the source DF to have different numbers.
  source.data = source.from_df(data[['date','pft0']]) # pass in dataframe of data created above
  source_static.data = source.data
  


menu = [x for x in os.listdir(DATA_DIR) if len(x.split("_")) == 3]
menu = set([(i.split("_")[0], i.split("_")[0]) for i in menu]) # get rid of duplicates that come from different stages, (i.e. NPP_monthly_eq.nc NPP_monthly_sp.nc)
menu = [i for i in menu] # Make sure its a list


#menu = [("NPP", "NPP"), ("VEGC", "VEGC"), ("INGPP", "INGPP")]
#from IPython import embed; embed()
variable_dropdown = Dropdown(label="Choose Variable", button_type="warning", menu=menu, default_value='NPP') #, value="NPP")

variable_dropdown.on_change('value', update)
# Set up widgets
# variable_multiselect = MultiSelect(
#   title="Choose varibales", 
#   value=['VEGC'],                            # The keys that are chosen 
#   options=[('NPP','NPP'),('VEGC','VEGC')])   # The key value pairs of what is available. Keys are shown to the user.

#stage_checkboxgroup = CheckboxGroup(labels=["pr","eq","sp","tr","sc"], active=[])  # <- Code to determine available stages?
#timeres_radiobuttongroup = RadioButtonGroup(labels=["daily", "monthly", "yearly"], active=0) # <- code to determine available time rez?



# Setup data: one structure for ALL the data (static), the other for the selected data
source = ColumnDataSource(data=dict(date=[], pft0=[]))
Esempio n. 20
0
def _create_ui_components() -> (Figure, ColumnDataSource):  # pylint: disable=too-many-statements
    global asp_table_source, asp_filter_src, op_table_source, op_filter_src
    global stats, aspects, tabs, lexicons_dropdown
    stats = pd.DataFrame(columns=['Quantity', 'Score'])
    aspects = pd.Series([])

    def new_col_data_src():
        return ColumnDataSource({'file_contents': [], 'file_name': []})

    large_text = HTMLTemplateFormatter(template='''<div><%= value %></div>''')

    def data_column(title):
        return TableColumn(field=title,
                           title='<span class="header">' + title + '</span>',
                           formatter=large_text)

    asp_table_columns = [
        data_column('Term'),
        data_column('Alias1'),
        data_column('Alias2'),
        data_column('Alias3')
    ]
    op_table_columns = [
        data_column('Term'),
        data_column('Score'),
        data_column('Polarity')
    ]

    asp_table_source = empty_table('Term', 'Alias1', 'Alias2', 'Alias3')
    asp_filter_src = empty_table('Term', 'Alias1', 'Alias2', 'Alias3')
    asp_src = new_col_data_src()

    op_table_source = empty_table('Term', 'Score', 'Polarity', 'Polarity')
    op_filter_src = empty_table('Term', 'Score', 'Polarity', 'Polarity')
    op_src = new_col_data_src()

    asp_table = DataTable(source=asp_table_source,
                          selectable='checkbox',
                          columns=asp_table_columns,
                          editable=True,
                          width=600,
                          height=500)
    op_table = DataTable(source=op_table_source,
                         selectable='checkbox',
                         columns=op_table_columns,
                         editable=True,
                         width=600,
                         height=500)

    asp_examples_box = _create_examples_table()
    op_examples_box = _create_examples_table()
    asp_layout = layout([[asp_table, asp_examples_box]])
    op_layout = layout([[op_table, op_examples_box]])
    asp_tab = Panel(child=asp_layout, title="Aspect Lexicon")
    op_tab = Panel(child=op_layout, title="Opinion Lexicon")
    tabs = Tabs(tabs=[asp_tab, op_tab], width=700, css_classes=['mytab'])

    lexicons_menu = [("Open", "open"), ("Save", "save")]
    lexicons_dropdown = Dropdown(label="Edit Lexicons",
                                 button_type="success",
                                 menu=lexicons_menu,
                                 width=140,
                                 height=31,
                                 css_classes=['mybutton'])

    train_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")]
    train_dropdown = Dropdown(label="Extract Lexicons",
                              button_type="success",
                              menu=train_menu,
                              width=162,
                              height=31,
                              css_classes=['mybutton'])

    inference_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")]
    inference_dropdown = Dropdown(label="Classify",
                                  button_type="success",
                                  menu=inference_menu,
                                  width=140,
                                  height=31,
                                  css_classes=['mybutton'])

    text_status = TextInput(value="Select training data",
                            title="Train Run Status:",
                            css_classes=['statusText'])
    text_status.visible = False

    train_src = new_col_data_src()
    infer_src = new_col_data_src()

    with open(join(dirname(__file__), "dropdown.js")) as f:
        args = dict(clicked=lexicons_dropdown,
                    asp_filter=asp_filter_src,
                    op_filter=op_filter_src,
                    asp_src=asp_src,
                    op_src=op_src,
                    tabs=tabs,
                    text_status=text_status,
                    train_src=train_src,
                    infer_src=infer_src,
                    train_clicked=train_dropdown,
                    infer_clicked=inference_dropdown,
                    opinion_lex_generic="")
        code = f.read()

    args['train_clicked'] = train_dropdown
    train_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    args['train_clicked'] = inference_dropdown
    inference_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    args['clicked'] = lexicons_dropdown
    lexicons_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    def update_filter_source(table_source, filter_source):
        df = table_source.to_df()
        sel_inx = sorted(table_source.selected.indices)
        df = df.iloc[sel_inx, 1:]
        new_source = ColumnDataSource(df)
        filter_source.data = new_source.data

    def update_examples_box(data, examples_box, old, new):
        examples_box.source.data = {'Examples': []}
        unselected = list(set(old) - set(new))
        selected = list(set(new) - set(old))
        if len(selected) <= 1 and len(unselected) <= 1:
            examples_box.source.data.update({
                'Examples':
                [str(data.iloc[unselected[0], i])
                 for i in range(4, 24)] if len(unselected) != 0 else
                [str(data.iloc[selected[0], i]) for i in range(4, 24)]
            })

    def asp_selected_change(_, old, new):
        global asp_filter_src, asp_table_source, aspects_data
        update_filter_source(asp_table_source, asp_filter_src)
        update_examples_box(aspects_data, asp_examples_box, old, new)

    def op_selected_change(_, old, new):
        global op_filter_src, op_table_source, opinions_data
        update_filter_source(op_table_source, op_filter_src)
        update_examples_box(opinions_data, op_examples_box, old, new)

    def read_csv(file_src, headers=False, index_cols=False, readCSV=True):
        if readCSV:
            raw_contents = file_src.data['file_contents'][0]

            if len(raw_contents.split(",")) == 1:
                b64_contents = raw_contents
            else:
                # remove the prefix that JS adds
                b64_contents = raw_contents.split(",", 1)[1]
            file_contents = base64.b64decode(b64_contents)
            return pd.read_csv(io.BytesIO(file_contents),
                               encoding="ISO-8859-1",
                               keep_default_na=False,
                               na_values={None},
                               engine='python',
                               index_col=index_cols,
                               header=0 if headers else None)
        return file_src

    def read_parsed_files(file_content, file_name):
        try:
            # remove the prefix that JS adds
            b64_contents = file_content.split(",", 1)[1]
            file_content = base64.b64decode(b64_contents)
            with open(SENTIMENT_OUT / file_name, 'w') as json_file:
                data_dict = json.loads(file_content.decode("utf-8"))
                json.dump(data_dict, json_file)
        except Exception as e:
            print(str(e))

    # pylint: disable=unused-argument
    def train_file_callback(attr, old, new):
        global train_data
        SENTIMENT_OUT.mkdir(parents=True, exist_ok=True)
        train = TrainSentiment(parse=True, rerank_model=None)
        if len(train_src.data['file_contents']) == 1:
            train_data = read_csv(train_src, index_cols=0)
            file_name = train_src.data['file_name'][0]
            raw_data_path = SENTIMENT_OUT / file_name
            train_data.to_csv(raw_data_path, header=False)
            print(f'Running_SentimentTraining on data...')
            train.run(data=raw_data_path)
        else:
            f_contents = train_src.data['file_contents']
            f_names = train_src.data['file_name']
            raw_data_path = SENTIMENT_OUT / train_src.data['file_name'][
                0].split('/')[0]
            if not os.path.exists(raw_data_path):
                os.makedirs(raw_data_path)
            for f_content, f_name in zip(f_contents, f_names):
                read_parsed_files(f_content, f_name)
            print(f'Running_SentimentTraining on data...')
            train.run(parsed_data=raw_data_path)

        text_status.value = "Lexicon extraction completed"

        with io.open(AcquireTerms.acquired_aspect_terms_path, "r") as fp:
            aspect_data_csv = fp.read()
        file_data = base64.b64encode(str.encode(aspect_data_csv))
        file_data = file_data.decode("utf-8")
        asp_src.data = {
            'file_contents': [file_data],
            'file_name': ['nameFile.csv']
        }

        out_path = RerankTerms.out_dir / 'generated_opinion_lex_reranked.csv'
        with io.open(out_path, "r") as fp:
            opinion_data_csv = fp.read()
        file_data = base64.b64encode(str.encode(opinion_data_csv))
        file_data = file_data.decode("utf-8")
        op_src.data = {
            'file_contents': [file_data],
            'file_name': ['nameFile.csv']
        }

    def show_analysis() -> None:
        global stats, aspects, plot, source, tabs
        plot, source = _create_plot()
        events_table = _create_events_table()

        # pylint: disable=unused-argument
        def _events_handler(attr, old, new):
            _update_events(events_table, events_type.active)

        # Toggle display of in-domain / All aspect mentions
        events_type = RadioButtonGroup(
            labels=['All Events', 'In-Domain Events'], active=0)

        analysis_layout = layout([[plot], [events_table]])

        # events_type display toggle disabled
        # analysis_layout = layout([[plot],[events_type],[events_table]])

        analysis_tab = Panel(child=analysis_layout, title="Analysis")
        tabs.tabs.insert(2, analysis_tab)
        tabs.active = 2
        events_type.on_change('active', _events_handler)
        source.selected.on_change('indices', _events_handler)  # pylint: disable=no-member

    # pylint: disable=unused-argument
    def infer_file_callback(attr, old, new):

        # run inference on input data and current aspect/opinion lexicons in view
        global infer_data, stats, aspects

        SENTIMENT_OUT.mkdir(parents=True, exist_ok=True)

        df_aspect = pd.DataFrame.from_dict(asp_filter_src.data)
        aspect_col_list = ['Term', 'Alias1', 'Alias2', 'Alias3']
        df_aspect = df_aspect[aspect_col_list]
        df_aspect.to_csv(SENTIMENT_OUT / 'aspects.csv',
                         index=False,
                         na_rep="NaN")

        df_opinion = pd.DataFrame.from_dict(op_filter_src.data)
        opinion_col_list = ['Term', 'Score', 'Polarity', 'isAcquired']
        df_opinion = df_opinion[opinion_col_list]
        df_opinion.to_csv(SENTIMENT_OUT / 'opinions.csv',
                          index=False,
                          na_rep="NaN")

        solution = SentimentSolution()

        if len(infer_src.data['file_contents']) == 1:
            infer_data = read_csv(infer_src, index_cols=0)
            file_name = infer_src.data['file_name'][0]
            raw_data_path = SENTIMENT_OUT / file_name
            infer_data.to_csv(raw_data_path, header=False)
            print(f'Running_SentimentInference on data...')
            text_status.value = "Running classification on data..."
            stats = solution.run(data=raw_data_path,
                                 aspect_lex=SENTIMENT_OUT / 'aspects.csv',
                                 opinion_lex=SENTIMENT_OUT / 'opinions.csv')
        else:
            f_contents = infer_src.data['file_contents']
            f_names = infer_src.data['file_name']
            raw_data_path = SENTIMENT_OUT / infer_src.data['file_name'][
                0].split('/')[0]
            if not os.path.exists(raw_data_path):
                os.makedirs(raw_data_path)
            for f_content, f_name in zip(f_contents, f_names):
                read_parsed_files(f_content, f_name)
            print(f'Running_SentimentInference on data...')
            text_status.value = "Running classification on data..."
            stats = solution.run(parsed_data=raw_data_path,
                                 aspect_lex=SENTIMENT_OUT / 'aspects.csv',
                                 opinion_lex=SENTIMENT_OUT / 'opinions.csv')

        aspects = pd.read_csv(SENTIMENT_OUT / 'aspects.csv',
                              encoding='utf-8')['Term']
        text_status.value = "Classification completed"
        show_analysis()

    # pylint: disable=unused-argument
    def asp_file_callback(attr, old, new):
        global aspects_data, asp_table_source
        aspects_data = read_csv(asp_src, headers=True)
        # Replaces None values by empty string
        aspects_data = aspects_data.fillna('')
        new_source = ColumnDataSource(aspects_data)
        asp_table_source.data = new_source.data
        asp_table_source.selected.indices = list(range(len(aspects_data)))

    # pylint: disable=unused-argument
    def op_file_callback(attr, old, new):
        global opinions_data, op_table_source, lexicons_dropdown, df_opinion_generic
        df = read_csv(op_src, headers=True)
        # Replaces None values by empty string
        df = df.fillna('')
        # Placeholder for generic opinion lexicons from the given csv file
        df_opinion_generic = df[df['isAcquired'] == 'N']
        # Update the argument value for the callback customJS
        lexicons_dropdown.js_property_callbacks.get(
            'change:value')[0].args['opinion_lex_generic'] \
            = df_opinion_generic.to_dict(orient='list')
        opinions_data = df[df['isAcquired'] == 'Y']
        new_source = ColumnDataSource(opinions_data)
        op_table_source.data = new_source.data
        op_table_source.selected.indices = list(range(len(opinions_data)))

    # pylint: disable=unused-argument
    def txt_status_callback(attr, old, new):
        print("Previous label: " + old)
        print("Updated label: " + new)

    text_status.on_change("value", txt_status_callback)

    asp_src.on_change('data', asp_file_callback)
    # pylint: disable=no-member
    asp_table_source.selected.on_change('indices', asp_selected_change)

    op_src.on_change('data', op_file_callback)
    op_table_source.selected.on_change('indices', op_selected_change)  # pylint: disable=no-member

    train_src.on_change('data', train_file_callback)
    infer_src.on_change('data', infer_file_callback)

    return layout(
        [[_create_header(train_dropdown, inference_dropdown, text_status)],
         [tabs]])
Esempio n. 21
0
def plotDataset(ds,template='dataset.html',title='Dataset',color=None,*args, **kwargs):

    ds = ds.copy()
    ds.data.columns = ds.data.columns.astype(str)


    # ts = TimeSeries(ds.data)

    numlines=len(ds.data.columns)

    if color is None:
        color = ds.meta[ds.meta.columns[0]]
    label = color
    color = colorby(color)

    # print color

    # source = ColumnDataSource(data=ds.data)
    source = ColumnDataSource(dict(xs=[ds.data.index.values]*ds.data.shape[1],
                ys = [ds.data[name].values for name in ds.data], yslog = [np.log2(ds.data[name].values) for name in ds.data], color=color, label=label))

    labelsource = ColumnDataSource(ds.meta)
    colorsource = ColumnDataSource({k:colorby(ds.meta[k]) for k in ds.meta.columns.tolist()})


    # if color is None:
    #     # color = viridis(numlines)
    #     color = colorby(range(numlines))
    # else:
    #     # v = viridis(max(color)+1)
    #     # color = [v[c] for c in color]
    #     color = colorby(color)

    fig = figure(title=title,plot_width=97*8,)
    # plot = Plot()
    # fig.line(ds.data.index.values, ds.data, line_width=2)

    # fig.multi_line(xs=[ds.data.index.values]*ds.data.shape[1],
    #             ys = [ds.data[name].values for name in ds.data],
    #             line_color=color,
    #             line_width=5)
    fig.multi_line('xs', 'ys', color='color', legend='label', source=source)

    fig.legend.location = "top_left"

    # glyph = MultiLine(xs="xs", ys="ys", line_color="", line_width=2)
    # fig.add_glyph(source, glyph)
    # plot.add_glyph(source, glyph)

    callback = CustomJS(args=dict(source=source,colorsource=colorsource,labelsource=labelsource), code="""
        var data = source.get('data');
        var data2 = colorsource.get('data');
        var data3 = labelsource.get('data');
        var f = cb_obj.get('value')

        color = data['color']
        color2 = data2[f]

        label = data['label']
        label2 = data3[f]

        for (i = 0; i < color.length; i++) {
            color[i] = color2[i]
            label[i] = label2[i]
        }

        source.trigger('change');
    """)

    logcallback = CustomJS(args=dict(source=source), code="""
        var data = source.get('data');

        data['ys'] = data['yslog']

        source.trigger('change');
    """)


    menu = [(c,c) for c in ds.meta.columns]
    dropdown = Dropdown(label="Color by", button_type="warning", menu=menu, callback=callback)

    # layout = vform(dropdown, fig)
    layout = column(dropdown, fig)

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    # script, div = components(ts)
    script, div = components(layout)
    # script, div = components(fig)

    html = render_template(
        template,
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
        *args, **kwargs
    )
    return encode_utf8(html)
Esempio n. 22
0
T1_input = TextInput(value='3.0',
                     title="Input t"
                     u"\u2080 "
                     u"\u2264 t "
                     u"\u2081 "
                     u"\u2264 5:",
                     width=200)
Amp_input = TextInput(value='1.0',
                      title="Input -3 "
                      u"\u2264 Amplitude "
                      u"\u2264 3:",
                      width=200)
User_Func = TextInput(value=None, title="Input function f(t):", width=200)
Resolution = TextInput(value='60', title="Input resolution:", width=200)
sample_fun_input_f = Dropdown(label="Choose a sample function f(t)",
                              menu=sample_f_names,
                              width=200)
Wavelet_fun_input = Dropdown(label="Choose a wavelet function "
                             u"\u03A8 (t)",
                             menu=sample_Wavelet_names,
                             width=200)
a_param = Slider(title="Scaling parameter 'a'",
                 value=1.0,
                 start=0.5,
                 end=5.0,
                 step=0.1,
                 width=200)
b_param = Slider(title="Shifting parameter 'b'",
                 value=0.0,
                 start=-10.0,
                 end=10.0,
Esempio n. 23
0
                       title="ROI Prefix",
                       width=int(total_width / 4),
                       height=50)

accept_ROI_button = Button(label="Accept ROI Inputs",
                           width=int(total_width / 4),
                           height=32,
                           margin=[23, 0, 0, 0])
accept_ROI_button.on_click(accept_ROI_path_and_prefix)

# initiate ROI figure stiff
ROI_fig = figure(tools=TOOLS, width=int(total_width / 2), height=550)
drop_menu = [("dim1", '0'), ("dim2", '1'), ("dim3", '2')]
choose_dim = Dropdown(label="choose dimension to slide",
                      menu=drop_menu,
                      value='0',
                      width=int(total_width / 2),
                      height=50)
slider = Slider(start=0,
                end=100,
                step=1,
                value=40,
                width=int(total_width / 2),
                height=50)


def remove_brain(old_brain):
    for glyph in old_brain:
        ROI_fig.renderers.remove(glyph)

Esempio n. 24
0
def modify_doc(doc):
    # Bokeh renderers that hold current viz as its state
    hvplot = renderer.get_plot(dmap, doc)
    timeseriesPlot = renderer.get_plot(dmap_time_series, doc)

    def animate_update():
        year = slider.value + 1
        if year > end:
            year = start
        slider.value = year

    callback_id = None
    def animate():
        global callback_id
        if button.label == '► Play':
            button.label = '❚❚ Pause'
            callback_id = doc.add_periodic_callback(animate_update, 75)
        else:
            button.label = '► Play'
            doc.remove_periodic_callback(callback_id)

    def slider_update(attrname, old, new):
        # Notify the HoloViews stream of the slider update 
        year = 2000 + (new // 12)
        month = (new % 12) + 1
        stream.event(time_step=cftime.DatetimeNoLeap(year,month,1))
        slider.title = "{}-{}".format(year,month)
        
    def variable_update(event):
        global path, fram_data, curr_var, min_range, max_range, control_path, control_data, global_data, global_path, gv_geo_plot, curr_dataset, curr_intervention, DATA_DICT
        path = './iceClinic/data/f09_g16.B.cobalt.FRAM.MAY.{}.200005-208106.nc'.format(event.item)
        control_path = './iceClinic/data/f09_g16.B.cobalt.CONTROL.MAY.{}.200005-208106.nc'.format(event.item)
        global_path = './iceClinic/data/f09_g16.B.cobalt.GLOBAL.MAY.{}.200005-208106.nc'.format(event.item)
        curr_var = event.item
        fram_data = xr.open_dataset(path)
        control_data = xr.open_dataset(control_path)
        global_data = xr.open_dataset(global_path)
        DATA_DICT = {'CONTROL': control_data, 'FRAM' : fram_data, 'GLOBAL' : global_data}
        curr_dataset = DATA_DICT[curr_intervention]
       
        dataset = gv.Dataset(curr_dataset)
        stateBasemap = gv.Feature(feature.STATES)
        gv_geo_plot = dataset.to(gv.Image, ['lon', 'lat'], curr_var, dynamic=True).opts(title = '{} Intervention, {} data'.format(curr_intervention, curr_var), cmap=CMAP_DICT[curr_var], colorbar=True, backend='bokeh', projection = crs.PlateCarree()) *gf.coastline() * gf.borders() * stateBasemap.opts(fill_alpha=0,line_width=0.5)

        #control_min_range, control_max_range = getMinMax(control_data, curr_var)
        #print(control_min_range, control_max_range)
        fram_min_range, fram_max_range = getMinMax(fram_data, curr_var)
        global_min_range, global_max_range = getMinMax(global_data, curr_var)
        min_range = min(fram_min_range, global_min_range)
        max_range = max(fram_max_range,global_max_range)
        
        gv_geo_plot = gv_geo_plot.redim(**{curr_var:hv.Dimension(curr_var, range=(min_range, max_range))})
        var_stream.event(var=event.item)

    def lat_update(attr, old, new):
        if int(new) in range(-90,90):
            lat_stream.event(lat=int(new)) 

    def lon_update(attr, old, new):
        if int(new) in range(-180,180):
            new_lon = int(new) + 180
            lon_stream.event(lon=new_lon) 

    def intervention_update(event):
        global curr_var, DATA_DICT, control_data, curr_intervention, gv_geo_plot, min_range, max_range
        curr_intervention = event.item
        curr_ds = DATA_DICT[event.item]
        dataset = gv.Dataset(curr_ds)
        gv_geo_plot = dataset.to(gv.Image, ['lon', 'lat'], curr_var, dynamic=True).opts(title = '{} Intervention, {} data'.format(curr_intervention, curr_var), cmap=CMAP_DICT[curr_var], colorbar=True, backend='bokeh', projection = crs.PlateCarree()) *gf.coastline() * gf.borders() * stateBasemap.opts(fill_alpha=0,line_width=0.5)        
        gv_geo_plot = gv_geo_plot.redim(**{curr_var:hv.Dimension(curr_var, range=(min_range, max_range))})
        intervention_stream.event(intervention=event.item)

    #Time_slider
    #Note: It starts as 5 because the datasets start in June 2000, the fifth month with zero indexing
    start, end = 5, 900
    slider = Slider(start=start, end=end, value=start, step=1, title="Date", show_value=False)
    slider.on_change('value', slider_update)
    
    #Variable Dropdown
    menu = [("Temperature", "TS"), ("Precipitation", "PRECT"), ("Fire Weather", "FWI"), ("Precipitation Index", "SPI")]
    dropdown = Dropdown(label="Select Variable", button_type="primary", menu=menu)
    dropdown.on_click(variable_update)

    #Intervention Dropdown
    intervention_menu = [("Control", "CONTROL"), ("Fram", "FRAM"), ("Global", "GLOBAL")]
    intervention_dropdown = Dropdown(label="Select Intervention Type", button_type="primary", menu=intervention_menu)
    intervention_dropdown.on_click(intervention_update)

    #Lat Text Input
    lat_input = TextInput(value="45", title="Latitude:")
    lat_input.on_change("value", lat_update)

    #Lon Text Input
    lon_input = TextInput(value="122", title="Longitude:")
    lon_input.on_change("value", lon_update)

    #Slider Play Button
    button = Button(label='► Play', width=60)
    button.on_click(animate)
    

    #Code to generate the layout
    lat_lon_text = Div(text="<b>Note:</b> Latitude ranges from -90 to 90 and longitude from -180 to 180")
    spacer = Div(height=200)

    logo = figure(x_range=(0, 10), y_range=(0, 10), plot_width=300, plot_height=300)
    logo.image_url( url=['./iceClinic/static/logo.png'], x=0, y=0, w=10, h=10, anchor="bottom_left")
    logo.toolbar.logo, logo.toolbar_location = None, None
    logo.xaxis.visible, logo.yaxis.visible = None, None
    logo.xgrid.grid_line_color, logo.ygrid.grid_line_color = None, None
    # Combine the holoviews plot and widgets in a layout

    logo = row(logo, align='center')
    options_row = row(slider, button, align='center')
    left_plot_row= row(hvplot.state, align='center')
    left_column = column(left_plot_row, options_row, dropdown, intervention_dropdown, sizing_mode='stretch_width', align='center')
    coords_row = row(lat_input, lon_input, align='center')
    right_plot_row = row(timeseriesPlot.state, align='center')
    right_column = column(right_plot_row, coords_row, lat_lon_text)

    graphs = row(left_column, right_column, sizing_mode="stretch_width", align='center')

    plot = column(logo, graphs, spacer, sizing_mode='stretch_width', align='center')
    
    curdoc().add_root(plot)
Esempio n. 25
0
    CustomJS(
        code="console.log('toggle_inactive: ' + this.active, this.toString())")
)

toggle_active = Toggle(label="Toggle button (initially active)",
                       button_type="success",
                       active=True)
toggle_active.on_click(lambda value: print('toggle_active: %s' % value))
toggle_active.js_on_click(
    CustomJS(
        code="console.log('toggle_active: ' + this.active, this.toString())"))

menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None,
        ("Item 3", "item_3_value")]

dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.on_click(lambda value: print('dropdown: %s' % value))
dropdown.js_on_click(
    CustomJS(code="console.log('dropdown: ' + this.value, this.toString())"))

dropdown_disabled = Dropdown(label="Dropdown button (disabled)",
                             button_type="warning",
                             menu=menu)
dropdown_disabled.on_click(
    lambda value: print('dropdown_disabled: %s' % value))
dropdown_disabled.js_on_click(
    CustomJS(
        code="console.log('dropdown_disabled: ' + this.value, this.toString())"
    ))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
Esempio n. 26
0
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

# Set up widgets
text = TextInput(title="Custom function", value='Enter f(x)')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude",
                   value=1.0,
                   start=-3.0,
                   end=3.0,
                   step=0.01)
Speed = Slider(title="Speed", value=100, start=100, end=250)
Delay = Slider(title="Delay", value=1, start=1, end=100)

CurveList = [("Sin", "C1"), ("Poly", "C2"), ("Abs", "C3"), ("Custom", "C4")]
dropdown = Dropdown(label="Curve Lists", button_type="warning", menu=CurveList)

button = Button(label="Run ", button_type="success")
button1 = Button(label="Stop ", button_type="success")


# Set up callbacks
def update_title(attrname, old, new):
    plot.title.text = text.value
    x = np.linspace(-4 * np.pi, 4 * np.pi, N)


text.on_change('value', update_title)

div = Div(width=1000)
Esempio n. 27
0
lg_id_message = Div(
    text='<b><p style="color: green;">League accessed successfully.</p></b>')

september_month = 9
today = datetime.today()

if today.month < september_month:
    default_yr = str(today.year - 1)
else:
    default_yr = str(today.year)

league_obj, num_teams, week_num, owners, owners_list, team_objs, weeks, owner_to_idx = retrieve_lg_info(
    int(lg_id_input.value), default_yr)

team1_dd = Dropdown(label='Team 1 - Select', menu=owners_list)
team2_dd = Dropdown(label='Team 2 - Select', menu=owners_list)
comp_button = Button(label='Compare', button_type='danger')

week_slider = RangeSlider(title='Weeks',
                          start=1,
                          end=week_num,
                          value=(1, week_num),
                          step=1)
year_input = TextInput(value=str(default_yr), title='Season:')

plot1 = initialize_sc_figure(league_obj, week_num)
plot2 = initialize_ew_figure(league_obj, week_num)

plot1_wrap = column(children=[plot1])
plot2_wrap = column(children=[plot2])
#%%
from bokeh.io import output_notebook, show
from bokeh.models.widgets import Dropdown

output_notebook()

menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)

show(dropdown)

Esempio n. 29
0
'''
import numpy as np
import pandas as pd
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox, gridplot
from bokeh.models import ColumnDataSource, Legend
from bokeh.models.widgets import Slider, TextInput, Button, Dropdown, CheckboxButtonGroup, RadioButtonGroup
from bokeh.plotting import figure

# Set up widgets
#menu_T = [('160', "TStamp 160"), ('180', "TStamp 180"), ('200', "TStamp 200")]
t_stampList = range(30, 1320, 10)
menu_T = [(str(t), "TStamp " + str(t)) for t in t_stampList]
menu_C = [('1.0', "Class 1"), ('-1.0', "Class -1")]
dropdown1 = Dropdown(label="Select Time Stamp",
                     button_type="success",
                     menu=menu_T)
dropdown2 = Dropdown(label="Select Class", button_type="primary", menu=menu_C)
dropdown3 = Dropdown(label="Select Time Stamp",
                     button_type="success",
                     menu=menu_T)
dropdown4 = Dropdown(label="Select Class", button_type="primary", menu=menu_C)
dropdown5 = Dropdown(label="Select Time Stamp",
                     button_type="success",
                     menu=menu_T)
dropdown6 = Dropdown(label="Select Class", button_type="primary", menu=menu_C)
class_1 = '1.0'
class_2 = '1.0'
class_3 = '-1.0'
t_stamp1 = '160'
t_stamp2 = '200'
Esempio n. 30
0
#Step 2: Make the columns
columns = [
    TableColumn(field="criteria", title=""),
    TableColumn(field="land", title="Land Area (ha)"),
    TableColumn(field="Nuse", title="N use (kg)"),
    TableColumn(field="prod", title="Production (kg)"),
]

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

#Button to change crop
menu_crop = [("Sorghum", "sorghum"), ("Maize", "maize"),
             ("Cassava", "cassava"), ("Groundnuts", "groundnuts"),
             ("Sesame", "sesame")]
dd_crop = Dropdown(label="Crop",
                   button_type="primary",
                   menu=menu_crop,
                   value='maize')
dd_crop.on_change('value', update)

#Make another div for crop cc1/cc2 criteria
if (dffilt['cc1'] > 0).any():
    cc1_crop = 'Myopic elasticity calibration criteria met'
else:
    cc1_crop = 'Myopic elasticity calibration criteria not met'

if (dffilt['cc2'] < 0).any():
    cc2_crop = 'No dominant response criteria met'
else:
    cc2_crop = 'No dominant response criteria not met'

div2 = Div(text='<p> Maize </p><p>' + cc1_crop + '</p><p>' + cc2_crop +