Exemple #1
1
def show(sample_size):
    global session
    global scatter_plot
    global source
    global pie_chart_source
    global line_chart_source
    global slider
    DB.__init__(sample_size)
    min_time = DB.min_time()
    max_time = DB.max_time()
    print min_time
    print min_time
    xs, ys, color, time = DB.get_current()
    xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time]
    ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time]
    color = [color[i] for i,v in enumerate(time) if time[i] == min_time]

    time_dict = Counter(time)
    pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color))
    line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict]))
    source = ColumnDataSource(data=dict(x=xs, y=ys, color=color))

    scatter_plot = Figure(plot_height=800,
                          plot_width=1200,
                          title="Plot of Voters",
                          tools="pan, reset, resize, save, wheel_zoom",
                          )

    scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15)
    scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1)

    scatter_plot.x_range.on_change('end', update_coordinates)
    line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350)
    line_chart.line(x='x', y='y', source=line_chart_source)
    pie_chart_plot = Figure(plot_height=350,
                            plot_width=350,
                            title="Voter Distribution",
                            x_range=(-1, 1),
                            y_range=(-1, 1))
    pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color")
    slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time")

    slider.on_change('value', update_coordinates)
    h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart))
    vplot(slider, h, width=1600, height=1800)
    session = push_session(curdoc())
    session.show()
    #script = autoload_server(scatter_plot, session_id=session.id)
    session.loop_until_closed()
Exemple #2
0
    def use_server_to_change_glyphs(self):
        source_original = ColumnDataSource(
            dict(average_grades=[7, 8, 10],
                 exam_grades=[6, 9, 8],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        source = ColumnDataSource(
            dict(average_grades=[7, 8, 10],
                 exam_grades=[6, 9, 8],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        # create the figure
        f = figure(x_range=Range1d(start=0, end=12),
                   y_range=Range1d(start=0, end=12))

        # 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 filtering function
        def filter_grades(attr, old, new):
            source.data = {
                key: [
                    value for i, value in enumerate(source_original.data[key])
                    if source_original.data["exam_grades"][i] >= slider.value
                ]
                for key in source_original.data
            }
            print(slider.value)

        # create label 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)

        slider = Slider(start=min(source_original.data["exam_grades"]) - 1,
                        end=max(source_original.data["exam_grades"]) + 1,
                        value=8,
                        step=0.1,
                        title="Exam Grade: ")
        slider.on_change("value", filter_grades)

        # create layout and add to curdoc
        lay_out = layout([[select], [slider]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Exemple #3
0
class DynamicSimulRow:
    """Clase DynamicSimulRow para representar una fila dinámica con slider y textbox.

    Attributes:
		start: Valor inicial del slider
		end: Valor final del slider
		value: Valor por defecto del slider y el textbox
		title: Título del slider
    """
    def __init__(self, start, end, value, title):
        self.start = start
        self.end = end
        self.value = value
        self.title = title
        self.slider = Slider(start=self.start,
                             end=self.end,
                             value=self.value,
                             step=0.1,
                             title=self.title,
                             min_width=580)
        self.text_input = TextInput(value=f"{self.value:.2f}", max_width=100)
        self.dyn_row = row([self.slider, self.text_input],
                           sizing_mode='stretch_height')
        self.slider.on_change('value', self.slider_handler)
        self.text_input.on_change('value', self.text_handler)

    def slider_handler(self, attrname, old, new):
        self.text_input.value = f"{new:.2f}"

    def text_handler(self, attrname, old, new):
        self.slider.value = float(new)
Exemple #4
0
def make_page_flow(doc):
    
#    return make_document(doc)
#    if __name__=='__main__':
#        df = pd.read_csv('salary_data.csv')
#    else:
#    #    df = pd.read_csv('./bokeh_pages/salary_data.csv')
    df = pd.read_csv(fileName_csv_source)
#    
    source = ColumnDataSource(data=dict())

    def update():
        print ("slider update")
#        current = df[df['salary'] <= slider.value].dropna()  # df ##
#        adjustment by https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/fPAoHTyMcuQ
        current = df[df['salary'] <= slider.value].dropna() # df ##
#        print (list(current.name))
#        print (type(current.salary)) # <class 'pandas.core.series.Series'>
#        print (type(current.years_experience))
        source.data = {
            'name'             : list(current.name),
            'salary'           : list(current.salary),
            'years_experience' : list(current.years_experience),
        }
    
    slider = Slider(title="values range", start=0, end=100000, value=20000, step=1)
    slider.on_change('value', lambda attr, old, new: update())
    
    def on_button_change():
        print("visiting on button change")
    button = Button(label="Phase #1 ", button_type="success") # button_type: ‘default’, ‘primary’, ‘success’, ‘warning’, ‘danger’, ‘link’
    button.on_click(on_button_change)
#    button.callback = CustomJS(args=dict(source=source),
#                               code=open(join(dirname(__file__), "download.js")).read())
    
    columns = [
        TableColumn(field="name", title="Employee Name"),
        TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")),
        TableColumn(field="years_experience", title="Experience (years)")
    ]
    
    data_table = DataTable(source=source, columns=columns, width=800)
    
    controls = widgetbox(slider, button)
    table = widgetbox(data_table)
    
    total_row = row(controls, table)
    
    doc_add_root(doc, total_row, title = 'work flow page')
#    if __name__!='__main__':    
#        print("doc : ", str(doc))
#        print("name : ",__name__)
#        doc().add_root(row(controls, table))
#        doc().title = "work flow page, from caller"
#    elif __name__=='__main__':   
#        print("doc : ", str(doc)) 
#        doc.add_root(row(controls, table))
#        doc.title = "work flow page, from main"
    
    update()
Exemple #5
0
    def init_solar_wx(self):

        sun_luminos_slider = Slider(
            start=0.1,
            end=10,
            step=0.1,
            value=self.rel_solar_lum,
            title='Relative Solar Luminosity (Solar Units)')

        earth_radius_slider = Slider(start=0.1,
                                     end=10,
                                     step=0.1,
                                     value=self.dist_from_sun_au,
                                     title='Distance from Sun (AU)')

        def _lum_handler(attr, old, new):
            self.rel_solar_lum = new
            self.update_solar_in()
            self.update_input_rays()
            self._update_atm_refl()

        def _radius_handler(attr, old, new):
            self.dist_from_sun_au = new
            self.update_solar_in()
            self.update_input_rays()
            self._update_atm_refl()

        sun_luminos_slider.on_change('value', _lum_handler)
        earth_radius_slider.on_change('value', _radius_handler)

        solar_sliders = WidgetBox(sun_luminos_slider, earth_radius_slider)

        return [solar_sliders]
    def add_slider(self, min, max, step, init, title, callback=None):
        slider = Slider(start=min, end=max, value=init, step=step, title=title)

        slider.on_change('value', self.slider_handler_callback)
        self.slider_callback = callback

        self.layout = column(self.plot, widgetbox(slider))
Exemple #7
0
def app(doc):

    # Set up data
    N = 200
    x = np.linspace(0, 4*np.pi, N)
    y = np.sin(x)
    source = ColumnDataSource(data=dict(x=x, y=y))

    # Set up plot
    plot = figure(plot_height=400, plot_width=400, title="my sine wave",
                  tools="crosshair,pan,reset,save,wheel_zoom",
                  x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])

    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

    freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)

    def update_data(attrname, old, new):
        k = freq.value
        # Generate the new curve
        x = np.linspace(0, 4*np.pi, N)
        y = np.sin(k*x)
        source.data = dict(x=x, y=y)

    freq.on_change('value', update_data)

    widget_box = widgetbox(freq)
    doc.add_root(row(widget_box, plot, width=800))
    doc.title = "Sliders"
    def createSnakeControls(self):
        #snake mode controls
        snakeModeControls = RadioButtonGroup(labels=["Square", "LED"],
                                             active=0,
                                             width=400,
                                             button_type="primary")
        # snakeModeControls.on_change("active",self.visibilityCallback)

        self.snakeSpeed = 500
        snakeSpeedSlider = Slider(title="Speed",
                                  show_value=False,
                                  value=self.snakeSpeed,
                                  start=30,
                                  end=1000,
                                  step=5)
        snakeSpeedSlider.on_change("value", self.snakeSpeedCallback)
        snakeNumberControls = RadioButtonGroup(labels=["1", "2"],
                                               active=0,
                                               width=400,
                                               button_type="primary",
                                               name="Num Snakes")
        snakeColorWindow = self.createColorOutputWindow(2)

        sendSnakeButton = Button(label="Send")
        sendSnakeButton.on_click(self.postSnake)

        return [
            snakeModeControls, snakeNumberControls, snakeSpeedSlider,
            snakeColorWindow, sendSnakeButton
        ]
Exemple #9
0
class DerivViewer(object):

    def __init__(self):
        self.xs = np.linspace(-2.0, 2.0, 100)
        self.ys = test_func(self.xs)

        self.source1 = ColumnDataSource(data=dict(xs=self.xs,
                                                  ys=self.ys))
        a = 0
        txs, tys = get_tangentdata(a)
        self.source2 = ColumnDataSource(data=dict(txs=txs,
                                                  tys=tys))
        self.source3 = ColumnDataSource(data=dict(x=[a], y=[test_func(a)]))
        self.fig = figure(title='view tangent line',
                          x_range=(-2.0, 2.0),
                          y_range=(-0.2, 1.2))
        self.fig.line('xs', 'ys', source=self.source1)
        self.fig.line('txs', 'tys', source=self.source2, color='orange')
        self.fig.circle('x', 'y', source=self.source3, color='red')

        self.slider = Slider(title='position',
                             value=0,
                             start=-1.5,
                             end=1.5,
                             step=0.1)
        self.slider.on_change('value', self.update_data)
        self.plot = column(self.slider, self.fig)

    def update_data(self, attr, old, new):
        a = self.slider.value
        txs, tys = get_tangentdata(a)
        self.source2.data = dict(txs=txs, tys=tys)
        self.source3.data = dict(x=[a], y=[test_func(a)])
Exemple #10
0
class slider():
    def __init__(self, widget_lst, label, start, end, step, callback_throttle,
                 default):
        self.label = label
        self.start = start
        self.end = end
        self.step = step
        self.callback_throttle = callback_throttle
        self.default = default
        self.slider = None
        self.callback = None
        # self.initialize(label, start, end, step, callback_throttle, default)
        widget_lst.append(self)

    def initialize(self, widget_lst):
        self.slider = Slider(start=self.start,
                             end=self.end,
                             value=self.default,
                             step=self.step,
                             title=self.label)
        widget_lst.append(self.slider)
        if self.callback is not None:
            self.slider.on_change('value', self.callback)

    def add_callback(self, callback):
        self.callback = callback
        if self.slider is not None:
            self.slider.on_change('value',
                                  self.callback)  #May not keep that one

    def set_value(self, value):
        if self.slider is not None:
            self.slider.value = value
        self.default = value
Exemple #11
0
class DerivViewer(object):
    def __init__(self):
        self.xs = np.linspace(-2.0, 2.0, 100)
        self.ys = test_func(self.xs)

        self.source1 = ColumnDataSource(data=dict(xs=self.xs, ys=self.ys))
        a = 0
        txs, tys = get_tangentdata(a)
        self.source2 = ColumnDataSource(data=dict(txs=txs, tys=tys))
        self.source3 = ColumnDataSource(data=dict(x=[a], y=[test_func(a)]))
        self.fig = figure(title='view tangent line',
                          x_range=(-2.0, 2.0),
                          y_range=(-0.2, 1.2))
        self.fig.line('xs', 'ys', source=self.source1)
        self.fig.line('txs', 'tys', source=self.source2, color='orange')
        self.fig.circle('x', 'y', source=self.source3, color='red')

        self.slider = Slider(title='position',
                             value=0,
                             start=-1.5,
                             end=1.5,
                             step=0.1)
        self.slider.on_change('value', self.update_data)
        self.plot = column(self.slider, self.fig)

    def update_data(self, attr, old, new):
        a = self.slider.value
        txs, tys = get_tangentdata(a)
        self.source2.data = dict(txs=txs, tys=tys)
        self.source3.data = dict(x=[a], y=[test_func(a)])
Exemple #12
0
def interactive_field_history(doc, fld=None, islice=0, dgrid=0):
    """         
    
    Use with code similar to:
    
    my_fld =  parsers.parse_genesis_fld(fld_fname, g.input_params['ncar'], nslice)
    
    from bokeh.plotting import show, output_notebook
    output_notebook()
    
    def app(doc):
       return interactive_field_history(doc, fld=my_fld, dgrid=dgrid, slice = 0)
    show(app)
    
    
    """

    nhist = fld.shape[3]

    ihist = nhist - 1

    fdat = fld[:, :, islice, ihist]

    d = np.angle(fdat)
    ds = ColumnDataSource(data=dict(image=[d]))

    xyrange = (-1000 * dgrid, 1000 * dgrid)
    p = figure(x_range=xyrange,
               y_range=xyrange,
               title='Phase',
               plot_width=500,
               plot_height=500,
               x_axis_label='x (mm)',
               y_axis_label='y (mm)')
    p.image(image='image',
            source=ds,
            x=-dgrid * 1000,
            y=-dgrid * 1000,
            dw=2 * dgrid * 1000,
            dh=2 * dgrid * 1000,
            palette=pal)

    slider = Slider(start=0,
                    end=nhist - 1,
                    value=ihist,
                    step=1,
                    title='History')

    def handler(attr, old, new):
        fdat = fld[:, :, islice, new]
        d = np.angle(fdat)
        ds.data = dict(ColumnDataSource(data=dict(image=[d])).data)

    slider.on_change('value', handler)

    doc.add_root(column(slider, p))
Exemple #13
0
class Create():
    def __init__(self):
        dateNow = datetime.now()
        self.startDay = DatePicker(title="Start Date",
                                   min_date=datetime(2000, 1, 1),
                                   max_date=datetime(2030, 12, 31),
                                   value=datetime(dateNow.year, dateNow.month,
                                                  dateNow.day))

        # snapshot time hours minutes
        self.Hour = Slider(title="Time of day [h]",
                           value=1.0,
                           start=1.0,
                           end=24.0,
                           step=0.25)
        self.timeStep = Slider(title="Time step [min]",
                               value=15.0,
                               start=1.0,
                               end=60.0,
                               step=1.0)
        self.timeStep.on_change('value', self.updateHourSlider)

        r1 = row(self.startDay, self.Hour, self.timeStep)

        self.Vul = Slider(title="Voltage upper limit [p.u]",
                          value=1.05,
                          start=0.9,
                          end=1.1,
                          step=0.005)
        self.Vll = Slider(title="Voltage lower limit [p.u]",
                          value=0.95,
                          start=0.9,
                          end=1.1,
                          step=0.005)
        self.Lul = Slider(title="Loading upper limit [%]",
                          value=90,
                          start=0,
                          end=120,
                          step=1)

        r2 = row(self.Vll, self.Vul, self.Lul)
        self.final_layout = column(r1, r2)
        return

    def GetLineSliders(self):
        return self.Vll, self.Vul, self.Lul

    def layout(self):
        return self.final_layout

    def updateHourSlider(self, attr, old, new):
        self.Hour.step = self.timeStep.value / 60
        return

    def UpdatePlot(self):
        return
Exemple #14
0
def gamma_shape(doc):
    alpha = 3
    x = np.linspace(0, gamma.ppf(0.999, alpha), 100)
    y = gamma.pdf(x, alpha)

    source = ColumnDataSource(data={'x_1': x, 'y_1': y})

    # tooltips_formatting =[('random variable', '@x_1'), ('PD', '@y_1')]
    # or
    tooltips_formatting = """
                        <div>
                            <div>
                                <span style="font-size: 14px; color: #3c6978">random variable: </span>
                                <span style="font-size: 14px; float: right;  margin: 0px 0px 0px 15px">@x_1</span>
                            </div>
                            <div>
                                <span style="font-size: 14px; color: #3c6978">max:</span>
                                <span style="font-size: 14px; float: right; margin: 0px 0px 0px 15px">@y_1</span>
                            </div>
                        </div>
                        """

    p = figure(plot_width=700,
               plot_height=600,
               title="Gamma distribution",
               tooltips=tooltips_formatting)

    p.line(x='x_1', y='y_1', line_width=2, source=source)

    p.x_range.start = 0
    p.xaxis.axis_label = 'Random variable'
    p.yaxis.axis_label = 'Probability density'

    def callback_shape(attr, old, new):
        x_updated = np.linspace(0, gamma.ppf(0.999, new), 100)
        y_updated = gamma.pdf(source.data['x_1'], new)
        new_source = ColumnDataSource(data={
            'x_1': x_updated,
            'y_1': y_updated
        })
        source.data.update(new_source.data)

    slider_shape = Slider(start=1,
                          end=30,
                          value=3,
                          step=.1,
                          title="Gamma shape")
    slider_shape.on_change('value', callback_shape)

    doc.add_root(column(slider_shape, p))
    doc.theme = Theme(json=yaml.load("""
            attrs:
                Figure:
                    height: 600
                    width: 800
        """))
Exemple #15
0
def index():  
    slider_freq = Slider(orientation="horizontal", start=1, end=5, value=1, step=1, name="freq1", title = "Frequency")
    slider_freq.on_change('value', eventHandler, 'input_change')

    layout = HBox(
        children = [slider_freq]
    )
    script, div = components(layout)

    return render_template('index.html', script = script, div = div)
Exemple #16
0
 def make_slider(self, callback_func, title, init_val, start_val, end_val,
                 step):
     #スライダーを作る関数
     slider = Slider(title=title,
                     value=init_val,
                     start=start_val,
                     end=end_val,
                     step=step)
     slider.on_change('value', callback_func)
     return slider
Exemple #17
0
def render_vizard(doc):
    args = doc.session_context.request.arguments
    req_path = args["req_path"][0].decode('utf-8')

    data = logparser.read_output_log(req_path)
    hover = create_hover_tool()

    score_plot, score_source = create_score_chart(data, title="Scores", x_name="Step", y_name="Average Score",
                                                  text_font_size="20pt")

    molecule_plot = create_2d_molecule(data, position=-1)
    slider = Slider(start=-1, end=len(data) - 1, value=-1, step=1, title="Step")

    template = """<span data-toggle="tooltip" title="<%= value %>"><%= svg %></span>"""
    columns = [
        TableColumn(field="Step", title="Step"),
        TableColumn(field="Score", title="Score"),
        TableColumn(field="SMILES", title="SMILES", formatter=HTMLTemplateFormatter(template=template)),
    ]
    smiles, score = extract_compounds(data, -1)
    molsvg = [create_hover_svg(smi) for smi in smiles]
    tabledf = dict(Step=[get_position(data, -1)] * len(smiles), SMILES=smiles, Score=score, svg=molsvg)
    table_source = ColumnDataSource(data=tabledf)
    data_table = DataTable(source=table_source, columns=columns, width=900, height=400)

    def slider_callback(attr, old, new):
        new = int(new)
        data = score_source.data["raw_data"]
        new_molecule_plot = create_2d_molecule(data, position=new)
        molecule_plot.text = new_molecule_plot.text
        smiles, score = extract_compounds(data, new)
        molsvg = [create_hover_svg(smi) for smi in smiles]
        tabledf = dict(Step=[get_position(data, new)] * len(smiles), SMILES=smiles, Score=score, svg=molsvg)
        table_source.data = tabledf

    def redraw_new_sliderend(attr, old, new):
        if slider.value == -1:
            slider_callback(attr, -1, -1)

    slider.on_change('value', slider_callback)
    slider.on_change('end', redraw_new_sliderend)

    bokehlayout = layout([row(column(molecule_plot, slider), score_plot), ], sizing_mode="fixed")
    doc.add_root(bokehlayout)

    def check_new_data():
        newdata = logparser.read_output_log(req_path)
        if len(newdata) > len(score_source.data["raw_data"]):
            x, y = extract_average_scores(newdata)
            y_mean = running_average(y, 50)
            score_source.data.update(x=x.tolist(), y=y.tolist(), y_mean=y_mean.tolist(), raw_data=newdata)
            slider.end = len(x) - 1

    doc.add_periodic_callback(check_new_data, 1000)
    doc.theme = Theme(filename=os.path.dirname(os.path.realpath(__file__)) + "/templates/theme.yaml")
Exemple #18
0
    def create_layout(self):

        # create figure
        self.x_range = Range1d(start=self.model.map_extent[0],
                               end=self.model.map_extent[2], bounds=None)
        self.y_range = Range1d(start=self.model.map_extent[1],
                               end=self.model.map_extent[3], bounds=None)

        self.fig = Figure(tools='wheel_zoom,pan', x_range=self.x_range,
                          y_range=self.y_range)
        self.fig.plot_height = 660
        self.fig.plot_width = 990
        self.fig.axis.visible = False

        # add tiled basemap
        self.tile_source = WMTSTileSource(url=self.model.basemap)
        self.tile_renderer = TileRenderer(tile_source=self.tile_source)
        self.fig.renderers.append(self.tile_renderer)

        # add datashader layer
        self.image_source = ImageSource(url=self.model.service_url,
                                        extra_url_vars=self.model.shader_url_vars)
        self.image_renderer = DynamicImageRenderer(image_source=self.image_source)
        self.fig.renderers.append(self.image_renderer)

        # add ui components
        axes_select = Select.create(name='Axes',
                                        options=self.model.axes)
        axes_select.on_change('value', self.on_axes_change)

        field_select = Select.create(name='Field', options=self.model.fields)
        field_select.on_change('value', self.on_field_change)

        aggregate_select = Select.create(name='Aggregate',
                                         options=self.model.aggregate_functions)
        aggregate_select.on_change('value', self.on_aggregate_change)

        transfer_select = Select.create(name='Transfer Function',
                                        options=self.model.transfer_functions)
        transfer_select.on_change('value', self.on_transfer_function_change)

        basemap_select = Select.create(name='Basemap', value='Toner',
                                       options=self.model.basemaps)
        basemap_select.on_change('value', self.on_basemap_change)

        opacity_slider = Slider(title="Opacity", value=100, start=0,
                                end=100, step=1)
        opacity_slider.on_change('value', self.on_opacity_slider_change)

        controls = [axes_select, field_select, aggregate_select,
                    transfer_select, basemap_select, opacity_slider]
        self.controls = HBox(width=self.fig.plot_width, children=controls)
        self.layout = VBox(width=self.fig.plot_width,
                           height=self.fig.plot_height,
                           children=[self.controls, self.fig])
Exemple #19
0
def make_page_flow(doc):
    
#    return make_document(doc)
#    if __name__=='__main__':
#        df = pd.read_csv('salary_data.csv')
#    else:
#    #    df = pd.read_csv('./bokeh_pages/salary_data.csv')
    df = pd.read_csv(fileName)
#    
    source = ColumnDataSource(data=dict())

    def update():
        print ("slider update")
        current = df[df['salary'] <= slider.value].dropna()  # df ## 
        source.data = {
            'name'             : current.name,
            'salary'           : current.salary,
            'years_experience' : current.years_experience,
        }
    
    slider = Slider(title="values range", start=0, end=100000, value=50000, step=1)
    slider.on_change('value', lambda attr, old, new: update())
    
    def on_button_change():
        print("visiting on button change")
    button = Button(label="phase #1 ", button_type="success") # button_type: ‘default’, ‘primary’, ‘success’, ‘warning’, ‘danger’, ‘link’
    button.on_click(on_button_change)
#    button.callback = CustomJS(args=dict(source=source),
#                               code=open(join(dirname(__file__), "download.js")).read())
    
    columns = [
        TableColumn(field="name", title="Employee Name"),
        TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")),
        TableColumn(field="years_experience", title="Experience (years)")
    ]
    
    data_table = DataTable(source=source, columns=columns, width=800)
    
    controls = widgetbox(slider, button)
    table = widgetbox(data_table)
    if __name__!='__main__':    
        print("doc : ", doc)
        print("name : ",__name__)
        doc().add_root(row(controls, table))
        doc().title = "work flow page, from caller"
    elif __name__=='__main__':    
        doc.add_root(row(controls, table))
        doc.title = "work flow page, from main"
    
#    if __name__=='__main__':
    update()
Exemple #20
0
def modify_doc(doc):
    p = Paragraph(text=""" """, width=800, height=100)

    def callback(attr, old, new):
        print(
            "called"
        )  # This outputs to console (In Jupyter goes back to UI via Jupyter websocket)
        p.text = "{}:{}->{}".format(
            attr, old, new)  # This outputs to widget UI via bokeh websocket

    slider_bokeh = Slider(start=0, end=100, value=1, step=.1, title="Stuff")

    # widget on_change event can only with bokeh server
    slider_bokeh.on_change("value", callback)
    doc.add_root(widgetbox(p, slider_bokeh))
Exemple #21
0
	def init_controls(self):
		btnStop = Button(label="Stop", type="danger")
		btnStart = Button(label="Start", type="success")	
		
		btnStop.on_click(self.handle_btnStop_press)
		btnStart.on_click(self.handle_btnStart_press)
				
		curdoc().add_root(btnStop)
		curdoc().add_root(btnStart)
		

		sliderHPThreshold = Slider(start=0, end=500, value=100, step=1, title="High pass threshold")
			
		sliderHPThreshold.on_change('value', self.onChangeHPThreshold)
		curdoc().add_root(vplot(sliderHPThreshold))
Exemple #22
0
class RotationViewer(object):
    def __init__(self):
        xs = np.linspace(-np.pi, np.pi, 11)
        ys = xs
        Xs, Ys = np.meshgrid(xs, ys)
        self.Xs, self.Ys = Xs.flatten(), Ys.flatten()
        initdegree = 0
        mat = rot_mat(initdegree)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])

        TOOLS = "pan,lasso_select,save,reset"

        self.source = ColumnDataSource(data=dict(
            Xs=self.Xs, Ys=self.Ys, transXs=transXs, transYs=transYs))

        self.fig = figure(tools=TOOLS,
                          title="target",
                          x_range=(-np.pi * np.sqrt(2) - 1,
                                   np.pi * np.sqrt(2) + 1),
                          y_range=(-np.pi * np.sqrt(2) - 1,
                                   np.pi * np.sqrt(2) + 1))
        self.fig.circle('Xs', 'Ys', source=self.source)

        self.transfig = figure(tools=TOOLS,
                               title="transformed",
                               x_range=self.fig.x_range,
                               y_range=self.fig.y_range)
        self.transfig.circle('transXs', 'transYs', source=self.source, size=6)

        self.rot_param = Slider(title="degree",
                                value=0,
                                start=0,
                                end=360,
                                step=1)
        self.rot_param.on_change('value', self.update_data)

        self.plot = column(self.rot_param, gridplot([[self.fig,
                                                      self.transfig]]))

    def update_data(self, attr, old, new):
        mat = rot_mat(self.rot_param.value)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])
        self.source.data = dict(Xs=self.Xs,
                                Ys=self.Ys,
                                transXs=transXs,
                                transYs=transYs)
        self.transfig.title.text = "degree {}".format(self.rot_param.value)
Exemple #23
0
def make_table():
    if __name__ == '__main__':
        df = pd.read_csv('salary_data.csv')
    else:
        #    df = pd.read_csv('./bokeh_pages/salary_data.csv')
        df = pd.read_csv('salary_data.csv')

    source = ColumnDataSource(data=dict())

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

    slider = Slider(title="Max Salary",
                    start=10000,
                    end=250000,
                    value=150000,
                    step=1000)
    slider.on_change('value', lambda attr, old, new: update())

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

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

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

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

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

    update()
Exemple #24
0
    def init_controls(self):
        btnStop = Button(label="Stop", type="danger")
        btnStart = Button(label="Start", type="success")

        btnStop.on_click(self.handle_btnStop_press)
        btnStart.on_click(self.handle_btnStart_press)

        curdoc().add_root(btnStop)
        curdoc().add_root(btnStart)

        sliderHPThreshold = Slider(start=0,
                                   end=500,
                                   value=100,
                                   step=1,
                                   title="High pass threshold")

        sliderHPThreshold.on_change('value', self.onChangeHPThreshold)
        curdoc().add_root(vplot(sliderHPThreshold))
Exemple #25
0
def main():
    state_xs, state_ys = get_us_state_outline()
    left, right = minmax(state_xs)
    bottom, top = minmax(state_ys)
    plot = Figure(title=TITLE, plot_width=1000,
                  plot_height=700,
                  tools="pan, wheel_zoom, box_zoom, reset",
                  x_range=Range1d(left, right),
                  y_range=Range1d(bottom, top),
                  x_axis_label='Longitude',
                  y_axis_label='Latitude')

    plot_state_outline(plot, state_xs, state_ys)

    density_overlay = DensityOverlay(plot, left, right, bottom, top)
    density_overlay.draw()

    grid_slider = Slider(title="Details", value=density_overlay.gridcount,
                         start=10, end=100, step=10)
    grid_slider.on_change("value", density_overlay.grid_change_listener)

    radiance_slider = Slider(title="Min. Radiance",
                             value=density_overlay.radiance,
                             start=np.min(density_overlay.rad),
                             end=np.max(density_overlay.rad), step=10)
    radiance_slider.on_change("value", density_overlay.radiance_change_listener)

    listener = ViewListener(plot, density_overlay, name="viewport")

    plot.x_range.on_change("start", listener)
    plot.x_range.on_change("end", listener)
    plot.y_range.on_change("start", listener)
    plot.y_range.on_change("end", listener)

    backends = ["CPU", "HSA"]
    default_value = backends[kde.USE_HSA]
    backend_select = Select(name="backend", value=default_value,
                            options=backends)
    backend_select.on_change('value', density_overlay.backend_change_listener)

    doc = curdoc()
    doc.add(VBox(children=[plot, grid_slider, radiance_slider, backend_select]))
    doc.add_periodic_callback(density_overlay.periodic_callback, 0.5)
Exemple #26
0
    def setupControls(self):
        repeatResolutionSlider = Slider(
            start=1, end=10, value=1, step=1, title="Repeat resolution"
        )  #,width = self.figureWidth,height = self.buttonHeight)
        repeatResolutionSlider.on_change("value",
                                         self.repeatResolutionCallback)

        chunkModeButtons = RadioButtonGroup(
            labels=["Time", "Sample"], active=0, button_type="warning"
        )  #,width=self.buttonWidth,height = self.buttonHeight)
        chunkModeButtons.on_change("active", self.chunkModeCallback)

        yAxisModeButtons = RadioButtonGroup(labels=["Linear", "Log"],
                                            active=0,
                                            button_type="warning")
        yAxisModeButtons.on_change("active", self.yAxisModeCallback)

        self.controls = row(repeatResolutionSlider, chunkModeButtons,
                            yAxisModeButtons)
Exemple #27
0
    def init_slider_widget(cls,
                           update_value_callback,
                           on_change_callback,
                           title="Default",
                           start=1,
                           end=10,
                           step=1,
                           value=None):
        if not value:
            value = cls.get_value_or_none(update_value_callback)

        slider = Slider(start=start,
                        end=end,
                        value=value,
                        step=step,
                        title=title)
        slider.on_change('value', on_change_callback)

        return SliderWidget(slider, update_value_callback)
    def createFadeOutControls(self):
        self.fadeSpeed = 500
        fadeSpeedSlider = Slider(title="Speed",
                                 show_value=False,
                                 value=self.fadeSpeed,
                                 start=30,
                                 end=1000,
                                 step=5)
        fadeSpeedSlider.on_change("value", self.fadeSpeedCallback)

        self.fadeStride = .1
        fadeStrideSlider = Slider(title="Stride",
                                  show_value=False,
                                  value=self.fadeStride,
                                  start=.01,
                                  end=.2,
                                  step=.01)
        fadeStrideSlider.on_change("value", self.fadeStrideCallback)

        return [fadeSpeedSlider, fadeStrideSlider]
Exemple #29
0
class slider():
    def __init__(self, widget_lst, label, start, end, step, callback_throttle,
                 default):
        self.widget_lst = widget_lst
        self.slider = None
        self.initialize(label, start, end, step, callback_throttle, default)

    def initialize(self, label, start, end, step, callback_throttle, default):
        self.slider = Slider(start=start,
                             end=end,
                             value=default,
                             step=step,
                             title=label,
                             callback_throttle=callback_throttle)
        self.widget_lst.append(self.slider)

    def add_callback(self, callback):
        self.slider.on_change('value', callback)

    def set_value(self, value):
        self.slider.value = value
    def update(attr, old, new):
        doc.clear()
        network = make_dataset(0)
        if new > 0:
            new_network = make_dataset(new)
            network.update(new_network)

        timeselect_slider = Slider(start=0,
                                   end=1000,
                                   value=new,
                                   value_throttled=new,
                                   step=1,
                                   title="Time",
                                   callback_policy='mouseup')
        timeselect_slider.on_change('value_throttled', update)

        p = make_plot(network)

        controls = WidgetBox(timeselect_slider)
        layout = row(controls, p)

        doc.add_root(layout)
Exemple #31
0
class RotationViewer(object):

    def __init__(self):
        xs = np.linspace(-np.pi, np.pi, 11)
        ys = xs
        Xs, Ys = np.meshgrid(xs, ys)
        self.Xs, self.Ys = Xs.flatten(), Ys.flatten()
        initdegree = 0
        mat = rot_mat(initdegree)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])

        TOOLS = "pan,lasso_select,save,reset"

        self.source = ColumnDataSource(data=dict(Xs=self.Xs, Ys=self.Ys,
                                                 transXs=transXs,
                                                 transYs=transYs))

        self.fig = figure(tools=TOOLS, title="target",
                          x_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1),
                          y_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1))
        self.fig.circle('Xs', 'Ys', source=self.source)

        self.transfig = figure(tools=TOOLS, title="transformed",
                               x_range=self.fig.x_range, y_range=self.fig.y_range)
        self.transfig.circle('transXs', 'transYs', source=self.source, size=6)

        self.rot_param = Slider(title="degree", value=0,
                                start=0, end=360, step=1)
        self.rot_param.on_change('value', self.update_data)

        self.plot = column(self.rot_param, gridplot([[self.fig, self.transfig]]))

    def update_data(self, attr, old, new):
        mat = rot_mat(self.rot_param.value)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])
        self.source.data = dict(Xs=self.Xs, Ys=self.Ys,
                                transXs=transXs, transYs=transYs)
        self.transfig.title.text = "degree {}".format(self.rot_param.value)
Exemple #32
0
def make_layout():
    """Inclui o gráficos e os controles no curdoc do Bokeh Server."""
    plot = Plot(DISTS)
    numbins_slider = Slider(title="Number of bins",
                            value=10,
                            start=5,
                            end=15,
                            step=1)
    div = Div(text="<b>Goodness of fit tests (p-values)</b>")
    table = fit_table([dist.name for dist in DISTS])

    def numbins_slider_callback(attr, old, new):  # pylint: disable=unused-argument
        """Função que atualiza o histograma e a CDF dos observações."""
        hist, edges = np.histogram(plot.values, density=True, bins=new)
        plot.update_histogram(hist, edges)
        data = plot.cumulative_source.data
        chi = [chi_squared(plot.values, dist.cdf, new) for dist in DISTS]
        ks = [kolmogorov_smirnov(plot.values, dist.cdf) for dist in DISTS]
        wms = [weverton(dist.cdf, data["x"], data["y"]) for dist in DISTS]
        table.source.data.update(ks=ks, chi=chi, wms=wms)  # pylint: disable=no-member

    def upload_callback(attr, old, new):
        """Função que atualiza os dados do plot com os dados do arquivo enviado."""
        file_contents = base64.b64decode(new)
        file_contents_bytes = io.BytesIO(file_contents)
        observed = np.loadtxt(file_contents_bytes)
        plot.update_data(observed)
        numbins_slider.value = plot.num_bins
        numbins_slider.end = len(observed) // 3
        numbins_slider_callback(attr, old, numbins_slider.value)

    button = FileInput()
    button.on_change("value", upload_callback)
    numbins_slider.on_change("value", numbins_slider_callback)
    controls = column(button, numbins_slider, div, table, width=300)
    return row(controls, plot.layout, sizing_mode="scale_height")
Exemple #33
0
def root():
    # Konstante für maximale X-Ausdehnung
    N = 100
    X_MAX = 4 * np.pi
    k = 1

    # Definiere Initiale Daten
    x = np.linspace(0, X_MAX, N)
    y = np.sin(k * x)

    # Definiere eine Datenquelle
    source = ColumnDataSource(data=dict(x=x, y=y))

    # Ein Plot-Objekt wird definiert
    plot = figure()
    # welches einen Linien-Plot beinhaltet
    plot.line('x', 'y', source=source)

    # Ein Schieberegler wird definiert
    freq = Slider(title="freq", value=1.0, start=1, end=105, step=0.1)

    # Diese Funktion soll gerufen werden, wenn der Schieberegler sich ändert ..
    def update_data(attrname, old, new):
        k = freq.value
        x = np.linspace(0, X_MAX, N)
        y = np.sin(k * x)
        source.data = dict(x=x, y=y)

    # .. was hier verdrahtet wird
    freq.on_change('value', update_data)

    # Hier wird eine Box im Browser erzeut, welche den Schieberegler enthält
    inputs = widgetbox(freq)

    # Diese Box wird zurück übergeben
    return row(inputs, plot, width=800)
Exemple #34
0
    def init_slider_wx(self):
        t_eff_slider = Slider(start=1000, end=40000, step=100, value=6000,
                              title='Star Effective Temperature (K)')
        luminosity_slider = Slider(start=-5, end=5, step=0.1, value=0,
                                   title='Relative Luminosity (10^x, solar units)')
        planet_radius_slider = Slider(start=0.1, end=4, step=0.1, value=1,
                                      title='Relative Planet Radius (earth radii)')
        planet_distance_slider = Slider(start=-1, end=3, step=0.1, value=0,
                                        title='Relative Planet Distance (10^x, AU)')

        t_eff_slider.on_change('value', self._t_eff_handler)
        luminosity_slider.on_change('value', self._luminosity_handler)
        planet_radius_slider.on_change('value', self._planet_radius_handler)
        planet_distance_slider.on_change('value', self._planet_dist_handler)

        star_wx = WidgetBox(t_eff_slider, luminosity_slider)
        planet_wx = WidgetBox(planet_radius_slider, planet_distance_slider)

        return [star_wx, planet_wx]
# text input for input of the parametrized curve [cx(t),cy(t)]
cx_input = TextInput(value=curveintegral_settings.sample_curves[curveintegral_settings.init_curve_key][0],
                     title="cx(t):")
cy_input = TextInput(value=curveintegral_settings.sample_curves[curveintegral_settings.init_curve_key][1],
                     title="cy(t):")
# slider controlling the parameter t
parameter_input = Slider(title="t",
                         value=curveintegral_settings.parameter_input_init,
                         start=curveintegral_settings.parameter_min,
                         end=curveintegral_settings.parameter_max,
                         step=curveintegral_settings.parameter_step)

cx_input.on_change('value', curve_change)
cy_input.on_change('value', curve_change)
parameter_input.on_change('value', parameter_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container for the field
plot_field = Figure(plot_height=400,
                    plot_width=400,
                    tools=toolset,
                    title="Vector valued function",
                    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
                    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max]
                    )

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0
    x_last = 0
    t_last = 0
    l_forward.data_source.data["y"] = vpulse(x - u*current_time)
    l_reverse.data_source.data["y"] = vpulse(x + u*current_time)
    t2.data_source.data["text"] = ['t = {:.3f} s'.format(current_time)]
button_reset = Button(label="Reset", type="success")
button_reset.on_click(reset_handler)

# Set up slider & callback function
def update_velocity(attrname, old, new):
    global u, current_time, x_last, t_last
    x_last += u * (current_time - t_last)
    t_last = current_time
    u = velocity.value
    t1.data_source.data["text"] = ['u = {} m/s'.format(u)]
velocity = Slider(title="Velocity (m/s)", value=5.0, start=0.1, end=10.0, step=0.1)
velocity.on_change('value', update_velocity)

# Set up layout
layout = hplot(p, VBox(toggle, button_reset, velocity, height=400), width=900)

# Create callback function for periodic callback
def update():
    global ii, current_time
    if toggle.active:
        ii += 1
        current_time = ii * 1.e-3 * periodic_callback_time_ms
        l_forward.data_source.data["y"] = vpulse( x - x_last - u*(current_time-t_last) )
        l_reverse.data_source.data["y"] = vpulse( x + x_last + u*(current_time-t_last) )
        t2.data_source.data["text"] = ['t = {:.3f} s'.format(current_time)]
Exemple #37
0
    text_reg_season.value = str(selected_presets[i]['reg_season'])
    slider_freq_days.value = selected_presets[i]['freq_days']
    text_periods.value = str(selected_presets[i]['periods'])


select_preset.on_change('value', select_preset_callback)

# Slider: Last month in time window
number_of_months = df_piv.shape[1]
slider_et = Slider(
    start=2,
    end=number_of_months,
    value=number_of_months,
    step=1,  # current month
    title="Last month in time window")
slider_et.on_change('value', slider_et_callback)

# Slider: Previous months to accumulate
slider_ws = Slider(
    start=1,
    end=slider_et.value,
    value=36,
    step=1,  # acc months
    title="Previous months to accumulate")
slider_ws.on_change('value', slider_ws_callback)

# Text: Start month / End month
text_period = Div(text=get_period_text())

# Prophet parameter controls
text_prophet_parameters = Div(text='<h3>Prophet parameters</h3>')
Exemple #38
0
class widgetDIMS(object):

    column_names_rocks = ['kclay', 'muclay', 'rhoclay',
                          'knonclay', 'munonclay', 'rhononclay',
                          'vclay', 'phi', 'dryEk', 'dryPk', 'dryEg', 'dryPg']
    column_names_fluids = ['Name', 'ko', 'rhoo', 'kw', 'rhow', 'kg', 'rhog', 'so', 'sw', 'sg'   ]
    column_names_pres = ['Name', 'OB_Grad', 'init_Pres', 'curr_Pres']
    column_names_output = ['rock', 'fluid', 'Vp', 'Vs', 'rho', 'other']

    def __init__(self,init_depth,file_rocks,file_fluids,file_prespfs,fdi=None):
        '''
        :param init_depth: Initial depth to model (TVDSS).
        :param file_rocks: File with input mineral parameters.
        :param file_fluids: File with input fluid parameters.
        :param file_prespfs: File with input pressure profiles.
        :keyword dependents: A list of geoPy widgets which need to be updated when widgetDIMS is changed.
        '''
        # Initial Data
        self.df_rocks = pd.read_csv(file_rocks, skipinitialspace=True)
        self.df_fluids = pd.read_csv(file_fluids, skipinitialspace=True)
        self.df_pres = pd.read_csv(file_prespfs, skipinitialspace=True)
        self.init_depth = init_depth  # mTVDSS
        self.pagewidth = 1000  # pixels
        self.fdi = fdi

        # Setup Sources
        self.CDS_rocks = ColumnDataSource(self.df_rocks)
        self.CDS_fluids = ColumnDataSource(self.df_fluids)
        self.CDS_pres = ColumnDataSource(self.df_pres)
        self.CDS_out = ColumnDataSource(data=dict())
        # Extract Names
        self.odict_rocks = self.__odictIndex(self.df_rocks.Name.tolist())
        self.odict_fluids = self.__odictIndex(self.df_fluids.Name.tolist())
        self.odict_pres = self.__odictIndex(self.df_pres.Name.tolist())
        # Setup widgets
        self.createTableWidgets()
        self.createControls()
        self.createLayout()

        self.on_selection_change('value',1,1)

    def __odictIndex(self,keys):
        out = ExtOrderedDict()
        for ind,key in enumerate(keys):
            out[key] = ind
        return out

    def createTableWidgets(self):
        self.col_rocks =  [TableColumn(field=Ci, title=Ci) for Ci in self.column_names_rocks]
        self.col_fluids = [TableColumn(field=Ci, title=Ci) for Ci in self.column_names_fluids]
        self.col_pres =   [TableColumn(field=Ci, title=Ci) for Ci in self.column_names_pres]
        self.col_out =    [TableColumn(field=Ci, title=Ci) for Ci in self.column_names_output]
        #Setup table widgets
        tablekwargs = {'width': self.pagewidth, 'editable': True}
        self.TW_rocks =  DataTable(source=self.CDS_rocks,  columns=self.col_rocks,  **tablekwargs)
        self.TW_fluids = DataTable(source=self.CDS_fluids, columns=self.col_fluids, **tablekwargs)
        self.TW_pres =   DataTable(source=self.CDS_pres,   columns=self.col_pres,   **tablekwargs)
        self.TW_out =    DataTable(source=self.CDS_out,    columns=self.col_out,    **tablekwargs)

    def createControls(self):
        # Setup Select Panes and Input Widgets

        #Obr - Overburden rock  #ResR - Reservoir rock
        #Obf - Oberburden fluid #Resf - Reservoir fluid
        self.selectObr = Select(value=self.odict_rocks.keyslist()[0], options=self.odict_rocks.keyslist(),
                                title="Rock  Model")
        self.selectResR = Select(value=self.odict_rocks.keyslist()[0], options=self.odict_rocks.keyslist(),
                                 title="Rock  Model")
        self.selectObf = Select(value=self.odict_fluids.keyslist()[0], options=self.odict_fluids.keyslist(),
                                title="Fluid Model")
        self.selectResf = Select(value=self.odict_fluids.keyslist()[0], options=self.odict_fluids.keyslist(),
                                 title="Fluid Model")
        self.selectPres = Select(value=self.odict_pres.keyslist()[0], options=self.odict_pres.keyslist(),
                                 title="Pressure Scenario")

        self.slideDepth = Slider(start=0, end=10000, value=self.init_depth, step=10, title='Depth (TVDSS)',
                                 callback_policy='mouseup')

        self.selectObr.on_change('value', self.on_selection_change)
        self.selectResR.on_change('value', self.on_selection_change)
        self.selectObf.on_change('value', self.on_selection_change)
        self.selectResf.on_change('value', self.on_selection_change)
        self.selectPres.on_change('value', self.on_selection_change)
        self.slideDepth.on_change('value', self.on_selection_change)

    def createLayout(self):
        # Layout of Page
        self.inputTab1 = Panel(child=self.TW_rocks,  title='Rock Models')
        self.inputTab2 = Panel(child=self.TW_fluids, title='Fluid Mixes')
        self.inputTab3 = Panel(child=self.TW_pres,   title='Pressure Scenarios')
        self.inputTab4 = Panel(child=self.TW_out,    title='Model Calculations')

        self.inputTabs = Tabs(tabs=[self.inputTab1, self.inputTab2,
                                    self.inputTab3, self.inputTab4],
                                    width=self.pagewidth, height=200)

        textrowob = Div(text="<h1> Overburden: </h1>")
        selectrowob = row(self.selectObr, self.selectObf, width=500, height=50, sizing_mode="scale_both")
        textrowres = Div(text="<h1> Reservoir: </h1>")
        selectrowres = row(self.selectResR, self.selectResf, width=500, height=50, sizing_mode="scale_both")
        selectrowpres = row(self.selectPres, self.slideDepth, width=500, height=50, sizing_mode="scale_both")
        self.layout = column(self.inputTabs,
                             textrowob,
                             selectrowob,
                             textrowres,
                             selectrowres,
                             selectrowpres, width=self.pagewidth)

    def on_selection_change(self,attribute,old,new):
        # update active selections
        self.activeObr =  self.df_rocks.loc[self.odict_rocks[self.selectObr.value]]     #Overburden Rock and Fluid
        self.activeObf =  self.df_fluids.loc[self.odict_fluids[self.selectObf.value]]
        self.activeResR = self.df_rocks.loc[self.odict_rocks[self.selectResR.value]]    #Reservoir Rock and Fluid
        self.activeResF = self.df_fluids.loc[self.odict_fluids[self.selectResf.value]]
        self.activePresPf = self.df_pres.loc[self.odict_pres[self.selectPres.value]]  #Pressure Profile
        self.cur_depth = self.slideDepth.value
        self.updateRocks()
        self.updateFluids()
        self.updateRockModel()
        if self.fdi != None:
            self.fdi.updateModel(self.activeResR_dry, self.activeResF_mix, self.fdi.min_pres, self.fdi.max_pres,
                                 init_imp=self.activeResRM.pimp)

    def updateRocks(self):
        #update rock models based upon selections
        parnonclay = ['knonclay', 'munonclay', 'rhononclay'];
        parclay = ['kclay', 'muclay', 'rhoclay']
        obnonshale = structMineral('nonshale', *[self.activeObr[par] for par in parnonclay])
        obshale = structMineral('shale', *[self.activeObr[par] for par in parclay])
        nonshale = structMineral('nonshale', *[self.activeResR[par] for par in parnonclay])
        shale = structMineral('shale', *[self.activeResR[par] for par in parclay])
        # output rock names to table
        self.CDS_out.data['rock'] = [self.activeObr['Name'], self.activeResR['Name']]

        #update dryrock properties
        self.activeObr_dry = structDryFrame(self.activeObr['Name'], obnonshale, obshale, self.activeObr['vclay'],
                                   self.activeObr['phi'])
        self.activeResR_dry = structDryFrame(self.activeResR['Name'], nonshale, shale, self.activeResR['vclay'],
                                    self.activeResR['phi'])
        self.activeObr_dry.calcRockMatrix(); self.activeResR_dry.calcRockMatrix()
        parp = ['init_Pres', 'curr_Pres']; pardry = ['dryEk', 'dryPk', 'dryEg', 'dryEk']
        self.activeObr_dry.calcDryFrame(self.activePresPf['OB_Grad'], self.cur_depth, *[self.activePresPf[par] for par in parp],
                               *[self.activeObr[par] for par in pardry])
        self.activeResR_dry.calcDryFrame(self.activePresPf['OB_Grad'], self.cur_depth, *[self.activePresPf[par] for par in parp],
                                *[self.activeResR[par] for par in pardry])

    def updateFluids(self):
        # oil, water, gas, setup and mixing
        parw = ['kw', 'rhow', 'sw']; paro = ['ko', 'rhoo', 'so']; parg = ['kg', 'rhog', 'sg']
        self.activeObf_mix = structFluid(self.activeObf['Name'], water=[self.activeObf[ind] for ind in parw],
                                                         oil=[self.activeObf[ind] for ind in paro],
                                                         gas=[self.activeObf[ind] for ind in parg])
        self.activeResF_mix = structFluid(self.activeResF['Name'], water=[self.activeResF[ind] for ind in parw],
                                                           oil=[self.activeResF[ind] for ind in paro],
                                                           gas=[self.activeResF[ind] for ind in parg])
        # output fluid names to table
        self.CDS_out.data['fluid'] = [self.activeObf['Name'], self.activeResF['Name']]


    def updateRockModel(self):

        # calculate rock models and properties
        self.activeObrM = structRock(self.activeObr_dry, self.activeObf_mix)
        self.activeObrM.calcGassmann(); self.activeObrM.calcDensity(); self.activeObrM.calcElastic()
        self.activeResRM = structRock(self.activeResR_dry, self.activeResF_mix)
        self.activeResRM.calcGassmann(); self.activeResRM.calcDensity(); self.activeResRM.calcElastic()

        # output rockproperties to table
        self.CDS_out.data['Vp'] = [self.activeObrM.velp, self.activeResRM.velp]
        self.CDS_out.data['Vs'] = [self.activeObrM.vels, self.activeResRM.vels]
        self.CDS_out.data['rho'] = [self.activeObrM.den, self.activeResRM.den]
        self.CDS_out.data['other'] = [self.activeObrM.pimp, self.activeResRM.pimp]
Exemple #39
0
    order = int(new)
    update_data()

def on_text_value_change(attr, old, new):
    try:
        global expr
        expr = sy.sympify(new, dict(x=xs))
    except (sy.SympifyError, TypeError, ValueError) as exception:
        dialog.content = str(exception)
        dialog.visible = True
    else:
        update_data()

dialog = Dialog(title="Invalid expression")

slider = Slider(start=1, end=20, value=order, step=1, title="Order:")
slider.on_change('value', on_slider_value_change)

text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', on_text_value_change)

inputs = HBox(children=[slider, text])
layout = VBox(children=[inputs, plot, dialog])
update_data()
document.add_root(layout)
session.show(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
# initialize controls
# buttons for choosing a sample function
sample_function_type = RadioButtonGroup(labels=fs.function_names, active=fs.function_init)

# here one can choose arbitrary input function
default_function_input = TextInput(value=fs.function_input_init)
default_function_period_start = TextInput(title='period start', value=fs.timeinterval_start_init)
default_function_period_end = TextInput(title='period end', value=fs.timeinterval_end_init)

# slider controlling degree of the fourier series
degree = Slider(title="degree", name='degree', value=fs.degree_init, start=fs.degree_min,
                end=fs.degree_max, step=fs.degree_step)

# initialize callback behaviour
degree.on_change('value', degree_change)
default_function_input.on_change('value',
                                 type_input_change)  # todo write default functions for any callback, like above
default_function_period_start.on_change('value', type_input_change)
default_function_period_end.on_change('value', type_input_change)
sample_function_type.on_change('active', type_input_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=fs.resolution,
              plot_width=fs.resolution,
              tools=toolset,
              title="Fourier Series Approximation",
              x_range=[fs.x_min, fs.x_max],
              y_range=[fs.y_min, fs.y_max]
Exemple #41
0
class FPDApp(HBox):
    extra_generated_classes = [["FPDApp", "FPDApp", "HBox"]]

    main_frame = Instance(VBox)
    top_frame = Instance(HBox)
    table_frame = Instance(HBox)
    input_frame = Instance(VBoxForm)
    plot_frame = Instance(HBox)

    # widget instances
    min_excitation = Instance(Slider)
    max_excitation = Instance(Slider)
    min_emission = Instance(Slider)
    max_emission = Instance(Slider)
    chrom_class_select = Instance(Select)
    # chrom_class = String(default='All')
    data_table = Instance(DataTable)

    plot = Instance(Plot)
    source = Instance(ColumnDataSource)
    # pretext = Instance(PreText)


    @classmethod
    def create(cls):
        obj = cls()
        obj.init_input()
        obj.init_source()
        obj.init_plot()
        obj.set_children()
        return obj

    def __init__(self, *args, **kwargs):
        super(FPDApp, self).__init__(*args, **kwargs)

    def init_source(self):
        self.source = ColumnDataSource(data=data)
        self.data_table = DataTable(source=self.source, columns=[
            TableColumn(field='fpid', title='FPID'),
            TableColumn(field='chromophore_name', title='chromophore_name'),
            TableColumn(field='chromophore_class', title='chromophore_class'),
            TableColumn(field='protein_name', title='Protein name'),
            TableColumn(field='excitation_new', title='Excitation'),
            TableColumn(field='emission_new', title='Emission'),
            TableColumn(field='pdb_id', title='PDB ID'),
            TableColumn(field='genbank', title='Genbank ID'),
            TableColumn(field='mutation', title='Mutation'),
            TableColumn(field='quantum_yield', title='Quantum Yield'),
            TableColumn(field='pka', title='pka'),
            TableColumn(field='amino_acid_sequence', title='Sequence'),
        ])
        self.data_table.width = 1200
        # obj.pretext = PreText(text='No selected items', width=400)

    def init_plot(self):
        self.plot = self.scatter_plot()

    def init_input(self):
        # create input widgets only once
        self.min_excitation = Slider(
                title="Min Excitation", name="min_excitation",
                value=min_excitation,
                start=min_excitation,
                end=max_excitation,
                )
        self.max_excitation = Slider(
                title="Max Excitation", name="max_excitation",
                value=max_excitation,
                start=min_excitation,
                end=max_excitation,
                )
        self.min_emission = Slider(
                title="Min Emission", name="min_emission",
                value=min_emission,
                start=min_emission,
                end=max_emission,
                )
        self.max_emission = Slider(
                title="Max Emission", name="max_emission",
                value=max_emission,
                start=min_emission,
                end=max_emission,
                )

        self.chrom_class_select = Select(
                title="Chromophore",
                value='All',
                options=['All'] + CHROMOPHORES,
                )


    def set_sliders(self):
        self.min_excitation = Slider(
                title="Min Excitation", name="min_excitation",
                value=self.min_excitation.value,
                start=min_excitation,
                end=max_excitation,
                )
        self.max_excitation = Slider(
                title="Max Excitation", name="max_excitation",
                value=self.max_excitation.value,
                start=min_excitation,
                end=max_excitation,
                )
        self.min_emission = Slider(
                title="Min Emission", name="min_emission",
                value=self.min_emission.value,
                start=min_emission,
                end=max_emission,
                )
        self.max_emission = Slider(
                title="Max Emission", name="max_emission",
                value=self.max_emission.value,
                start=min_emission,
                end=max_emission,
                )


    def get_data(self):
        df = data

        df = df[df['excitation_new']>=self.min_excitation.value]
        df = df[df['excitation_new']<=self.max_excitation.value]
        df = df[df['emission_new']>=self.min_emission.value]
        df = df[df['emission_new']<=self.max_emission.value]

        if self.chrom_class_select.value == 'All':  # all chromophore classes
            return df
        else:
            df = df[df['chromophore_class']==self.chrom_class_select.value]

        return df


    def make_source(self):
        self.source.data = self.get_data().to_dict('list')

    def make_plots(self):
    #     # print('CALL: make_plots')
        self.plot = self.scatter_plot()

    @property
    def selected_df(self):
        df = data
        selected = self.source.selected
        if selected:
            df = df.iloc[selected, :]
        return df


    def scatter_plot(self):
        toolset = "pan,reset,resize,save,wheel_zoom,hover,box_select"

        plot = figure(tools=toolset)
        plot.scatter('excitation_new', 'emission_new',
                source=self.source,
                plot_width=100, plot_height=200,
                radius=4, fill_alpha=0.4,
                fill_color='excitation_color_new',
                line_color='#000000',
                )
        plot.xaxis.axis_label = 'Emission'
        plot.yaxis.axis_label = 'Excitation'

        plot.x_range = Range1d(start=min_excitation, end=max_excitation)
        plot.y_range = Range1d(start=min_emission, end=max_excitation)

        hover = plot.select(dict(type=HoverTool))

        hover.tooltips = [
            ("FPID ", "@fpid"),
            ("Chromophore name ", "@chromophore_name"),
            ("Excitation color class ", "@excitation_color_class"),
            ("Emission color class ", "@emission_color_class"),
            ("Primary excitation ", "@excitation_new"),
            ("Secondary excitation ", "@excitation_alt"),
            ("Primary emission ", "@emission_new"),
            ("Secondary emission ", "@emission_alt"),
        ]
        return plot

    def set_children(self):
        self.input_frame = VBoxForm(children=[
                                self.min_excitation,
                                self.max_excitation,
                                self.min_emission,
                                self.max_emission,
                                self.chrom_class_select,
                            ])

        self.plot_frame = HBox(children=[self.plot])
        self.top_frame = HBox(children=[self.plot_frame, self.input_frame])
        self.table_frame = HBox(children=[self.data_table])
        self.main_frame = VBox(children=[self.top_frame, self.table_frame])
        self.children = [self.main_frame]


    def setup_events(self):
        super(FPDApp, self).setup_events()

        if self.source:
            self.source.on_change('selected', self, 'on_slider_change')

        if self.min_excitation:
            self.min_excitation.on_change('value', self, 'on_slider_change')

        if self.max_excitation:
            self.max_excitation.on_change('value', self, 'on_slider_change')

        if self.min_emission:
            self.min_emission.on_change('value', self, 'on_slider_change')

        if self.max_emission:
            self.max_emission.on_change('value', self, 'on_slider_change')

        if self.chrom_class_select:
            self.chrom_class_select.on_change(
                                'value', self, 'on_class_change')


    def on_class_change(self, obj, attrname, old, new):
        self.chrom_class_select.value = new
        self.make_source()
        self.make_plots()
        curdoc().add(self)

    def on_slider_change(self, obj, attrname, old, new):
        if obj == self.min_excitation:
            self.min_excitation.value = new
            if self.min_excitation.value > self.max_excitation.value:
                self.min_excitation.value = old

        if obj == self.max_excitation:
            self.max_excitation.value = new
            if self.max_excitation.value < self.min_excitation.value:
                self.max_excitation.value = old

        if obj == self.min_emission:
            self.min_emission.value = new
            if self.min_emission.value > self.max_emission.value:
                self.min_emission.value = old

        if obj == self.max_emission:
            self.max_emission.value = new
            if self.max_emission.value < self.min_emission.value:
                self.max_emission.value = old

        self.set_sliders()
        self.make_source()
        self.set_children()
        curdoc().add(self)
                           end=[math.radians(alpha), math.radians(
                               alpha + beta), math.radians(alpha + beta)],
                           color=["red", "blue", "purple"])


def update_beta(attr, old, new):
    global beta
    beta = beta_slider.value
    xs, ys = set_patches(alpha, beta)
    patch_source.data = dict(xs=xs, ys=ys, color=color)
    xs, ys = set_lines(alpha, beta)
    dotted_line_source.data = dict(
        xs=xs, ys=ys, color=["black", "black"])
    arc_source.data = dict(x=[0, 0, 0], y=[0, 0, 0, ],
                           radius=[0.2, 0.25, 0.3],
                           start=[0, math.radians(alpha), 0],
                           end=[math.radians(alpha), math.radians(
                               alpha + beta), math.radians(alpha + beta)],
                           color=["red", "blue", "purple"])


alpha_slider.on_change('value', update_alpha)
beta_slider.on_change('value', update_beta)

sliders = column(alpha_slider,
                 beta_slider)
plot = column(sliders, fig)

document = curdoc()
document.add_root(plot)
# plotting for arc length parametrization
source_point_arc = ColumnDataSource(data=dict(x=[], y=[]))


# initialize controls
# choose between original and arc length parametrization
parametrization_input = CheckboxGroup(labels=['show original parametrization',
                                              'show arc length parametrization'],
                                      active=[0, 1])
parametrization_input.on_click(parametrization_change)
# slider controlling the current parameter t
t_value_input = Slider(title="parameter t", name='parameter t', value=arc_settings.t_value_init,
                       start=arc_settings.t_value_min, end=arc_settings.t_value_max,
                       step=arc_settings.t_value_step)
t_value_input.on_change('value', t_value_change)
# text input for the x component of the curve
x_component_input = TextInput(value=arc_settings.x_component_input_msg, title="curve x")
x_component_input.on_change('value', curve_change)
# text input for the y component of the curve
y_component_input = TextInput(value=arc_settings.y_component_input_msg, title="curve y")
y_component_input.on_change('value', curve_change)
# dropdown menu for selecting one of the sample curves
sample_curve_input = Dropdown(label="choose a sample function pair or enter one below",
                              menu=arc_settings.sample_curve_names)
sample_curve_input.on_click(sample_curve_change)


# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
Exemple #44
0

def on_text_value_change(attr, old, new):
    try:
        global expr
        expr = sy.sympify(new, dict(x=xs))
    except (sy.SympifyError, TypeError, ValueError) as exception:
        dialog.content = str(exception)
        dialog.visible = True
    else:
        update_data()


dialog = Dialog(title="Invalid expression")

slider = Slider(start=1, end=20, value=order, step=1, title="Order", callback_policy="mouseup")
slider.on_change("value", on_slider_value_change)

text = TextInput(value=str(expr), title="Expression:")
text.on_change("value", on_text_value_change)

inputs = WidgetBox(children=[slider, text], width=400)
layout = Column(children=[inputs, plot, dialog])
update_data()
document.add_root(layout)
session.show(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
Exemple #45
0
df = pd.DataFrame()
boundaryDF = pd.DataFrame()
colorDF = pd.DataFrame()
outDF = pd.DataFrame()


Console = PreText(
    text="Console:\nStart visualize by entering \nannotations, pickle file and gene.\nPress Enter to submit.\n",
    width=250,
    height=100,
)
p = createPlot(df, boundaryDF)

Gene.on_change("value", updateGene)
Full.on_change("value", updateFP)
Partial.on_change("value", updateFP)
Alpha.on_change("value", updateFP)
Cluster.on_change("value", updateGroup)
Save.on_change("value", saveFasta)
Width.on_change("value", updateWidth)

dataColumns = [TableColumn(field="Gene", title="Gene"), TableColumn(field="Cluster", title="Cluster")]
data_table = DataTable(source=geneSource, columns=dataColumns, width=200, height=1200)

paramSource = ColumnDataSource(
    data=dict(
        Parameter=[
            "annotation",
            "format",
            "matches",
                           range_start = range_select.value[0],
                           range_end = range_select.value[1],
                           bin_width = binwidth_select.value)

    src.data.update(new_src.data)


# CheckboxGroup to select carrier to display
carrier_selection = CheckboxGroup(labels=available_carriers, active = [0, 1])
carrier_selection.on_change('active', update)

# Slider to select width of bin
binwidth_select = Slider(start = 1, end = 30, 
                     step = 1, value = 5,
                     title = 'Delay Width (min)')
binwidth_select.on_change('value', update)

# RangeSlider control to select start and end of plotted delays
range_select = RangeSlider(start = -60, end = 180, value = (-60, 120),
                           step = 5, title = 'Delay Range (min)')
range_select.on_change('value', update)


# Find the initially selected carrieres
initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active]

src = make_dataset(initial_carriers,
                  range_start = range_select.value[0],
                  range_end = range_select.value[1],
                  bin_width = binwidth_select.value)
Exemple #47
0
        "date": [conso_date, conso_date],
        "conso": (0., conso_bounds[1])
    }
    title = "Consommation {}, {}".format(sector_id, conso_date)
    print(title)
    conso_plot.update_title(title)
    conso_plot.set_active(mode)

def update(attrname, old, new):
    print("update {} {} {}".format(attrname, old, new))
    sector_id = int(sector_select.value)
    conso_date = datetime(2016, 3, int(date_slider.value),
                          int(time_slider.value))
    update_sources(sector_id, conso_date, type_button.active)
sector_select.on_change("value", update)
date_slider.on_change("value", update)
time_slider.on_change("value", update)
type_button.on_change("active", update)

def on_selection_change(attr, old, new):
    print("on_selection_change")
    indices = new["1d"]["indices"]
    if indices:
        sector_id = geo_sectors.loc[indices[0]]["sector_id"]
        sector_select.value = str(sector_id) # Calls update in chain
        #update_sources(sector_id=sector_id)
map_plot.get_data_source().on_change("selected", on_selection_change)

def close_session():
    session.close()
button.on_click(close_session)
Exemple #48
0
def slider_change(attr, old, new):
    global interval
    interval = (10 * max_interval + min_interval + new * (min_interval - max_interval)) / 9
    if play:
        curdoc().remove_periodic_callback(update)
        curdoc().add_periodic_callback(update, interval)


def button_group_click(new):
    global play
    if new == 0: # play
        play = True
        curdoc().add_periodic_callback(update, interval)
    else:
        play = False
        curdoc().remove_periodic_callback(update)

def button_click():
    global X, step
    step = 1
    X = np.copy(X_init)
    redraw()


slider.on_change("value", slider_change)
button_group.on_click(button_group_click)
button.on_click(button_click)

session.show(row(wb, p1, p2))
session.loop_until_closed()
            and update the image data as well as the coloring of the image.
        2.  if any relevant parameters for the computation of the colormap have changed, apply the colormap to unchanged
            raw mandelbrot set data and save the changed colors to the corresponding data source
    """

    parameters_have_changed = check_parameters(slider_max_iterations.value)
    frequency_has_changed = check_frequency(slider_frequency.value)

    if parameters_have_changed:
        update_mandelbrot_set()
        update_colormap(None, None, slider_frequency.value)
        return
    elif frequency_has_changed:
        update_colormap(None, None, slider_frequency.value)
        return
    else:
        return


# initialize data
update_mandelbrot_set()
update_colormap(None, None, slider_frequency.value)

# setup callback for colormap frequency change
slider_frequency.on_change('value', update_colormap)

# update picture all 100 ms w.r.t current view
curdoc().add_periodic_callback(update_data, mandelbrot_settings.update_time)
# make layout
curdoc().add_root(column(plot, slider_max_iterations, slider_frequency))
Exemple #50
0
import numpy as np

x = np.linspace(0, 10, 500)
y=np.sin(x)

df=pd.DataFrame({'x':x,'y':y})

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

plot_figure = figure(title='Slider',plot_height=450, plot_width=600,
              tools="save,reset", toolbar_location="below")

plot_figure.line('x', 'y', line_width=3, source=source)

slider = Slider(start=0.1, end=10, value=1, step=.1, title="Change Frequency")

def slider_change(attr,old,new):
    slider_value=slider.value ##Getting radio button value

    y_change=np.sin(x*slider_value)

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


slider.on_change('value',slider_change)

layout=row(slider, plot_figure)

curdoc().add_root(layout)
curdoc().title = "Slider Bokeh Server"
    colors = [spectral[i] for i in y_pred]

    source.data['x'] = X[:, 0]
    source.data['y'] = X[:, 1]
    source.data['colors'] = colors

def update_clusters(attrname, old, new):
    algorithm = algorithm_select.value
    n_clusters = int(clusters_slider.value)
    n_samples = int(samples_slider.value)

    global X
    X, y_pred = clustering(X, algorithm, n_clusters)
    colors = [spectral[i] for i in y_pred]

    source.data['x'] = X[:, 0]
    source.data['y'] = X[:, 1]
    source.data['colors'] = colors

algorithm_select.on_change('value', update_algorithm)
dataset_select.on_change('value', update_dataset)
clusters_slider.on_change('value', update_clusters)
samples_slider.on_change('value', update_samples)

# SET UP LAYOUT
sliders = VBox(children=[samples_slider, clusters_slider])
selects = HBox(children=[dataset_select, algorithm_select])
inputs = VBox(children=[sliders, selects])
plots = HBox(children=[plot])
# add to document
curdoc().add_root(HBox(children=[inputs, plots]))
Exemple #52
0
plot.renderers.append(p_line)


p_value_text = bokeh.models.Paragraph()
def get_p_text():
    return 'p={}'.format(get_p())

p_value_text.text = get_p_text()
def callback(attr, old, new):
    p_line.location = -math.log10(get_p())
    left.location = left_limit.value
    right.location = right_limit.value
    p_value_text.text = get_p_text()


p_value.on_change('value', callback)
p_mult.on_change('value', callback)
left_limit.on_change('value', callback)
right_limit.on_change('value', callback)

###################################################
##   Data table      ##############################
###################################################

aux_source = bokeh.models.ColumnDataSource()
table = bokeh.models.DataTable(
    source=aux_source,
    columns=[
        bokeh.models.TableColumn(field='text', title='text')
    ],
    fit_columns=True,
checkbox_group = CheckboxGroup(
        labels=["Forward Propagating Wave", "Reverse Propagating Wave", "Sum of Waves",
                "Standing Wave (valid only for \u03B1=0)"], active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

# Set up slider & callback function
def update_alpha(attrname, old, new):
    global alpha
    alpha = alpha_slider.value
    if not toggle.active:
        l_forward.data_source.data["y"] = forward_wave()
        l_reverse.data_source.data["y"] = reverse_wave()
        l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \
                                      l_reverse.data_source.data["y"]
alpha_slider = Slider(title="Attenuation Constant, \u03B1 (1/m)", value=0.0, start=0.0, end=0.25, step=0.005)
alpha_slider.on_change('value', update_alpha)

# Set up slider & callback function for reflection_coef
def update_gamma(attrname, old, new):
    global reflection_coef
    reflection_coef = gamma_slider.value
    if not toggle.active:
        l_forward.data_source.data["y"] = forward_wave()
        l_reverse.data_source.data["y"] = reverse_wave()
        l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \
                                      l_reverse.data_source.data["y"]
        l_standing.data_source.data["y"] = standing_wave()
gamma_slider = Slider(title="Reflection Coefficient, \u0393", value=reflection_coef, start=-1.0, end=1.0, step=0.01)
gamma_slider.on_change('value', update_gamma)

# Set up layout
Exemple #54
0
    alpha = alphaSlider.value
    offset = offsetSlider.value
    response.data['y'] = contrast**alpha + offset
    response_plus_noise.data['y'] = contrast**alpha + offset + (np.random.random(contrast.shape)-0.5)/CNR
    baseline.data['y'] = offset*np.ones(contrast.shape)
    baseline_plus_noise.data['y'] = offset+(np.random.random(contrast.shape)-0.5)/CNR 
    p1.title = 'CNR = %2.1f' %CNR
    # sim some data
    data = np.zeros([nRep,3])
    for iRep in range(nRep):
        stim = offset + np.array([0.08,0.16,0.32])**alpha + (np.random.random((1,3))-0.5)/CNR
        fonly = offset + (np.random.random()-0.5)/CNR
        data[iRep,:] = stim - fonly
    # and push to plots
    for iC,c in enumerate([0.08,0.16,0.32]):
        data_all[iC].data['y'] = data[:,iC]
        data_all[iC].data['x'] = c*np.ones([nRep])
    data_means.data['y'] = np.mean(data,axis=0)
    for iC,c in enumerate([0.08,0.16,0.32]):
        data_eb[iC].data['y'] = np.mean(data[:,iC]) + np.std(data[:,iC])/np.sqrt(nRep)*np.array([-1,1])  

CNRslider.on_change('value',update)
nREPslider.on_change('value',update)
alphaSlider.on_change('value',update)
offsetSlider.on_change('value',update)
redrawButton.on_change('clicks',update)

    


Exemple #55
0
from bokeh.io import curdoc

df = pd.read_csv(join(dirname(__file__), 'salary_data.csv'))

source = ColumnDataSource(data=dict())

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

slider = Slider(title="Max Salary", start=10000, end=250000, value=150000, step=1000)
slider.on_change('value', lambda attr, old, new: update())

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

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

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

controls = widgetbox(slider, button)
table = widgetbox(data_table)
Exemple #56
0
    zip_data = build_zip_data(
        where_inner = where_inner,
        where_outer = where_outer
    )

    zip_source.data = dict(
        x=zip_data["median_income"],
        y=zip_data["complaint_count"]
    )

    table_source.data = build_data_table(where_inner)

state_widget.on_change('value', update)
product_widget.on_change('value', update)
issue_widget.on_change('value', update)
min_complaints_widget.on_change('value', update)

### Step 3: Build the charts

# Build state bar chart
state_bar_chart = Bar(build_state_data(), label="state",
                      values='complaint_count', toolbar_location=None,
                      title="Complaints by State", width=1300, height=200,
                      ylabel="", xlabel="", color="#2cb34a")

# Build zip code scatter plot
zip_data = build_zip_data()
zip_source.data = dict(x = zip_data["median_income"],
                       y = zip_data["complaint_count"])
zip_scatter_plot = Figure(plot_height=500, plot_width=1000,
                          title="Complaints by Median Income",
Exemple #57
0
    response_plus_noise = response + (np.random.random(contrast.shape)-0.5)/CNR
    # sim some data
    data = np.zeros([nRep,3])
    for iRep in range(nRep):
        stim = baseline + np.array([0.08,0.16,0.32])**alpha + (np.random.random((1,3))-0.5)/CNR
        fonly = baseline + np.random.random()-0.5
        data[iRep,:] = stim - fonly
       
    #p1.line([0,1], [baseline,baseline], line_dash=[8,8], color = 'green')
    #p1.line(contrast, (np.random.random(contrast.shape)-0.5)/CNR+baseline, alpha=0.6, color='green')
    #p1.line(contrast,response, alpha=0.6, color='black')
    #p1.line(contrast,response_plus_noise, alpha=0.6, color='black')
    sourceLine.data['xs']=[[0,1],contrast,contrast,contrast]
    sourceLine.data['ys']=[[baseline,baseline],[(np.random.random(contrast.shape)-0.5)/CNR+baseline],response, response_plus_noise]
 

    p1.title = 'CNR = %2.1f' %CNR

    p2.line([0,1], [0,0], line_dash=[8,8], color = 'green')
    for iC,c in enumerate([0.08,0.16,0.32]):
        p2.circle(c*np.ones([nRep]), data[:,iC], color='red', fill_alpha=0.3, line_alpha=0.3)
    for iC,c in enumerate([0.08,0.16,0.32]):
        p2.circle(c, np.mean(data[:,iC]), color='red')
        p2.line([c,c], np.mean(data[:,iC]) + np.std(data[:,iC])/np.sqrt(nRep)*np.array([-1,1]), color='red')
    
CNRslider.on_change('value',update)

    


Exemple #58
0
class plotter_bif:
    def __init__(self, _aggr, _depl, _dRdt, _S_0,
                 _kvalues=np.ones(7), _kmax=0, _wire_url=0, _formula_url=0,
                _N=200, _Rmax=2, _Rmin=0, _Smax=3, _Smin=0, _title='test', _R0=0, _imgheight=150):
        self.aggregation = _aggr
        self.depletion = _depl
        self.dRdt = _dRdt
        self.kvalues = _kvalues
        self.N = _N #density of plot points
        self.Rmax = _Rmax
        self.Rmin = _Rmin
        self.Smax = _Smax
        self.Smin = _Smin
        self.S = _S_0
        S0 = [_S_0] #this is necessary since some struct need a list as input
        self.wire_url = _wire_url
        self.formula_url = _formula_url
        self.title = _title
        self.R = _R0
        self.imgheight=_imgheight
        
        if (np.size(_kmax)==1):
            self.kmax=np.array(_kvalues)
            self.kmax[:]['value'] = self.kmax[:]['value']*2
        else:
            self.kmax=_kmax
            
        
        
        # Set up data
        R_x = np.linspace(self.Rmin, self.Rmax, self.N)
        self.dRmin = np.max(self.depletion(R_x, self.kvalues))
        dR_dt_depl = self.depletion(R_x, self.kvalues)
        dR_dt_aggr = self.aggregation(R_x, self.S, self.kvalues)
        #R_ss = self.Rss(self.S, self.kvalues)
        #dR_dt_ss = self.depletion(R_ss, self.kvalues)
        self.dRmax = max(np.max(dR_dt_depl), np.max(dR_dt_aggr))
        self.dRmin = min(np.min(dR_dt_depl), np.min(dR_dt_aggr))
        
        self.data_dR_dt_R = ColumnDataSource(data=dict(R=R_x, dR_dt_depl=dR_dt_depl, dR_dt_aggr=dR_dt_aggr)) #graphs
        #self.data_dR_dt_R_lines = ColumnDataSource(data=dict(R_ss_y=[R_ss, R_ss], dR_dt_ss_y=[0, depletion(R_ss, self.kvalues)]))#y parallel
        #self.data_dR_dt_R_point_lab = ColumnDataSource(data=dict(R_ss=[R_ss], dR_dt_ss=[dR_dt_ss], lab=["R_ss = %.2f" % R_ss])) #label
        #self.data_dR_dt_R_point = ColumnDataSource(data=dict(R_ss=R_ss, dR_dt_ss=dR_dt_ss)) #label
        #we need to separate this, since bokeh has problem with drawing circles from data in the label structure
        
        #2nd graph, this differs from original graph
        R_y = np.linspace(self.Rmin, self.Rmax, self.N)
        S_x = np.linspace(self.Smin, self.Smax, self.N)
        
        R_, S_ = np.meshgrid(R_y, S_x)
        RS = self.dRdt(R_, S_, self.kvalues)
        R_split = self.split_R(RS, R_)
        S_split = np.split(S_x, self.get_index_Scrit(RS))
        #self.data_S_R = ColumnDataSource(data=dict(R_split=R_split, S_split=S_split))
        
        #implement a list of columnnames and use that list with add to append datasource
        R = np.array([])
        R_dotted = np.array([])
        S = np.array([])
        S_dotted = np.array([])
        self.data_R_S2 = ColumnDataSource()
        self.data_R_S2_dotted = ColumnDataSource()
        
        for i, r_ in enumerate(R_split):
            for j, r in enumerate(r_):
                s = S_split[i]
                _r = r
                _s = s
                if j%2 == 1:
                    _r = np.flip(r, 0)
                    _s = np.flip(s, 0)
                    R_dotted = np.append(R_dotted, _r)
                    S_dotted = np.append(S_dotted, _s)
                R = np.append(R, _r)
                S = np.append(S, _s)
        self.data_R_S2.add(R, "R")
        self.data_R_S2.add(S, "S")
        self.data_R_S2_dotted.add(R_dotted, "R")
        self.data_R_S2_dotted.add(S_dotted, "S")
        
        
        # Set up widgets
        self.S_var = Slider(title="S", value=self.S, start=self.Smin, end=self.Smax, step=(self.Smax - self.Smin)/100)
        self.k_var = list(np.empty(np.size(self.kvalues)))
        for i, k in enumerate(self.kvalues):
            self.k_var[i] = Slider(title=k['name'], value=k['value'], start=0.0, end=self.kmax[i]['value'], step=0.01)            
            
    def signchange2D(self, a):
        asign = np.sign(a)
        return ((np.roll(asign, 1, axis=1) - asign) != 0).astype(int)
    
    def signchange(self, a):
        asign = np.sign(a)
        return ((np.roll(asign, 1) - asign) != 0).astype(int)
    
    def corr_sign(self, a):
        signed = self.signchange2D(a)
        #print(signed[300])
        #get rid of preceeeding 1 due to wrap around -> correct all 1s at [0] and then roll left
        signed[:, 0] = 0
        signed = np.roll(signed, -1, axis=1)
        return signed
    
    #get indices that have equal numbers of root / get subarrays
    def get_index_Scrit(self, a):
        roots = np.sum(self.corr_sign(a), axis=1)
        #print(roots)
        root_indeces = np.array([0])
        #the first index is always the beginning of a subarray
        
        #use np.roll to find 'signchanges' in mask
        for n in np.unique(roots):
            mask = np.isin(roots, n)
            mask = mask.astype(int)
            changes = self.signchange(mask)
            #changes[:, 0] = 1
            #mark first element, as the first element of each subarray is marked
            indeces = np.argwhere(changes==1)
            root_indeces = np.append(root_indeces, indeces)
            
        return np.unique(root_indeces)[1:]
        #return only unique indeces, since some indeces might appear more often
        #also 0 index is not needed
        
    def split_R(self, RS, R_):
        #if np.size(self.get_index_Scrit(RS))==0:
            #return R_
        Rs = R_[self.corr_sign(RS)==1]
        N = np.size(RS, 0)
        result = []
        old_n = 0
        first_ind = 0
        for n in np.append(self.get_index_Scrit(RS), N):
            R = np.empty(n-old_n)
            m = np.sum(self.corr_sign(RS), axis=1)[n-1]
            #get #roots
            #print(first_ind, old_n, m, n)
            for i in range(m):
                #print(i, m, n, first_ind, old_n , np.shape(R), np.shape(Rs), np.shape(Rs[first_ind+i:first_ind+(n-old_n)*m+i:m]))
                #R = np.vstack((R, Rs[first_ind+i:first_ind+m*n+i:m]))
                R = np.vstack((R, Rs[first_ind+i:first_ind+(n-old_n)*m+i:m]))
                #start:stop:step, stop is not inclusive
            result.append(R[1:])
            #get rid of preceeding zeros
            #first_ind = first_ind+m*n
            first_ind = first_ind+(n-old_n)*m
            old_n = n
        return result
    
            
    def create_figure(self):
        # Set up plot
        #plot_dR_dt = figure(plot_height=600, plot_width=600, title="Depletion/Aggregation Rate",
        #      #tools="crosshair,pan,reset,save,wheel_zoom",
        #      x_range=[self.Rmin, self.Rmax], y_range=[self.dRmin, self.dRmax], toolbar_location="above")
        

        plot_dR_dt = figure(plot_height=800, plot_width=600, title="Depletion/Aggregation Rate",
              x_range=[self.Rmin, self.Rmax], y_range=[self.dRmin, self.dRmax])
        
        
        plot_dR_dt.line('R', 'dR_dt_aggr', source=self.data_dR_dt_R, line_width=3, line_alpha=0.6, color='steelblue')
        plot_dR_dt.line('R', 'dR_dt_depl', source=self.data_dR_dt_R, line_width=3, line_alpha=0.6, color='crimson')
        #plot_dR_dt.line('R_ss_y', 'dR_dt_ss_y', source=self.data_dR_dt_R_lines, line_width=3, line_alpha=0.6, color='red', line_dash='4 4')
        
        #labels = LabelSet(x='R_ss', y='dR_dt_ss', text='lab', level='glyph',
        #      x_offset=7, y_offset=-25, source=self.data_dR_dt_R_point_lab, render_mode='canvas')
        #plot_dR_dt.add_layout(labels)
        
        #plot_dR_dt.circle('R_ss', 'dR_dt_ss', source=self.data_dR_dt_R_point, fill_color="white", size=10)
        
        plot_dR_dt.yaxis.axis_label = "dR/dt"
        plot_dR_dt.xaxis.axis_label = "R"
        
        plot_dR_dt.toolbar.logo = None
        plot_dR_dt.toolbar_location = None
        
            
        #this part differs to original class 
        plot_R_S= figure(plot_height=800, plot_width=600, title="Steady State Solutions",
                  x_range=[self.Smin, self.Smax], y_range=[self.Rmin, self.Rmax], toolbar_location="above")
        
        plot_R_S.line(x='S', y='R', source=self.data_R_S2, line_width=3, line_alpha=0.6, color='black')        
        plot_R_S.line(x='S', y='R', source=self.data_R_S2_dotted, line_width=3, line_alpha=1.0, color='white', line_dash='4 4')        
        
        plot_R_S.yaxis.axis_label = "R_ss"
        plot_R_S.xaxis.axis_label = "S"
        
        plot_R_S.toolbar.logo = None
        plot_R_S.toolbar_location = None
        
        plot_wire = figure(plot_height=300, plot_width=300, x_range=(0,1), y_range=(0,1), title='Wire Diagramm')
        plot_wire.image_url(url=[self.wire_url], x=0, y=1, w=1, h=1)
        
        plot_wire.toolbar.logo = None
        plot_wire.toolbar_location = None
        plot_wire.axis.visible = False
        
        plot_formula = figure(plot_width=300, plot_height=self.imgheight, x_range=(0,1), y_range=(0,1), title='Formulas')
        plot_formula.image_url(url=[self.formula_url], x=.01, y=.99, w=.99, h=.99)
        
        plot_formula.toolbar.logo = None
        plot_formula.toolbar_location = None
        plot_formula.axis.visible = False
        
        return plot_dR_dt, plot_R_S, plot_wire, plot_formula 
        
    def update_data(self, attrname, old, new):
    
        # Get the current slider values
        self.S = self.S_var.value
        S0 = [self.S]
        for i,k in enumerate(self.k_var):
             self.kvalues['value'][i] = k.value
    
        ## update curve
        R_x = np.linspace(self.Rmin, self.Rmax, self.N)
        dR_dt_depl = self.depletion(R_x, self.kvalues)
        dR_dt_aggr = self.aggregation(R_x, self.S, self.kvalues)
        #R_ss = Rss(self.S, self.kvalues)
        
        self.data_dR_dt_R.data = dict(R=R_x, dR_dt_depl=dR_dt_depl, dR_dt_aggr=dR_dt_aggr) #graphs
        #self.data_dR_dt_R_lines.data = dict(R_ss_y=[R_ss, R_ss], dR_dt_ss_y=[0, depletion(R_ss, self.kvalues)])#y parallel
        #self.data_dR_dt_R_point_lab.data = dict(R_ss=[R_ss], dR_dt_ss=[depletion(R_ss, self.kvalues)], lab=["R_ss = %.2f" % R_ss]) #label
        #self.data_dR_dt_R_point.data = dict(R_ss=R_ss, dR_dt_ss=depletion(R_ss, self.kvalues))
          
        #S = np.linspace(self.Smin, self.Smax, self.N)
        #R_y = Rss(S, self.kvalues)
        
        R_y = np.linspace(self.Rmin, self.Rmax, self.N)
        S_x = np.linspace(self.Smin, self.Smax, self.N)
        
        R_, S_ = np.meshgrid(R_y, S_x)
        RS = self.dRdt(R_, S_, self.kvalues)
        R_split = self.split_R(RS, R_)
        S_split = np.split(S_x, self.get_index_Scrit(RS))
        
        #implement a list of column_names and use that list with add to append datasource
        R = np.array([])
        R_dotted = np.array([])
        S = np.array([])
        S_dotted = np.array([])
        
        for i, r_ in enumerate(R_split):
            for j, r in enumerate(r_):
                s = S_split[i]
                _r = r
                _s = s
                if j%2 == 1:
                    _r = np.flip(r, 0)
                    _s = np.flip(s, 0)
                    R_dotted = np.append(R_dotted, _r)
                    S_dotted = np.append(S_dotted, _s)
                R = np.append(R, _r)
                S = np.append(S, _s)
        self.data_R_S2.data["R"] = R
        self.data_R_S2.data["S"] = S
        self.data_R_S2_dotted.data["R"] = R_dotted
        self.data_R_S2_dotted.data["S"] = S_dotted
        
        
        #self.data_S_R_lines.data=dict(R_ss_y=[0, R_ss], S_ss_y=[self.S, self.S], #y parallel
        #                              R_ss_x=[R_ss, R_ss], S_ss_x=[0, self.S]) #x parallel
        #self.data_S_R_point.data = dict(S_ss=S0, R_ss=R_ss)#dot
    
    def plot(self, doc):
        for w in self.k_var:
            w.on_change('value', self.update_data)
        self.S_var.on_change('value', self.update_data)
        
        # Set up layouts and add to document
        plot_dR_dt, plot_R_S, plot_wire, plot_formula = self.create_figure()
        l = row([column([plot_wire, plot_formula, widgetbox(self.S_var), row([widgetbox(self.k_var[0::2], width=150), widgetbox(self.k_var[1::2], width=150)])]),
                 plot_dR_dt, plot_R_S], sizing_mode='fixed', width=1500, height=800)
        doc.add_root(l)
    
    def show_notebook(self):
        handler = FunctionHandler(self.plot)
        app = Application(handler)
        show(app, notebook_url="localhost:8888")
        
    def show_server(self):
        self.plot(curdoc())
        curdoc().title = self.title 
Exemple #59
0
source = ColumnDataSource(data=dict())

columns = [TableColumn(field="name", title="Employee Name"),
           TableColumn(field="salary", title="Income"),
           TableColumn(field="years_experience", title="Experience (years)")]

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

def update(attr, old, new):
    curr_df = df[df['salary'] <= salary_range.value].dropna()
    source.data = dict(name=curr_df['name'].tolist(),
                       salary=curr_df['salary'].tolist(),
                       years_experience=curr_df['years_experience'].tolist())


salary_range.on_change('value', update)

js_callback = """
var data = source.get('data');
var filetext = 'name,income,years_experience\\n';
for (i=0; i < data['name'].length; i++) {
    var currRow = [data['name'][i].toString(),
                   data['salary'][i].toString(),
                   data['years_experience'][i].toString().concat('\\n')];

    var joined = currRow.join();
    filetext = filetext.concat(joined);
}

var filename = 'data_result.csv';
var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' });