예제 #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()
예제 #2
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)])
예제 #3
0
파일: fpdapp.py 프로젝트: cdmbi/FPD
    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,
                )
예제 #4
0
파일: fpdapp.py 프로젝트: cdmbi/FPD
 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,
             )
예제 #5
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)
예제 #6
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])
예제 #7
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))
예제 #8
0
파일: dims.py 프로젝트: trhallam/geoPy
    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)
예제 #9
0
    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 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)
예제 #11
0
OD = output_data[output_data['Cluster'] == 1]

global slider

CL = list(OD._get_numeric_data().columns)

X = OD._get_numeric_data().columns[0]

Y = OD._get_numeric_data().columns[1]

Z = OD._get_numeric_data().columns[2]

threhsold_slider = Slider(
    start=min(OD[Z]),
    end=max(OD[Z]),
    value=1,
    step=1,
    title="Color Threshold (For determining color of points)")

Xselect = Select(title="X-axis", value=X, options=CL)
#Xselect.on_change('value', my_slider_handler)

Yselect = Select(title="Y-axis", value=Y, options=CL)
#Yselect.on_change('value', my_slider_handler)

Zselect = Select(title="Color Threshold Column", value=Z, options=CL)
#Zselect.on_change('value', my_slider_handler)

seg_plot = figure(tools="pan,wheel_zoom,box_zoom,box_select,reset,save",
                  height=400,
                  width=400)
예제 #12
0
파일: main.py 프로젝트: bgyarfas/bokeh
from bokeh.models.widgets import Slider, Button, DataTable, TableColumn, NumberFormatter
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)
예제 #13
0
파일: rmclt.py 프로젝트: alexschlueter/ba
# X = np.full(num_runs, -5.0)
X = np.copy(X_init)
hist, edges = np.histogram(X, density=True, bins=50)

p1 = figure(x_range=[-10, 10], y_range=[-0.7, 0.7])
p1.add_tools(ResizeTool())
r1 = p1.line(x, y, color="navy")
h1 = p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#036564", line_color="#033649", alpha=0.5)

p2 = figure()
p2.add_tools(ResizeTool())
h2 = p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#036564", line_color="#033649", alpha=0.5)

slider = Slider(start=1, end=10, value=1, step=.1, title="Speed")
button_group = RadioButtonGroup(labels=["Play", "Pause"], active=1)
button = Button(label="Reset", button_type="warning")
it = PreText(text="Iteration 1")
wb = widgetbox(slider, button_group, button, it)


session = push_session(curdoc())

def redraw():
    hist, edges = np.histogram(X, density=True, bins=50)
    h1.data_source.data["top"] = hist
    h1.data_source.data["left"] = edges[:-1]
    h1.data_source.data["right"] = edges[1:]

    hist, edges = np.histogram(math.sqrt(step)*X, density=True, bins=50)
예제 #14
0
outputDF = pd.DataFrame(columns=X_train.columns)
resultDF = ColumnDataSource(outputDF)
columns = [TableColumn(field=col, title=col) for col in outputDF.columns]
data_table = DataTable(source=resultDF, columns=columns, width=1000, height=400)

imp_outputDF = imp.sort_values(by='score', ascending=False)
imp_resultDF = ColumnDataSource(imp_outputDF)
imp_columns = [TableColumn(field=col, title=col) for col in imp_outputDF.columns]
imp_data_table = DataTable(source=imp_resultDF, columns=imp_columns, width=300, height=400)

text = TextInput(title='title', value='my indicator')
SliderList_x = [Slider(title=col,
                       value=x_values.loc['mean', col],
                       start=x_values.loc['amin', col],
                       end=x_values.loc['amax', col],
                       step=.01,
                       orientation='vertical',
                       width=100,
                       height=400) for col in x_values.columns]

x = [1]

presentDF = pd.DataFrame.from_dict({val.title: val.value for val in SliderList_x}, orient='index').T
pred = fit.predict(presentDF)
source = ColumnDataSource(data=dict(x=x, y=pred))

y_indicator = Paragraph(text=str('%f' % pred[0]), width=100, height=10)

plot = figure(plot_height=450, plot_width=70, title='',
              tools='crosshair, pan, reset, save, wheel_zoom')
plot.vbar_stack(['y'], x=.5, width=.5, source=source, color='firebrick')
예제 #15
0
파일: main.py 프로젝트: alex-marty/demo-eau
dates = conso_sectors.index.get_level_values("date")
conso_bounds = (conso_sectors_pert["real"].min(), conso_sectors_pert["real"].max())

geo_source = ColumnDataSource(data=dict(xs=[], ys=[], colors=[]))
conso_source = ColumnDataSource(data=dict(date=[], conso=[], diff=[]))
datetime_source = ColumnDataSource(data=dict(date=[], conso=[]))


# Inputs
print("Building page")
button = Button(label="Close")
sector_select = Select(title="Secteur", value="1",
                       options=list(map(str, range(1, n_sectors))))
date_slider = Slider(title="Date",
                     start=dates.min().day,
                     end=dates.max().day,
                     step=1,
                     value=dates.min().day)
time_slider = Slider(title="Heure", start=0, end=23, step=1, value=0)
type_button = CheckboxButtonGroup(labels=["Secteur", "Signal"], active=[0])


# Plots
class MapPlot(object):
    def __init__(self):
        self.map_plot = Figure(
            tools="pan,wheel_zoom,tap", toolbar_location="right",
            logo=None, min_border=0, min_border_left=0,
            **get_paris_extent(0.6), # x_range & y_range
            plot_width=1100, plot_height=650)
        self.map_plot.add_tile(tile_source=OSM_TILE_SOURCE)
    new_src = make_dataset(carriers_to_plot,
                           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],
예제 #17
0
def effect_tab(df):
    """
    This will create a tab which show the relationship between
    year and Attack counts
    Parameters:
        df (DadaFrame): a pandas dataframe

    Returns:
        tab: bokeh object
    """
    # Setup needed variable
    abb = [
        'Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'June', 'July', 'Aug.', 'Sept.',
        'Oct.', 'Nov.', 'Dec.'
    ]

    def make_data(df, year=1970, month=abb):
        """
        Modify the dataframe for plotting
        Parameter:
            df (DataFrame): a pandas dataframe
            month (list): a list of month abbreviated
            year (int): specific year passed by client,
                        default value 1970

        Returns:
            ColumnDataSource: a bokeh object like dataframe
        """
        modified = df[df['iyear'] == year].groupby(
            'imonth', as_index=False)['eventid'].count()
        modified = modified[modified['imonth'] != 0]
        abb = []
        for i in list(modified['imonth']):
            abb.append(month[i - 1])
        modified['months'] = abb
        return ColumnDataSource(modified)

    def make_static_data(df, month=abb):
        """
        Modify the dataframe for plotting
        Parameter:
            df (Dataframe): a pandas dataframe
            month (list): a list of month abbreviated

        Returns:
            ColumnDataSource: a bokeh object
        """
        modified = df.groupby('imonth', as_index=False)['eventid'].count()
        modified = modified[modified['imonth'] != 0]
        abb = []
        for i in list(modified['imonth']):
            abb.append(month[i - 1])
        modified['months'] = abb
        return ColumnDataSource(modified)

    def update():
        """
        update the dataframe when client interact with slider
        """
        new_src = make_data(df, year.value)
        src.data.update(new_src.data)

    # Setup nessary value
    year = Slider(start=1970, end=2017, value=1970, step=1, title="Year Range")
    year.on_change('value', lambda attr, old, new: update())
    src = make_data(df)
    static = make_static_data(df)

    # Hover information
    TOOLTIPS = [('Month', '@months'), ('Counts', '@eventid')]

    # Plot one show relationship between attack numbers and each year
    p1 = figure(plot_height=600,
                plot_width=800,
                title='Total Attacks Over Different Year by Month',
                x_axis_label='Month',
                y_axis_label='Attacks',
                tooltips=TOOLTIPS,
                output_backend="webgl")
    p1.line(x='imonth', y='eventid', source=src, line_width=2, color='red')
    p1.circle(x='imonth', y='eventid', source=src, size=8, fill_color='white')

    # Plot two show relationship between attack numbers and each month
    p2 = figure(plot_height=600,
                plot_width=800,
                title='Total Attacks Over Years by Month',
                x_axis_label='Month',
                y_axis_label='Attacks',
                tooltips=TOOLTIPS,
                output_backend="webgl")
    p2.line(x='imonth', y='eventid', source=static, line_width=2, color='blue')
    p2.circle(x='imonth',
              y='eventid',
              source=static,
              size=8,
              fill_color='white')

    # Setup tab name and structure
    tab = Panel(child=column(year, p1, p2), title='Year Effect Attacks')

    return tab
예제 #18
0
DELIM_4 = Div(text="""<h2><span style="color: #800080;"
width=500 height=15>Almost Done. Just Submit!</span></h2>""")
DELIM_5 = Div(text="""<h2><span style="color: #800080;"
width=500 height=15>Ta Daa .....!</span></h2>""")

# Import dataset, the first sheet in the merged dataset
MAIN_DATA = pd.read_csv("main_data.csv", sep=",")

# Create widgets
BED = Select(title="Bedroom number:", value="3", options=['2', '3', '4', '5'])
BATH = Select(title="Bathroom number:",
              value="2",
              options=['2', '3', '4', '5'])
BUILTYEAR = Slider(title="Built year:",
                   value=1900,
                   start=1900,
                   end=2015,
                   step=1)
ZIPCODE = Select(
    title="Zipcode:",
    value="98004",
    options=[str(x) for x in sorted(list(set(MAIN_DATA.zipcode.values)))])
SQFT_LIVING = Slider(title="Living Sqft:",
                     value=500,
                     start=500,
                     end=5500,
                     step=10)
SQFT_LOT = Slider(title="Lot Sqft:", value=500, start=500, end=5500, step=10)
WATERFRONT = Select(title="Waterfront:",
                    value="Either",
                    options=['Either', 'Yes', 'No'])
예제 #19
0
def kde():
    ###------------------------PARAMETER DEFAULTS-----------------------------###
    #  range[Lower, Upper, Step Size]
    ### - SAMPLING Parameters
    d_nsamp, r_nsamp = 500, [100, 2000, 50]  # Number of samples

    plot_data = figure(
        plot_height=400,
        plot_width=800,
        title="Data Histogram",
        toolbar_location="above",
        x_axis_label="x",
        y_axis_label="Density",
        tools="pan,save,box_zoom,wheel_zoom",
    )
    style(plot_data)

    plot_clear = Button(label="Clear All", button_type="warning")

    # Plot Control Buttons

    ctl_title = Div(text="<h3>1 - Simulator</h3>")
    dist_type = Select(
        title="Select sampling distribution:",
        value="Gaussian",
        options=["Gaussian", "Beta", "Gamma"],
    )

    div1 = Div(
        text=
        """<p style="border:3px; border-style:solid; border-color:grey; padding: 1em;">
                    Parameters depend on the distribution. Refer to Scipy Documentation. <br />  
                    - Gaussian: loc (mean), scale (variance).<br />  
                    - Gamma: a, loc, scale.<br /> 
                    - Beta: a, b, loc, scale.<br /> 
                    </p>""",
        width=300,
        height=130,
    )

    ctl_nsamp = Slider(
        title="Number of samples",
        value=d_nsamp,
        start=r_nsamp[0],
        end=r_nsamp[1],
        step=r_nsamp[2],
    )

    mu = TextInput(title="Mean", value="0.0")
    sigma = TextInput(title="Variance", value="1.0")
    a = TextInput(title="a", value="1.0")
    b = TextInput(title="b", value="1.0")

    plot_sim = Button(label="Simulate", button_type="primary")
    simulate = widgetbox(ctl_title, dist_type, div1, ctl_nsamp, mu, sigma, a,
                         b, plot_sim)

    # plot_ctls = column(ctl_title, div1, plot_sim)

    ### Manual Fitting
    fit_title = Div(text="<h3>2 - Manual KDE</h3>")

    kernel = Select(
        title="Select kernel to fit on data:",
        value="gaussian",
        options=["gaussian", "tophat", "exponential", "linear", "cosine"],
    )
    bandwidth = TextInput(title="Bandwidth", value="1.0")

    fit_sim = Button(label="Fit", button_type="success")

    fit1 = widgetbox(fit_title, kernel, bandwidth, fit_sim)

    ### Cross Validation fit
    fit_title = Div(
        text=
        "<h3>3 - Cross Validation - Params Search</h3> <br /> Select kernels for parameter search."
    )

    kernels = CheckboxButtonGroup(
        active=[0, 1],
        labels=["gaussian", "tophat", "exponential", "linear", "cosine"])
    bandwidths = RangeSlider(title="Bandwidth in Log-space",
                             start=-2,
                             end=1,
                             value=(-1, 0.5),
                             step=0.05)

    cv_slider = Slider(title="Nb of cross-validation",
                       value=5,
                       start=1,
                       end=10,
                       step=1)

    fit_sim2 = Button(label="Fit", button_type="success")
    text_output = TextAreaInput(
        value="Choose Bandwidth Range and Kernels from above.",
        rows=4,
        title="Estimated Paramters:",
    )

    fit2 = widgetbox(fit_title, kernels, bandwidths, cv_slider, fit_sim2,
                     text_output)

    ###-----------------------------------------------------------------------###
    ###-----------------------BASE-LEVEL FUNCTIONS----------------------------###

    def make_data(dist_type, params):
        # sample data according to dist_type
        data = DISTRIBUTIONS[dist_type].rvs(**params)
        return data

    ###-----------------------------------------------------------------------###
    ###------------------DATA SOURCES AND INITIALIZATION----------------------###

    source1 = ColumnDataSource(data=dict(hist=[], left=[], right=[]))
    plot_data.quad(
        source=source1,
        bottom=0,
        top="hist",
        left="left",
        right="right",
        fill_color="blue",
        line_color="white",
        alpha=0.5,
    )

    source2 = ColumnDataSource(data=dict(x=[], y=[]))
    plot_data.line(
        "x",
        "y",
        source=source2,
        line_width=2,
        alpha=0.7,
        legend="Estimated PDF",
        line_color="black",
    )

    def click_simulate():
        # Make it global to be used later
        global d_data
        # reset pdf
        source2.data = dict(x=[], y=[])
        text_output.value = ""

        if dist_type.value == "Gaussian":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Gamma":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Beta":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "b": float(b.value),
                "size": int(ctl_nsamp.value),
            }

        d_data = make_data(dist_type.value, params)

        hist, edges = np.histogram(d_data, density=True, bins=100)

        source1.data = dict(hist=hist, left=edges[:-1], right=edges[1:])

        plot_data.y_range.start = 0
        plot_data.y_range.end = 1.2 * hist.max()

        plot_data.x_range.start = edges.min() - 1 * (dist_type.value != "Beta")
        plot_data.x_range.end = edges.max() + 1 * (dist_type.value != "Beta")

        plot_data.xaxis.axis_label = "x"
        plot_data.yaxis.axis_label = "Density"

    plot_sim.on_click(click_simulate)

    # KDE Fit

    def fit_kde():
        kde = KernelDensity(kernel=kernel.value,
                            bandwidth=float(bandwidth.value)).fit(
                                d_data.reshape(-1, 1))

        x = np.linspace(d_data.min() - 0.5,
                        d_data.max() + 0.5, 1000).reshape(-1, 1)
        log_dens = kde.score_samples(x)

        source2.data = dict(x=x, y=np.exp(log_dens))

    fit_sim.on_click(fit_kde)

    # Fir CV-model

    def fit_kde_cv():
        text_output.value = "Running..."

        kernels_space = [KERNELS[i] for i in kernels.active]

        min_b = list(bandwidths.value)[0]
        max_b = list(bandwidths.value)[1]

        params = {
            "bandwidth": np.logspace(min_b, max_b, 10),
            "kernel": kernels_space
        }

        grid = GridSearchCV(KernelDensity(),
                            params,
                            cv=int(cv_slider.value),
                            iid=False)

        grid.fit(d_data.reshape(-1, 1))

        x = np.linspace(d_data.min() - 0.5,
                        d_data.max() + 0.5, 1000).reshape(-1, 1)
        log_dens = grid.best_estimator_.score_samples(x)

        source2.data = dict(x=x, y=np.exp(log_dens))

        text_output.value = "CV done. \nBest Params: \n" + str(
            grid.best_params_)

    fit_sim2.on_click(fit_kde_cv)

    # Behavior when the "Clear" button is clicked
    def clear_plot():
        source1.data = dict(hist=[], left=[], right=[])
        source2.data = dict(x=[], y=[])
        text_output.value = ""

    plot_clear.on_click(clear_plot)

    ###-----------------------------------------------------------------------###
    ###----------------------------PAGE LAYOUT--------------------------------###

    col_inputs = column(simulate)
    col_output = column(fit1, fit2, plot_clear)
    col_plots = column(plot_data)
    row_page = row(col_inputs, col_plots, col_output, width=1200)

    # Make a tab with the layout
    tab = Panel(child=row_page, title="Kernel Density Estimation")
    return tab
root_select = Select(title="Kök niteliği seçiniz:",
                     options=['Hiçbiri'] +
                     [attr for attr in list(Instance.attr_list)[:-1]],
                     value="Hiçbiri")
method_select = Select(title="Metodu seçiniz:",
                       options=radio_button_labels,
                       value="gini")
tree_select = Select(title="Ağacın görünümünü seçiniz:",
                     options=tree_mode_labels,
                     value="Basit")
dataset_select = Select(title="Veri kümesini seç:",
                        value="lens",
                        options=["lens", "car"])
dataset_slider = Slider(start=0,
                        end=50,
                        value=0,
                        step=1,
                        title="Test verisi oranı")
rect_width = 2
rect_height = 0.5
circle_radius = 5
TOOLTIPS = [("Metod Değeri", "@{nonLeafNodes_stat}"),
            ("Örnek Sayısı", "@{instances}"), ("Sonuç", "@{decision}")]
"""""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""
"""Adapted from https://groups.google.com/a/continuum.io/d/msg/bokeh/EtuMtJI39qQ/ZWuXjBhaAgAJ"""
"""vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"""
file_button = Button(label="Veri kümesi yükleyin", button_type="success")
file_source = ColumnDataSource({'contents': [], 'name': []})
_upload_js = """
function read_file(filename) {
    var reader = new FileReader();
예제 #21
0
# WDIR = Path(r"C:\Users\riw\tubCloud\Uni\Market_Tool\pomato_studies\data_temp\bokeh_files")
# Init Data
option_market_db = [
    path for path in os.listdir(WDIR.joinpath("market_result"))
    if "." not in path
]
(nodes, g_by_fuel, demand, inj, f_dc, t_first, t_last, lines, dclines,
 lodf_matrix, n_0_flows, n_1_flows) = init_market_data(option_market_db[0])

## Define Widgets and function calls
select_market_db = Select(title="Model Run:",
                          value=option_market_db[0],
                          options=option_market_db)
slider = Slider(start=t_first,
                end=t_last,
                value=t_first,
                step=1,
                title="Timestep")
# value_throttled=0, callback_policy="throttle") # Throttle doesnt work as of now

flow_type_botton = RadioButtonGroup(name="Choose Flow Case:",
                                    width=300,
                                    labels=["N-0", "N-1", "Voltage Level"],
                                    active=0)
flow_type_botton.on_change('active', update_line_loadings)

##Update things when slider or selects are changed
slider.on_change('value', update_line_loadings)
slider.on_change('value', update_stacked_bars)
slider.on_change('value', update_node_injections)
예제 #22
0
    'transform': LinearColorMapper(palette=palette, low=0, high=650)
}
fill_color3 = {
    'field': source.data['evics'],
    'transform': LinearColorMapper(palette=palette, low=0, high=75)
}
fill_color4 = {
    'field': source.data['evics'],
    'transform': LinearColorMapper(palette=palette, low=0, high=500)
}
#---------------------------------------------------------------#
# Widgets Setup
year = Slider(title='',
              value=0,
              start=0,
              end=len(sorted_unique_dates) - 2,
              step=1,
              callback_policy='throttle',
              callback_throttle=500)
year.show_value = False
year2 = Slider(title='',
               value=2000,
               start=2000,
               end=2018,
               step=1,
               callback_policy='throttle',
               callback_throttle=500)
year2.visible = False
paragraph = Paragraph(text='January 2000', width=200, height=8)
paragraph.default_size = 500
opacity = Slider(title='Opacity', value=0.6, start=0, end=1.0, step=0.1)
def searches_tab(countries):

    # Dataset for density plot based on carriers, range of delays,
    # and bandwidth for density estimation
    def make_dataset(country_list, range_start, range_end, bandwidth):

        xs = []
        ys = []
        colors = []
        labels = []

        for i, country in enumerate(country_list):
            subset = countries[countries['country_region'] == country]
            subset = subset[subset['residential'].between(
                range_start, range_end)]

            kde = gaussian_kde(subset['residential'], bw_method=bandwidth)

            # Evenly space x values
            x = np.linspace(range_start, range_end, 100)
            # Evaluate pdf at every value of x
            y = kde.pdf(x)

            # Append the values to plot
            xs.append(list(x))
            ys.append(list(y))

            # Append the colors and label
            colors.append(country_colors[i])
            labels.append(country)

        new_src = ColumnDataSource(data={
            'x': xs,
            'y': ys,
            'color': colors,
            'label': labels
        })

        return new_src

    def make_plot(src):
        p = figure(plot_width=700,
                   plot_height=700,
                   title='Plot of Residential Searches by Country',
                   x_axis_label='Number of Searches',
                   y_axis_label='Scaled Value')

        p.multi_line('x',
                     'y',
                     color='color',
                     legend='label',
                     line_width=3,
                     source=src)

        # Hover tool with next line policy
        hover = HoverTool(tooltips=[('Country', '@label'), ('Searches', '$x'),
                                    ('Scaled Value', '$y')],
                          line_policy='next')

        # Add the hover tool and styling
        p.add_tools(hover)

        p = style(p)

        return p

    def update(attr, old, new):

        country_to_plot = [
            country_selection.labels[i] for i in country_selection.active
        ]

        # If no bandwidth is selected, use the default value
        if bandwidth_choose.active == []:
            bandwidth = None
        # If the bandwidth select is activated, use the specified bandwith
        else:
            bandwidth = bandwidth_select.value

        new_src = make_dataset(country_to_plot,
                               range_start=range_select.value[0],
                               range_end=range_select.value[1],
                               bandwidth=bandwidth)

        src.data.update(new_src.data)

    def style(p):
        # Title
        p.title.align = 'center'
        p.title.text_font_size = '20pt'
        p.title.text_font = 'serif'

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

        # Tick labels
        p.xaxis.major_label_text_font_size = '12pt'
        p.yaxis.major_label_text_font_size = '12pt'

        return p

    available_countries = list(set(countries['country_region']))
    available_countries.sort()

    country_colors = Category20_16
    sorted(country_colors)

    country_selection = CheckboxGroup(labels=available_countries,
                                      active=[0, 1])
    country_selection.on_change('active', update)

    range_select = RangeSlider(start=-60,
                               end=180,
                               value=(-60, 120),
                               step=5,
                               title='Range of Delays (min)')
    range_select.on_change('value', update)

    initial_countries = [
        country_selection.labels[i] for i in country_selection.active
    ]

    # Bandwidth of kernel
    bandwidth_select = Slider(start=0.1,
                              end=5,
                              step=0.1,
                              value=0.5,
                              title='Bandwidth for Density Plot')
    bandwidth_select.on_change('value', update)

    # Whether to set the bandwidth or have it done automatically
    bandwidth_choose = CheckboxButtonGroup(
        labels=['Choose Bandwidth (Else Auto)'], active=[])
    bandwidth_choose.on_change('active', update)

    # Make the density data source
    src = make_dataset(initial_countries,
                       range_start=range_select.value[0],
                       range_end=range_select.value[1],
                       bandwidth=bandwidth_select.value)

    # Make the density plot
    p = make_plot(src)

    # Add style to the plot
    p = style(p)

    # Put controls in a single element
    controls = WidgetBox(country_selection)
    col_inputs = column(controls,
                        sizing_mode='fixed',
                        height=700,
                        width=350,
                        css_classes=['scrollable'])

    # Create a row layout
    layout = row(col_inputs, p)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Density Plot')

    return tab
예제 #24
0
          source=source,
          line_width=3,
          line_alpha=0.6,
          color="turquoise")

arrayoftimes = np.array(photometry_time)

text = TextInput(title="Insert the name of the supernova here:",
                 value='',
                 callback=callback2)
lumdist_input = TextInput(title="title", value=str(lumdist))
redshift_input = TextInput(title="title", value=str(redshift))

M_slider = Slider(start=0.1,
                  end=10,
                  value=1,
                  step=.1,
                  title="Ejecta Mass",
                  callback=callback)
n_slider = Slider(start=6,
                  end=14,
                  value=7,
                  step=0.1,
                  title="n",
                  callback=callback)
rho_slider = Slider(start=-15,
                    end=-1,
                    value=-10,
                    step=.1,
                    title="rho",
                    callback=callback)
r0_slider = Slider(start=1,
예제 #25
0
         line_dash=[4, 4], line_color="orange", line_width=2)

arc_source = ColumnDataSource(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"]))
fig.arc(x='x', y='y',
        radius='radius',
        start_angle='start',
        end_angle='end',
        radius_units="data", color="color", source=arc_source)


alpha_slider = Slider(title="alpha", value=alpha, bar_color="red",
                      start=0, end=360, step=1)
beta_slider = Slider(title="beta", value=beta, bar_color="blue",
                     start=0, end=360, step=1)


def update_alpha(attr, old, new):
    global alpha
    alpha = alpha_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],
예제 #26
0
from bokeh.models.widgets import Slider, Button, DataTable, TableColumn, NumberFormatter
from bokeh.io import curdoc

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)
예제 #27
0
파일: main.py 프로젝트: 280185386/bokeh
### NOTE: The csv export will not work on Safari
import bokeh
import pandas as pd

from bokeh.plotting import ColumnDataSource
from bokeh.models import CustomJS, HBox, VBox, VBoxForm
from bokeh.models.widgets import Slider, Button, DataTable, TableColumn
from bokeh.io import curdoc, vform

# note this is fake data
df = pd.read_csv('salary_data.csv')

salary_range = Slider(title="Max Salary", start=10000, end=250000, value=150000, step=1000)
button = Button(label="Download")
button.button_type = "success"

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())

예제 #28
0
        'Keyword': current.Keyword,
        'daily_impressions_average': impressions,
        'daily_clicks_average': current.daily_clicks_average,
        'ad_position_average': current.ad_position_average,
        'cpc_average': current.cpc_average,
        'daily_cost_average': current.daily_cost_average,
        'source': current.source
    }
    bar_data[choice[0]] = np.log([gkp[x].sum() for x in metric])
    bar_data[choice[1]] = np.log([current[x].sum() for x in metric])
    bar_source.data = bar_data


slider = Slider(title="Daily budget",
                start=minimum,
                end=maximum,
                value=first_budget,
                step=0.1,
                format="0,0")
slider.on_change('value', lambda attr, old, new: update())

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

columns = [
    TableColumn(field="Keyword", title="Keyword"),
    TableColumn(field="daily_cost_average",
                title="Cost",
                formatter=NumberFormatter(format="$0,0.00")),
    TableColumn(field="ad_position_average", title="Position"),
예제 #29
0
# plotting for normal parametrization
source_point_normal = ColumnDataSource(data=dict(x=[], y=[]))

# 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
예제 #30
0
파일: widgets.py 프로젝트: desihub/prospect
    def add_redshift_widgets(self, z, viewer_cds, plots):
        ## TODO handle "z" (same issue as viewerplots TBD)

        #-----
        #- Redshift / wavelength scale widgets
        z1 = np.floor(z*100)/100
        dz = z-z1
        self.zslider = Slider(start=-0.1, end=5.0, value=z1, step=0.01, title='Redshift rough tuning')
        self.dzslider = Slider(start=0.0, end=0.0099, value=dz, step=0.0001, title='Redshift fine-tuning')
        self.dzslider.format = "0[.]0000"
        self.z_input = TextInput(value="{:.4f}".format(z), title="Redshift value:")

        #- Observer vs. Rest frame wavelengths
        self.waveframe_buttons = RadioButtonGroup(
            labels=["Obs", "Rest"], active=0)

        self.zslider_callback  = CustomJS(
            args=dict(zslider=self.zslider, dzslider=self.dzslider, z_input=self.z_input),
            code="""
            // Protect against 1) recursive call with z_input callback;
            //   2) out-of-range zslider values (should never happen in principle)
            var z1 = Math.floor(parseFloat(z_input.value)*100) / 100
            if ( (Math.abs(zslider.value-z1) >= 0.01) &&
                 (zslider.value >= -0.1) && (zslider.value <= 5.0) ){
                 var new_z = zslider.value + dzslider.value
                 z_input.value = new_z.toFixed(4)
                }
            """)

        self.dzslider_callback  = CustomJS(
            args=dict(zslider=self.zslider, dzslider=self.dzslider, z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            var z1 = Math.floor(z) / 100
            var z2 = z-z1
            if ( (Math.abs(dzslider.value-z2) >= 0.0001) &&
                 (dzslider.value >= 0.0) && (dzslider.value <= 0.0099) ){
                 var new_z = zslider.value + dzslider.value
                 z_input.value = new_z.toFixed(4)
                }
            """)

        self.zslider.js_on_change('value', self.zslider_callback)
        self.dzslider.js_on_change('value', self.dzslider_callback)

        self.z_minus_button = Button(label="<", width=self.z_button_width)
        self.z_plus_button = Button(label=">", width=self.z_button_width)
        self.z_minus_callback = CustomJS(
            args=dict(z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            if(z >= -0.09) {
                z -= 0.01
                z_input.value = z.toFixed(4)
            }
            """)
        self.z_plus_callback = CustomJS(
            args=dict(z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            if(z <= 4.99) {
                z += 0.01
                z_input.value = z.toFixed(4)
            }
            """)
        self.z_minus_button.js_on_event('button_click', self.z_minus_callback)
        self.z_plus_button.js_on_event('button_click', self.z_plus_callback)

        self.zreset_button = Button(label='Reset to z_pipe')
        self.zreset_callback = CustomJS(
            args=dict(z_input=self.z_input, metadata=viewer_cds.cds_metadata, ifiberslider=self.ifiberslider),
            code="""
                var ifiber = ifiberslider.value
                var z = metadata.data['Z'][ifiber]
                z_input.value = z.toFixed(4)
            """)
        self.zreset_button.js_on_event('button_click', self.zreset_callback)

        self.z_input_callback = CustomJS(
            args=dict(spectra = viewer_cds.cds_spectra,
                coaddcam_spec = viewer_cds.cds_coaddcam_spec,
                model = viewer_cds.cds_model,
                othermodel = viewer_cds.cds_othermodel,
                metadata = viewer_cds.cds_metadata,
                ifiberslider = self.ifiberslider,
                zslider = self.zslider,
                dzslider = self.dzslider,
                z_input = self.z_input,
                waveframe_buttons = self.waveframe_buttons,
                line_data = viewer_cds.cds_spectral_lines,
                lines = plots.speclines,
                line_labels = plots.specline_labels,
                zlines = plots.zoom_speclines,
                zline_labels = plots.zoom_specline_labels,
                overlap_waves = plots.overlap_waves,
                overlap_bands = plots.overlap_bands,
                fig = plots.fig
                ),
            code="""
                var z = parseFloat(z_input.value)
                if ( z >=-0.1 && z <= 5.0 ) {
                    // update zsliders only if needed (avoid recursive call)
                    z_input.value = parseFloat(z_input.value).toFixed(4)
                    var z1 = Math.floor(z*100) / 100
                    var z2 = z-z1
                    if ( Math.abs(z1-zslider.value) >= 0.01) zslider.value = parseFloat(parseFloat(z1).toFixed(2))
                    if ( Math.abs(z2-dzslider.value) >= 0.0001) dzslider.value = parseFloat(parseFloat(z2).toFixed(4))
                } else {
                    if (z_input.value < -0.1) z_input.value = (-0.1).toFixed(4)
                    if (z_input.value > 5) z_input.value = (5.0).toFixed(4)
                }

                var line_restwave = line_data.data['restwave']
                var ifiber = ifiberslider.value
                var waveshift_lines = (waveframe_buttons.active == 0) ? 1+z : 1 ;
                var waveshift_spec = (waveframe_buttons.active == 0) ? 1 : 1/(1+z) ;

                for(var i=0; i<line_restwave.length; i++) {
                    lines[i].location = line_restwave[i] * waveshift_lines
                    line_labels[i].x = line_restwave[i] * waveshift_lines
                    zlines[i].location = line_restwave[i] * waveshift_lines
                    zline_labels[i].x = line_restwave[i] * waveshift_lines
                }
                if (overlap_bands.length>0) {
                    for (var i=0; i<overlap_bands.length; i++) {
                        overlap_bands[i].left = overlap_waves[i][0] * waveshift_spec
                        overlap_bands[i].right = overlap_waves[i][1] * waveshift_spec
                    }
                }

                function shift_plotwave(cds_spec, waveshift) {
                    var data = cds_spec.data
                    var origwave = data['origwave']
                    var plotwave = data['plotwave']
                    if ( plotwave[0] != origwave[0] * waveshift ) { // Avoid redo calculation if not needed
                        for (var j=0; j<plotwave.length; j++) {
                            plotwave[j] = origwave[j] * waveshift ;
                        }
                        cds_spec.change.emit()
                    }
                }

                for(var i=0; i<spectra.length; i++) {
                    shift_plotwave(spectra[i], waveshift_spec)
                }
                if (coaddcam_spec) shift_plotwave(coaddcam_spec, waveshift_spec)

                // Update model wavelength array
                // NEW : don't shift model if othermodel is there
                if (othermodel) {
                    var zref = othermodel.data['zref'][0]
                    var waveshift_model = (waveframe_buttons.active == 0) ? (1+z)/(1+zref) : 1/(1+zref) ;
                    shift_plotwave(othermodel, waveshift_model)
                } else if (model) {
                    var zfit = 0.0
                    if(metadata.data['Z'] !== undefined) {
                        zfit = metadata.data['Z'][ifiber]
                    }
                    var waveshift_model = (waveframe_buttons.active == 0) ? (1+z)/(1+zfit) : 1/(1+zfit) ;
                    shift_plotwave(model, waveshift_model)
                }
            """)
        self.z_input.js_on_change('value', self.z_input_callback)
        self.waveframe_buttons.js_on_click(self.z_input_callback)

        self.plotrange_callback = CustomJS(
            args = dict(
                z_input=self.z_input,
                waveframe_buttons=self.waveframe_buttons,
                fig=plots.fig,
            ),
            code="""
            var z =  parseFloat(z_input.value)
            // Observer Frame
            if(waveframe_buttons.active == 0) {
                fig.x_range.start = fig.x_range.start * (1+z)
                fig.x_range.end = fig.x_range.end * (1+z)
            } else {
                fig.x_range.start = fig.x_range.start / (1+z)
                fig.x_range.end = fig.x_range.end / (1+z)
            }
            """
        )
        self.waveframe_buttons.js_on_click(self.plotrange_callback) # TODO: for record: is this related to waveframe bug? : 2 callbakcs for same click...
예제 #31
0
def line_tab(source, total_weekly):
    def create_data(source, total_weekly, year, state):
        df = source[(source["year"] == year) & (source["state_name"] == state)]
        totals = total_weekly[total_weekly["year"] == year]
        #Remove missing weeks
        weeks_in_both = set(df["week_num"]).intersection(totals["week_num"])
        df = df[df["week_num"].isin(weeks_in_both)]
        totals = totals[totals["week_num"].isin(weeks_in_both)]
        assert len(df) > 0, "No data for this state and year combination"
        data = dict(
            state_name=df["state_name"],
            incidence_per_capita_state=df["incidence_per_capita"],
            total_cases_state=df["cases"],
            incidence_per_capita_total=totals["avg_incidence_per_week"],
            total_cases_total=totals["total_cases_per_year"],
            avg_cases_total=totals["avg_cases_per_week"],
            year=df["year"],
            week_num=df["week_num"])

        return ColumnDataSource(data)

    def line_plot(src, chosen_state):
        line = figure(x_range=(1, 52),
                      plot_width=800,
                      plot_height=500,
                      title="Incidence of Measles",
                      toolbar_location=None,
                      tools="")
        line.line(x="week_num",
                  y="incidence_per_capita_total",
                  line_width=2,
                  source=src,
                  line_color="red",
                  legend="National weekly average incidence per capita")
        line.line(x="week_num",
                  y="incidence_per_capita_state",
                  line_width=2,
                  source=src,
                  legend="State weekly incidence per capita")
        line.xaxis.axis_label = "Week number"
        line.yaxis.axis_label = "Incidence per capita"
        line.circle(x="week_num",
                    y="incidence_per_capita_state",
                    size=12,
                    fill_color="grey",
                    hover_fill_color="firebrick",
                    fill_alpha=0.5,
                    hover_alpha=0.8,
                    line_color=None,
                    hover_line_color="white",
                    source=src)
        line.circle(x="week_num",
                    y="incidence_per_capita_total",
                    size=12,
                    fill_color="firebrick",
                    hover_fill_color="firebrick",
                    fill_alpha=0.3,
                    hover_alpha=0.5,
                    line_color=None,
                    hover_line_color="white",
                    source=src)

        line.add_tools(
            HoverTool(
                tooltips=[("Total cases (state)", "@total_cases_state"
                           ), ("Total cases (national)",
                               "@total_cases_total"), ("Week", "@week_num")]))
        return line

    def update_map(attr, old, new):
        chosen_year = choose_year.value
        chosen_state = choose_state.value
        new_data = create_data(source, total_weekly, chosen_year, chosen_state)
        src.data.update(new_data.data)

    #Define Widgets
    choose_year = Slider(start=1928,
                         end=2002,
                         value=1928,
                         step=1,
                         title="Year")
    choose_year.on_change('value', update_map)
    states = source["state_name"].unique()
    menu = [(state, state) for state in states]
    choose_state = Select(options=menu,
                          value="NEW YORK",
                          title="Choose a US State")
    choose_state.on_change('value', update_map)

    #Select starting data
    src = create_data(source, total_weekly, 1928, "NEW YORK")

    #Init plot and set layout
    controls = WidgetBox(choose_year, choose_state)
    l = line_plot(src, choose_state.value)
    layout = column(controls, l)
    tab = Panel(child=layout, title="Weekly Incidence")
    return tab
예제 #32
0
파일: widgets.py 프로젝트: desihub/prospect
class ViewerWidgets(object):
    """ 
    Encapsulates Bokeh widgets, and related callbacks, that are part of prospect's GUI.
        Except for VI widgets
    """
    
    def __init__(self, plots, nspec):
        self.js_files = get_resources('js')
        self.navigation_button_width = 30
        self.z_button_width = 30
        self.plot_widget_width = (plots.plot_width+(plots.plot_height//2))//2 - 40 # used for widgets scaling
    
        #-----
        #- Ifiberslider and smoothing widgets
        # Ifiberslider's value controls which spectrum is displayed
        # These two widgets call update_plot(), later defined
        slider_end = nspec-1 if nspec > 1 else 0.5 # Slider cannot have start=end
        self.ifiberslider = Slider(start=0, end=slider_end, value=0, step=1, title='Spectrum (of '+str(nspec)+')')
        self.smootherslider = Slider(start=0, end=26, value=0, step=1.0, title='Gaussian Sigma Smooth')
        self.coaddcam_buttons = None
        self.model_select = None


    def add_navigation(self, nspec):
        #-----
        #- Navigation buttons
        self.prev_button = Button(label="<", width=self.navigation_button_width)
        self.next_button = Button(label=">", width=self.navigation_button_width)
        self.prev_callback = CustomJS(
            args=dict(ifiberslider=self.ifiberslider),
            code="""
            if(ifiberslider.value>0 && ifiberslider.end>=1) {
                ifiberslider.value--
            }
            """)
        self.next_callback = CustomJS(
            args=dict(ifiberslider=self.ifiberslider, nspec=nspec),
            code="""
            if(ifiberslider.value<nspec-1 && ifiberslider.end>=1) {
                ifiberslider.value++
            }
            """)
        self.prev_button.js_on_event('button_click', self.prev_callback)
        self.next_button.js_on_event('button_click', self.next_callback)

    def add_resetrange(self, viewer_cds, plots):
        #-----
        #- Axis reset button (superseeds the default bokeh "reset"
        self.reset_plotrange_button = Button(label="Reset X-Y range", button_type="default")
        reset_plotrange_code = self.js_files["adapt_plotrange.js"] + self.js_files["reset_plotrange.js"]
        self.reset_plotrange_callback = CustomJS(args = dict(fig=plots.fig, xmin=plots.xmin, xmax=plots.xmax, spectra=viewer_cds.cds_spectra),
                                            code = reset_plotrange_code)
        self.reset_plotrange_button.js_on_event('button_click', self.reset_plotrange_callback)


    def add_redshift_widgets(self, z, viewer_cds, plots):
        ## TODO handle "z" (same issue as viewerplots TBD)

        #-----
        #- Redshift / wavelength scale widgets
        z1 = np.floor(z*100)/100
        dz = z-z1
        self.zslider = Slider(start=-0.1, end=5.0, value=z1, step=0.01, title='Redshift rough tuning')
        self.dzslider = Slider(start=0.0, end=0.0099, value=dz, step=0.0001, title='Redshift fine-tuning')
        self.dzslider.format = "0[.]0000"
        self.z_input = TextInput(value="{:.4f}".format(z), title="Redshift value:")

        #- Observer vs. Rest frame wavelengths
        self.waveframe_buttons = RadioButtonGroup(
            labels=["Obs", "Rest"], active=0)

        self.zslider_callback  = CustomJS(
            args=dict(zslider=self.zslider, dzslider=self.dzslider, z_input=self.z_input),
            code="""
            // Protect against 1) recursive call with z_input callback;
            //   2) out-of-range zslider values (should never happen in principle)
            var z1 = Math.floor(parseFloat(z_input.value)*100) / 100
            if ( (Math.abs(zslider.value-z1) >= 0.01) &&
                 (zslider.value >= -0.1) && (zslider.value <= 5.0) ){
                 var new_z = zslider.value + dzslider.value
                 z_input.value = new_z.toFixed(4)
                }
            """)

        self.dzslider_callback  = CustomJS(
            args=dict(zslider=self.zslider, dzslider=self.dzslider, z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            var z1 = Math.floor(z) / 100
            var z2 = z-z1
            if ( (Math.abs(dzslider.value-z2) >= 0.0001) &&
                 (dzslider.value >= 0.0) && (dzslider.value <= 0.0099) ){
                 var new_z = zslider.value + dzslider.value
                 z_input.value = new_z.toFixed(4)
                }
            """)

        self.zslider.js_on_change('value', self.zslider_callback)
        self.dzslider.js_on_change('value', self.dzslider_callback)

        self.z_minus_button = Button(label="<", width=self.z_button_width)
        self.z_plus_button = Button(label=">", width=self.z_button_width)
        self.z_minus_callback = CustomJS(
            args=dict(z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            if(z >= -0.09) {
                z -= 0.01
                z_input.value = z.toFixed(4)
            }
            """)
        self.z_plus_callback = CustomJS(
            args=dict(z_input=self.z_input),
            code="""
            var z = parseFloat(z_input.value)
            if(z <= 4.99) {
                z += 0.01
                z_input.value = z.toFixed(4)
            }
            """)
        self.z_minus_button.js_on_event('button_click', self.z_minus_callback)
        self.z_plus_button.js_on_event('button_click', self.z_plus_callback)

        self.zreset_button = Button(label='Reset to z_pipe')
        self.zreset_callback = CustomJS(
            args=dict(z_input=self.z_input, metadata=viewer_cds.cds_metadata, ifiberslider=self.ifiberslider),
            code="""
                var ifiber = ifiberslider.value
                var z = metadata.data['Z'][ifiber]
                z_input.value = z.toFixed(4)
            """)
        self.zreset_button.js_on_event('button_click', self.zreset_callback)

        self.z_input_callback = CustomJS(
            args=dict(spectra = viewer_cds.cds_spectra,
                coaddcam_spec = viewer_cds.cds_coaddcam_spec,
                model = viewer_cds.cds_model,
                othermodel = viewer_cds.cds_othermodel,
                metadata = viewer_cds.cds_metadata,
                ifiberslider = self.ifiberslider,
                zslider = self.zslider,
                dzslider = self.dzslider,
                z_input = self.z_input,
                waveframe_buttons = self.waveframe_buttons,
                line_data = viewer_cds.cds_spectral_lines,
                lines = plots.speclines,
                line_labels = plots.specline_labels,
                zlines = plots.zoom_speclines,
                zline_labels = plots.zoom_specline_labels,
                overlap_waves = plots.overlap_waves,
                overlap_bands = plots.overlap_bands,
                fig = plots.fig
                ),
            code="""
                var z = parseFloat(z_input.value)
                if ( z >=-0.1 && z <= 5.0 ) {
                    // update zsliders only if needed (avoid recursive call)
                    z_input.value = parseFloat(z_input.value).toFixed(4)
                    var z1 = Math.floor(z*100) / 100
                    var z2 = z-z1
                    if ( Math.abs(z1-zslider.value) >= 0.01) zslider.value = parseFloat(parseFloat(z1).toFixed(2))
                    if ( Math.abs(z2-dzslider.value) >= 0.0001) dzslider.value = parseFloat(parseFloat(z2).toFixed(4))
                } else {
                    if (z_input.value < -0.1) z_input.value = (-0.1).toFixed(4)
                    if (z_input.value > 5) z_input.value = (5.0).toFixed(4)
                }

                var line_restwave = line_data.data['restwave']
                var ifiber = ifiberslider.value
                var waveshift_lines = (waveframe_buttons.active == 0) ? 1+z : 1 ;
                var waveshift_spec = (waveframe_buttons.active == 0) ? 1 : 1/(1+z) ;

                for(var i=0; i<line_restwave.length; i++) {
                    lines[i].location = line_restwave[i] * waveshift_lines
                    line_labels[i].x = line_restwave[i] * waveshift_lines
                    zlines[i].location = line_restwave[i] * waveshift_lines
                    zline_labels[i].x = line_restwave[i] * waveshift_lines
                }
                if (overlap_bands.length>0) {
                    for (var i=0; i<overlap_bands.length; i++) {
                        overlap_bands[i].left = overlap_waves[i][0] * waveshift_spec
                        overlap_bands[i].right = overlap_waves[i][1] * waveshift_spec
                    }
                }

                function shift_plotwave(cds_spec, waveshift) {
                    var data = cds_spec.data
                    var origwave = data['origwave']
                    var plotwave = data['plotwave']
                    if ( plotwave[0] != origwave[0] * waveshift ) { // Avoid redo calculation if not needed
                        for (var j=0; j<plotwave.length; j++) {
                            plotwave[j] = origwave[j] * waveshift ;
                        }
                        cds_spec.change.emit()
                    }
                }

                for(var i=0; i<spectra.length; i++) {
                    shift_plotwave(spectra[i], waveshift_spec)
                }
                if (coaddcam_spec) shift_plotwave(coaddcam_spec, waveshift_spec)

                // Update model wavelength array
                // NEW : don't shift model if othermodel is there
                if (othermodel) {
                    var zref = othermodel.data['zref'][0]
                    var waveshift_model = (waveframe_buttons.active == 0) ? (1+z)/(1+zref) : 1/(1+zref) ;
                    shift_plotwave(othermodel, waveshift_model)
                } else if (model) {
                    var zfit = 0.0
                    if(metadata.data['Z'] !== undefined) {
                        zfit = metadata.data['Z'][ifiber]
                    }
                    var waveshift_model = (waveframe_buttons.active == 0) ? (1+z)/(1+zfit) : 1/(1+zfit) ;
                    shift_plotwave(model, waveshift_model)
                }
            """)
        self.z_input.js_on_change('value', self.z_input_callback)
        self.waveframe_buttons.js_on_click(self.z_input_callback)

        self.plotrange_callback = CustomJS(
            args = dict(
                z_input=self.z_input,
                waveframe_buttons=self.waveframe_buttons,
                fig=plots.fig,
            ),
            code="""
            var z =  parseFloat(z_input.value)
            // Observer Frame
            if(waveframe_buttons.active == 0) {
                fig.x_range.start = fig.x_range.start * (1+z)
                fig.x_range.end = fig.x_range.end * (1+z)
            } else {
                fig.x_range.start = fig.x_range.start / (1+z)
                fig.x_range.end = fig.x_range.end / (1+z)
            }
            """
        )
        self.waveframe_buttons.js_on_click(self.plotrange_callback) # TODO: for record: is this related to waveframe bug? : 2 callbakcs for same click...


    def add_oii_widgets(self, plots):
        #------
        #- Zoom on the OII doublet TODO mv js code to other file
        # TODO: is there another trick than using a cds to pass the "oii_saveinfo" ?
        # TODO: optimize smoothing for autozoom (current value: 0)
        cds_oii_saveinfo = ColumnDataSource(
            {'xmin':[plots.fig.x_range.start], 'xmax':[plots.fig.x_range.end], 'nsmooth':[self.smootherslider.value]})
        self.oii_zoom_button = Button(label="OII-zoom", button_type="default")
        self.oii_zoom_callback = CustomJS(
            args = dict(z_input=self.z_input, fig=plots.fig, smootherslider=self.smootherslider,
                       cds_oii_saveinfo=cds_oii_saveinfo),
            code = """
            // Save previous setting (for the "Undo" button)
            cds_oii_saveinfo.data['xmin'] = [fig.x_range.start]
            cds_oii_saveinfo.data['xmax'] = [fig.x_range.end]
            cds_oii_saveinfo.data['nsmooth'] = [smootherslider.value]
            // Center on the middle of the redshifted OII doublet (vaccum)
            var z = parseFloat(z_input.value)
            fig.x_range.start = 3728.48 * (1+z) - 100
            fig.x_range.end = 3728.48 * (1+z) + 100
            // No smoothing (this implies a call to update_plot)
            smootherslider.value = 0
            """)
        self.oii_zoom_button.js_on_event('button_click', self.oii_zoom_callback)

        self.oii_undo_button = Button(label="Undo OII-zoom", button_type="default")
        self.oii_undo_callback = CustomJS(
            args = dict(fig=plots.fig, smootherslider=self.smootherslider, cds_oii_saveinfo=cds_oii_saveinfo),
            code = """
            fig.x_range.start = cds_oii_saveinfo.data['xmin'][0]
            fig.x_range.end = cds_oii_saveinfo.data['xmax'][0]
            smootherslider.value = cds_oii_saveinfo.data['nsmooth'][0]
            """)
        self.oii_undo_button.js_on_event('button_click', self.oii_undo_callback)


    def add_coaddcam(self, plots):
        #-----
        #- Highlight individual-arm or camera-coadded spectra
        coaddcam_labels = ["Camera-coadded", "Single-arm"]
        self.coaddcam_buttons = RadioButtonGroup(labels=coaddcam_labels, active=0)
        self.coaddcam_callback = CustomJS(
            args = dict(coaddcam_buttons = self.coaddcam_buttons,
                        list_lines=[plots.data_lines, plots.noise_lines,
                                    plots.zoom_data_lines, plots.zoom_noise_lines],
                        alpha_discrete = plots.alpha_discrete,
                        overlap_bands = plots.overlap_bands,
                        alpha_overlapband = plots.alpha_overlapband),
            code="""
            var n_lines = list_lines[0].length
            for (var i=0; i<n_lines; i++) {
                var new_alpha = 1
                if (coaddcam_buttons.active == 0 && i<n_lines-1) new_alpha = alpha_discrete
                if (coaddcam_buttons.active == 1 && i==n_lines-1) new_alpha = alpha_discrete
                for (var j=0; j<list_lines.length; j++) {
                    list_lines[j][i].glyph.line_alpha = new_alpha
                }
            }
            var new_alpha = 0
            if (coaddcam_buttons.active == 0) new_alpha = alpha_overlapband
            for (var j=0; j<overlap_bands.length; j++) {
                    overlap_bands[j].fill_alpha = new_alpha
            }
            """
        )
        self.coaddcam_buttons.js_on_click(self.coaddcam_callback)
    
    
    def add_metadata_tables(self, viewer_cds, show_zcat=True, template_dicts=None,
                           top_metadata=['TARGETID', 'EXPID']):
        """ Display object-related informations
                top_metadata: metadata to be highlighted in table_a
            
            Note: "short" CDS, with a single row, are used to fill these bokeh tables.
            When changing object, js code modifies these short CDS so that tables are updated.  
        """

        #- Sorted list of potential metadata:
        metadata_to_check = ['TARGETID', 'HPXPIXEL', 'TILEID', 'COADD_NUMEXP', 'COADD_EXPTIME', 
                             'NIGHT', 'EXPID', 'FIBER', 'CAMERA', 'MORPHTYPE']
        metadata_to_check += [ ('mag_'+x) for x in viewer_cds.phot_bands ]
        table_keys = []
        for key in metadata_to_check:
            if key in viewer_cds.cds_metadata.data.keys():
                table_keys.append(key)
            if 'NUM_'+key in viewer_cds.cds_metadata.data.keys():
                for prefix in ['FIRST','LAST','NUM']:
                    table_keys.append(prefix+'_'+key)
                    if key in top_metadata:
                        top_metadata.append(prefix+'_'+key)
        
        #- Table a: "top metadata"
        table_a_keys = [ x for x in table_keys if x in top_metadata ]
        self.shortcds_table_a, self.table_a = _metadata_table(table_a_keys, viewer_cds, table_width=600, 
                                                              shortcds_name='shortcds_table_a', selectable=True)
        #- Table b: Targeting information
        self.shortcds_table_b, self.table_b = _metadata_table(['Targeting masks'], viewer_cds, table_width=self.plot_widget_width,
                                                              shortcds_name='shortcds_table_b', selectable=True)
        #- Table(s) c/d : Other information (imaging, etc.)
        remaining_keys = [ x for x in table_keys if x not in top_metadata ]
        if len(remaining_keys) > 7:
            table_c_keys = remaining_keys[0:len(remaining_keys)//2]
            table_d_keys = remaining_keys[len(remaining_keys)//2:]
        else:
            table_c_keys = remaining_keys
            table_d_keys = None
        self.shortcds_table_c, self.table_c = _metadata_table(table_c_keys, viewer_cds, table_width=self.plot_widget_width,
                                                             shortcds_name='shortcds_table_c', selectable=False)
        if table_d_keys is None:
            self.shortcds_table_d, self.table_d = None, None
        else:
            self.shortcds_table_d, self.table_d = _metadata_table(table_d_keys, viewer_cds, table_width=self.plot_widget_width,
                                                                 shortcds_name='shortcds_table_d', selectable=False)

        #- Table z: redshift fitting information
        if show_zcat is not None :
            if template_dicts is not None : # Add other best fits
                fit_results = template_dicts[1]
                # Case of DeltaChi2 : compute it from Chi2s
                #    The "DeltaChi2" in rr fits is between best fits for a given (spectype,subtype)
                #    Convention: DeltaChi2 = -1 for the last fit.
                chi2s = fit_results['CHI2'][0]
                full_deltachi2s = np.zeros(len(chi2s))-1
                full_deltachi2s[:-1] = chi2s[1:]-chi2s[:-1]
                cdsdata = dict(Nfit = np.arange(1,len(chi2s)+1),
                                SPECTYPE = fit_results['SPECTYPE'][0],  # [0:num_best_fits] (if we want to restrict... TODO?)
                                SUBTYPE = fit_results['SUBTYPE'][0],
                                Z = [ "{:.4f}".format(x) for x in fit_results['Z'][0] ],
                                ZERR = [ "{:.4f}".format(x) for x in fit_results['ZERR'][0] ],
                                ZWARN = fit_results['ZWARN'][0],
                                CHI2 = [ "{:.1f}".format(x) for x in fit_results['CHI2'][0] ],
                                DELTACHI2 = [ "{:.1f}".format(x) for x in full_deltachi2s ])
                self.shortcds_table_z = ColumnDataSource(cdsdata, name='shortcds_table_z')
                columns_table_z = [ TableColumn(field=x, title=t, width=w) for x,t,w in [ ('Nfit','Nfit',5), ('SPECTYPE','SPECTYPE',70), ('SUBTYPE','SUBTYPE',60), ('Z','Z',50) , ('ZERR','ZERR',50), ('ZWARN','ZWARN',50), ('DELTACHI2','Δχ2(N+1/N)',70)] ]
                self.table_z = DataTable(source=self.shortcds_table_z, columns=columns_table_z,
                                         selectable=False, index_position=None, width=self.plot_widget_width)
                self.table_z.height = 3 * self.table_z.row_height
            else :
                self.shortcds_table_z, self.table_z = _metadata_table(viewer_cds.zcat_keys, viewer_cds,
                                    table_width=self.plot_widget_width, shortcds_name='shortcds_table_z', selectable=False)
        else :
            self.table_z = Div(text="Not available ")
            self.shortcds_table_z = None


    def add_specline_toggles(self, viewer_cds, plots):
        #-----
        #- Toggle lines
        self.speclines_button_group = CheckboxButtonGroup(
                labels=["Emission lines", "Absorption lines"], active=[])
        self.majorline_checkbox = CheckboxGroup(
                labels=['Show only major lines'], active=[])

        self.speclines_callback = CustomJS(
            args = dict(line_data = viewer_cds.cds_spectral_lines,
                        lines = plots.speclines,
                        line_labels = plots.specline_labels,
                        zlines = plots.zoom_speclines,
                        zline_labels = plots.zoom_specline_labels,
                        lines_button_group = self.speclines_button_group,
                        majorline_checkbox = self.majorline_checkbox),
            code="""
            var show_emission = false
            var show_absorption = false
            if (lines_button_group.active.indexOf(0) >= 0) {  // index 0=Emission in active list
                show_emission = true
            }
            if (lines_button_group.active.indexOf(1) >= 0) {  // index 1=Absorption in active list
                show_absorption = true
            }

            for(var i=0; i<lines.length; i++) {
                if ( !(line_data.data['major'][i]) && (majorline_checkbox.active.indexOf(0)>=0) ) {
                    lines[i].visible = false
                    line_labels[i].visible = false
                    zlines[i].visible = false
                    zline_labels[i].visible = false
                } else if (line_data.data['emission'][i]) {
                    lines[i].visible = show_emission
                    line_labels[i].visible = show_emission
                    zlines[i].visible = show_emission
                    zline_labels[i].visible = show_emission
                } else {
                    lines[i].visible = show_absorption
                    line_labels[i].visible = show_absorption
                    zlines[i].visible = show_absorption
                    zline_labels[i].visible = show_absorption
                }
            }
            """
        )
        self.speclines_button_group.js_on_click(self.speclines_callback)
        self.majorline_checkbox.js_on_click(self.speclines_callback)


    def add_model_select(self, viewer_cds, template_dicts, num_approx_fits, with_full_2ndfit=True):
        #------
        #- Select secondary model to display
        model_options = ['Best fit', '2nd best fit']
        for i in range(1,1+num_approx_fits) :
            ith = 'th'
            if i==1 : ith='st'
            if i==2 : ith='nd'
            if i==3 : ith='rd'
            model_options.append(str(i)+ith+' fit (approx)')
        if with_full_2ndfit is False :
            model_options.remove('2nd best fit')
        for std_template in ['QSO', 'GALAXY', 'STAR'] :
            model_options.append('STD '+std_template)
        self.model_select = Select(value=model_options[0], title="Other model (dashed curve):", options=model_options)
        model_select_code = self.js_files["interp_grid.js"] + self.js_files["smooth_data.js"] + self.js_files["select_model.js"]
        self.model_select_callback = CustomJS(
            args = dict(ifiberslider = self.ifiberslider,
                        model_select = self.model_select,
                        fit_templates=template_dicts[0],
                        cds_othermodel = viewer_cds.cds_othermodel,
                        cds_model_2ndfit = viewer_cds.cds_model_2ndfit,
                        cds_model = viewer_cds.cds_model,
                        fit_results=template_dicts[1],
                        std_templates=template_dicts[2],
                        median_spectra = viewer_cds.cds_median_spectra,
                        smootherslider = self.smootherslider,
                        z_input = self.z_input,
                        cds_metadata = viewer_cds.cds_metadata),
                        code = model_select_code)
        self.model_select.js_on_change('value', self.model_select_callback)


    def add_update_plot_callback(self, viewer_cds, plots, vi_widgets, template_dicts):
        #-----
        #- Main js code to update plots
        update_plot_code = (self.js_files["adapt_plotrange.js"] + self.js_files["interp_grid.js"] +
                            self.js_files["smooth_data.js"] + self.js_files["coadd_brz_cameras.js"] +
                            self.js_files["update_plot.js"])
        # TMP handling of template_dicts
        the_fit_results = None if template_dicts is None else template_dicts[1] # dirty
        self.update_plot_callback = CustomJS(
            args = dict(
                spectra = viewer_cds.cds_spectra,
                coaddcam_spec = viewer_cds.cds_coaddcam_spec,
                model = viewer_cds.cds_model,
                othermodel = viewer_cds.cds_othermodel,
                model_2ndfit = viewer_cds.cds_model_2ndfit,
                metadata = viewer_cds.cds_metadata,
                fit_results = the_fit_results,
                shortcds_table_z = self.shortcds_table_z,
                shortcds_table_a = self.shortcds_table_a,
                shortcds_table_b = self.shortcds_table_b,
                shortcds_table_c = self.shortcds_table_c,
                shortcds_table_d = self.shortcds_table_d,
                ifiberslider = self.ifiberslider,
                smootherslider = self.smootherslider,
                z_input = self.z_input,
                fig = plots.fig,
                imfig_source = plots.imfig_source,
                imfig_urls = plots.imfig_urls,
                model_select = self.model_select,
                vi_comment_input = vi_widgets.vi_comment_input,
                vi_std_comment_select = vi_widgets.vi_std_comment_select,
                vi_name_input = vi_widgets.vi_name_input,
                vi_quality_input = vi_widgets.vi_quality_input,
                vi_quality_labels = vi_widgets.vi_quality_labels,
                vi_issue_input = vi_widgets.vi_issue_input,
                vi_z_input = vi_widgets.vi_z_input,
                vi_category_select = vi_widgets.vi_category_select,
                vi_issue_slabels = vi_widgets.vi_issue_slabels
                ),
            code = update_plot_code
        )
        self.smootherslider.js_on_change('value', self.update_plot_callback)
        self.ifiberslider.js_on_change('value', self.update_plot_callback)
예제 #33
0
파일: main.py 프로젝트: jtanman/guilds
    'Wood Balance': 'piercing',
    'Breeding Token Balance': 'breedingtoken',
    'Daily Tokens Collected': 'dailytokenscollected',
    'Total Number of Purchases': 'revcounttotalpast',
    'Rev (Past 2 Weeks)': 'revwindowpast',
    'League Chats': 'numleaguechats',
    'Custom Chats': 'numcustomchats',
}

desc = Div(text=open(join(dirname(__file__), "description.html")).read(),
           width=800)

# Create Input controls
members = Slider(title="Minimum number of members",
                 start=0,
                 end=50,
                 value=5,
                 step=1)
eloMin = Slider(title="Minimum Elo", start=800, end=2500, value=1000, step=50)
eloMax = Slider(title="Max Elo", start=800, end=2500, value=2500, step=50)
activityMin = Slider(title="Minimum Activity",
                     start=0,
                     end=100,
                     value=0,
                     step=1)
activityMax = Slider(title="Max Activity", start=0, end=100, value=100, step=1)
tier = Select(title="Tier",
              value="All",
              options=open(join(dirname(__file__),
                                'tiers.txt')).read().split())
guild_lang = Select(title="Guild Language",
예제 #34
0
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)

text_input = TextInput(placeholder="Enter value ...")

completions = ["aaa", "aab", "aac", "baa", "caa"]
autocomplete_input = AutocompleteInput(placeholder="Enter value ...",
                                       completions=completions)

select = Select(options=["Option 1", "Option 2", "Option 3"])

multi_select = MultiSelect(options=["Option %d" % (i + 1) for i in range(16)],
                           size=6)

slider = Slider(value=10, start=0, end=100, step=0.5)

range_slider = RangeSlider(value=[10, 90], start=0, end=100, step=0.5)

#date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)))

date_picker = DatePicker()

paragraph = Paragraph(text="some text")

div = Div(text="some <b>text</b>")

pre_text = PreText(text="some text")


def mk_tab(color):
예제 #35
0
users_div = Div(text = '<h1 id="users_title"> Users <h1>', css_classes=['users_div','panel_div'])
size_div = Div(text = '<h1 id="size_title"> Size <h1>', css_classes=['size_div','panel_div'])

cbg_pages = CheckboxGroup(labels=cbg_labels[0:4],active=[0], css_classes =['pages_checks'])
cbg_editions =CheckboxGroup(labels=cbg_labels[4:10],active=[0], css_classes =['edition_checks'])
cbg_users = CheckboxGroup(labels=cbg_labels[10:17],active=[], css_classes =['users_checks'])
cbg_ratios=CheckboxGroup(labels=cbg_labels[17:20],active=[], css_classes =['other_checks'])

cbg_pages.on_click(cb_callback)
cbg_editions.on_click(cb_callback)
cbg_users.on_click(cb_callback)
cbg_ratios.on_click(cb_callback)

#cbg.on_click(cb_callback)
sizing_mode = "fixed"
time_slider = Slider(start=1, end= len(dates), value= len(dates), step = 1, title = "Months from creation",width=1580)
date_div = Div(text = '<h1 style="text-align:center"> Stats until:'+time[-1]+'<h1>',width=1600)
banners_div = Div(text = banners_html(len(dates)-1),width=1600)
time_slider.on_change('value',slider_callback)


top_users_columns = [
  TableColumn(field="users",title="User"),
  TableColumn(field="editions",title="Editions"),
  TableColumn(field="creations",title="Creations")]

date = dates[-1]
top_users_table = DataTable(source = top_users_table_ds[date],
                                                        columns = top_users_columns,
                                                        width = 500,height = 300,
                                                        row_headers=False)
예제 #36
0
from bokeh.layouts import row, column
from bokeh.models import BoxSelectTool, LassoSelectTool, CDSView, BooleanFilter, \
    Span
from bokeh.plotting import curdoc, figure
from bokeh.models.widgets import Select, Tabs, Slider, RangeSlider
from bokeh.models.tools import HoverTool
from modules.utils import *
from scripts.data_opener import wind, cn2_file2, time_series_data, max_corr, correlations, cn2_file1
from modules.config import file1_name, file2_name

date_keys = time_series_data['date_key'].unique().tolist()

select_bin_width = Slider(
    start=2,
    end=10,
    value=2,
    step=1,
    title="How many max mean periods to use as bin width",
    width=900)

date_keys_options = list(time_series_data['date_key'].unique())
date_keys_options.sort()
select_date_key = Select(title='Select day to inspect',
                         value='2009-04-01',
                         options=date_keys_options)

a, b = max_corr.n_points.min(), max_corr.n_points.max()

select_n_samples = RangeSlider(start=a,
                               end=b,
                               value=(a, b),
예제 #37
0
              max_iter=[mandelbrot_settings.iter_init]  # maximum iterations for computing the mandelbrot set
              ))

# initialize controls
# slider for maximum number of iterations for the computation of the mandelbrot set
slider_max_iterations = Slider(title="iterations",
                               name='iterations',
                               value=mandelbrot_settings.iter_init,
                               start=0,
                               end=mandelbrot_settings.iter_max,
                               step=mandelbrot_settings.iter_step)

# slider controlling the frequency of the colormap
slider_frequency = Slider(title="coloring",
                          name='coloring',
                          value=mandelbrot_settings.freq_init,
                          start=mandelbrot_settings.freq_min,
                          end=mandelbrot_settings.freq_max,
                          step=mandelbrot_settings.freq_step)

# Generate a figure container
toolset = "pan,reset,wheel_zoom,save"
plot = Figure(plot_height=mandelbrot_settings.x_res,
              plot_width=mandelbrot_settings.y_res,
              x_range=[mandelbrot_settings.x0, mandelbrot_settings.x1],
              y_range=[mandelbrot_settings.y0, mandelbrot_settings.y1],
              tools=toolset,
              title="Mandelbrot Set"
              )

# Plot the mandelbrot set as a image
# data source for image data
예제 #38
0
              title_text_font_size='10pt', toolbar_location=None)
plot.circle('x', 'y', fill_color='colors', line_color=None, source=source)
plot.xgrid[0].grid_line_color=None
plot.ygrid[0].grid_line_color=None

# SET UP WIDGETS
clustering_algorithms= ['MiniBatchKMeans', 'AffinityPropagation', 
    'MeanShift', 'SpectralClustering', 'Ward', 'AgglomerativeClustering',
    'DBSCAN', 'Birch']

datasets_names = ['Noisy Circles', 'Noisy Moons', 'Blobs', 'No Structure']

algorithm_select = Select(value='MiniBatchKMeans', title='Select algorithm:', options=clustering_algorithms)
dataset_select = Select(value='Noisy Circles', title='Select dataset:', options=datasets_names)

samples_slider = Slider(title="Number of samples", value=1500.0, start=1000.0, end=3000.0, step=100)
clusters_slider = Slider(title="Number of clusters", value=2.0, start=2.0, end=10.0, step=1)


def clustering(X, algorithm, n_clusters):
    # normalize dataset for easier parameter selection
    X = StandardScaler().fit_transform(X)
    # estimate bandwidth for mean shift
    bandwidth = cluster.estimate_bandwidth(X, quantile=0.3)
    # connectivity matrix for structured Ward
    connectivity = kneighbors_graph(X, n_neighbors=10, include_self=False)
    # make connectivity symmetric
    connectivity = 0.5 * (connectivity + connectivity.T)
    # Generate the new colors:
    if algorithm=='MiniBatchKMeans':
        model = cluster.MiniBatchKMeans(n_clusters=n_clusters)
예제 #39
0
파일: Test2.py 프로젝트: skianzad/MagicPen
source = ColumnDataSource(data=dict(x=x, y=y))
ser=serial.Serial('COM4',19200,timeout=0.2)

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

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




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


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


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



def update_title(attrname, old, new):
    plot.title.text = text.value
예제 #40
0
from bokeh.io import curdoc
# the following for the alternate form of page lay-out
#from bokeh.models import HBox, VBox
from bokeh.models.widgets import Slider, Button
from bokeh.models import ColumnDataSource
from bokeh.models.glyphs import MultiLine
# set up params for basic CRF w/ baseline offset (provided by presence of flankers)
contrast = np.arange(0,1,.01)
alpha= 0.6
baseline = 0.3

    
# interactive tools
nRep = 7 # eventually turn this into an option
redrawButton = Button(label="New Sample", type="success")
CNRslider = Slider(title="CNR", value=1.0, start=0.0, end=2.0)
 


#https://github.com/bokeh/bokeh/blob/master/tests/glyphs/MultiLine.py
#set up staring data set
CNR=CNRslider.value
response = contrast**alpha + baseline
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
thing=[(np.random.random(contrast.shape)-0.5)/CNR+baseline]
예제 #41
0
파일: fpdapp.py 프로젝트: cdmbi/FPD
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)
예제 #42
0
    plot.circle(x='x',
                y=filt,
                source=source2,
                line_width=3,
                line_alpha=0.6,
                color=filt_data[i, 2])

arrayoftimes = np.array(photometry_time)

text = TextInput(title="Insert the name of the supernova here:",
                 value='',
                 callback=callback2)

M_slider = Slider(start=0.1,
                  end=10,
                  value=1,
                  step=.1,
                  title="Ejecta Mass (solar mass)",
                  callback=callback)
f_slider = Slider(start=0.01,
                  end=1.0,
                  value=0.1,
                  step=.01,
                  title="Nickel Fraction",
                  callback=callback)
v_slider = Slider(start=5000,
                  end=20000,
                  value=10000,
                  step=1000,
                  title="Ejecta Velocity (km/s)",
                  callback=callback)
k_slider = Slider(start=0.05,
예제 #43
0
        self.title = title
        self.notes = notes
        self.highsupport = highsupport
        self.full = full
        self.partial = partial
        self.annotations = annotations


GTF = TextInput(title="Enter the name of annotation file", value="gencode.vM8.annotation.gtf")
Format = TextInput(title="Enter the format of annotation file, standard is gtf", value="standard")
Matches = TextInput(
    title="Enter the name of pickle files from MatchAnnot, e.g. of multiple files: match1.pickle,match2.pickle",
    value="matches.pickle",
)
Gene = TextInput(title="Select gene to visualize")
Alpha = Slider(title="Alpha value of exons", value=1.0, start=0, end=1.0, step=0.1)
Full = Slider(title="Full support threshold", value=0, start=0, end=30, step=1.0)
Partial = Slider(title="Partial support threshold", value=0, start=0, end=50, step=1.0)
Group = Select(title="Group isoform or not", value="on", options=["on", "off"])
Cluster = Slider(title="The number of groups", value=3, start=1, end=5, step=1.0)
Width = Slider(title="The width of transcripts", value=20, start=5, end=30, step=1)
Save = TextInput(title="Enter the folder name to data in Fasta", value=None)

blockSource = ColumnDataSource(
    data=dict(top=[], bottom=[], left=[], right=[], exon=[], start=[], end=[], chromosome=[], xs=[], ys=[])
)
source = ColumnDataSource(data=dict(x=[], y=[], color=[], line_alpha=[], width=[], QScore=[], start=[], end=[]))
geneSource = ColumnDataSource(data=dict(Gene=[], Cluster=[]))

df = pd.DataFrame()
boundaryDF = pd.DataFrame()
예제 #44
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()
    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)]
def create_figure():
    global data_source, data_source_map, center_of_mass_data_source, select
    tools = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo," \
            "redo,reset,tap,save,box_select,poly_select,lasso_select,"

    kmeans = KMeans(n_clusters=5)
    kmeans.fit(vote_results)

    cluster_xs = kmeans.cluster_centers_[:, 0]
    cluster_ys = kmeans.cluster_centers_[:, 1]

    com_df = pd.DataFrame.from_dict({'x': cluster_xs, 'y': cluster_ys})
    center_of_mass_data_source = ColumnDataSource(data=com_df)

    # Data visualized
    df = pd.DataFrame(columns=columns)

    for index, coords in enumerate(vote_results):
        df = df.append(
            {
                'x': coords[0],
                'y': coords[1],
                'cluster': str(kmeans.labels_[index]),
                "ilce_adi": districts[index],
                "il_adi": cities[index],
                "katilim_oran": turnout[index],
                "gecersiz_oran": invalid_ratio[index],
                "color": cmap[str(kmeans.labels_[index])]
            },
            ignore_index=True)

    p = figure(tools=tools,
               tooltips=[("İl Adı", "@il_adi"), ("İlçe Adı", "@ilce_adi"),
                         ("Geçersiz Oy Oranı", "@gecersiz_oran"),
                         ("Katılım Oranı", "@katilim_oran")])
    p.title.text = "Seçim"
    data_source = ColumnDataSource(data=pd.DataFrame.from_dict(df))

    p.circle(x='x', y='y', size=5, source=data_source, color='color')

    p.rect('x',
           'y',
           10,
           10,
           width_units="screen",
           height_units="screen",
           color="black",
           source=center_of_mass_data_source)

    # Data projected visulized
    df_map = pd.DataFrame(columns=columns)

    for index, coords in enumerate(vote_results_map):
        df_map = df_map.append(
            {
                'x': merc_x(coords[0]),
                'y': merc_y(coords[1]) + 30000,
                'cluster': str(kmeans.labels_[index]),
                "ilce_adi": districts[index],
                "il_adi": cities[index],
                "katilim_oran": turnout[index],
                "gecersiz_oran": invalid_ratio[index],
                "color": cmap[str(kmeans.labels_[index])]
            },
            ignore_index=True)
    p2 = figure(tools=tools,
                tooltips=[("İl Adı", "@il_adi"), ("İlçe Adı", "@ilce_adi"),
                          ("Geçersiz Oy Oranı", "@gecersiz_oran"),
                          ("Katılım Oranı", "@katilim_oran")],
                x_range=(-2000000, 6000000),
                y_range=(-1000000, 7000000),
                x_axis_type="mercator",
                y_axis_type="mercator")
    p2.add_tile(CARTODBPOSITRON_RETINA)

    data_source_map = ColumnDataSource(data=pd.DataFrame.from_dict(df_map))

    p2.circle(x='x', y='y', size=5, source=data_source_map, color='color')

    dataset_slider = Slider(start=1,
                            end=6,
                            value=5,
                            step=1,
                            title="Küme sayısı")

    dataset_slider.on_change('value', change_cluster)

    select = Select(title="Renk:",
                    value="Hiçbiri",
                    options=["Hiçbiri"] + [cmap[str(i)] for i in range(5)])
    select.on_change('value', choose_color)

    return column(dataset_slider, select, row(p, p2))
예제 #47
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()
예제 #48
0
movies.loc[movies.imdbID.isin(razzies), "color"] = "purple"
movies.loc[movies.imdbID.isin(razzies), "alpha"] = 0.9

axis_map = {
    "Tomato Meter": "Meter",
    "Numeric Rating": "numericRating",
    "Number of Reviews": "Reviews",
    "Box Office (dollars)": "BoxOffice",
    "Length (minutes)": "Runtime",
    "Year": "Year",
}

# Create Input controls
reviews = Slider(title="Minimum number of reviews",
                 value=80,
                 start=10,
                 end=300,
                 step=10)
min_year = Slider(title="Year released",
                  start=1940,
                  end=2014,
                  value=1970,
                  step=1)
max_year = Slider(title="End Year released",
                  start=1940,
                  end=2014,
                  value=2014,
                  step=1)
oscars = Slider(title="Minimum number of Oscar wins",
                start=0,
                end=4,
예제 #49
0
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)
    # füge eine fiktive Berechnugns-Zeit von einer Sekunde ein
    sleep(1)


# .. was hier verdrahtet wird
freq.on_change('value', update_data)
예제 #50
0
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,resize,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)

# Set up widgets
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0)
phase = Slider(title="phase", value=0.0, start=0.0, end=2 * np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1)


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


text.on_change('value', update_title)


def update_data(attrname, old, new):
    #t1.data_source.data["text"] = ['{} {}'.format(l_forward.glyph.line_alpha,l_reverse.glyph.line_alpha)]
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)
예제 #52
0
파일: Culture.py 프로젝트: agilly/vraidebat
                    title="Titre",
                    formatter=HTMLTemplateFormatter(
                        template='<div><%= title %></div>')),
        TableColumn(field="body",
                    title="Corps",
                    formatter=HTMLTemplateFormatter(
                        template='<div><%= body %></div>')),
    ]

    p2 = DataTable(source=s2, columns=columns, width=1200)
    #    p2= DataTable(source=s2, columns=columns, width=wi, height=400)

    end_slider = max(df.n_vote)
    nvote_slider = Slider(start=0,
                          end=end_slider,
                          value=0,
                          step=10,
                          title="Nombre de votes minimum",
                          callback=filtervote)
    filtervote.args["nvote"] = nvote_slider
    vote_slider = Slider(start=50,
                         end=100,
                         value=50,
                         title="Approbation/rejet(%)",
                         callback=filtervote)
    filtervote.args["vote"] = vote_slider

    toggle = Toggle(label="Cacher points non significatifs",
                    callback=filtervote,
                    width=50)
    toggle_expl = Div(
        text=
                    title="fx(x,y):")
v_input = TextInput(value=curveintegral_settings.sample_functions[curveintegral_settings.init_fun_key][1],
                    title="fy(x,y):")

u_input.on_change('value', function_change)
v_input.on_change('value', function_change)

# 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],
예제 #54
0
        corr_ir_cd,
        div_call_model,
    )

    # Update the data on the plot
    src_call_model.data.update(new_src_call_model.data)


######################################################################
# BOND QUOTING
######################################################################
# Marking
marking_mode_select = Slider(
    start=1,
    end=N_MARKING_MODES,
    step=1,
    title='Marking mode',
    value=1,
)
mark_select = TextInput(value='100.00', title='Mark')

# Bond term sheet
coupon_select = TextInput(value='5.00', title='Coupon (%)')
principal_select = TextInput(value='100', title='Principal')
maturity_select = TextInput(value='5', title='Maturity (y)')
coupon_frequency_select = TextInput(value='1',
                                    title='Coupon Frequency (per year)')

# Update the plot when parameters are changed
marking_mode_select.on_change('value', update)
mark_select.on_change('value', update)
예제 #55
0
from bokeh.plotting import figure
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"
예제 #56
0
# Set up plot
plot = Figure(plot_height=500, plot_width=500, title="ball sliding along semicircle, angle=0",
              tools="crosshair,pan,reset,resize,save,wheel_zoom",
              x_range=[-1.1, 1.1], y_range=[-1.1, 1.1])

plot.circle('x', 'y', source=source, size=10, color='navy', line_alpha=0.6)

theta_line = np.linspace(0, pi, 101)
plot.line(-np.cos(theta_line), -np.sin(theta_line), line_width=2)



# Set up widgets
titlevalue = 'ball sliding along semicircle, angle='
mu = Slider(title="mu", value=0.0, start=0, end=1, step=0.1)
tau = Slider(title="tau", value=0.0, start=0, end=10.0, step=0.1)
print mu.value

# Set up callbacks

def update_data(attrname, old, new):

    # Get the current slider values
    mu_v = mu.value
    tau_v = tau.value
    dtau = 0.1
    N = round(tau_v/dtau)
    mu_str = str(mu_v)
    if mu_str =='1':
        mu_str = '1.0'
예제 #57
0
data_path = './main.csv'

data = pd.read_csv(data_path, dtype={'x': np.float, 'y': np.float, 'label': np.int})

hover = HoverTool(tooltips=[("value", "@text"), ], active=False)
plot = Figure(tools=[hover,  WheelZoomTool(), BoxZoomTool(), PanTool(), ResetTool()],
    webgl=True,
    plot_width=800,
    plot_height=800,
    y_axis_type="log")

source = ColumnDataSource(data)
scatter = plot.scatter(source=source, line_width=0, line_alpha=0, size=10, x="x", y="y", alpha=0.5)

p_value = Slider(title='p value', value=0.5, start=1, end=10, step=0.5, orientation='horizontal')
p_mult = Slider(title='x', value=1, start=1, end=70, step=1)

def get_p():
    return p_value.value * 10**-p_mult.value


left_limit = Slider(title='left_limit', value=-0.5, start=-1, end=0, step=0.001, orientation='horizontal')
right_limit = Slider(title='right_limit', value=0.5, start=0, end=1, step=0.001, orientation='horizontal')

left = Span(location=left_limit.value, dimension='height', line_color='maroon', render_mode='css')
plot.renderers.append(left)
right = Span(location=right_limit.value, dimension='height', line_color='maroon', render_mode='css')
plot.renderers.append(right)

p_line = Span(location=-math.log10(get_p()), dimension='width', line_color='red', line_width=3, render_mode='css')
예제 #58
0
class HistView():
    """
    Histogram viewer which plots histograms of a feature, the feature displayed
    can be controlled by using a slider. Currently all features values must be 
    bounded between 0 and 1.

    Parameters:
    -----------
    X : pd.DataFrame, shape [n_instances, n_features]
        The training set.

    y: array-like, shape [n_instances] (default=None)
        Target class of each instance in X.

    url : str, default="localhost:8888"
        Location (port) of the jupyter notebook to display figure too.
    
    bin_count : int, (default=50)
        Number of bins to seperate histogram into.
        
    Attributes:
    -----------
    X : pd.DataFrame, shape [n_instances, n_features]
        The training set.

    y: array-like, shape [n_instances] (default=None)
        Target class of each instance in X.
    """

    # TO DO:
    # 1. Add catch / check for if a target is not provided
    # 2. Make robust to non-scaled features.

    def __init__(self, X, y=None, url="localhost:8888", bin_count=50):
        """
        Constructer for the HistView class.
        """
        # Need to add checks to only plot a fraction of the data if it is large.
        self.X, self.y = X, y
        self.bin_edges = np.linspace(0, 1, bin_count + 1)
        self._are_features_bounded(X)
        app = Application(FunctionHandler(
            self._make_bokeh_doc))  # make document
        show(app, notebook_url=url)  # show document in notebook

    def _make_bokeh_doc(self, doc):
        """
        Main method controlling the construction of the bokeh document.

        Parameters:
        -----------
        doc : bokeh.Document object
            Document instance to contain all required Bokeh models.
        """
        self._init_figure()
        self._init_slider()
        self._init_histogram()

        doc_layout = layout([self.slider, self.figure])
        doc.add_root(doc_layout)  # add layout to our document

    def _are_features_bounded(self, X):
        """
        Checks features are bounded between 0 and 1 and if not raises an 
        exception suggesting the use of MinMaxScaler.

        Parameters:
        -----------
        X : pd.DataFrame, shape [n_instances, n_features]
            Training set.
        """
        max_feature_value = X.max(axis=0).values
        min_feature_value = X.min(axis=0).values
        features_bounded = all((min_feature_value > -1e-6)
                               & (max_feature_value < 1.00001))
        if not features_bounded:
            raise Exception('Features must be bounded between 0 and 1!'
                            'Try using MinMaxScaler from sklearn to prepare'
                            'your features for HistView.')

    def _init_figure(
        self,
        fig_props={
            'plot_height': 500,
            'plot_width': 500,
            'tools': ('box_zoom,'
                      'wheel_zoom,'
                      'reset,'
                      'help,'
                      'save')
        }):
        """
        Instantiates the figure.

        Parameters:
        -----------
        fig_props : dict 
            kwargs to be passed to figure instance.
        """
        self.figure = figure(x_axis_label='Value',
                             y_axis_label='Count',
                             title='Feature Histogram by Class',
                             **fig_props)

    def _init_slider(self):
        """
        Instantiates the feature selection slider.
        """
        self.slider = Slider(start=0,
                             end=float(self.X.shape[1] - 1),
                             step=1.0,
                             value=0,
                             show_value=False)
        self.slider.on_change('value', self._slider_callback)
        self.slider.title = self.X.columns[0]

    def _slider_callback(self, attr, old, new):
        """
        Callback for the feature selection slider. Code will be ran when the value of the slider changes.
        
        Parameters:
        -----------
        attr : str 
            Attribute of slider to monitor
        
        old : Any
            Old value of attr
        
        new : Any 
            New value of attr
        """
        idx = int(new)
        feature_values = self.X.iloc[:, idx].values
        self._update_histogram(feature_values)
        self.slider.title = self.X.columns[idx]

    def _get_histogram_values(self, values):
        """
        Given an array of values generates a histogram for each value of target.
        These are then stacked in columns.

        Parameters:
        -----------
        values : array-like, shape [n_instances] 
            array-like object of values to bin.

        Returns:
        --------
        count_arr : array-like : [n_bins, n_targets] 
            Each column contains is the histogram for training instances for a 
            given value of target.
        """
        target_values = np.unique(self.y)
        # init empty array to store counts of each target [n_bins, n_targets]
        count_arr = np.zeros((len(self.bin_edges) - 1, len(target_values)))
        for idx, target in enumerate(target_values):
            masked_values = values[self.y == target]
            counts, _ = np.histogram(masked_values, bins=self.bin_edges)
            count_arr[:, idx] = counts
        return count_arr

    def _update_histogram(self, values):
        """
        Function which updates histogram after the slider has changed.

        Parameters:
        -----------
        values : array-like 
            Values to create histogram of.
        """
        count_arr = self._get_histogram_values(values)
        hist_bottoms = np.zeros(count_arr.shape[0])
        for i, hist in enumerate(self.hists):
            hist.data_source.data['bottom'] = hist_bottoms
            hist.data_source.data['top'] = hist_bottoms + count_arr[:, i]
            hist_bottoms = hist_bottoms + count_arr[:, i]

    def _init_histogram(self):
        """
        Plots the initial histogram, uses the 0th feature.
        """
        feature_values = self.X.iloc[:, 0].values
        count_arr = self._get_histogram_values(feature_values)
        possible_targets = np.unique(self.y)
        num_targets = len(possible_targets)
        try:
            colours = Category20[num_targets]
        except KeyError:
            # if there are two features, use three feature cs
            colours = Category20[num_targets + 1]

        left_edges = self.bin_edges[:-1]
        right_edges = self.bin_edges[1:]
        hist_bottoms = np.zeros(count_arr.shape[0])
        self.hists = []
        for i in range(num_targets):
            hist = self.figure.quad(bottom=hist_bottoms,
                                    left=left_edges,
                                    right=right_edges,
                                    top=count_arr[:, i] + hist_bottoms,
                                    alpha=0.75,
                                    color=colours[i],
                                    legend=str(possible_targets[i]))
            hist_bottoms = hist_bottoms + count_arr[:, i]
            self.hists.append(hist)
예제 #59
0
파일: main.py 프로젝트: tanderegg/ccdb_viz
cur.execute(ISSUE_NAMES)
issue_names = sorted([x[0] for x in cur.fetchall()])
issue_names.insert(0, "All")

# Create data source for state totals
state_source = ColumnDataSource(data=dict())
zip_source = ColumnDataSource(data=dict(x=[], y=[]))
table_source = ColumnDataSource(data=dict(labels=[], data=[]))

### Step 2: Build the UI

# Build inputs
state_widget = Select(title="State", value="All", options=states)
issue_widget = Select(title="Issues", value="All", options=issue_names)
product_widget = Select(title="Products", value="All", options=product_names)
min_complaints_widget = Slider(title="Min # Complaints", value=0,
                               start=0, end=100, step=10)

# Helper Functions
def generate_where_clause(state=None, product=None,
                          issue=None, min_complaints=None):
    """
    Generate a where clause given a set of filters
    """
    where_inner = []
    where_outer = []

    if state and not state == "All":
        where_inner.append("ccdb.state = '{}'".format(state))

    if product and not product == "All":
        where_inner.append("ccdb.product = '{}'".format(product))
예제 #60
0
    def create_widget(self, dim, holomap=None, editable=False):
        """"
        Given a Dimension creates bokeh widgets to select along that
        dimension. For numeric data a slider widget is created which
        may be either discrete, if a holomap is supplied or the
        Dimension.values are set, or a continuous widget for
        DynamicMaps. If the slider is discrete the returned mapping
        defines a mapping between values and labels making it possible
        sync the two slider and label widgets. For non-numeric data
        a simple dropdown selection widget is generated.
        """
        label, mapping = None, None
        if holomap is None:
            if dim.values:
                if dim.default is None:
                    default = dim.values[0]
                elif dim.default not in dim.values:
                    raise ValueError(
                        "%s dimension default %r is not in dimension values: %s"
                        % (dim, dim.default, dim.values))
                else:
                    default = dim.default
                value = dim.values.index(default)

                if all(isnumeric(v) for v in dim.values):
                    values = sorted(dim.values)
                    labels = [unicode(dim.pprint_value(v)) for v in values]
                    if editable:
                        label = AutocompleteInput(value=labels[value],
                                                  completions=labels,
                                                  title=dim.pprint_label)
                    else:
                        label = Div(text='<b>%s</b>' %
                                    dim.pprint_value_string(labels[value]))
                    widget = Slider(value=value,
                                    start=0,
                                    end=len(dim.values) - 1,
                                    title=None,
                                    step=1)
                    mapping = list(enumerate(zip(values, labels)))
                else:
                    values = [(v, dim.pprint_value(v)) for v in dim.values]
                    widget = Select(title=dim.pprint_label,
                                    value=values[value][0],
                                    options=values)
            else:
                start = dim.soft_range[0] if dim.soft_range[0] else dim.range[0]
                end = dim.soft_range[1] if dim.soft_range[1] else dim.range[1]
                dim_range = end - start
                int_type = isinstance(dim.type, type) and issubclass(
                    dim.type, int)
                if dim.step is not None:
                    step = dim.step
                elif isinstance(dim_range, int) or int_type:
                    step = 1
                else:
                    step = 10**((round(math.log10(dim_range)) - 3))

                if dim.default is None:
                    default = start
                elif (dim.default < start or dim.default > end):
                    raise ValueError(
                        "%s dimension default %r is not in the provided range: %s"
                        % (dim, dim.default, (start, end)))
                else:
                    default = dim.default

                if editable:
                    label = TextInput(value=str(default),
                                      title=dim.pprint_label)
                else:
                    label = Div(text='<b>%s</b>' %
                                dim.pprint_value_string(default))
                widget = Slider(value=default,
                                start=start,
                                end=end,
                                step=step,
                                title=None)
        else:
            values = (dim.values if dim.values else list(
                unique_array(holomap.dimension_values(dim.name))))
            if dim.default is None:
                default = values[0]
            elif dim.default not in values:
                raise ValueError(
                    "%s dimension default %r is not in dimension values: %s" %
                    (dim, dim.default, values))
            else:
                default = dim.default
            if isinstance(values[0], np.datetime64) or isnumeric(values[0]):
                values = sorted(values)
                labels = [dim.pprint_value(v) for v in values]
                value = values.index(default)
                if editable:
                    label = AutocompleteInput(value=labels[value],
                                              completions=labels,
                                              title=dim.pprint_label)
                else:
                    label = Div(text='<b>%s</b>' %
                                (dim.pprint_value_string(labels[value])))
                widget = Slider(value=value,
                                start=0,
                                end=len(values) - 1,
                                title=None,
                                step=1)
            else:
                labels = [dim.pprint_value(v) for v in values]
                widget = Select(title=dim.pprint_label,
                                value=default,
                                options=list(zip(values, labels)))
            mapping = list(enumerate(zip(values, labels)))
        return widget, label, mapping