Example #1
0
    height=10)

stats_title_s = PreText(text='Selected Data of current setting',
                        width=600,
                        height=5)
stats_title_a = PreText(text='All Data of current setting',
                        width=600,
                        height=5)
stats_title_n = PreText(text="Default Stress Level", width=600, height=5)
stats_select = PreText(text='', width=600)
stats_all = PreText(text='', width=600)
stats_normal = PreText(text='', width=600)

# original ticker (work)
ticker1 = Select(title="user",
                 value='userB',
                 options=DEFAULT_TICKERS_1,
                 width=100)
ticker2 = Select(title="role",
                 value='driver',
                 options=DEFAULT_TICKERS_2,
                 width=100)
ticker3 = Select(title="expiment type",
                 value='crazy',
                 options=DEFAULT_TICKERS_3,
                 width=100)

# dummy ticker
ticker_d0 = Select(title="Loose Ball",
                   value='LooseBall_id_1',
                   options=DUMMY_TICKERS_0,
                   width=260)
Example #2
0
def sw_industry_analysis():

    def nix(val, lst):
        return [x for x in lst if x != val]

    def get_data(ticker_1, ticker_2, start='20180101', end=datetime.today().date()):
        df = get_price([ticker_1, ticker_2], start, end, fields='close')
        df['t1_returns'] = np.log(df[ticker_1]).diff()
        df['t2_returns'] = np.log(df[ticker_2]).diff()
        return df.dropna().reset_index()

    def get_hhist_data(data):
        hhist, hedges = np.histogram(data['t1_returns'], bins=20)
        hzeros = np.zeros_like(hhist)
        hhist_data = {'left': hedges[:-1], 'right': hedges[1:], 'bottom': hzeros,
                      'top': hhist, 'top_1': hzeros, 'top_2': hzeros}
        return hhist_data

    def get_vhist_data(data):
        vhist, vedges = np.histogram(data['t2_returns'], bins=20)
        vzeros = np.zeros_like(vhist)
        vhist_data = {'left': vzeros, 'right': vhist, 'bottom': vedges[:-1],
                      'top': vedges[1:], 'right_1': vzeros, 'right_2': vzeros}
        return vhist_data

    def ticker1_change(attr, old, new):
        ticker_2.options = nix(new, DEFAULT_TICKERS)
        update()

    def ticker2_change(attr, old, new):
        ticker_1.options = nix(new, DEFAULT_TICKERS)
        update()

    def update():
        global df
        ticker_1_name, ticker_2_name = SHENWAN_INDUSTRY_MAP_[ticker_1.value], SHENWAN_INDUSTRY_MAP_[ticker_2.value]
        df = get_data(ticker_1_name, ticker_2_name)

        source.data.update(dict(x=df['t1_returns'], y=df['t2_returns'], x_p=df[ticker_1_name],
                                y_p=df[ticker_2_name], date=df['date']))

        hhist_data_dict = get_hhist_data(df)
        source_hhist.data.update(hhist_data_dict)
        hmax = max(source_hhist.data['top']) * 1.1
        ph.y_range.update(start=-hmax, end=hmax)
        print('ph.y_range', ph.y_range.end)

        vhist_data_dict = get_vhist_data(df)
        source_vhist.data.update(vhist_data_dict)
        vmax = max(source_vhist.data['right']) * 1.1
        pv.x_range.update(start=vmax, end=-vmax)
        print('pv.x_range', pv.x_range.end)
        print(20 * '=')

        update_stats(df, ticker_1_name, ticker_2_name)

        corr.title.text = "{} vs. {}".format(ticker_1.value, ticker_2.value)
        ts1.title.text = ticker_1.value
        ts2.title.text = ticker_2.value

    def udpate_selection(attr, old, new):
        inds = new  # 选定的数据对应的索引
        length = len(df)
        if 0 < len(inds) < length:
            neg_inds = [s for s in range(length) if s not in inds]  # 未选定数据点的对应索引
            _, hedges = np.histogram(df['t1_returns'], bins=20)
            _, vedges = np.histogram(df['t2_returns'], bins=20)

            new_hhist_df = df['t1_returns']
            new_vhist_df = df['t2_returns']

            hhist1, _ = np.histogram(new_hhist_df.iloc[inds], bins=hedges)
            hhist2, _ = np.histogram(new_hhist_df.iloc[neg_inds], bins=hedges)

            vhist1, _ = np.histogram(new_vhist_df.iloc[inds], bins=vedges)
            vhist2, _ = np.histogram(new_vhist_df.iloc[neg_inds], bins=vedges)

            source_hhist.patch({'top_1': [(slice(None), hhist1)], 'top_2': [(slice(None), -hhist2)]})
            source_vhist.patch({'right_1': [(slice(None), vhist1)], 'right_2': [(slice(None), -vhist2)]})

    def update_stats(data, t1, t2):
        stats_indicator = data[[t1, t2, 't1_returns', 't2_returns']].describe()
        ticker_1_name, ticker_2_name = ticker_1.value, ticker_2.value
        stats_indicator.columns = [ticker_1_name, ticker_2_name, ticker_1_name + '收益率', ticker_2_name + '收益率']
        stats.text = str(stats_indicator)

    # Set Up Widgets
    stats = PreText(text='', width=700)
    ticker_1 = Select(value='非银金融', options=nix('食品饮料', DEFAULT_TICKERS))
    ticker_2 = Select(value='食品饮料', options=nix('非银金融', DEFAULT_TICKERS))

    # Callback
    ticker_1.on_change('value', ticker1_change)
    ticker_2.on_change('value', ticker2_change)

    # Construct DataSource
    source = ColumnDataSource(data=dict(x=[], y=[], x_p=[], y_p=[], date=[]))
    source_hhist = ColumnDataSource(data=dict(left=[], right=[], bottom=[], top=[], top_1=[], top_2=[]))
    source_vhist = ColumnDataSource(data=dict(left=[], right=[], bottom=[], top=[], right_1=[], right_2=[]))

    # 收益率散点图
    corr = figure(plot_width=500, plot_height=500, tools=TOOLS)
    r = corr.scatter(x='x', y='y', size=2, source=source, selection_color='orange', alpha=0.6,
                     nonselection_alpha=0.1, selection_alpha=0.4)

    # 添加横轴直方图
    hmax = 40
    ph = figure(toolbar_location=None, plot_width=corr.plot_width, plot_height=200, y_range=(-hmax, hmax),
                min_border=10, min_border_left=None, y_axis_location='left', x_axis_location='above')
    ph.quad(bottom='bottom', top='top', left='left', right='right', color='white', line_color="#3A5785",
            source=source_hhist)
    ph.quad(bottom='bottom', top='top_1', left='left', right='right', alpha=0.5, source=source_hhist, **LINE_ARGS)
    ph.quad(bottom='bottom', top='top_2', left='left', right='right', alpha=0.1, source=source_hhist, **LINE_ARGS)

    ph.xgrid.grid_line_color = None
    ph.yaxis.major_label_orientation = np.pi / 4
    ph.background_fill_color = '#fafafa'

    # 添加纵轴直方图
    vmax = 40
    pv = figure(toolbar_location=None, plot_height=corr.plot_height, plot_width=200, x_range=(vmax, -vmax),
                min_border=10, min_border_left=None, y_axis_location='left')
    pv.quad(bottom='bottom', top='top', left='left', right='right', color='white', line_color="#3A5785",
            source=source_vhist)
    pv.quad(bottom='bottom', top='top', left='left', right='right_1', alpha=0.5, source=source_vhist, **LINE_ARGS)
    pv.quad(bottom='bottom', top='top', left='left', right='right_2', alpha=0.1, source=source_vhist, **LINE_ARGS)

    # 股价时间序列图
    ts1 = figure(plot_width=900, plot_height=200, tools=TOOLS, x_axis_type='datetime', active_drag='box_select',
                 toolbar_location='above')
    ts1.line('date', 'x_p', source=source)
    ts1.circle('date', 'x_p', size=1, source=source, color=None, selection_color='orange')

    ts2 = figure(plot_width=ts1.plot_width, plot_height=ts1.plot_height, tools=TOOLS, x_axis_type='datetime',
                 active_drag='box_select', toolbar_location='above')
    ts2.x_range = ts1.x_range
    ts2.line('date', 'y_p', source=source)
    ts2.circle('date', 'y_p', size=1, source=source, color=None, selection_color='orange')

    # 初始化数据
    update()

    r.data_source.selected.on_change('indices', udpate_selection)

    widgets = column(ticker_1, ticker_2, widgetbox(stats))
    layout_1 = column(row(Spacer(width=200, height=200), ph), row(pv, corr, widgets))

    layout_2 = column(layout_1, ts1, ts2)

    tab = Panel(child=layout_2, title='IndustryAnalysis')

    return tab
    def add_controllers(self):
        titles = {'npeople': 'Number of people',
                  'sensorinterval': 'Interval',
                  'sensortpr': 'True positive rate',
                  'sensorexfp': 'Expected num of FP',
                  'sensorrange': 'Sensor range',
                  'sensorsnum': 'Fleet size',
                  'sensorspeed': 'Fleet speed'}
        idx0 = 1

        stacked = []

        #Create a controller for the scaling
        def on_scaling_changed(_, _old, _new):
            self.scaling = _new
            self.update_plot()

        self.scalingwidget = Select(title='Scaling', value='linear',
                              options=['linear', 'log'])
        self.scalingwidget.on_change('value', on_scaling_changed)
        stacked.append(self.scalingwidget)
        # Create a controller for each param
        for k in titles.keys():
            def on_radio_changed(attr, old, new, kk):
                if self.blocked: return
                newvalue = self.config[kk][new-1] if new != FIXEDIDX else -1
                print('Changed ' + str(kk) + ' to ' + str(newvalue))
                self.currparams[kk] = newvalue

                if new == FIXEDIDX:
                    self.blocked = True
                    for param in self.contr.keys():
                        if param == kk or self.contr[param].active != FIXEDIDX:
                            continue

                        self.contr[param].active = 1
                        self.currparams[param] = self.config[param][0]
                    self.var = kk

                varyingparam = False
                for kkk, vvv in self.currparams.items():
                    if vvv == -1:
                        varyingparam = True
                        break
                if not varyingparam: self.var = None
                self.update_plot()
                if self.blocked: self.blocked = False

            my_radio_changed = partial(on_radio_changed, kk=k)
            params = ['varying'] + list(map(str, self.config[k]))

            buttonisactive = FIXEDIDX if self.var == k else idx0
            self.contr[k] = RadioButtonGroup(labels=params, active=buttonisactive)

            self.contr[k].on_change('active', my_radio_changed)
            self.currparams[k] = params[idx0]

            r = Row(widgetbox(Div(text='{}:'.format(titles[k]))),
                    self.contr[k])
            stacked.append(r)


        self.currparams[self.var] = -1
        adjwidget = Column(*stacked)
        self.guirow.children[0] = adjwidget
Example #4
0
from simuojo_module import ic50_simu, DR_5PL, Kd_simu, ric50_simu, ri50_coop_simu
from bokeh.io import curdoc
from bokeh.layouts import row, layout
from bokeh.models.widgets import Div, Select
import os
#
# from dotenv import load_dotenv
#
# basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
#
# load_dotenv(os.path.join(basedir, '.env'))

simu_sele = Select(title='Select a simulation model',
                   value='Select a model',
                   options=[
                       'Select a model', 'kd simulation', 'ic_50 simulation',
                       'ric_50 simulation', 'ric_50_coop simulation',
                       'Dose-Response 5 Para Logistic'
                   ])

model_display = Div(text="""<h1>Welcome to Simuojo!</h1>""",
                    width=600,
                    height=75)


def simu_sele_cb(attr, old, new):
    if new == 'kd simulation':
        kd_layout = Kd_simu().layout
        temp = layout([model_display, simu_sele], *kd_layout)
        select_layout.children = temp.children
        model_display.text = """
    def __init__(self, model, resolution=50, doc=None):
        """
        Initialize parameters.

        Parameters
        ----------
        model : MetaModelComponent
            Reference to meta model component
        resolution : int
            Value used to calculate the size of contour plot meshgrid
        doc : Document
            The bokeh document to build.
        """
        self.prob = Problem()
        self.resolution = resolution
        logging.getLogger("bokeh").setLevel(logging.ERROR)

        # If the surrogate model coming in is structured
        if isinstance(model, MetaModelUnStructuredComp):
            self.is_structured_meta_model = False

            # Create list of input names, check if it has more than one input, then create list
            # of outputs
            self.input_names = [
                name[0] for name in model._surrogate_input_names
            ]
            if len(self.input_names) < 2:
                raise ValueError('Must have more than one input value')
            self.output_names = [
                name[0] for name in model._surrogate_output_names
            ]

            # Create reference for untructured component
            self.meta_model = MetaModelUnStructuredComp(
                default_surrogate=model.options['default_surrogate'])

        # If the surrogate model coming in is unstructured
        elif isinstance(model, MetaModelStructuredComp):
            self.is_structured_meta_model = True

            self.input_names = [name for name in model._var_rel_names['input']]

            if len(self.input_names) < 2:
                raise ValueError('Must have more than one input value')

            self.output_names = [
                name for name in model._var_rel_names['output']
            ]

            self.meta_model = MetaModelStructuredComp(
                distributed=model.options['distributed'],
                extrapolate=model.options['extrapolate'],
                method=model.options['method'],
                training_data_gradients=model.
                options['training_data_gradients'],
                vec_size=1)

        # Pair input list names with their respective data
        self.training_inputs = {}

        self._setup_empty_prob_comp(model)

        # Setup dropdown menus for x/y inputs and the output value
        self.x_input_select = Select(title="X Input:",
                                     value=[x for x in self.input_names][0],
                                     options=[x for x in self.input_names])
        self.x_input_select.on_change('value', self._x_input_update)

        self.y_input_select = Select(title="Y Input:",
                                     value=[x for x in self.input_names][1],
                                     options=[x for x in self.input_names])
        self.y_input_select.on_change('value', self._y_input_update)

        self.output_select = Select(title="Output:",
                                    value=[x for x in self.output_names][0],
                                    options=[x for x in self.output_names])
        self.output_select.on_change('value', self._output_value_update)

        # Create sliders for each input
        self.slider_dict = {}
        self.predict_inputs = {}
        for title, values in self.training_inputs.items():
            slider_data = np.linspace(min(values), max(values),
                                      self.resolution)
            self.predict_inputs[title] = slider_data
            # Calculates the distance between slider ticks
            slider_step = slider_data[1] - slider_data[0]
            slider_object = Slider(start=min(values),
                                   end=max(values),
                                   value=min(values),
                                   step=slider_step,
                                   title=str(title))
            self.slider_dict[title] = slider_object

        self._slider_attrs()

        # Length of inputs and outputs
        self.num_inputs = len(self.input_names)
        self.num_outputs = len(self.output_names)

        # Precalculate the problem bounds.
        limits = np.array([[min(value), max(value)]
                           for value in self.training_inputs.values()])
        self.limit_range = limits[:, 1] - limits[:, 0]

        # Positional indicies
        self.x_index = 0
        self.y_index = 1
        self.output_variable = self.output_names.index(
            self.output_select.value)

        # Data sources are filled with initial values
        # Slider Column Data Source
        self.slider_source = ColumnDataSource(data=self.predict_inputs)

        # Contour plot Column Data Source
        self.contour_plot_source = ColumnDataSource(data=dict(
            z=np.random.rand(self.resolution, self.resolution)))
        self.contour_training_data_source = ColumnDataSource(data=dict(
            x=np.repeat(0, self.resolution), y=np.repeat(0, self.resolution)))

        # Bottom plot Column Data Source
        self.bottom_plot_source = ColumnDataSource(data=dict(
            x=np.repeat(0, self.resolution), y=np.repeat(0, self.resolution)))
        self.bottom_plot_scatter_source = ColumnDataSource(
            data=dict(bot_slice_x=np.repeat(0, self.resolution),
                      bot_slice_y=np.repeat(0, self.resolution)))

        # Right plot Column Data Source
        self.right_plot_source = ColumnDataSource(data=dict(
            x=np.repeat(0, self.resolution), y=np.repeat(0, self.resolution)))
        self.right_plot_scatter_source = ColumnDataSource(
            data=dict(right_slice_x=np.repeat(0, self.resolution),
                      right_slice_y=np.repeat(0, self.resolution)))

        # Text input to change the distance of reach when searching for nearest data points
        self.scatter_distance = TextInput(value="0.1",
                                          title="Scatter Distance")
        self.scatter_distance.on_change('value', self._scatter_input)
        self.dist_range = float(self.scatter_distance.value)

        # Grouping all of the sliders and dropdowns into one column
        sliders = [value for value in self.slider_dict.values()]
        sliders.extend([
            self.x_input_select, self.y_input_select, self.output_select,
            self.scatter_distance
        ])
        self.sliders_and_selects = row(column(*sliders))

        # Layout creation
        self.doc_layout = row(self._contour_data(), self._right_plot(),
                              self.sliders_and_selects)
        self.doc_layout2 = row(self._bottom_plot())

        if doc is None:
            doc = curdoc()

        doc.add_root(self.doc_layout)
        doc.add_root(self.doc_layout2)
        doc.title = 'Meta Model Visualization'
Example #6
0
                               button_type="success",
                               width=120)
file_selection_button.on_click(load_files_group)

files_selector_spacer = Spacer(width=10)

group_selection_button = Button(label="Select Directory",
                                button_type="primary",
                                width=140)
group_selection_button.on_click(load_directory_group)

unload_file_button = Button(label="Unload", button_type="danger", width=50)
unload_file_button.on_click(unload_file)

# files selection box
files_selector = Select(title="Files:", options=[])
files_selector.on_change('value', change_data_selector)

# data selection box
data_selector = MultiSelect(title="Data:", options=[], size=12)
data_selector.on_change('value', select_data)

# x axis selection box
x_axis_selector_title = Div(text="""X Axis:""")
x_axis_selector = RadioButtonGroup(labels=x_axis_options, active=0)
x_axis_selector.on_click(change_x_axis)

# toggle second axis button
toggle_second_axis_button = Button(label="Toggle Second Axis",
                                   button_type="success")
toggle_second_axis_button.on_click(toggle_second_axis)
Example #7
0
def single_pie_tab(df_means, df_stdev, Time, Treatments, number_cmpds_run):

    len_t = len(Treatments)

    colors = [
        "firebrick", "navy", 'green', 'orange', 'violet', 'lawngreen',
        'lightgreen', 'yellow', 'olive', 'red', 'grey', 'skyblue', 'indigo',
        'slategray', 'hotpink', 'peachpuff', 'powderblue'
    ]

    df_means = df_means.reindex(index=order_by_index(
        df_means.index, index_natsorted(df_means[Time[0]])))
    cmpd_options = cmpd_options_func(df_means, len_t + 1, number_cmpds_run)

    time_vals = df_means[Time[0]].drop_duplicates().tolist()
    if len(Treatments) == 4:
        df_means[Treatments[0]] = df_means[Treatments[0]].astype('str')
        df_means[Treatments[1]] = df_means[Treatments[1]].astype('str')
        df_means[Treatments[2]] = df_means[Treatments[2]].astype('str')
        df_means[Treatments[3]] = df_means[Treatments[3]].astype('str')
        tm0_vals = df_means[Treatments[0]].drop_duplicates().tolist()
        tm1_vals = df_means[Treatments[1]].drop_duplicates().tolist()
        tm2_vals = df_means[Treatments[2]].drop_duplicates().tolist()
        tm3_vals = df_means[Treatments[3]].drop_duplicates().tolist()
        df_for_pie = df_means.loc[(df_means[Time[0]] == time_vals[0])
                                  & (df_means[Treatments[0]] == tm0_vals[0]) &
                                  (df_means[Treatments[1]] == tm1_vals[0]) &
                                  (df_means[Treatments[2]] == tm2_vals[0]) &
                                  (df_means[Treatments[3]] == tm3_vals[0])]
    elif len(Treatments) == 3:
        df_means[Treatments[0]] = df_means[Treatments[0]].astype('str')
        df_means[Treatments[1]] = df_means[Treatments[1]].astype('str')
        df_means[Treatments[2]] = df_means[Treatments[2]].astype('str')
        tm0_vals = df_means[Treatments[0]].drop_duplicates().tolist()
        tm1_vals = df_means[Treatments[1]].drop_duplicates().tolist()
        tm2_vals = df_means[Treatments[2]].drop_duplicates().tolist()
        df_for_pie = df_means.loc[(df_means[Time[0]] == time_vals[0])
                                  & (df_means[Treatments[0]] == tm0_vals[0]) &
                                  (df_means[Treatments[1]] == tm1_vals[0]) &
                                  (df_means[Treatments[2]] == tm2_vals[0])]
    elif len(Treatments) == 2:
        df_means[Treatments[0]] = df_means[Treatments[0]].astype('str')
        df_means[Treatments[1]] = df_means[Treatments[1]].astype('str')
        tm0_vals = df_means[Treatments[0]].drop_duplicates().tolist()
        tm1_vals = df_means[Treatments[1]].drop_duplicates().tolist()
        df_for_pie = df_means.loc[(df_means[Time[0]] == time_vals[0])
                                  & (df_means[Treatments[0]] == tm0_vals[0]) &
                                  (df_means[Treatments[1]] == tm1_vals[0])]
    elif len(Treatments) == 1:
        df_means[Treatments[0]] = df_means[Treatments[0]].astype('str')
        tm0_vals = df_means[Treatments[0]].drop_duplicates().tolist()
        df_for_pie = df_means.loc[(df_means[Time[0]] == time_vals[0])
                                  & (df_means[Treatments[0]] == tm0_vals[0])]
    df_means = df_means.replace(float('nan'), 0)
    def_cmpds = []
    for i in range(5):
        def_cmpds.append(df_means.columns[len_t + 1 + i])
    len_cmpds = len(def_cmpds)
    df_pie_values = df_for_pie[def_cmpds]
    pie_vals = list(df_pie_values.values.flatten())
    pie_fracs = [x / sum(pie_vals) for x in pie_vals]
    percents = [0]
    per_labels = []
    for f in range(0, len(pie_fracs)):
        ff = percents[f] + pie_fracs[f]
        percents.append(ff)
        per_labels.append(df_means.columns[len_t + 1 + f] + ':' +
                          str("{0:0.1f}".format(100.0 * pie_fracs[f])))
    ss = [per * 2 * pi for per in percents[:-1]]
    ee = [per * 2 * pi for per in percents[1:]]
    mid = []
    for pp in range(len(ss)):
        mid.append(.5 * ss[pp] + .5 * ee[pp])
    cc = colors[0:len_cmpds]
    source = ColumnDataSource(data=dict(starts=ss, ends=ee, color=cc))
    x_label, y_label = circ(.5, mid)
    p_label_data = ColumnDataSource({
        'x_label': x_label,
        'y_label': y_label,
        'p_labels': per_labels
    })
    p = figure(match_aspect=True, plot_height=1000, plot_width=1000)
    x_vals, y_vals = circ(1)
    p.line(x_vals, y_vals, line_width=5, color='black')
    p.wedge(x=0,
            y=0,
            radius=1,
            start_angle='starts',
            end_angle='ends',
            color='color',
            source=source)
    p_labels = LabelSet(x="x_label",
                        y="y_label",
                        text="p_labels",
                        source=p_label_data,
                        text_color='black')
    p.add_layout(p_labels)

    #widget for pie charts
    sel_t = Select(title="Choose a time:",
                   value=time_vals[0],
                   options=time_vals)

    if len(Treatments) == 4:
        select0 = Select(title=Treatments[0],
                         value=str(tm0_vals[0]),
                         options=tm0_vals)
        select1 = Select(title=Treatments[1],
                         value=str(tm1_vals[0]),
                         options=tm1_vals)
        select2 = Select(title=Treatments[2],
                         value=str(tm2_vals[0]),
                         options=tm2_vals)
        select3 = Select(title=Treatments[3],
                         value=str(tm3_vals[0]),
                         options=tm3_vals)
    elif len(Treatments) == 3:
        select0 = Select(title=Treatments[0],
                         value=str(tm0_vals[0]),
                         options=tm0_vals)
        select1 = Select(title=Treatments[1],
                         value=str(tm1_vals[0]),
                         options=tm1_vals)
        select2 = Select(title=Treatments[2],
                         value=str(tm2_vals[0]),
                         options=tm2_vals)
    elif len(Treatments) == 2:
        select0 = Select(title=Treatments[0],
                         value=str(tm0_vals[0]),
                         options=tm0_vals)
        select1 = Select(title=Treatments[1],
                         value=str(tm1_vals[0]),
                         options=tm1_vals)
    elif len(Treatments) == 1:
        select0 = Select(title=Treatments[0],
                         value=str(tm0_vals[0]),
                         options=tm0_vals)

    checkbox_group = CheckboxGroup(labels=cmpd_options, active=[0, 1, 2, 3, 4])

    def update_data(attrname, old, new):
        if len(Treatments) == 4:
            df_for_pie = df_means.loc[
                (df_means[Time[0]] == sel_t.value)
                & (df_means[Treatments[0]] == select0.value) &
                (df_means[Treatments[1]] == select1.value) &
                (df_means[Treatments[2]] == select2.value) &
                (df_means[Treatments[3]] == select3.value)]
        elif len(Treatments) == 3:
            df_for_pie = df_means.loc[
                (df_means[Time[0]] == sel_t.value)
                & (df_means[Treatments[0]] == select0.value) &
                (df_means[Treatments[1]] == select1.value) &
                (df_means[Treatments[2]] == select2.value)]
        elif len(Treatments) == 2:
            df_for_pie = df_means.loc[
                (df_means[Time[0]] == sel_t.value)
                & (df_means[Treatments[0]] == select0.value) &
                (df_means[Treatments[1]] == select1.value)]
        elif len(Treatments) == 1:
            df_for_pie = df_means.loc[(df_means[Time[0]] == sel_t.value) & (
                df_means[Treatments[0]] == select0.value)]
        compounds_in_pie = []
        for i in checkbox_group.active:
            compounds_in_pie.append(cmpd_options[i])

        df_pie_values = df_for_pie[compounds_in_pie]
        pie_vals = list(df_pie_values.values.flatten())
        pie_fracs = [x / sum(pie_vals) for x in pie_vals]
        percents = [0]
        per_labels = []
        for f in range(0, len(pie_fracs)):
            ff = percents[f] + pie_fracs[f]
            percents.append(ff)
            per_labels.append(compounds_in_pie[f] + ':' +
                              str("{0:0.1f}".format(100.0 * pie_fracs[f])))
        starts = [per * 2 * pi for per in percents[:-1]]
        ends = [per * 2 * pi for per in percents[1:]]
        if len(ends) == 0:
            ends = [0] * len(compounds_in_pie)
            starts = [0] * len(compounds_in_pie)
            #per_labels=[0] * len(compounds_in_pie)
            #per_labels=['{:.2f}'.format(x) for x in per_labels]
        mid = []
        for pp in range(len(starts)):
            mid.append(.5 * starts[pp] + .5 * ends[pp])
        pie_colors = colors[0:len(compounds_in_pie)]
        x_label, y_label = circ(.5, mid)
        result2_label = {
            'x_label': x_label,
            'y_label': y_label,
            'p_labels': per_labels
        }
        result2 = {'starts': starts, 'ends': ends, 'color': pie_colors}
        source.data = result2
        p_label_data.data = result2_label

    if len(Treatments) == 4:
        for w in [sel_t, select0, select1, select2, select3]:
            w.on_change('value', update_data)
    elif len(Treatments) == 3:
        for w in [sel_t, select0, select1, select2]:
            w.on_change('value', update_data)
    elif len(Treatments) == 2:
        for w in [sel_t, select0, select1]:
            w.on_change('value', update_data)
    elif len(Treatments) == 1:
        for w in [sel_t, select0]:
            w.on_change('value', update_data)

    checkbox_group.on_change('active', update_data)

    ## Set up the widgets for pie
    if len(Treatments) == 4:
        inputs1 = widgetbox(sel_t, select0, select1, select2, select3)
    elif len(Treatments) == 3:
        inputs1 = widgetbox(sel_t, select0, select1, select2)
    elif len(Treatments) == 2:
        inputs1 = widgetbox(sel_t, select0, select1)
    elif len(Treatments) == 1:
        inputs1 = widgetbox(sel_t, select0)
    inputs2 = widgetbox(checkbox_group)

    # Set up layouts and add to document
    layout = row(column(inputs1), inputs2, p, width=1500)
    tab = Panel(child=layout, title='Pie Charts')

    return tab
Example #8
0
def symbol_size(values):
    """ Rescale given values to reasonable symbol sizes in the plot. """

    max_size = 50.0
    min_size = 5.0

    # Rescale max.
    slope = (max_size - min_size) / (values.max() - values.min())

    return slope * (values - values.max()) + max_size


# Directory selection.
dirs = os.listdir(model.parent_dir)
dirs.sort()
directory_selection = Select(options=dirs, value=dirs[1])
directory_selection.on_change('value', directory_update)

# Init model first time.
model.frames = get_frames(directory_selection.value)

# Slider to select frame.
idx_selection_slider = Slider(start=model.idxs[0],
                              end=model.idxs[-1],
                              step=1.0,
                              value=model.idxs[0],
                              title="Select frame id")
idx_selection_slider.on_change('value', idx_slider_update)

# Spinner to select frame.
idx_selection_spinner = Spinner(low=model.idxs[0],
Example #9
0
from src.clusterController import ClusterController


def getAllClusterSubset(allClusters, subsetsize):
    clusters = allClusters[0:subsetsize]
    return clusters


#cst_data = pd.read_csv(join(dirname(__file__), 'data', 'CTSData.csv'))
#cst_data = pd.read_csv(join(dirname(__file__), 'data', 'CTSData.csv')).dropna()

clustCont = ClusterController()
tab_perm = clustCont.tab

b1 = Button(label="Run")
s1 = Select(title="Option:", value="fd", options=["fd", "bar", "baz", "quux"])
controls = column(b1, s1)

src = ColumnDataSource(data={'x': [3, 5], 'y': [8, -1]})

columns = [
    TableColumn(field="x", title="x"),
    TableColumn(field="y", title="y"),
]

datatable = DataTable(
    source=src,
    columns=columns,
    width=800,
    height=300,
    editable=False,
Example #10
0
           ])

#add labels for glyphs
labels = LabelSet(x="average_grades",
                  y="exam_grades",
                  text="student_names",
                  x_offset=5,
                  y_offset=5,
                  source=source)
f.add_layout(labels)

#create glyphs
f.circle(x="average_grades", y="exam_grades", source=source, size=8)


#create function
def update_labels(attr, old, new):
    labels.text = select.value


#create select widget
options = [("average_grades", "Average Grades"),
           ("exam_grades", "Exam Grades"), ("student_names", "Student Names")]
select = Select(title="Attribute", options=options)
select.on_change("value", update_labels)

#create layout and add to curdoc
lay_out = layout([[select]])
curdoc().add_root(f)
curdoc().add_root(lay_out)
    def create(self):

        self.oldData = dict(peaks=[], classes=[])
        self.sources['table'] = ColumnDataSource(
            dict(xStart=[],
                 xStop=[],
                 name=[],
                 classes=[],
                 j=[],
                 h=[],
                 integral=[],
                 peaks=[],
                 top=[],
                 bottom=[]))
        columns = [
            TableColumn(field="xStart",
                        title="start",
                        formatter=NumberFormatter(format="0.00")),
            TableColumn(field="xStop",
                        title="stop",
                        formatter=NumberFormatter(format="0.00")),
            TableColumn(field="name", title="Name"),
            TableColumn(field="classes", title="Class"),
            TableColumn(field="j", title="J"),
            TableColumn(field="h",
                        title="H",
                        formatter=NumberFormatter(format="0")),
            TableColumn(field="integral",
                        title="Integral",
                        formatter=NumberFormatter(format="0.00"))
        ]
        self.dataTable = DataTable(source=self.sources['table'],
                                   columns=columns,
                                   reorderable=False,
                                   width=500)
        self.sources['table'].on_change(
            'selected',
            lambda attr, old, new: self.rowSelect(new['1d']['indices']))
        self.sources['table'].on_change(
            'data', lambda attr, old, new: self.dataChanged(new))

        self.manual = CustomButton(
            label="Multiplet Analysis",
            button_type="primary",
            width=250,
            error="Please select area using the multiplet analysis tool.")
        self.manual.on_click(self.manualMultipletAnalysis)

        self.createTool()

        self.title = Div(text="<strong>Edit Multiplet:</strong>", width=500)

        self.classes = Select(title="Class:",
                              options=[
                                  "m", "s", "d", "t", "q", "p", "h", "hept",
                                  "dd", "ddd", "dt", "td", "ddt"
                              ],
                              width=100,
                              disabled=True)
        self.classes.on_change(
            'value', lambda attr, old, new: self.manualChange('classes', new))

        self.integral = TextInput(title="Integral:",
                                  value="",
                                  placeholder="Integral",
                                  width=175,
                                  disabled=True)
        self.integral.on_change(
            'value', lambda attr, old, new: self.changeIntegral(new))

        self.j = TextInput(title='J-list:', value="", width=175, disabled=True)
        self.j.on_change('value',
                         lambda attr, old, new: self.manualChange('j', new))

        self.delete = Button(label="Delete Multiplet",
                             button_type="danger",
                             width=500,
                             disabled=True)
        self.delete.on_click(self.deleteMultiplet)

        self.reportTitle = Div(text="<strong>Multiplet Report:</strong>")
        self.report = Paragraph(width=500)
Example #12
0
def graph_tab(data):
    def f(data, year, month):
        recent = data[(data['year'] == year) & (data['month'] == month)]
        recent_by_day = recent.groupby('day')
        sales_by_year = recent_by_day['Sales'].agg(np.sum)
        sales = [sales for sales in sales_by_year]
        return sales

    recent = data[(data['year'] == 2017) & (data['month'] == 12)]

    group_by_day = recent.groupby('day')
    x = group_by_day['Sales'].agg(np.sum)
    sales = [sale for sale in x]

    source = ColumnDataSource(data={
        'days': [x for x in range(len(sales))],
        'sales': sales
    })
    p = figure(plot_width=800,
               plot_height=600,
               title="Day wise Total Sales for a given Year and Month",
               x_axis_label="Days of Month",
               y_axis_label="Total Sales")
    p.title.align = 'center'
    p.title.text_font_size = '20pt'
    p.title.text_font = 'serif'

    # Axis titles
    p.xaxis.axis_label_text_font_size = '14pt'
    p.xaxis.axis_label_text_font_style = 'bold'
    p.yaxis.axis_label_text_font_size = '14pt'
    p.yaxis.axis_label_text_font_style = 'bold'

    # Tick labels
    p.xaxis.major_label_text_font_size = '12pt'
    p.yaxis.major_label_text_font_size = '12pt'
    p.line(x='days', y='sales', source=source, line_width=1.5)
    p.circle(x='days', y='sales', source=source)

    menu1 = Select(title="Year",
                   value="2017",
                   options=['2017', '2016', '2015', '2014'])
    menu2 = Select(title="Month",
                   value="Dec",
                   options=[
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                       'Sep', 'Oct', 'Nov', 'Dec'
                   ])

    def callback(attr, old, new):
        month_num = {
            'Jan': 1,
            'Feb': 2,
            'Mar': 3,
            'Apr': 4,
            'May': 5,
            'Jun': 6,
            'Jul': 7,
            'Aug': 8,
            'Sep': 9,
            'Oct': 10,
            'Nov': 11,
            'Dec': 12
        }
        year = int(menu1.value)
        month = month_num[menu2.value]
        source.data = {
            'days': [x for x in range(1, 31)],
            'sales': f(data, year, month)
        }

    menu1.on_change('value', callback)
    menu2.on_change('value', callback)

    controls = widgetbox(menu1, menu2)
    layout = row(controls, p)

    tab = Panel(child=layout, title='Total Sales')

    return tab


#curdoc().add_root(layout)
# reference: https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html
# how to add "all" category into the selector
# reference: https://stackoverflow.com//questions/50603077/bokeh-select-widget-does-not-update-plot

category = []
category.append('All')
category.extend(df['CATEGORY'].unique().tolist())

# ===== optionally: =====
# category = []
# category.append('All')
# category.extend(df['CATEGORY'].unique().tolist())

# add the selector, options can be: category, name, locality, protocol, etc....
# reference: https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html
select_category = Select(title="Option:", value="All", options=category)

# ==================================================================

#        Task2: define the datasource construction function

# ==================================================================
# input: dataframe, either the original one or the updated one after triggering the selector
# output: column data source, which will be used for plotting, in our case, will serve as the input for the draw_plot function


def datasource_construct(dfnew):

    # sort dfnew based on "OBSERVATION DATE", then reset the index for sorted dfnew
    dfnew.sort_values(by=['OBSERVATION_DATE']).reset_index(inplace=True)
Example #14
0
def get_data(t1, t2):
    df1 = load_ticker(t1)
    df2 = load_ticker(t2)
    data = pd.concat([df1, df2], axis=1)
    data = data.dropna()
    data['t1'] = data[t1]
    data['t2'] = data[t2]
    data['t1_returns'] = data[t1 + '_returns']
    data['t2_returns'] = data[t2 + '_returns']
    return data


# set up widgets

stats = PreText(text='', width=500)
ticker1 = Select(value='AAPL', options=nix('GOOG', DEFAULT_TICKERS))
ticker2 = Select(value='GOOG', options=nix('AAPL', DEFAULT_TICKERS))

# set up plots

source = ColumnDataSource(
    data=dict(date=[], t1=[], t2=[], t1_returns=[], t2_returns=[]))
source_static = ColumnDataSource(
    data=dict(date=[], t1=[], t2=[], t1_returns=[], t2_returns=[]))
tools = 'pan,wheel_zoom,xbox_select,reset'

corr = figure(plot_width=350,
              plot_height=350,
              tools='pan,wheel_zoom,box_select,reset')
corr.circle('t1_returns',
            't2_returns',
Example #15
0
    NewOrder = {'type': 'NewOrder', 'clientOrderId': str(clientOrderId), 'symbol': symbol , 'buySell': OrderType, 'qty': qty}
    with SocketIO(server) as socketIO:
        socketIO.emit('submitOrder', NewOrder)
        socketIO.on('onOrderMessage', order_response)
        socketIO.wait()




buyButton = Button(label="BUY", button_type="success")
buyButton.on_click(buyThreadFunc)

sellButton = Button(label="SELL", button_type="warning")
sellButton.on_click(sellThreadFunc)

select = Select(title="Ticker:", value=stocks_list[0], options=stocks_list)
select.on_change("value", ticker_handler)

quantity_input = TextInput(value="100", title="quantity:")
quantity_input.on_change("value", quantity_handler)


if currentPNL == 0 : 
    PNLbutton = Button(label="PNL : " + str(currentPNL), button_type="warning")
elif currentPNL >0 : 
    PNLbutton = Button(label="PNL : " + str(currentPNL), button_type="success")
else:
    PNLbutton = Button(label="PNL : " + str(currentPNL), button_type="danger")


disp_buttons =  dict(AAPL = Button(label= 'AAPL', button_type = "success"),
Example #16
0
def bokeh_summary_plot(df, savepath=None):
    """Summary plot"""

    from bokeh.plotting import figure
    from bokeh.layouts import column
    from bokeh.models import ColumnDataSource, Range1d, HoverTool, TapTool, CustomJS, OpenURL

    TOOLS = "pan,wheel_zoom,hover,tap,reset,save"

    colors = get_bokeh_colors()
    df = df.rename(columns={'level_0': 'predictor'})
    df['color'] = [colors[x] for x in df['predictor']]
    p = figure(title="Summary", tools=TOOLS, width=500, height=500)
    p.xaxis.axis_label = 'binder_density'
    p.yaxis.axis_label = 'binders'

    #make metric for point sizes
    #df['point_size'] = df.binder_density
    source = ColumnDataSource(data=df)

    p.circle(x='binder_density',
             y='binders',
             line_color='black',
             fill_color='color',
             fill_alpha=0.4,
             size=10,
             source=source,
             legend='predictor')
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("name", "@name"),
        ("length", "@length"),
        ("binders", "@binders"),
        ("binder_density", "@binder_density"),
        ("top_peptide", "@top_peptide"),
        ("max_score", "@max_score"),
    ])
    p.toolbar.logo = None
    if savepath != None:
        url = "http://*****:*****@name" % savepath
        taptool = p.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    callback = CustomJS(args=dict(source=source),
                        code="""
        var data = source.data;
        var f = cb_obj.value

        data['x'] = f
        source.trigger('change');
        source.change.emit();
    """)

    from bokeh.layouts import widgetbox
    from bokeh.models.widgets import Select
    menu = [(i, i) for i in df.columns]
    select = Select(title='X', value='A', options=list(df.columns), width=8)
    select.js_on_change('value', callback)

    #layout = column(p, select, sizing_mode='scale_width')
    return p
Example #17
0
    def modify_doc(doc):
        def change_categorical():
            '''
            bokeh plot application for categorical variables
            '''
            def update_bars(attr, old, new):
                '''
                callback for reindexing x-axis with slider
                '''
                data = df[select.value].value_counts()

                if radio_button_group.active == 1:
                    data = data.sort_index()

                start = int(round(new[0], 0))
                end = int(round(new[1], 0)) + 1

                data = data.iloc[start:end]
                keys = data.keys().tolist()
                vals = data.values

                p.x_range.factors = keys
                datasource.data = {'x': keys, 'top': vals}

            def update_barsort(attr, old, new):
                '''
                callback for changing sort method of bars
                '''
                data = df[select.value].value_counts()
                range_slider.value = (range_slider.start, range_slider.end)

                if new == 1:
                    data = data.sort_index()

                keys = data.keys().tolist()
                vals = data.values

                p.x_range.factors = keys
                datasource.data = {'x': keys, 'top': vals}

            # ============================
            # Plot Setup (Categorical)
            # ============================

            # fetch data
            data = df[select.value].value_counts()
            categories = len(data) - 1
            keys = data.keys().tolist()
            vals = data.values
            datasource = ColumnDataSource({'x': keys, 'top': vals})

            # create plot
            p = figure(x_range=keys,
                       plot_height=600,
                       plot_width=680,
                       min_border_bottom=200,
                       min_border_left=80)
            p.vbar(x='x', top='top', width=0.9, source=datasource)

            # format plot
            p.xaxis.major_label_orientation = math.pi / 2
            p.yaxis.axis_label = 'count'
            p.title.text = 'Barchart of {}'.format(select.value)
            p.xgrid.visible = False

            # create interactive tools
            range_slider = RangeSlider(start=0,
                                       end=categories,
                                       value=(0, categories),
                                       step=1,
                                       title="Index Selector")
            radio_button_group = RadioButtonGroup(
                labels=["Sort by y-axis", "Sort by x-axis"], active=0)

            range_slider.on_change('value', update_bars)
            radio_button_group.on_change('active', update_barsort)

            # add to application
            root = column(
                row(
                    column(widgetbox(radio_button_group),
                           widgetbox(range_slider)), Spacer(height=150)), p)
            doc.add_root(root)

            if len(doc.roots) == 3:
                # remove plots for previous column variable
                doc.remove_root(doc.roots[1])

        def change_numeric():
            '''
            bokeh plot application for numeric variables
            '''
            def make_title(label, minval, maxval):
                '''
                adds title to plot with minimum and maximum limits if specified
                '''
                title = 'Histogram'

                if label is not None:
                    title += ' of {}'.format(label)

                if minval != '':
                    title += '; Minimum={}'.format(minval)

                if maxval != '':
                    title += '; Maximum={}'.format(maxval)

                return title

            def update_data(low, high):
                '''
                recalculates histograms
                '''
                hist, edges = np.histogram(data[(data >= low)
                                                & (data <= high)],
                                           bins=bins.value)
                datasource.data = {
                    'top': hist,
                    'left': edges[:-1],
                    'right': edges[1:]
                }
                p.title.text = make_title(label, minval.value, maxval.value)

                if low > -1 * np.inf:
                    p.x_range.start = low

                if high < np.inf:
                    p.x_range.end = high

            def update_bins(attr, old, new):
                '''
                callback for changing number of bins
                '''
                if minval.value == '':
                    low = -1 * np.inf
                else:
                    low = float(minval.value)

                if maxval.value == '':
                    high = np.inf
                else:
                    high = float(maxval.value)

                update_data(low, high)

            def update_min(attr, old, new):
                '''
                callback for setting minimum value limit
                '''
                if new == '':
                    low = -1 * np.inf
                else:
                    low = float(new)

                if maxval.value == '':
                    high = np.inf
                else:
                    high = float(maxval.value)

                update_data(low, high)

            def update_max(attr, old, new):
                '''
                callback for setting maximum value limit
                '''
                if minval.value == '':
                    low = -1 * np.inf
                else:
                    low = float(minval.value)

                if new == '':
                    high = np.inf
                else:
                    high = float(new)

                update_data(low, high)

            # ============================
            # Plot Setup (Numeric)
            # ============================

            # fetch data
            label = select.value
            data = df[label]
            data = data[~data.isna()]
            datasource = ColumnDataSource({'top': [], 'left': [], 'right': []})

            # create plot
            p = figure(plot_height=600,
                       plot_width=680,
                       min_border_bottom=200,
                       min_border_left=80)
            p.quad(top='top',
                   bottom=0,
                   left='left',
                   right='right',
                   alpha=0.4,
                   source=datasource)

            # format plot
            p.xaxis.major_label_orientation = math.pi / 2
            p.yaxis.axis_label = 'count'
            p.below[0].formatter.use_scientific = False

            # create interactive tools
            bins = Slider(start=10,
                          end=100,
                          value=default_bins,
                          step=1,
                          title="Bins")
            minval = TextInput(value=default_min, title="Min Value:")
            maxval = TextInput(value=default_max, title="Max Value:")

            bins.on_change('value', update_bins)
            minval.on_change('value', update_min)
            maxval.on_change('value', update_max)

            update_bins(None, None, default_bins)

            # add to application
            root = column(
                row(column(bins, row(minval, maxval)), Spacer(height=150)), p)
            doc.add_root(root)

            if len(doc.roots) == 3:
                # remove plots for previous column variable
                doc.remove_root(doc.roots[1])

        def update_column(attr, old, new):
            '''
            callback for changing data to column specified in dropdown
            '''
            if df[new].dtype in [int, float]:
                change_numeric()
            else:
                change_categorical()

        # crette interactive dropdown for column selection
        select = Select(title="Column:", value=default_col, options=cols)
        select.on_change('value', update_column)

        doc.add_root(widgetbox(select))
        doc.title = "Histoviewer"
        update_column(None, None, select.value)
Example #18
0
f.flush()
my_supply = None

supplies_from_file = open('settings.csv', 'r+')
read = csv.reader(supplies_from_file)
supplies_load = []
for val in read:
    for subval in val:
        supplies_load.append(subval)
apply_button = Button(label='Apply settings')
current_control = TextInput(title='Current control (A)')
ip_control_textbox = TextInput(title='Enter your device\'s IP address')
connect_button = Button(label='Connect to device')
voltage_control = TextInput(title='Voltage control (V)')
power_control = TextInput(title='Power control (W)')
channel_dropdown = Select(title='Channel control', options=['1', '2', '3'])
supply_textbox = TextInput(title='Current supply')
supply_dropdown = MultiSelect(options=supplies_load)
ocp_control = TextInput(title='OCP control (A)')
file_control = TextInput(title='Desired name of save file',
                         value='readings.csv')
directory_control = TextInput(
    title="Absolute path to desired directory (Ex: /home/pi/Documents)")
comment_box = TextInput(title='Annotation (Will add when box is unselected)')
start_button = Button(label='Start recording data')
PS1C1Voltage = figure(x_range=(0, 300),
                      y_range=(0, 30),
                      x_axis_label='Time (150 ms)',
                      y_axis_label='Volts',
                      title='Power Supply 1 Channel 1 Voltage over time',
                      plot_width=300,
Example #19
0
def modify_doc(doc):
    Q_API_key = '2QQxWV_Ycg2ULirbUMxB'  # Quandl
    AV_API_key = '567TRV8RTL728INO'  # Alpha Vantage
    # Download WIKI metadata from Quandl via API
    url_0 = 'https://www.quandl.com/api/v3/databases/WIKI/metadata?api_key=' + Q_API_key
    response_0 = requests.get(url_0)
    # Unzip the bytes and extract the csv file into memory
    myzip = ZipFile(BytesIO(response_0.content)).extract('WIKI_metadata.csv')
    # Read the csv into pandas dataframe
    df_0 = pd.read_csv(myzip)
    # Clean up the name fields
    df_0['name'] = df_0['name'].apply(lambda s: s[:s.find(')') + 1].rstrip())
    # Drop extraneous fields and reorder
    df_0 = df_0.reindex(columns=['name', 'code'])
    # Make widgets
    stock_picker = Select(title="Select a Stock",
                          value=df_0['name'][0],
                          options=df_0['name'].tolist())
    year_picker = Select(title="Select a Year",
                         value="2018",
                         options=[str(i) for i in range(2008, 2019)],
                         width=100)
    months = [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ]
    month_picker = Select(title="Select a Month",
                          value="January",
                          options=months,
                          width=150)
    widgets = row(stock_picker, year_picker, month_picker)

    # Get data
    def get_data(AV_API_key, ticker):
        from alpha_vantage.timeseries import TimeSeries
        ts = TimeSeries(key=AV_API_key)
        data, metadata = ts.get_daily(ticker, 'full')
        data_dict = {}
        for sub in data.values():
            for key, value in sub.items():
                data_dict.setdefault(key[3:], []).append(float(value))
        data_dict['date'] = list(data.keys())
        df = pd.DataFrame.from_dict(data_dict)
        df['date'] = pd.to_datetime(df['date'])
        df = df.iloc[::-1].reset_index(drop=True)
        # do some finance things
        df['inc'] = df.close > df.open
        df['inc'] = df['inc'].apply(lambda bool: str(bool))

        def SMA(n, s):
            return [s[0]] * n + [np.mean(s[i - n:i]) for i in range(n, len(s))]

        def EMA(n, s):
            k = 2 / (n + 1)
            ema = np.zeros(len(s))
            ema[0] = s[0]
            for i in range(1, len(s) - 1):
                ema[i] = k * s[i] + (1 - k) * ema[i - 1]
            return ema

        df['ema12'] = EMA(12, df['open'])
        df['ema26'] = EMA(26, df['open'])
        df['macd'] = df['ema12'] - df['ema26']
        df['signal'] = EMA(9, df['macd'])
        df['zero'] = df['volume'].apply(lambda x: x * 0)
        df['hist'] = df.macd - df.signal
        df['histc'] = df.macd > df.signal
        df['histc'] = df['histc'].apply(lambda bool: str(bool))
        return df

    # Make figure
    df = get_data(AV_API_key, 'A')
    data_dict = df.to_dict('series')
    source = ColumnDataSource(data=data_dict)
    # create a new plot with a datetime axis type
    p1 = figure(plot_height=400,
                x_axis_type="datetime",
                tools="xwheel_pan,xwheel_zoom,pan,box_zoom",
                active_scroll='xwheel_zoom')
    p2 = figure(plot_height=150,
                x_axis_type="datetime",
                x_range=p1.x_range,
                tools="xwheel_pan,xwheel_zoom,pan,box_zoom",
                active_scroll='xwheel_pan')
    p3 = figure(plot_height=250,
                x_axis_type="datetime",
                x_range=p1.x_range,
                tools="xwheel_pan,xwheel_zoom,pan,box_zoom",
                active_scroll='xwheel_pan')
    # create price glyphs and volume glyph
    p1O = p1.line(x='date',
                  y='open',
                  source=source,
                  color=Spectral5[0],
                  alpha=0.8,
                  legend="OPEN")
    p1C = p1.line(x='date',
                  y='close',
                  source=source,
                  color=Spectral5[1],
                  alpha=0.8,
                  legend="CLOSE")
    p1L = p1.line(x='date',
                  y='low',
                  source=source,
                  color=Spectral5[4],
                  alpha=0.8,
                  legend="LOW")
    p1H = p1.line(x='date',
                  y='high',
                  source=source,
                  color=Spectral5[3],
                  alpha=0.8,
                  legend="HIGH")
    p1.line(x='date',
            y='ema12',
            source=source,
            color="magenta",
            legend="EMA-12")
    p1.line(x='date', y='ema26', source=source, color="black", legend="EMA-26")
    color_mapper = CategoricalColorMapper(factors=["True", "False"],
                                          palette=["green", "red"])
    p1.segment(x0='date',
               y0='high',
               x1='date',
               y1='low',
               color={
                   'field': 'inc',
                   'transform': color_mapper
               },
               source=source)
    width_ms = 12 * 60 * 60 * 1000  # half day in ms
    p1.vbar(x='date',
            width=width_ms,
            top='open',
            bottom='close',
            color={
                'field': 'inc',
                'transform': color_mapper
            },
            source=source)
    p2V = p2.varea(x='date',
                   y1='volume',
                   y2='zero',
                   source=source,
                   color="black",
                   alpha=0.8)
    p3.line(x='date', y='macd', source=source, color="green", legend="MACD")
    p3.line(x='date', y='signal', source=source, color="red", legend="Signal")
    p3.vbar(x='date',
            top='hist',
            source=source,
            width=width_ms,
            color={
                'field': 'histc',
                'transform': color_mapper
            },
            alpha=0.5)
    # Add HoverTools to each line
    p1.add_tools(
        HoverTool(tooltips=[('Date', '@date{%F}'), ('Open', '@open{($ 0.00)}'),
                            ('Close', '@close{($ 0.00)}'),
                            ('Low', '@low{($ 0.00)}'),
                            ('High', '@high{($ 0.00)}'),
                            ('Volume', '@volume{(0.00 a)}')],
                  formatters={'date': 'datetime'},
                  mode='mouse'))
    p2.add_tools(
        HoverTool(tooltips=[('Date', '@date{%F}'), ('Open', '@open{($ 0.00)}'),
                            ('Close', '@close{($ 0.00)}'),
                            ('Low', '@low{($ 0.00)}'),
                            ('High', '@high{($ 0.00)}'),
                            ('Volume', '@volume{(0.00 a)}')],
                  formatters={'date': 'datetime'},
                  mode='mouse'))
    p3.add_tools(
        HoverTool(tooltips=[('Date', '@date{%F}'),
                            ('EMA-12', '@ema12{($ 0.00)}'),
                            ('EMA-26', '@ema26{($ 0.00)}'),
                            ('MACD', '@macd{($ 0.00)}'),
                            ('Signal', '@signal{($ 0.00)}')],
                  formatters={'date': 'datetime'},
                  mode='mouse'))
    p1.toolbar.logo = None
    p2.toolbar.logo = None
    p3.toolbar.logo = None
    # Add legend
    p1.legend.orientation = 'horizontal'
    p1.legend.title = 'Daily Stock Price'
    p1.legend.click_policy = "hide"
    p1.legend.location = "top_left"
    p3.legend.orientation = 'horizontal'
    p3.legend.location = "top_left"
    p3.legend.orientation = 'horizontal'
    p3.legend.title = 'Moving Average Convergence Divergence'
    p3.legend.location = "top_left"
    # Add axis labels
    #p1.xaxis.axis_label = 'Date'
    #p3.xaxis.axis_label = 'Date'
    p2.xaxis.axis_label = 'Date'
    p1.yaxis.axis_label = 'Price ($USD/share)'
    p2.yaxis.axis_label = 'Volume (shares)'
    p3.yaxis.axis_label = 'Indicator ($USD)'
    # Add tick formatting
    p1.yaxis[0].formatter = NumeralTickFormatter(format="$0.00")
    p2.yaxis[0].formatter = NumeralTickFormatter(format="0.0a")
    p3.yaxis[0].formatter = NumeralTickFormatter(format="$0.00")
    p1.outline_line_width = 1
    p2.outline_line_width = 1
    p3.outline_line_width = 1

    # Activate tools
    #p1.toolbar.active_scroll = 'xwheel_zoom'
    #p2.toolbar.active_scrool = 'xwheel_pan'

    # Set up callbacks
    def update_data(attrname, old, new):
        # Get the current Select value
        ticker = df_0.loc[df_0['name'] == stock_picker.value, 'code'].iloc[0]
        print('ticker:', ticker)
        # Get the new data
        df = get_data(AV_API_key, ticker)
        dfi = df.set_index(['date'])
        data_dict = df.to_dict('series')
        data_dict = {k: data_dict[k][::-1] for k in data_dict.keys()}
        source.data = ColumnDataSource(data=data_dict).data

    def update_axis(attrname, old, new):
        # Get the current Select values
        source.data = ColumnDataSource(data=data_dict).data
        year = year_picker.value
        month = f'{months.index(month_picker.value) + 1:02d}'
        start = datetime.strptime(f'{year}-{month}-01', "%Y-%m-%d")
        if month == '12':
            end = datetime.strptime(f'{str(int(year)+1)}-01-01', "%Y-%m-%d")
        else:
            end = datetime.strptime(f'{year}-{int(month)+1:02d}-01',
                                    "%Y-%m-%d")
        p1.x_range.start = start
        p1.x_range.end = end
        dfi = df.set_index(['date'])
        p1.y_range.start = dfi.loc[end:start]['low'].min() * 0.95
        p1.y_range.end = dfi.loc[end:start]['high'].max() * 1.05
        p2.y_range.start = dfi.loc[end:start]['volume'].min() * 0.95
        p2.y_range.end = dfi.loc[end:start]['volume'].max() * 1.05
        p3.y_range.start = dfi.loc[end:start]['macd'].min() * 0.75
        p3.y_range.end = dfi.loc[end:start]['macd'].max() * 1.25

    # setup JScallback
    JS = '''
        clearTimeout(window._autoscale_timeout);

        var date = source.data.date,
            low = source.data.low,
            high = source.data.high,
            volume = source.data.volume,
            macd = source.data.macd,
            start = cb_obj.start,
            end = cb_obj.end,
            min1 = Infinity,
            max1 = -Infinity,
            min2 = Infinity,
            max2 = -Infinity,
            min3 = Infinity,
            max3 = -Infinity;

        for (var i=0; i < date.length; ++i) {
            if (start <= date[i] && date[i] <= end) {
                max1 = Math.max(high[i], max1);
                min1 = Math.min(low[i], min1);
                max2 = Math.max(volume[i], max2);
                min2 = Math.min(volume[i], min2);
                max3 = Math.max(macd[i], max3);
                min3 = Math.min(macd[i], min3);
            }
        }
        var pad1 = (max1 - min1) * .05;
        var pad2 = (max2 - min2) * .05;
        var pad3 = (max3 - min3) * .05;

        window._autoscale_timeout = setTimeout(function() {
            y1_range.start = min1 - pad1;
            y1_range.end = max1 + pad1;
            y2_range.start = min2 - pad2;
            y2_range.end = max2 + pad2;
            y3d = Math.max(Math.abs(min3 - pad3), Math.abs(max3 + pad3))
            y3_range.start = -y3d;
            y3_range.end = y3d;
        });
    '''
    callbackJS = CustomJS(args={
        'y1_range': p1.y_range,
        'y2_range': p2.y_range,
        'y3_range': p3.y_range,
        'source': source
    },
                          code=JS)

    p1.x_range.js_on_change('start', callbackJS)
    p1.x_range.js_on_change('end', callbackJS)

    stock_picker.on_change('value', update_data)
    year_picker.on_change('value', update_axis)
    month_picker.on_change('value', update_axis)

    b = Button(label='Full History')
    b.js_on_click(
        CustomJS(args=dict(p1=p1, p2=p2),
                 code="""
    p1.reset.emit()
    p2.reset.emit()
    """))
    c = column(Div(text="", height=8), b, width=100)

    # Set up layouts and add to document
    row1 = row(stock_picker,
               year_picker,
               month_picker,
               c,
               height=65,
               width=800,
               sizing_mode='stretch_width')
    row2 = row(p1, width=800, height=400, sizing_mode='stretch_width')
    row3 = row(p2, width=800, height=150, sizing_mode='stretch_width')
    row4 = row(p3, width=800, height=250, sizing_mode='stretch_width')
    layout = column(row1,
                    row2,
                    row4,
                    row3,
                    width=800,
                    height=800,
                    sizing_mode='scale_both')
    doc.add_root(layout)
Example #20
0
                + dt_picker.value.strftime('%Y-%m-%d') \
                + " with option " +  dummy_select.value


def updateBtn():
    update(attrname=None, old=None, new=None)


text_input = TextInput(value="Ivana")
button = Button(label="Generate Text")

dt_picker_ = DatePicker(min_date='2010-01-01',
                        max_date='2018-03-28',
                        value='2018-03-27')

dummy_select = Select(value='select an option', options=['a', 'b'])

output = Paragraph()

button.on_click(updateBtn)
dummy_select.on_change('value', update)
dt_picker.on_change('value', update)

lay_out = layout([[text_input, button, dt_picker], [output]])

#show(lay_out)
#curdoc().add_root(lay_out)

# curdoc().add_root(
#     column(
#         row(text_input),
    def getBokehComponent(self):
        self.select = Select(title=self._settings['title'], 
                             value=self._settings["value"], 
                             options=self._settings['options'])

        return self.select
Example #22
0
import numpy as np
import pandas as pd

from bokeh.models import ColumnDataSource, Plot
from bokeh.plotting import figure, curdoc
from bokeh.properties import String, Instance
from bokeh.server.app import bokeh_app
from bokeh.server.utils.plugins import object_page
from bokeh.models.widgets import (HBox, VBox, VBoxForm, PreText, Select,
                                  AppHBox, AppVBox, AppVBoxForm)

from bokeh.simpleapp import simpleapp

select1 = Select(name='ticker1',
                 value='AAPL',
                 options=['AAPL', 'GOOG', 'INTC', 'BRCM', 'YHOO'])
select2 = Select(name='ticker2',
                 value='GOOG',
                 options=['AAPL', 'GOOG', 'INTC', 'BRCM', 'YHOO'])


@simpleapp(select1, select2)
def stock(ticker1, ticker2):
    pretext = PreText(text="", width=500)
    df = get_data(ticker1, ticker2)
    source = ColumnDataSource(data=df)
    source.tags = ['main_source']
    p = figure(
        title="%s vs %s" % (ticker1, ticker2),
        plot_width=400,
Example #23
0
from bokeh.models.widgets import Select
from bokeh.io import curdoc
from plot_options import apply_plot_options

world = pd.read_csv(join(dirname(__file__), "data.csv"))

axis_map = {
    "GNP Per-Capita (USD)": "per_cap_gnp",
    "Life Expectancy (years)": "lifeexpectancy",
    "Surface Area (sq km)": "surfacearea",
    "Year of Independence": "indepyear"
}

# Create Input controls
ctry_selec = Select(title="Country",
                    options=sorted(set(world.country.values)),
                    value='All')
regn_selec = Select(title="Region",
                    options=sorted(set(world.region.values)),
                    value='All')
cont_selec = Select(title="Continent",
                    options=sorted(set(world.continent.values)),
                    value='All')
govt_selec = Select(title="Form of Government",
                    options=sorted(set(world.govtform.values)),
                    value='All')
x_axis = Select(title="X-Axis (choose quantity to plot)",
                options=sorted(axis_map.keys()),
                value='GNP Per-Capita (USD)')
y_axis = Select(title="Y-Axis (choose quantity to plot)",
                options=sorted(axis_map.keys()),
Example #24
0
def generate_summary_plot():
#x = [x*0.005 for x in range(0, 200)]
    #y = x
    x = np.arange(0, 10)
    #x = [x*0.005 for x in range(0, 200)]
    y = [i*i for i in x]

    z = [i*3.0 for i in x]

    source = ColumnDataSource(data=dict(x=x, y=y))
    source2 = ColumnDataSource(data=dict(x=x, z=z))

    print(source)
    print(dict(source=source))



    summary_fig = figure(x_axis_location='above', plot_width=400, plot_height=400)
    line_one = summary_fig.line('x', 'y', source=source, line_width=3, line_alpha=0.6)#, xaxis.axis_label = 'initalized')#,axis.axis_label='title')

    line_two = summary_fig.line('x', 'z', source=source2, line_width=3, line_alpha=0.6)#, xaxis.axis_label = 'initalized')#,axis.axis_label='title')

    #selector_options=['alpha','beta','gamma']
    #selector1=Select(title='X-Axis',value=selector_options[0],options=selector_options, callback = callback)
    
    #summary_fig.xaxis.visible = None
    xaxis = LinearAxis(axis_label="Initial x-axis label")
    summary_fig.add_layout(xaxis, 'below')
    #summary_fig.xaxis.axis_label = 'Time (Years)'    
    #selector1.on_change('value',callback)  #plot.yaxis.axis_label = y_title
    #controls = widgetbox([selector1], width=200)

    code1 = '''\
    object.visible = toggle.active
    '''

    code2 = '''\
    object.visible = radio_button.active
    '''

	#var f = cb_obj.value
    callback2 = CustomJS(args=dict(source=source2), code="""
    var data = source.data;
    var f = cb_obj.value
    x = data['x']
    z = data['z']
    if (f == "alpha") {
    	for (i = 0; i < x.length; i++) {
        z[i] = Math.pow(x[i], 3.)}
    	}
    else if (f = "beta") {
   		for (i = 0; i < x.length; i++) {
        z[i] = 20}
     	}
    source.trigger('change');
    """)


    callback3 = CustomJS(args=dict(xaxis=xaxis), code="""
    var f = cb_obj.value
    xaxis.attributes.axis_label = f 
    xaxis.trigger('change');
    """)


    callback4 = CustomJS(args=dict(source=source2), code="""
    var data = source.data;
    var f = cb_obj.value
    x = data['x']
    z = data['z']
    if (f == "A alpha") {
    	for (i = 0; i < x.length; i++) {
        z[i] = Math.pow(x[i], 3.)}
    	}
    else if (f = "B alpha") {
   		for (i = 0; i < x.length; i++) {
        z[i] = 20}
     	}
    source.trigger('change');
    """)



    callback1 = CustomJS.from_coffeescript(code=code1, args={})
    toggle1 = Toggle(label="Green Box", button_type="success", callback=callback1)
    callback1.args = {'toggle': toggle1, 'object': line_one}


    #callback2 = CustomJS.from_coffeescript(code=code2, args={})
    radio_button_group = RadioButtonGroup(labels=['alpha','beta','gamma'], active=0)# callback=callback2)
    radio_button_group.js_on_change('value', callback2)
    #print([method for method in dir(radio_button_group)])
    #callback2.args = {'radio_button': radio_button_group, 'object': line_two}
    #output_file("styling_visible_annotation_with_interaction.html")

    selector_options = ['A alpha', 'B beta', 'G gamma']
    selector1 = Select(title='X-Axis', value=selector_options[0], options=selector_options)#, callback=callback4)
    selector1.js_on_change('value', callback4)


    selector2_options = ['Aa alpha', 'Ba beta', 'Ga gamma']
    selector2 = Select(title='X-Axis', value=selector_options[0], options=selector2_options)#, callback=callback4)
    selector2.js_on_change('value', callback3)

    #slider = Slider(start=0.1, end=4, value=1, step=.1, title="power")
    #slider.js_on_change('value', callback)



    controls = widgetbox([toggle1,radio_button_group, selector1, selector2], width=200)
    layout = row(controls, summary_fig)
    return layout
    """We're looking to gauge interest in buying some property to satisfy the hippies in the group that want a farm. There are a few important
questions here that need answering to see where everyone's at. Please answer honestly. The answers will be collected and displayed for all, so we can make sound investment decisions.""",
    'black',
    size=3),
               width=1000)

text_input = TextInput(value=" ", title="Name", width=width_number)
text_input.js_on_change(
    "value",
    CustomJS(
        code=
        """console.log('text_input: value=' + this.value, this.toString())"""))

select_property = Select(
    title='What type of property are you most interested in?',
    value='Land',
    options=sorted(['Land', 'Detached', "Townhome", "Condo"]),
    width=width_number)
select_property.on_change('value', update_property)

select_time = Select(title='What is your ideal time horizon to own?',
                     value='1-2 years',
                     options=[
                         '1-2 years',
                         '3-5 years',
                         '5-10 years',
                         "10+ years",
                     ],
                     width=width_number)
select_time.on_change('value', update_time)
Example #26
0
############################################################
# Plot using Bokeh
############################################################

# Imports
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models.tools import HoverTool

from bokeh.layouts import widgetbox
from bokeh.models.widgets import Select

from bokeh.io import curdoc
from bokeh.layouts import row, column

# Create drop down menu
select = Select(title="Roller Coaster:", value=rides[3][0], options=[x[0] for x in rides])

# Initialize canvas
p = figure(plot_width=600, plot_height=400)
p.y_range.start = 0
p.y_range.end = 120
lr = []

# Function to draw on canvas for a given roller coaster
def draw_plot(coaster_name):
    r = coaster_name
    Y = data[r]
    day_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
    
    for i in range(7):
        dates = sorted(Y[i].keys())
Example #27
0
def line_tab(df):

    cluster_indicators = df.columns[2:-1]
    clusters = df['Country'].unique()

    #define function to create data set for plotting
    def create_dataset(data, indicator, selected_clusters):

        color_palette = Category20_12

        #set color dictionary mapping regions to colors
        colormap = {
            cluster: color_palette[i]
            for i, cluster in enumerate(data['Country'].unique())
        }

        #subset data by selected clusters
        subset = data[data['Country'].isin(selected_clusters)]

        #create datasource for plotting points
        source_point = ColumnDataSource({
            'year':
            subset['Year'],
            'cluster':
            subset['Country'],
            'value':
            subset[indicator],  #values for selected indicator
            'colors': [colormap[cluster] for cluster in subset['Country']]
        })

        #create datasource for plotting lines. for multiple line plotting, data source has to be a list of lists, each list being data points for each group
        xs = []
        ys = []
        colors = []
        for cluster in subset['Country'].unique():
            df_cluster = subset[subset['Country'] == cluster]
            xs.append(list(df_cluster['Year']))
            ys.append(list(df_cluster[indicator]))
            colors.append(colormap[cluster])

        source_line = ColumnDataSource({
            'year':
            xs,
            'value':
            ys,
            'cluster':
            list(subset['Country'].unique()),
            'colors':
            colors
        })
        return source_point, source_line

    #define function to plot interactive line charts
    def create_plot(source_pt, source_line, y):

        #create plot figure
        p = figure(plot_width=800,
                   plot_height=500,
                   title=y,
                   x_axis_label='Year',
                   y_axis_label=y,
                   sizing_mode='scale_both')

        #plot lines
        p.multi_line('year',
                     'value',
                     line_width=1,
                     color='colors',
                     source=source_line,
                     legend='cluster')

        #plot points
        p.circle('year',
                 'value',
                 size=3,
                 fill_color='white',
                 line_color='colors',
                 source=source_pt)

        #set plot aesthetics
        p.legend.label_text_font_size = '8pt'
        p.x_range = Range1d(2001, 2030)
        p.xaxis.minor_tick_line_color = None
        p.xgrid.grid_line_color = None
        p.title.text_font_size = '12pt'
        p.xaxis.axis_label_text_font_style = 'normal'
        p.yaxis.axis_label_text_font_style = 'normal'

        #add hovertool to show details for each data point
        hover = HoverTool(tooltips=[
            ("Cluster: ", "@cluster"),
            ("Value:", "$y{1.1}"),
        ])
        p.add_tools(hover)

        return p

    #update plot on user input
    def update(attr, old, new):

        #get current values of inputs
        y = y_select.value
        selected_clusters = [
            cluster_selection.labels[i] for i in cluster_selection.active
        ]

        #update sources
        new_source_pt, new_source_line = create_dataset(
            df, y, selected_clusters)
        source_pt.data = new_source_pt.data
        source_line.data = new_source_line.data

        #update labels and titles
        p.title.text = y
        p.yaxis.axis_label = y

    #add selection widget
    y_select = Select(title="Select indicator",
                      value=cluster_indicators[3],
                      options=list(cluster_indicators))
    y_select.on_change('value', update)

    #add explanatory text for checkbox group
    text = Div(text="""Select cluster""")

    #add selection widget
    cluster_selection = CheckboxGroup(labels=list(clusters), active=[11])
    cluster_selection.on_change('active', update)

    #set initial values to current widget values
    y = y_select.value
    selected_clusters = [
        cluster_selection.labels[i] for i in cluster_selection.active
    ]

    #get initial dataset and plot
    source_pt, source_line = create_dataset(df, y, selected_clusters)
    p = create_plot(source_pt, source_line, y)

    #layout widgets and plot
    controls = WidgetBox(y_select,
                         text,
                         cluster_selection,
                         width=400,
                         sizing_mode='scale_both')
    layout = row(controls, p)

    tab = Panel(child=layout, title='Trend in gender indicators')

    return tab
Example #28
0
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html" target="_blank">Click here </a>for more information on the parameters </p>
""",
           width=1100)

df = pd.read_csv(datasetname)

y = df[df.columns[:1]].values.ravel()
df1 = df.drop(df.columns[:1], axis=1)

target = Paragraph(text='', name='target')
target.text = "Target feature is " + str(df.columns[:1].tolist())

features = MultiSelect(title="Features", options=df.columns[1:].tolist())
kfold = Slider(start=2, end=10, value=5, step=1, title="No of folds")
fit_intercept = Select(title="Fit_intercept:",
                       value="True",
                       options=["True", "False"])
normalize = Select(title="Normalize:",
                   value="False",
                   options=["True", "False"])
copy_X = Select(title="Copy_X:", value="True", options=["True", "False"])

stats = Paragraph(text='', width=1000, height=50, name='Selected Features:')
stats2 = Div(text='<h3>Results:</h3>', )

#columns =['avg_dist', 'avg_rating_by_driver','avg_rating_of_driver','avg_surge','surge_pct','trips_in_first_30_days','luxury_car_user','weekday_pct','city_Astapor',"city_KingsLanding",'city_Winterfell','phone_Android','phone_no_phone']
#columns = ['luxury_car_user','avg_dist','city_Astapor',"city_KingsLanding",'phone_Android','phone_iPhone']

#df1 = pd.DataFrame(df, columns=columns)
#y = df['churn']
y = df[df.columns[:1]].values.ravel()
Example #29
0
    def _plot(self,
              result_object,
              learning_curves,
              hyperparameter_names,
              reset_times=False):
        # Extract information from learning-curve-dict
        times, losses, config_ids, = [], [], []
        for conf_id, learning_curves in learning_curves.items():
            # self.logger.debug("Config ID: %s, learning_curves: %s", str(conf_id), str(learning_curves))
            for l in learning_curves:
                if len(l) == 0:
                    continue
                tmp = list(zip(*l))
                times.append(tmp[0])
                losses.append(tmp[1])
                config_ids.append(conf_id)

        if reset_times:
            times = [np.array(ts) - ts[0] for ts in times]

        # Prepare ColumnDataSource
        data = OrderedDict([
            ('config_id', []),
            ('config_info', []),
            ('times', []),
            ('losses', []),
            ('duration', []),
            ('HB_iteration', []),
            ('colors', []),
            ('colors_performance', []),
            ('colors_iteration', []),
        ])
        for hp in hyperparameter_names:
            data[hp] = []

        # Populate
        id2conf = result_object.get_id2config_mapping()
        for counter, c_id in enumerate(config_ids):
            if not (len(times[counter]) == len(losses[counter])):
                raise ValueError()
            longest_run = self.get_longest_run(c_id, result_object)
            if not longest_run:
                continue
            data['config_id'].append(str(c_id))
            try:
                config_info = '\n'.join([
                    str(k) + "=" + str(v)
                    for k, v in sorted(id2conf[c_id]['config_info'].items())
                ])
            except:
                config_info = 'Not Available'
            data['config_info'].append(config_info)
            data['times'].append(times[counter])
            data['losses'].append(losses[counter])
            if longest_run:
                data['duration'].append(
                    longest_run['time_stamps']['finished'] -
                    longest_run['time_stamps']['started'])
            else:
                data['duration'].append('N/A')
            data['HB_iteration'].append(str(c_id[0]))
            for hp in hyperparameter_names:
                try:
                    data[hp].append(id2conf[c_id]['config'][hp])
                except KeyError:
                    data[hp].append("None")
            data['colors'].append(losses[counter][-1])
            data['colors_performance'].append(losses[counter][-1])
            data['colors_iteration'].append(c_id[0])

        # Tooltips
        tooltips = [(key, '@' + key) for key in data.keys() if not key in [
            'times', 'duration', 'colors', 'colors_performance',
            'colors_iteration'
        ]]
        tooltips.insert(4, ('duration (sec)', '@duration'))
        tooltips.insert(5, ('Configuration', ' '))
        hover = HoverTool(tooltips=tooltips)

        # Create sources
        source_multiline = ColumnDataSource(data=data)
        # Special source for scattering points, since times and losses for multi_line are nested lists
        scatter_data = {key: [] for key in data.keys()}
        for idx, c_id in enumerate(data['config_id']):
            for t, l in zip(data['times'][idx], data['losses'][idx]):
                scatter_data['times'].append(t)
                scatter_data['losses'].append(l)
                for key in list(data.keys()):
                    if key in ['times', 'losses']:
                        continue
                    scatter_data[key].append(data[key][idx])
        source_scatter = ColumnDataSource(data=scatter_data)

        # Color
        min_perf, max_perf = min([l[-1] for l in data['losses']
                                  ]), max([l[-1] for l in data['losses']])
        min_iter, max_iter = min([int(i) for i in data['HB_iteration']]), max(
            [int(i) for i in data['HB_iteration']])
        color_mapper = LinearColorMapper(palette=Spectral11,
                                         low=min_perf,
                                         high=max_perf)

        # Create plot
        y_axis_type = "log" if len(
            [a for a in scatter_data['losses'] if a <= 0]) == 0 else 'linear'

        x_min, x_max = min(scatter_data['times']), max(scatter_data['times'])
        x_pad = (x_max - x_min) / 10
        x_min -= x_pad
        x_max += x_pad
        y_min, y_max = min(scatter_data['losses']), max(scatter_data['losses'])
        y_pad = (y_max - y_min) / 10
        y_min -= (
            y_min / 10
        ) if y_axis_type == 'log' else y_pad  # because this must not fall below 0 if it's a logscale
        y_max += y_pad * 10 if y_axis_type == 'log' else y_pad
        p = figure(
            plot_height=500,
            plot_width=600,
            y_axis_type=y_axis_type,
            tools=[hover, 'save', 'pan', 'wheel_zoom', 'box_zoom', 'reset'],
            x_axis_label='Time',
            y_axis_label='Cost',
            x_range=Range1d(x_min, x_max, bounds='auto'),
            y_range=Range1d(y_min, y_max, bounds='auto'),
        )

        # Plot per HB_iteration, each config individually
        HB_iterations = sorted(set(data['HB_iteration']))
        max_label_len = max([len(l) for l in HB_iterations])
        HB_handles, HB_labels = [], []
        self.logger.debug(
            "Assuming config_info to be either \"model_based_pick=True\" or \"model_based_pick=False\""
        )
        for it in HB_iterations:
            line_handles = []
            view = CDSView(source=source_multiline,
                           filters=[
                               GroupFilter(column_name='HB_iteration',
                                           group=str(it))
                           ])
            line_handles.append(
                p.multi_line(
                    xs='times',
                    ys='losses',
                    source=source_multiline,
                    view=view,
                    color={
                        'field': 'colors',
                        'transform': color_mapper
                    },
                    alpha=0.5,
                    line_width=5,
                ))
            # Separate modelbased and random
            view = CDSView(source=source_scatter,
                           filters=[
                               GroupFilter(column_name='HB_iteration',
                                           group=str(it)),
                               GroupFilter(column_name='config_info',
                                           group="model_based_pick=True")
                           ])
            line_handles.append(
                p.circle_x(
                    x='times',
                    y='losses',
                    source=source_scatter,
                    view=view,
                    fill_color={
                        'field': 'colors',
                        'transform': color_mapper
                    },
                    fill_alpha=0.5,
                    line_color='colors',
                    size=20,
                ))
            view = CDSView(source=source_scatter,
                           filters=[
                               GroupFilter(column_name='HB_iteration',
                                           group=str(it)),
                               GroupFilter(column_name='config_info',
                                           group="model_based_pick=False")
                           ])
            line_handles.append(
                p.circle(
                    x='times',
                    y='losses',
                    source=source_scatter,
                    view=view,
                    fill_color={
                        'field': 'colors',
                        'transform': color_mapper
                    },
                    fill_alpha=0.5,
                    line_color='colors',
                    size=20,
                ))
            HB_handles.append(line_handles)
            HB_labels.append('warmstart data' if l in
                             [-1, '-1'] else '{number:0{width}d}'.
                             format(width=max_label_len, number=int(it)))

        # Sort all lists according to label
        HB_iterations, HB_handles, HB_labels = zip(*sorted(
            zip(HB_iterations, HB_handles, HB_labels), key=lambda tup: tup[2]))
        HB_iterations, HB_handles, HB_labels = list(HB_iterations), list(
            HB_handles), list(HB_labels)
        self.logger.debug("HB_iterations to labels: %s",
                          str(list(zip(HB_iterations, HB_labels))))

        checkbox, select_all, select_none = get_checkbox(HB_handles, HB_labels)

        callback_color = CustomJS(args=dict(source_multiline=source_multiline,
                                            source_scatter=source_scatter,
                                            cm=color_mapper),
                                  code="""
            var data_multiline = source_multiline.data;
            var data_scatter = source_scatter.data;
            var min_perf = {0};
            var max_perf = {1};
            var min_iter = {2};
            var max_iter = {3};
            if (cb_obj.value == 'performance') {{
                data_multiline['colors'] = data_multiline['colors_performance'];
                data_scatter['colors'] = data_scatter['colors_performance'];
                cm.low = min_perf;
                cm.high = max_perf;
            }} else {{
                data_multiline['colors'] = data_multiline['colors_iteration'];
                data_scatter['colors'] = data_scatter['colors_iteration'];
                cm.low = min_iter;
                cm.high = max_iter;
            }}
            source.change.emit();
            """.format(min_perf, max_perf, min_iter, max_iter))

        select_color = Select(title="Select colors",
                              value="performance",
                              options=["performance", "iteration"],
                              callback=callback_color)

        # Put it all together in a layout (width of checkbox-field sizes with number of elements
        width_of_checkbox = 650 if len(HB_labels) > 100 else 500 if len(
            HB_labels) > 70 else 400
        layout = row(
            p,
            column(
                widgetbox(checkbox, width=width_of_checkbox),
                row(widgetbox(select_all, width=50),
                    widgetbox(select_none, width=50)),
                widgetbox(select_color, width=200)))
        return layout
Example #30
0
############## sources ##############
source3 = ColumnDataSource(data=get_most_similar_auto_complete(df, dfe, string_input, TOP_N))

############## plot ##############
title_no = [str(x) for x in range(TOP_N+1, 0, -1)] #['4', '3', '2', '1']

p = Figure(y_range=title_no, tools="", toolbar_location=None, x_range=[0, 3], x_axis_label='Expected View Count', plot_width=500, plot_height=300)

p.hbar(y = 'title_no', right = 'pred', fill_alpha=0.8,  height= 0.1, source=source3)



############## inputs ##############
string_input2 = TextInput(value='Data Scientist', title="Enter Your Job Ad Title here")
select_city = Select(options=list(df['city'].unique()), value='Zürich', title='choose a city')
select_package = Select(options=['A', 'B', 'C', 'D'], value='D', title='choose a package')
select_contract_pct_from = Select(options=[str(x) for x in range(10, 110, 10)], value='100', title='choose from %')
select_contract_pct_to = Select(options=[str(x) for x in range(10, 110, 10)], value='100', title='choose to %')
select_industry = Select(options=list(df['industry_name'].unique()), value='Industrie diverse', title='choose an industry')




############## updates ##############

    
def update_pred(attrname, old, new):
    string_input = string_input2.value
    package_id = select_package.value
    contract_pct_from = select_contract_pct_from.value