Example #1
0
def make_figure():
    #set up plot
    plot = figure(plot_height=400, plot_width=400, title="Sine Wave",
                  tools=TOOLS, x_range=[0,4*np.pi], y_range=[-5,5])
                  
    plot.line('x','y', source=source, line_width=3)
    plot.scatter('x','y', source=source,size=5)
    
    #call back CustomJS
    callback = CustomJS(args=dict(source=source), code="""
                var data = source.get('data')
                var f = cb_obj.get('value')
                x = data['x']
                y = data['y']
                for (i = 0; i < x.length; i++) {
                    y[i] = f*Math.sin(x[i])            
                    }
                    source.trigger('change');
                    """)

    #add slider
    amplitude = Slider(title="Amplitude", value=amp, start=0, end=5, callback=callback)

    #plot
    layout = VBoxForm(amplitude,plot)
    show(layout)
    return layout #need to return the layout
Example #2
0
def buildVendorsTab():
  defaultGfxVendors = [
    gfxVendors.index('NVIDIA Corporation'),
    gfxVendors.index('Advanced Micro Devices, Inc. [AMD/ATI]'),
    gfxVendors.index('Intel Corporation')
  ]

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

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

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

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

  fig.add_tools(hover)

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

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

  fig.xaxis.major_label_orientation = np.pi / 3

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

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

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

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

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

  gfxVendorCheckbox.on_click(update)

  update(gfxVendorCheckbox.active)

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

  return Panel(child=vendorComparison, title="GFX Vendor Comparison")
Example #3
0
def dataurl_change(attr, old, new):
    if new != "DEMO":
        try:
            source_url.data = requests.get(new).json()
            inputs = VBoxForm(text, threshold, dataurl)
            curdoc().remove_root(plot)
            curdoc().add_root(HBox(inputs, plot, width=800))
        except:
            logging.warn("unable to fetch {}".format(new))
    update_data()
Example #4
0
def buildOSesTab():
  osesCheckbox = CheckboxGroup(labels=oses, active=[i for i in range(len(oses))])

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

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

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

  fig.add_tools(hover)

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

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

  fig.xaxis.major_label_orientation = np.pi / 3

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

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

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

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

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

  osesCheckbox.on_click(update)

  update(osesCheckbox.active)

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

  return Panel(child=osesComparison, title="OS Comparison")
Example #5
0
def integration_with_sliders(rsys,
                             tend,
                             c0,
                             parameters,
                             fig_kwargs=None,
                             unit_registry=None,
                             output_conc_unit=None,
                             output_time_unit=None,
                             slider_kwargs=None,
                             x_axis_type="linear",
                             y_axis_type="linear",
                             integrate_kwargs=None,
                             odesys_extra=None,
                             get_odesys_kw=None):
    """
    Parameters
    ----------
    odesys_extra : tuple of :class:`pyodesys.ODESys` & dict
        From :func:`chempy.kinetics.ode.get_odesys`.
    get_odesys_kw : dict
        If odesys_extra is ``None`` the user may pass this for :func:`chempy.kinetics.ode.get_odesys`.
    """

    import numpy as np
    from bokeh.plotting import Figure
    from bokeh.models import ColumnDataSource, HBox, VBoxForm
    from bokeh.models.widgets import Slider

    if slider_kwargs is None:
        slider_kwargs = {}
    if get_odesys_kw is None:
        get_odesys_kw = {}
    if odesys_extra is None:
        odesys, extra = get_odesys(rsys, **get_odesys_kw)
    else:
        odesys, extra = odesys_extra

    state_keys, rarg_keys, p_units = [
        extra[k] for k in ('param_keys', 'unique', 'p_units')
    ]
    if output_conc_unit is None:
        output_conc_unit = 1
    if output_time_unit is None:
        output_conc_unit = 1

    param_keys = list(chain(state_keys, rarg_keys))
    if x_axis_type == 'linear':
        tout = linspace(tend * 0, tend)
    elif x_axis_type == 'log':
        tout = logspace_from_lin(tend * 1e-9, tend)
    else:
        raise NotImplementedError("Unknown x_axis_type: %s" % x_axis_type)

    tout, Cout, info = odesys.integrate(tout, c0, parameters,
                                        **(integrate_kwargs or {}))
    sources = [
        ColumnDataSource(
            data={
                'tout': to_unitless(tout, output_time_unit),
                k: to_unitless(Cout[:, idx], output_conc_unit)
            }) for idx, k in enumerate(rsys.substances)
    ]

    if fig_kwargs is None:
        Cmax = np.max(Cout)
        x_range = list(to_unitless([tend * 0, tend], output_time_unit))
        y_range = list(to_unitless([Cmax * 0, Cmax * 1.1], output_conc_unit))
        fig_kwargs = dict(plot_height=400,
                          plot_width=400,
                          title="C vs t",
                          tools="crosshair,pan,reset,resize,save,wheel_zoom",
                          x_range=x_range,
                          y_range=y_range,
                          x_axis_type=x_axis_type,
                          y_axis_type=y_axis_type)
    plot = Figure(**fig_kwargs)

    colors = 'red green blue black cyan magenta'.split()
    for idx, k in enumerate(rsys.substances):
        plot.line('tout',
                  k,
                  source=sources[idx],
                  line_width=3,
                  line_alpha=0.6,
                  color=colors[idx % len(colors)])

    def _C(k):
        return to_unitless(c0[k], output_conc_unit)

    if p_units is None:
        p_units = [None] * len(param_keys)
    p_ul = [
        to_unitless(parameters[k], _u) for k, _u in zip(param_keys, p_units)
    ]
    c0_widgets = OrderedDict([
        (k,
         Slider(title=k if output_conc_unit is 1 else k + ' / ' +
                output_conc_unit.dimensionality.unicode,
                value=_C(k),
                **slider_kwargs.get(
                    k, dict(start=_C(k) / 2, end=_C(k) * 2, step=_C(k) / 10))))
        for k in rsys.substances
    ])

    def _dict_to_unitless(d, u):
        return {k: to_unitless(v, u) for k, v in d.items()}

    param_widgets = OrderedDict([
        (k,
         Slider(title=k if u is None else k + ' / ' + u.dimensionality.unicode,
                value=v,
                **_dict_to_unitless(
                    slider_kwargs.get(
                        k, dict(start=v / 10, end=v * 10, step=v / 10)), u)))
        for k, v, u in zip(param_keys, p_ul, p_units)
    ])
    all_widgets = list(chain(param_widgets.values(), c0_widgets.values()))

    def update_data(attrname, old, new):
        _c0 = defaultdict(lambda: 0 * output_conc_unit)
        for k, w in c0_widgets.items():
            _c0[k] = w.value * output_conc_unit
        _params = {}
        for (k, w), u in zip(param_widgets.items(), p_units):
            _params[k] = w.value if u is None else w.value * u
        _tout, _Cout, _info = odesys.integrate(tout, _c0, _params)
        for idx, k in enumerate(rsys.substances):
            sources[idx].data = {
                'tout': to_unitless(_tout, output_time_unit),
                k: to_unitless(_Cout[:, idx], output_conc_unit)
            }

    for w in all_widgets:
        w.on_change('value', update_data)

    inputs = VBoxForm(children=all_widgets)
    return HBox(children=[inputs, plot], width=800)
Example #6
0

# Set up callbacks
def update_title(attrname, old, new):
    plot.title = attrname


text.on_change('value', update_title)


def update_data(attrname, old, new):

    # Get the current slider values
    a = amplitude.value
    b = offset.value
    w = phase.value
    k = freq.value

    # Generate the new curve
    x = np.linspace(0, 4 * np.pi, N)
    y = a * np.sin(k * x + w) + b

    source.data = dict(x=x, y=y)


for w in [offset, amplitude, phase, freq]:
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = VBoxForm(children=[text, offset, amplitude, phase, freq])
curdoc().add_root(HBox(children=[inputs, plot], width=800))
Example #7
0
}

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


cities=TextInput(title='location name')
companies=TextInput(title='company name')
industries=TextInput(title='industry name')
x_axis=Select(title='X axis',options=sorted(axis_map.keys()),value='Current Industry')

plot = figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover],x_range=industry[:10],y_range=[0,2000])
plot.rect(x='x',y='y',width=.8,height='height',source=source)
plot.xaxis.major_label_orientation = np.pi/3

controls=[x_axis,cities,companies,industries]
inputs=HBox(VBoxForm(*controls))


def select_types():
    city_val=cities.value.strip()
    company_val=companies.value.strip()
    industry_val=industries.value.strip()
    selected=data_all.copy()
    if(city_val!=""):
        selected=selected[selected['location'].str.contains(city_val)==True]
    if(company_val!=""):
        selected=selected[selected['company'].str.contains(company_val)==True]
    if(industry_val!=""):
        selected=selected[selected['industry'].str.contains(industry_val)==True]

    return selected
Example #8
0

def update_data(attrname, old, new):

    # Get the current slider values
    emax = eps_max.value
    E = modulus.value
    sy = yield_stress.value
    n = hard_exp.value

    # Generate the new curve
    eps = np.linspace(0, emax, N)
    sigma = Hollomon(eps, E=E, sy=sy, n=n)

    source.data = dict(x=eps, y=sigma)
    plot.x_range.end = eps.max()
    plot.y_range.end = sigma.max()


for w in [eps_max, modulus, yield_stress, hard_exp]:
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = VBoxForm(children=[text, eps_max, modulus, yield_stress, hard_exp])

curdoc().add_root(HBox(children=[inputs, plot], width=800))

from bokeh.embed import file_html

html = file_html(plot, "CDN", "my plot")
Example #9
0
    df_outliers_removed = outliers(df_subset, np.float(threshold_value))

    selection_dict = {
        'x': df_outliers_removed[x_feature_value + '_x'],
        'y': df_outliers_removed[y_feature_value + '_y']
    }

    return selection_dict


# Update plot
def update(attr, old, new):

    plot_dict = select_features()

    source.data = plot_dict


# Define controls list
# While server is running, update the values
input_values = [x_feature, y_feature, threshold]
for value in input_values:
    value.on_change('value', update)

inputs = VBox(VBoxForm(*input_values), width=300)

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

curdoc().add_root(HBox(inputs, plot, width=1100))
Example #10
0
    for n, param in enumerate(params):
        # get all parameter values:
        exec(param + " = " + 'param{0}.value'.format(n))

    # Generate the new curve:
    exec(new_plot_info[0])  #  execute y = f(x, params)

    source.data = dict(x=x, y=y)


for w in Slider_instances:
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = VBoxForm(children=Slider_instances)

layout = HBox(children=[inputs, plot], width=800)

# embed app in html template
old_file = "template.html"
new_file = "embed_template.html"
f1 = open(old_file, "r")
f2 = open(new_file, "w+")

for line in f1:
    if "IBPLOT" in line:
        f2.write(autoload_server(layout, session_id=session.id))
    else:
        f2.write(line)
f1.close()
Example #11
0
session = push_session(document)

file_name = "demo"

IBPLOT_tags = find_tags(file_name + ".html")

appLayoutList = []

for app_info in IBPLOT_tags:

    app = CreateApp(app_info)

    for w in app.sliderList:
        w.on_change('value', app.update_data)

    inputs = VBoxForm(children=app.sliderList)

    layout = HBox(children=[inputs, app.plot], width=800)
    document.add_root(layout)
    appLayoutList.append(layout)

# embed app in html template
old_file = file_name + ".html"
new_file = "embed_" + file_name + ".html"
f1 = open(old_file, "r")
f2 = open(new_file, "w+")

appNumber = 0
for line in f1:
    if 'IBPLOT' in line and line[0] != '#' and line[0] != '<':
        f2.write("<p>This app is created by the following tag: </p>")
Example #12
0
    # Generate the new curve
    x = [-cos(theta)]
    y = [-sin(theta)]

    angle_rad = acos(-x[0])
    angle_degree = round(angle_rad * 180. / pi)
    plot.title = titlevalue + str(angle_degree)

    source.data = dict(x=x, y=y)


for w in [mu, tau]:
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = VBoxForm(children=[mu, tau])

layout = HBox(children=[inputs, plot], width=800)

# embed app in html template
old_file = "sliding_ball.html"
new_file = "sliding_ball_embed.html"
f1 = open(old_file, "r")
f2 = open(new_file, "w+")

for line in f1:
    if "APP: [sliding_ball]" in line:
        f2.write(autoload_server(layout, session_id=session.id))
    else:
        f2.write(line)
f1.close()
Example #13
0
select = Select(title="Repay options:", value="base", options=["base", "ASAP"])


def update_data(attrname, old, new):
    # Get the current slider values
    d['debt'] = debt_input.value
    d['repay'] = debt_repay.value
    d['cash'] = cash_start.value
    d['max_cash'] = cash_max.value
    d['pay'] = [s1_input.value, s2_input.value]
    d['expenses'] = expense_input.value
    if select.value == 'base':
        print("In logic ", select.value)
        d['pay_debt_faster'] = False
    else:
        d['pay_debt_faster'] = True
    update_graphic()


interactive_list = [
    debt_input, debt_repay, expense_input, cash_start, cash_max, s1_input,
    s2_input, select
]

for w in interactive_list:
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = VBoxForm(children=interactive_list)
curdoc().add_root(HBox(children=[inputs, plot], width=800))
Example #14
0
def buildDevicesTab():
  gfxVendorSelect = Select(title='Vendor', options=gfxVendors, value=gfxVendors[0])
  gfxDeviceCheckbox = CheckboxGroup()

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

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

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

  fig.add_tools(hover)

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

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

  fig.xaxis.major_label_orientation = np.pi / 3

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

    gfxDeviceCheckbox.labels = deviceNames

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

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

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

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

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

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

  def click(selected):
    update_view()

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

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

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

  return Panel(child=deviceComparison, title="GFX Device Comparison")
Example #15
0
    #inputs = VBoxForm(children=[text, offset, amplitude, phase, freq])

    ticker_input = TextInput(value='SPFB.RTS')
    div_input = TextInput(value='1.')
    length_input = TextInput(value=str(start_candles))
    format_input = TextInput(value='0')
    button = Button(label='Change')
    button.on_click(change_source)

    curdoc().clear()

    curdoc().add_root(
        HBox(children=[
            button, ticker_input, div_input, length_input, format_input
        ],
             width=900))

    for graph in graphs:
        inputs = VBoxForm(children=[graph.box, graph.scale, graph.text])
        curdoc().add_root(HBox(children=[inputs, graph.plot], width=900))

    curdoc().add_periodic_callback(reload_data, data_refresh_interval)

except Exception as e:
    #button = Button(label='Error!')
    #curdoc().add_root(button)
    show_exception_info()
    text = PreText(text=traceback.format_exc())  #str(e)
    curdoc().clear()
    curdoc().add_root(text)
    """
    user_view_has_changed = my_bokeh_utils.check_user_view(
        source_view.data, plot_field)
    if user_view_has_changed:
        u_str = u_input.value
        v_str = v_input.value
        update_quiver_data(u_str, v_str)
        source_view.data = my_bokeh_utils.get_user_view(plot_field)


# calculate data
init_data()

# lists all the controls in our app associated with the default_funs panel
ww = 400
function_controls = VBoxForm(
    children=[u_input, v_input, VBox(width=ww, height=20)], width=ww)
curve_controls = VBoxForm(
    children=[cx_input, cy_input, parameter_input,
              VBox(width=ww, height=10)],
    width=ww)

# Panels for sample functions or default functions
function_panel = Panel(child=function_controls, title='choose function')
curve_panel = Panel(child=curve_controls, title='choose curve')
# Add panels to tabs
tabs = VBox(children=[Tabs(tabs=[function_panel, curve_panel])], width=ww)

# refresh quiver field all 100ms
curdoc().add_periodic_callback(refresh_quiver, 100)
# make layout
curdoc().add_root(
Example #17
0
    df = select_movies()
    x_name = axis_map[x_axis.value]
    y_name = axis_map[y_axis.value]

    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.title = "%d movies selected" % len(df)
    source.data = dict(
        x=df[x_name],
        y=df[y_name],
        color=df["color"],
        title=df["Title"],
        year=df["Year"],
        revenue=df["revenue"],
        alpha=df["alpha"],
    )


controls = [
    reviews, boxoffice, genre, min_year, max_year, oscars, director, cast,
    x_axis, y_axis
]
for control in controls:
    control.on_change('value', update)

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

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

curdoc().add_root(HBox(inputs, p, width=1100))
Example #18
0
text_props['text_font_size'] = "8pt"
plot.text(x=0.825, y=0.15, text="TP", source=conf_source, **text_props)
plot.text(x=0.925, y=0.15, text="FP", source=conf_source, **text_props)
plot.text(x=0.825, y=0.05, text="FN", source=conf_source, **text_props)
plot.text(x=0.925, y=0.05, text="TN", source=conf_source, **text_props)

update_data()

text.on_change('value', input_change)
dataurl.on_change('value', dataurl_change)

# There must be a better way:
dataurl.callback = CustomJS(args=dict(auc=auc,
                                      sample_size=sample_size),
                            code="""
         // $("label[for='"+auc.id+"']").parentNode.remove();
         document.getElementById(auc.id).parentNode.hidden = true;
         // $("label[for='"+sample_size.id+"']").parentNode.remove();
         document.getElementById(sample_size.id).parentNode.hidden = true;
    """)

for w in (threshold, text, auc, sample_size):
    w.on_change('value', input_change)

vbox_items = [text, sample_size, threshold, auc]
if HAS_REQUESTS:
    vbox_items.append(dataurl)
inputs = VBoxForm(*vbox_items)

curdoc().add_root(HBox(inputs, plot, width=800))
Example #19
0
def get_data(f, name):
    shape = f[name].shape
    # Empty array
    data = np.empty(shape, dtype=np.float64)
    # read_direct to empty arrays
    f[name].read_direct(data)
    return data


def select_data():
    data_val = data_select.value
    with h5py.File('demo_data.hdf5', 'r') as f:
        return get_data(f, data_val)


def update_data(attrname, old, new):
    # hardcoded length of 100
    x = list(range(1, 101))
    y = select_data()

    source.data = dict(x=x, y=y)


data_select.on_change('value', update_data)

inputs = VBoxForm(data_select, width=300)

update_data(None, None, None)

curdoc().add_root(HBox(inputs, p, width=1100))
Example #20
0
    if mu_str =='0':
        mu_str = '0.0'
        
    textFile_name = 'data/' + mu_str + '.txt'
    with open(textFile_name, 'r') as filename:
        n = 0
        for line in filename:
            if n == N:
                theta = float(line.split()[1])
            n += 1
            
    filename.close()
    # Generate the new curve
    x = [-cos(theta)]
    y = [-sin(theta)]

    degree_rad = acos(-x[0])
    degree_normal = round(degree_rad*180./pi)
    plot.title = text.value + str(degree_normal)

    source.data = dict(x=x, y=y)

for w in [mu, tau]:
    w.on_change('value', update_data)


# Set up layouts and add to document
inputs = VBoxForm(children=[text, mu, tau])

curdoc().add_root(HBox(children=[inputs, plot], width=800))