Example #1
0
def create_pairdensity_plot_widget(ls):
    """Create a pairwise density widget.

    Parameters
    ----------
    ls : :class:`~lens.Summary`
        Lens `Summary`.

    Returns
    -------
    :class:`ipywidgets.Widget`
        Jupyter widget to explore pairdensity plots.
    """
    numeric_columns = ls._report['column_summary']['_columns']
    dropdown1 = widgets.Dropdown(options=numeric_columns, description='First:')
    dropdown2 = widgets.Dropdown(options=numeric_columns,
                                 description='Second:')
    if len(numeric_columns) > 1:
        dropdown1.value, dropdown2.value = numeric_columns[:2]

    plot_area = widgets.HTML()

    for dropdown in [dropdown1, dropdown2]:
        dropdown.observe(lambda x: _update_pairdensity_plot(
            ls, dropdown1, dropdown2, plot_area),
                         names='value',
                         type='change')

    _update_pairdensity_plot(ls, dropdown1, dropdown2, plot_area)

    return widgets.VBox([dropdown1, dropdown2, plot_area], padding=PADDING)
Example #2
0
 def update_dropdown(self, search):
     '''
     Takes a search string as input. If this search string matches the name of any schools in the
     dataset, returns a dropdown menu containing up to the first twenty results. Initially, the dashboard
     plots are generated for the first matching school (to illustrate the output of this plot).
     If the user selects a different school from this dropdown menu, the dashboard plots are
     generated for the selected school.
     '''
     clear_output()
     schools = self.search_function(search)
     if len(schools) > 1:
         self.plot_school(schools[0])
         select_from = interactive(
             self.plot_school,
             school=widgets.Dropdown(options=schools,
                                     description='Select school to plot: '))
         self.container.children = [self.Search, select_from]
     if len(schools) == 1:
         self.plot_school(schools[0])
         select_from = interactive(
             self.plot_school,
             school=widgets.Dropdown(options=schools,
                                     description='Select school to plot: '))
         self.container.children = [self.Search, select_from]
     if len(schools) == 0:
         print '{} not found- please search for a different school'.format(
             self.Search.value)
         select_from = interactive(
             self.plot_school,
             school=widgets.Dropdown(options=schools,
                                     description='Select school to plot: '))
         self.container.children = [self.Search, select_from]
def EvenOdd():
    funcs = {
        "cos(x)": np.cos,
        "cos(2x)": cos2,
        "cos(2x)": cos2,
        "sin(x)": np.sin,
        "x^2": quad,
        "Odd Square": oddSquare,
        "Even Square": evenSquare
    }
    f1_drop = widgets.Dropdown(options=funcs)
    f2_drop = widgets.Dropdown(options=funcs)
    sym_check = widgets.Checkbox(value=False, description="Check Symmetry")
    area_check = widgets.Checkbox(value=False,
                                  description="Integration Region")

    display(
        widgets.VBox([
            widgets.HBox([f1_drop, f2_drop, sym_check, area_check]),
            widgets.interactive_output(
                symmetryCheck, {
                    'f1': f1_drop,
                    'f2': f2_drop,
                    "showSym": sym_check,
                    "showArea": area_check
                })
        ]))
Example #4
0
    def __init__(self):
        # retrieve list of vehicle makes
        query = session.query(Vehicle.make).distinct()
        self.makes = pd.read_sql(query.statement, query.session.bind)
        self.makes.sort_values('make', inplace=True)

        self.accidents1 = None

        # create widgets
        self.make1 = widgets.Dropdown(options=self.makes.make.values,
                                      description='Make:',
                                      disabled=False)
        self.model1 = widgets.Dropdown(description='Model:', disabled=False)
        self.year1 = widgets.Dropdown(description='Start Year:',
                                      disabled=False)
        self.year2 = widgets.Dropdown(description='End Year:', disabled=False)
        self.run = widgets.Button(description='Run', disabled=True)

        # connect widgets to commands
        self.make1.observe(self.update_model1, "value")
        self.model1.observe(self.update_year1, "value")
        self.year1.observe(self.update_year2, "value")
        self.run.on_click(self.get_accidents)

        display(
            VBox([
                HBox([self.make1]),
                HBox([self.model1]),
                HBox([self.year1, self.year2]),
                HBox([self.run])
            ]))
    def _create_widgets_for_vis_args(self):
        """
        Create the widgets that are necessary for adjusting the
        visualization parameters of this special visualizer.

        Returns
        -------
        a dict mapping keyword argument names of the PIC visualizer
        to the jupyter widgets responsible for adjusting those values.
        """
        self.species = widgets.Dropdown(description="Species",
                                        options=["e"],
                                        value='e')
        self.species_filter = widgets.Dropdown(description="Species_filter",
                                               options=['all'],
                                               value="all")
        self.ps = widgets.Dropdown(description="ps",
                                   options=['ypy'],
                                   value='ypy')

        return {
            'species': self.species,
            'species_filter': self.species_filter,
            'ps': self.ps
        }
Example #6
0
    def _build_inst_form(self):
        imager_config = read_json(os.path.join(os.environ['pandeia_refdata'], 'wfirst', 'wfirstimager', 'config.json'))
        ifu_config = read_json(os.path.join(os.environ['pandeia_refdata'], 'wfirst', 'wfirstifu', 'config.json'))

        self.inst_select = widgets.Dropdown(
            description="Instrument:",
            options=['Imager'],
            value='Imager'
        )
        im_filters = imager_config['filters']
        im_readmodes = imager_config['readmodes']
        im_subarrays = imager_config['subarrays']
        self.filt = widgets.Dropdown(
            description="Filter:",
            options=im_filters
        )
        self.readmode = widgets.Dropdown(
            description="Readmode:",
            options=im_readmodes
        )
        self.subarray = widgets.Dropdown(
            description="Sub-array:",
            options=im_subarrays,
        )
        return widgets.VBox([
            self.inst_select,
            self.filt,
            self.readmode,
            self.subarray,
        ])
Example #7
0
def explaining(data, rf, X_train, sov_lab_encoder, 
                le, feat_key):
    
    from ipywidgets import widgets
    from IPython.display import display, clear_output, Markdown
    
    def on_button_clicked(b):
        with output:
            clear_output()
            per1n = list(data.columns).index(per1.value)
            per2n = list(data.columns).index(per2.value)
#            print('Números de periodos:' + '[' + str(per1n) + ',' + str(per2n) + ']')
            display(Markdown('Explicación de resultados:'))
            explain_tree(data, [per1n,per2n], rf, X_train, sov_lab_encoder, le , feat_key)
            
    
    button = widgets.Button(description="Explicar trimestres escogidos")
    output = widgets.Output()
        
    per1 = widgets.Dropdown(
           options=list(data.columns),
           description='Periodo 1:')
    per2 = widgets.Dropdown(
           options=list(data.columns),
           description='Periodo 2:')
   
    box = widgets.VBox([per1, per2])
    display(box)
    display(button, output)
    button.on_click(on_button_clicked)       
    
#    interact(myfunc, Emisor=list(data.index))
    
    
Example #8
0
    def __init__(self, units: Units, unit_index=0):
        super().__init__()

        self.units = units

        self.trials = self.get_trials()
        if self.trials is None:
            self.children = [widgets.HTML('No trials present')]
            return

        groups = list(self.trials.colnames)

        rows_controller = widgets.Dropdown(options=[None] + list(groups),
                                           description='rows')
        cols_controller = widgets.Dropdown(options=[None] + list(groups),
                                           description='cols')

        trial_event_controller = make_trial_event_controller(self.trials)
        unit_controller = widgets.Dropdown(options=range(
            len(units['spike_times'].data)),
                                           value=unit_index,
                                           description='unit')

        before_slider = widgets.FloatSlider(.1,
                                            min=0,
                                            max=5.,
                                            description='before (s)',
                                            continuous_update=False)
        after_slider = widgets.FloatSlider(1.,
                                           min=0,
                                           max=5.,
                                           description='after (s)',
                                           continuous_update=False)

        self.controls = {
            'units': fixed(units),
            'time_intervals': fixed(self.trials),
            'index': unit_controller,
            'after': after_slider,
            'before': before_slider,
            'align_by': trial_event_controller,
            'rows_label': rows_controller,
            'cols_label': cols_controller
        }

        self.children = [
            unit_controller,
            rows_controller,
            cols_controller,
            trial_event_controller,
            before_slider,
            after_slider,
        ]

        self.select_trials()

        out_fig = interactive_output(raster_grid, self.controls,
                                     self.process_controls)

        self.children = list(self.children) + [out_fig]
Example #9
0
 def __init__(self, g=nx.DiGraph()):
     self.graph=g
     self.add_nodew=widgets.Text(placeholder='Type label of new state')
     self.add_node_buttonw=widgets.Button(description='Add state')
     self.del_node_buttonw=widgets.Button(description='Del state')
            
     self.node_box=VBox([self.add_nodew, 
                         HBox([self.add_node_buttonw, self.del_node_buttonw])
                         ])
     
     self.select_nodew=widgets.Dropdown(description='Select state')
     
     self.add_node_attr_labelw=widgets.Text(placeholder='Type label of new state attribute')
     self.add_node_attr_valuew=widgets.Text(placeholder='Type value of new state attribute')
     self.add_node_attr_buttonw=widgets.Button(description='Add attribute to state')
     self.del_node_attr_buttonw=widgets.Button(description='Del attribute from state')
     
     self.node_attr_box=VBox([self.select_nodew, 
                              VBox([self.add_node_attr_labelw, self.add_node_attr_valuew]), 
                              HBox([self.add_node_attr_buttonw, self.del_node_attr_buttonw])
                              ])
     
     self.from_nodew = widgets.Dropdown(description='From state', options=[])
     self.to_nodew = widgets.Dropdown(description='To state', options=[])
     self.from_to_pw=widgets.Text(placeholder = 'Type probability', description = 'Probability', value='0')
     self.add_edge_buttonw=widgets.Button(description='Add edge')
     self.del_edge_buttonw=widgets.Button(description='Del edge')
     
     self.edge_box=VBox([VBox([self.from_nodew, self.to_nodew]),
                         self.from_to_pw,                                     
                         HBox([self.add_edge_buttonw, self.del_edge_buttonw])
                         ])
     
     self.add_edge_attr_labelw=widgets.Text(placeholder='Type label of new edge attribute')
     self.add_edge_attr_valuew=widgets.Text(placeholder='Type value of new edge attribute')
     self.add_edge_attr_buttonw=widgets.Button(description='Add attribute to edge')
     self.del_edge_attr_buttonw=widgets.Button(description='Del attribute from edge')
     
     self.edge_attr_box=VBox([VBox([self.add_edge_attr_labelw, self.add_edge_attr_valuew]), 
                                 HBox([self.add_edge_attr_buttonw, self.del_edge_attr_buttonw])])     
                              
     self.graphw=widgets.Image()
                              
     self.left_menu = VBox([self.node_box,
                            self.node_attr_box,
                            self.edge_box,
                            self.edge_attr_box])
 
     self.box=HBox([self.left_menu, self.graphw])
     
     display(self.box)
     
     self.add_nodew.on_submit(self.add_node)
     self.del_node_buttonw.on_click(self.del_node)
     self.add_edge_buttonw.on_click(self.add_edge)
     self.del_edge_buttonw.on_click(self.del_edge)
     
     self.add_node_attr_buttonw.on_click(self.add_node_attr)
     self.add_edge_attr_buttonw.on_click(self.add_edge_attr)
def bar_dropdown(df):
    #df = merge_df
    df_initial = df[(df['Commodity']=='COTTON.') & (df['country'] == "IRAQ")]
    df2 = df_initial[['year','Export_Value','Import_Value']].groupby(['year']).sum().reset_index()


    drop_down_1 = widgets.Dropdown(
        description='Commodity:   ',
        value = 'COTTON.',
        options=df['Commodity'].unique().tolist()    )

    drop_down_2 = widgets.Dropdown(
        options=list(df['country'].unique()),
        value = 'IRAQ',
        description='Country:')


    # Assign an empty figure widget with two traces
    trace1 = go.Bar(x=df2['year'],y = df2['Export_Value'], name='Export Value')
    #trace1
    trace2 = go.Bar(x=df2['year'], y = df2['Import_Value'], name='Import Value')

    g = go.FigureWidget(data=[trace1,trace2],
                        layout=go.Layout(
                            title=dict(
                                text='Export vs Import '
                            ),
                            barmode='group'
                        ))

    def response(change):
        filter_list = [i and j for i, j in
                               zip(df['Commodity'] == drop_down_1.value
                                   , df['country'] == drop_down_2.value
                                  )]
        temp_df = df[filter_list]

        y1 = temp_df['Export_Value']
        #print(x1)
        y2 = temp_df['Import_Value']
        x1 = temp_df['year']
        with g.batch_update():
            g.data[0].x = x1
            g.data[0].y = y1
            g.data[1].x = x1
            g.data[1].y = y2
            #g.layout.barmode = 'overlay'
            g.layout.xaxis.title = 'Year'
            g.layout.yaxis.title = 'value'

            #g.layout.yaxis = temp_df['year']


    drop_down_1.observe(response, names="value")
    drop_down_2.observe(response, names="value")

    container = widgets.HBox([drop_down_1, drop_down_2])
#     widgets.VBox([container,g])
    return g,container
Example #11
0
def boop_menu():
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    wd = widgets.Dropdown(description='What input data?',
                          options=['Features', 'Trajectories'])
    plot = widgets.Checkbox(description='Plot', value=True)
    return widgets.VBox([input, wd, plot])
Example #12
0
def award_produced():
    global df, fig1, award_name, award_type
    df = pd.read_sql_query(
        "Select * from Country c Join Location l on (c.country_id = l.id)",
        conn)
    df['e'] = df.iloc[:, 2:31].sum(axis=1)
    df = df[['country_name', 'iso_2', 'iso_3', 'long', 'lat', 'e']]
    df = df[df['e'] != 0]
    df1 = pd.read_sql_query(
        "SELECT l.country_name, Count(m.country) as count, m.title from Movies m join Country c on (m.country = c.country_id) join Award a on (m.id = a.movie_id) join AwardType at on (a.type = at.id) join Location l on (c.country_id = l.id) where at.name = 'Best Picture' and at.type = 'winner' group by l.country_name",
        conn)
    df2 = pd.merge(df1, df, how='left', on='country_name')

    award_df = pd.read_sql_query("SELECT name, type from AwardType", conn)

    award_name = widgets.Dropdown(
        options=list(award_df['name'].unique()),
        value='Best Picture',
        description='Award name',
    )

    award_type = widgets.Dropdown(
        options=list(award_df['type'].unique()),
        value='winner',
        description='Award type',
    )

    container = widgets.HBox([award_name, award_type])

    fig1 = go.FigureWidget()

    fig1.add_trace(
        go.Scatter(x=df2['country_name'],
                   y=df2['count'],
                   yaxis='y2',
                   name='Award Movies',
                   line=dict(color='turquoise')))

    fig1.add_trace(
        go.Bar(x=df2['country_name'],
               y=df2['e'],
               name='Produced Movies',
               marker_color='darkcyan'))

    fig1.update_layout(title_text='Award Movies and Produced Movies',
                       yaxis=dict(title="Number of Produced Movies"),
                       yaxis2=dict(title="Number of Award Movies",
                                   anchor="free",
                                   overlaying="y",
                                   side="right",
                                   position=1),
                       legend=dict(x=1.07))

    award_name.observe(response, names="value")
    award_type.observe(response, names="value")

    return widgets.VBox([container, fig1])
Example #13
0
def raster_grid_widget(units: Units):

    trials = units.get_ancestor('NWBFile').trials
    if trials is None:
        return widgets.HTML('No trials present')

    groups = infer_categorical_columns(trials)

    control_widgets = widgets.VBox(children=[])

    rows_controller = widgets.Dropdown(options=[None] + list(groups),
                                       description='rows: ',
                                       layout=Layout(width='95%'))
    cols_controller = widgets.Dropdown(options=[None] + list(groups),
                                       description='cols: ',
                                       layout=Layout(width='95%'))
    control_widgets.children = list(
        control_widgets.children) + [rows_controller, cols_controller]

    trial_event_controller = make_trial_event_controller(trials)
    control_widgets.children = list(
        control_widgets.children) + [trial_event_controller]

    unit_controller = int_controller(len(units['spike_times'].data) - 1)
    control_widgets.children = list(
        control_widgets.children) + [unit_controller]

    before_slider = widgets.FloatSlider(.5,
                                        min=0,
                                        max=5.,
                                        description='before (s)',
                                        continuous_update=False)
    control_widgets.children = list(control_widgets.children) + [before_slider]

    after_slider = widgets.FloatSlider(2.,
                                       min=0,
                                       max=5.,
                                       description='after (s)',
                                       continuous_update=False)
    control_widgets.children = list(control_widgets.children) + [after_slider]

    controls = {
        'units': fixed(units),
        'trials': fixed(trials),
        'index': unit_controller.children[0],
        'after': after_slider,
        'before': before_slider,
        'align_by': trial_event_controller,
        'rows_label': rows_controller,
        'cols_label': cols_controller
    }

    out_fig = widgets.interactive_output(raster_grid, controls)
    vbox = widgets.VBox(children=[control_widgets, out_fig])

    return vbox
Example #14
0
    def __init__(self, cluster):
        self.cluster = cluster
        applications = self.cluster.get_applications()
        name_list = []
        for application in applications:
            name_list.append(application.get_information().name.replace(
                'fabric:/', ''))

        self.application_selector = widgets.Dropdown(
            options=name_list, description='Application:', disabled=False)

        self.service_selector = widgets.Dropdown(description='Service:',
                                                 disabled=False)

        self.dictionary_selector = widgets.Dropdown(description='Dictionary:',
                                                    disabled=False)

        self.partition_key_entry = widgets.Text(placeholder='Partition A',
                                                description='Optional Key',
                                                disabled=False)
        self.partition_guid_entry = widgets.Text(
            placeholder='00000000-0000-0000-0000-000000000000',
            description='Optional ID:',
            disabled=False)
        self.query_entry = widgets.Text(placeholder='$top=1',
                                        description='Query:',
                                        disabled=False)

        self.query_button = widgets.Button(
            description='Query',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Query',
            icon='check')
        self.query_button.on_click(self.try_query)
        self.query_results = widgets.Output(
            layout={'border': '1px solid black'})
        self.application_selector.observe(self.create_application)
        self.service_selector.observe(self.create_service)
        self.dictionary_selector.observe(self.create_dictionary)

        display(self.application_selector)
        display(self.service_selector)
        display(self.dictionary_selector)

        print('Query your dictionary')
        display(self.partition_key_entry)
        display(self.partition_guid_entry)
        display(self.query_entry)
        display(self.query_button)
        display(self.query_results)

        if (len(name_list) > 0):
            self.create_application(self.application_selector)
Example #15
0
    def __init__(self, dynamic_table: DynamicTable, group_by=None, window=None, start_discard_rows=None):
        """

        Parameters
        ----------
        dynamic_table
        group_by
        window: None or bool,
        """
        super().__init__(dynamic_table)

        groups = self.get_groups()

        self.discard_rows = start_discard_rows

        self.limit_bit = widgets.BoundedIntText(value=50, min=0, max=99999, disabled=True,
                                                layout=Layout(max_width='70px'))
        self.limit_bit.observe(self.limit_bit_observer)

        self.limit_cb = widgets.Checkbox(description='limit', style={'description_width': 'initial'}, disabled=True,
                                         indent=False, layout=Layout(max_width='70px'))
        self.limit_cb.observe(self.limit_cb_observer)

        self.order_dd = widgets.Dropdown(options=[None] + list(groups), description='order by',
                                         layout=Layout(max_width='120px'), style={'description_width': 'initial'})
        self.order_dd.observe(self.order_dd_observer)

        self.ascending_dd = widgets.Dropdown(options=['ASC', 'DESC'], disabled=True,
                                             layout=Layout(max_width='70px'))
        self.ascending_dd.observe(self.ascending_dd_observer)

        range_controller_max = min(30, self.nitems)
        if window is None:
            self.range_controller = RangeController(0, self.nitems, start_value=(0, range_controller_max), dtype='int', description='units',
                                                    orientation='vertical')
            self.range_controller.observe(self.range_controller_observer)
            self.window = self.range_controller.value
        elif window is False:
            self.window = (0, self.nitems)
            self.range_controller = widgets.HTML('')

        self.group_sm = widgets.SelectMultiple(layout=Layout(max_width='100px'), disabled=True, rows=1)
        self.group_sm.observe(self.group_sm_observer)

        if group_by is None:
            self.group_dd = widgets.Dropdown(options=[None] + list(groups), description='group by',
                                             style={'description_width': 'initial'}, layout=Layout(width='90%'))
            self.group_dd.observe(self.group_dd_observer)
        else:
            self.group_dd = None
            self.set_group_by(group_by)

        self.children = self.get_children()
        self.layout = Layout(width='280px')
        self.update_value()
Example #16
0
    def __init__(self, instrument, mode):
        self.container = widgets.VBox(width="100%", background_color="#CCCCCC")

        self.instrument = instrument
        self.instrument.set_mode(mode)
        self.instrument.get_apertures()

        self.aper_box = widgets.HBox(padding='10px', width="100%")
        self.aperture = widgets.Dropdown(description="Aperture:",
                                         options=self.instrument.apertures)
        self.aper_box.children = [self.aperture]
        self.on_aperture_change(dummy)

        self.inst_box = widgets.HBox(padding='10px', width="100%")
        self.filt = widgets.Dropdown(description="Filter:",
                                     options=self.instrument.filters)
        self.disp = widgets.Dropdown(description="Disperser:",
                                     options=self.instrument.dispersers)
        self.inst_box.children = [self.filt, self.disp]

        self.det_box = widgets.HBox(padding='10px', width="100%")
        self.ngroups = widgets.BoundedIntText(description="Groups: ",
                                              min=3,
                                              max=999,
                                              value=6,
                                              width=30)
        self.nints = widgets.BoundedIntText(description="Integrations: ",
                                            min=1,
                                            max=999,
                                            value=1,
                                            width=30)
        self.nexps = widgets.BoundedIntText(description="Exposures: ",
                                            min=1,
                                            max=999,
                                            value=1,
                                            width=30)
        self.det_box.children = [self.ngroups, self.nints, self.nexps]

        self.advanced = widgets.VBox(width="100%", background_color="#CCCCCC")
        self.readmode = widgets.Dropdown(description="Readmode:",
                                         options=self.instrument.readmodes,
                                         value='medium8')
        self.subarray = widgets.Dropdown(description="Sub-array:",
                                         options=self.instrument.subarrays,
                                         value='1024x1024')
        self.advanced.children = [self.readmode, self.subarray]

        self.advanced_drop = widgets.Accordion(children=[self.advanced])
        self.advanced_drop.set_title(0, "ADVANCED")
        self.advanced_drop.selected_index = None
        self.container.children = [
            self.aper_box, self.inst_box, self.det_box, self.advanced_drop
        ]

        self.aperture.observe(self.on_aperture_change)
Example #17
0
 def __init__(self):
     self.all_years_data = self.read_all_years_data()
     self.expenditure_options = self.build_expenditure_dicts()
     self.groupby_options = self.build_groupby_dicts()
     w = interactive(self.make_boxplot,
                     expenditure=widgets.Dropdown(options=self.expenditure_options,value='Total',description='Expenditure category:'),
                     groupby_feature=widgets.Dropdown(options=self.groupby_options,value='Title_1',description='Group schools by feature:'),
                     normalized=widgets.Checkbox(description='Plot expenditure as percent of total:', value=False))
     w.border_color = 'red'
     w.border_style = 'dotted'
     w.border_width = 3
     display(w)
Example #18
0
 def __init__(self, Notebook):
     super(Plot_Evolution_Observable, self).__init__(Notebook)
     self.widget_Xobs = widgets.Dropdown(options=[None],
                                         value=None,
                                         description='x-axis:',
                                         disabled=True)
     self.widget_Yobs = widgets.Dropdown(options=[None],
                                         value=None,
                                         description='y-axis:',
                                         disabled=True)
     self.widget_replot_observable = widgets.Button(description="Plot",
                                                    disabled=True)
     self.notebook.dependencies_dict["seed"].append(self)
Example #19
0
    def __init__(self, path=tumblrsPath):
        self.path = path
        self.AC = AccountCollection(path)
        self.A = self.AC[random.randint(0, len(self.AC))]

        self.accountSelector = widgets.Dropdown(
            options=self.AC.names,
            value=self.A.name,
            description='Account:',
        )

        self.tagsSelector = widgets.Dropdown(
            options=[f'{len(self.A)} None'] + self.A.sortedTags(count=True),
            value=f'{len(self.A)} None',
            description='tags:',
        )

        self.typesSelector = widgets.RadioButtons(
            options=self.A.postTypes,
            value=self.A.currentType,
            description='Post type:',
        )

        self.postSlider = widgets.IntSlider(min=0,
                                            max=len(self.A) - 1,
                                            value=0,
                                            description=str(len(self.A)) +
                                            ' posts')

        self.mainCaption = widgets.HTML(value=self.A(0))

        self.nextButton = widgets.Button(description="Next")

        self.previousButton = widgets.Button(description="Previous")

        self.tagSearchEnable = widgets.Button(description="Enable tag search")

        self.globalTagSelector = widgets.RadioButtons(
            options=['None'],
            value='None',
            description='Global tag filter:',
            disabled=True,
            display=False,
        )

        self.controls = HBox([
            VBox([
                HBox([self.accountSelector, self.tagsSelector]),
                HBox([self.postSlider, self.previousButton, self.nextButton])
            ]), self.typesSelector
        ])
Example #20
0
    def __init__(self, vizapp, filename=None):

        self._vizapp = vizapp

        self.mostable = None
        self.mostable_dir = None
        self.data = None
        self.html = None
        self.current_cutout = None

        #  Create File Menu
        self._menu_bar_file = widgets.Dropdown(
            options=['File', 'Load', 'Save'],
            value='File',
            description='',
            layout=widgets.Layout(width='10em'),
        )

        self._menu_bar_file.observe(self._on_change_menu_bar_file)
        self._menu_bar = widgets.HBox([self._menu_bar_file])

        #  Create Navigation Bar
        self._current_slit = widgets.Dropdown(
            options=[],
            description='Slit',
            layout=widgets.Layout(width='20em'),
        )
        self._current_slit.observe(self._on_change_current_slit)

        self._next_button = widgets.Button(description="Next")
        self._next_button.on_click(self._on_next)

        self._back_button = widgets.Button(description="Back")
        self._back_button.on_click(self._on_back)

        self._nav_bar = widgets.HBox(
            [self._current_slit, self._back_button, self._next_button])

        self._table = MOSVizTable(session=self._vizapp.glue_app.session)
        self._mos_widget = MOSVizWidget(session=self._vizapp.glue_app.session)

        self._viewer_box = widgets.VBox([self._mos_widget, self._table.show()])

        self._main_box = widgets.Box([
            widgets.VBox([self._nav_bar,
                          self._table.show(), self._mos_widget])
        ])

        if filename:
            self._vizapp.glue_app.load_data(filename)
Example #21
0
 def make_dropdown_widget(cls, description='Description', options=['Label 1', 'Label 2'], value='Label 1',
                         file_path=None, layout=Layout(), handler=None):
     "Return a Dropdown widget with specified `handler`."
     dd = widgets.Dropdown(description=description, options=options, value=value, layout=layout)
     if file_path is not None: dd.file_path = file_path
     if handler is not None: dd.observe(handler, names=['value'])
     return dd
Example #22
0
def riemann_plot_pplane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
    """Plots interactive riemann solution with time dependence and phase plane plot."""

    # Create plot function for interact
    pp_plot = full_riemann_solution_plot_fixed(ql, qr, rho, bulk)

    # Declare all widget sliders
    t_widget = widgets.FloatSlider(value=0,
                                   min=0.0,
                                   max=1.0,
                                   description='$t$')
    which_char_widget = widgets.Dropdown(options=[None, 1, 2],
                                         description='Characs.')

    # Set up interactive GUI
    interact_gui = widgets.HBox([t_widget, which_char_widget])

    # Define interactive widget and run GUI
    ppwidget = interact(pp_plot, t=t_widget, which_char=which_char_widget)

    try:
        ppwidget.widget.close()
        display(interact_gui)
        display(ppwidget.widget.out)
    except:
        pass
Example #23
0
def show_image_series(image_series: ImageSeries, neurodata_vis_spec: dict):
    if len(image_series.data.shape) == 3:
        return show_grayscale_image_series(image_series, neurodata_vis_spec)

    def show_image(index=0, mode='rgb'):
        fig, ax = plt.subplots(subplot_kw={'xticks': [], 'yticks': []})
        image = image_series.data[index]
        if mode == 'bgr':
            image = image[:, :, ::-1]
        ax.imshow(image, cmap='gray', aspect='auto')
        fig.show()
        return fig2widget(fig)

    slider = widgets.IntSlider(value=0,
                               min=0,
                               max=image_series.data.shape[0] - 1,
                               orientation='horizontal',
                               continuous_update=False,
                               description='index')
    mode = widgets.Dropdown(options=('rgb', 'bgr'),
                            layout=Layout(width='200px'),
                            description='mode')
    controls = {'index': slider, 'mode': mode}
    out_fig = widgets.interactive_output(show_image, controls)
    vbox = widgets.VBox(children=[out_fig, slider, mode])

    return vbox
Example #24
0
def DrawDNNWeights(fac, datasetName, methodName="DNN"):
    m = GetMethodObject(fac, datasetName, methodName)
    if m == None:
        return None
    try:
        net = GetDeepNetwork(str(m.GetWeightFileName()), True)
    except AttributeError:
        print(
            "STANDARD architecture not supported! If you want to use this function you must use CPU or GPU architecture"
        )
    numOfLayers = len(net["layers"])
    options = []
    vals = []
    for layer in xrange(numOfLayers):
        options.append(str(layer) + "->" + str(layer + 1))
        vals.append(layer)
    selectLayer = widgets.Dropdown(options=options,
                                   value=options[0],
                                   description='Layer')

    def drawWrapper(e):
        CreateWeightHist(net, selectLayer.value)
        pass

    button = widgets.Button(description="Draw",
                            font_weight="bold",
                            font_size="16")
    button.on_click(drawWrapper)
    box = widgets.HBox([selectLayer, button])
    display(box)
Example #25
0
 def __init__(self, text, correct, *wrong, sonst=False, inst=None):
     self.selection = ""
        
     self.richtig = correct    
     
     def makeAnswers(correct, wrong):    
         allAnsw = ["Keine der Alternativen"] + wrong
         allAnsw.append(correct)
         allAnsw.sort()
         return allAnsw
     
     allAnsw = makeAnswers(correct, list(wrong))
     
     textbox = widgets.HTML(value='<h4 style="font-size:14px;">{}</h4>'.format(text))
     instbox = widgets.HTML(value='<i>{}</i>'.format(inst), layout=widgets.Layout(justify_content="center")) 
     
     answer = widgets.Dropdown(options = allAnsw, value= allAnsw[0], description="Antwort:", layout={'width': '500px'})
     button = widgets.Button(description="Korrekt?",layout=widgets.Layout(width="250px"))
     super().__init__(children=[textbox, instbox, answer, button])
     
     def on_change_drop(change):
         if change['type'] == 'change' and change['name']=='value':
                 self.selection = change['new']
                 
         button.style.button_color = None        
                 
     answer.observe(on_change_drop)
     
     def on_button_clicked(b):
             if  self.selection == self.richtig:
                 b.style.button_color = 'lightgreen'
             else:
                 b.style.button_color = 'red'
     
     button.on_click(on_button_clicked)
def make_trial_event_controller(trials, layout=None, multiple=False):
    """Controller for which reference to use (e.g. start_time) when making time-aligned averages"""
    trial_events = ["start_time"]
    if not np.all(np.isnan(trials["stop_time"].data)):
        trial_events.append("stop_time")
    trial_events += [
        x.name for x in trials.columns
        if (("_time" in x.name) and (x.name not in ("start_time",
                                                    "stop_time")))
    ]
    kwargs = {}
    if layout is not None:
        kwargs.update(layout=layout)

    if multiple:
        trial_event_controller = widgets.SelectMultiple(
            options=trial_events,
            value=["start_time"],
            description='align to:',
            disabled=False,
            **kwargs)
    else:
        trial_event_controller = widgets.Dropdown(options=trial_events,
                                                  value="start_time",
                                                  description="align to: ",
                                                  **kwargs)
    return trial_event_controller
Example #27
0
    def __init__(self, xlim=(-1.2, 1.2), ylim=(-1.2, 1.2), data=None):
        self.xlim = xlim
        self.ylim = ylim
        input_x = np.arange(xlim[0], xlim[1], 0.1)
        input_y = np.arange(ylim[0], ylim[1], 0.1)
        self.input_x_matrix, self.input_y_matrix = np.meshgrid(
            input_x, input_y)
        self.inputs_xy = np.concatenate(
            (self.input_x_matrix.flatten()[:, np.newaxis],
             self.input_y_matrix.flatten()[:, np.newaxis]),
            axis=1)
        self.activation_functions_dict = {
            'Linear': linear,
            'Sigmoid': sigmoid,
            'Hyperbolic tangent': htan,
            'Gaussian': gaussian
        }
        self.data = data
        if len(data) > 0:
            self.c1_i = data[:, 2] > 0
            self.c2_i = data[:, 2] < 0
        self.error = []
        self.ax_line = None
        self.ax_im = None

        weight_x_slider = widgets.FloatSlider(
            value=0.5,
            min=-2.0,
            max=2.0,
            step=0.01,
            description='Weight x:',
        )
        weight_y_slider = widgets.FloatSlider(
            value=0.5,
            min=-2.0,
            max=2.0,
            step=0.01,
            description='Weight y:',
        )
        bias_slider = widgets.FloatSlider(
            value=0.0,
            min=-2.0,
            max=2.0,
            step=0.01,
            description='Bias:',
        )
        activation_function_list = widgets.Dropdown(
            options={
                list(self.activation_functions_dict.keys())[i]: i
                for i in range(len(self.activation_functions_dict))
            },
            value=1,
            description='Activation function:',
        )
        self.controls = {
            'weight_x': weight_x_slider,
            'weight_y': weight_y_slider,
            'bias': bias_slider,
            'activation_function_index': activation_function_list
        }
Example #28
0
 def make_dropdown_widget(options:Collection, value, handler:Callable, img_idx:Optional[int]=None,
                          description='', layout=Layout(width='auto')) -> widgets.Dropdown:
     "Return a Dropdown widget with specified `handler`."
     dd = widgets.Dropdown(description=description, options=options, value=value, layout=layout)
     dd.observe(handler, names='value')
     if img_idx is not None: dd.img_idx = img_idx
     return dd
Example #29
0
def create_platform_product_gui(platforms, products):
    """
    Description:

    -----
    """

    # Create widgets
    platform_sel = widgets.Dropdown(options=platforms, values=platforms)
    product_sel = widgets.Dropdown(options=products, values=products)

    # Display form
    display(widgets.Label('Platform: '), platform_sel)
    display(widgets.Label('Product: '), product_sel)

    return [platform_sel, product_sel]
    def retrieve_parameters(self):
        if self.uniqueness:
            list_of_input_files = glob.glob(
                os.path.join(self.working_dir, '*' + self.dominant_extension))
            list_of_input_files.sort()

            self.result = self.Result(list_files=list_of_input_files,
                                      ext=self.dominant_extension,
                                      uniqueness=True)

        else:

            list_of_maj_ext = [
                _ext for _ext in self.counter_extension.keys()
                if self.counter_extension[_ext] == self.dominant_number
            ]

            box = widgets.HBox([
                widgets.Label("Select Extension to work with",
                              layout=widgets.Layout(width='20%')),
                widgets.Dropdown(options=list_of_maj_ext,
                                 layout=widgets.Layout(width='20%'),
                                 value=list_of_maj_ext[0])
            ])
            display(box)
            self.dropdown_ui = box.children[1]