Exemple #1
0
    def updateParameterAndFilepathWidgets(self, ignore):
        cdatabases = self.dbPathWidget.value.split(' ')
        cdb = cdatabases[
            0]  #all databases are assumed to have same parameter list
        dbHeader = self.readDataBaseHeader(cdb)
        self.parameterWidgets.clear()
        self.filepathWidgets.clear()

        for param in dbHeader:
            pW = ipywidgets.ToggleButton(value=param != "FILE",
                                         description=param,
                                         disabled=False)
            pW.observe(self.updateParameterValueWidgets, names='value')
            self.parameterWidgets.append(pW)

            fW = ipywidgets.ToggleButton(value=param == "FILE",
                                         description=param,
                                         disabled=False)
            fW.observe(self.updateParameterValueWidgets, names='value')
            self.filepathWidgets.append(fW)

        grid = ipywidgets.GridspecLayout(2, len(self.parameterWidgets) + 1)
        grid[0, 0] = ipywidgets.Label("Parameters")
        for j in range(0, len(self.parameterWidgets)):
            grid[0, j + 1] = self.parameterWidgets[j]
        for j in range(0, len(self.filepathWidgets)):
            grid[1, j + 1] = self.filepathWidgets[j]

        with self.parametersAndFilepathsSelectionOutput:
            self.parametersAndFilepathsSelectionOutput.clear_output()
            # display(grid)

        self.updateParameterValueWidgets('')
        return
Exemple #2
0
    def create_tab(self):
        super(BqplotHistogramView, self).create_tab()
        self.button_normalize = widgets.ToggleButton(
            value=False, description='normalize', tooltip='Normalize histogram')
        link((self.button_normalize, 'value'), (self.state, 'normalize'))

        self.button_cumulative = widgets.ToggleButton(
            value=False, description='cumulative', tooltip='cumulative histogram')
        link((self.button_cumulative, 'value'), (self.state, 'cumulative'))


        self.widgets_axis = []
        for i, axis_name in enumerate('x'):
            if hasattr(self.state, axis_name + '_att_helper'):
                helper = getattr(self.state, axis_name + '_att_helper')
                widget_axis = widgets.Dropdown(options=[k.label for k in helper.choices],
                                               value=getattr(self.state, axis_name + '_att'), description=axis_name + ' axis')
                self.widgets_axis.append(widget_axis)
                link_component_id_to_select_widget(self.state, axis_name + '_att', widget_axis)
        # @on_change([(self.state, 'hist_n_bin')])
        # def trigger():

        # self.widget_hist_x_min = widgets.FloatText(description='x min')
        # link((self.state, 'hist_x_min'), (self.widget_hist_x_min, 'value'))

        # self.widget_hist_n_bin = widgets.IntSlider(min=1, max=1000, step=1, description='bins')
        # link((self.state, 'hist_n_bin'), (self.widget_hist_n_bin, 'value'))

        self.tab_general.children += (widgets.HBox([self.button_normalize, self.button_cumulative] ),) + tuple(self.widgets_axis)
Exemple #3
0
 def __init__(self):
     """
     
     Collect scalable physical parameters to be used for the N-Layer radiative model.
     
     """
     ###############################
     self.N_slider = widgets.IntSlider(min=3,
                                       max=20,
                                       value=3,
                                       description='N-Layers: ')
     widgets.interact(self.get_n_slider, N_slider=self.N_slider)
     ###############################
     self.albedo_slider = widgets.FloatSlider(min=0,
                                              max=1,
                                              value=0.3,
                                              description='Albedo: ')
     widgets.interact(self.get_albedo_slider,
                      albedo_slider=self.albedo_slider)
     ###############################
     self.S0_slider = widgets.IntSlider(min=10,
                                        max=10000,
                                        value=1368,
                                        description='$S_{0}$ ($W/m^2$): ')
     widgets.interact(self.get_S0_slider, S0_slider=self.S0_slider)
     ###############################
     style = {'description_width': 'initial'}
     self.SW_slider = widgets.IntSlider(
         min=0,
         max=100,
         value=3,
         style=style,
         layout=Layout(width='45%', height='20px'),
         description='SW absorbed in Stratosphere (%): ')
     widgets.interact(self.get_SW_slider, SW_slider=self.SW_slider)
     ###############################
     self.heatflux_slider = widgets.IntSlider(
         min=0,
         max=500,
         value=0,
         style=style,
         layout=Layout(width='35%', height='20px'),
         description='Surface Heat Flux ($W/m^2$): ')
     widgets.interact(self.get_heatflux_slider,
                      heatflux_slider=self.heatflux_slider)
     ###############################
     self.pertub_button = widgets.ToggleButton(value=False,
                                               description='Perturbation?',
                                               disabled=False,
                                               button_style='info',
                                               tooltip='Description')
     widgets.interact(self.get_perturbation,
                      pertub_button=self.pertub_button)
     ###############################
     self.calc_button = widgets.ToggleButton(value=False,
                                             description='Radiate',
                                             disabled=False,
                                             button_style='danger',
                                             tooltip='Description')
     widgets.interact(self.get_temps, calc_button=self.calc_button)
Exemple #4
0
    def create_tab(self):
        super(BqplotHistogramView, self).create_tab()
        self.button_normalize = widgets.ToggleButton(
            value=False,
            description='normalize',
            tooltip='Normalize histogram')
        link((self.button_normalize, 'value'), (self.state, 'normalize'))

        self.button_cumulative = widgets.ToggleButton(
            value=False,
            description='cumulative',
            tooltip='cumulative histogram')
        link((self.button_cumulative, 'value'), (self.state, 'cumulative'))

        # @on_change([(self.state, 'hist_n_bin')])
        # def trigger():

        # self.widget_hist_x_min = widgets.FloatText(description='x min')
        # link((self.state, 'hist_x_min'), (self.widget_hist_x_min, 'value'))

        # self.widget_hist_n_bin = widgets.IntSlider(min=1, max=1000, step=1, description='bins')
        # link((self.state, 'hist_n_bin'), (self.widget_hist_n_bin, 'value'))

        self.tab_general.children += (widgets.HBox(
            [self.button_normalize, self.button_cumulative]), )
Exemple #5
0
def _volume_widets(v, lighting=False):
    import ipywidgets
    #angle1 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle1, description="angle1")
    #angle2 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle2, description="angle2")
    #ipywidgets.jslink((v, 'angle1'), (angle1, 'value'))
    #ipywidgets.jslink((v, 'angle2'), (angle2, 'value'))
    if lighting:
        ambient_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=v.ambient_coefficient, description="ambient")
        diffuse_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=v.diffuse_coefficient, description="diffuse")
        specular_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=v.specular_coefficient, description="specular")
        specular_exponent = ipywidgets.FloatSlider(min=0, max=10, step=0.001, value=v.specular_exponent, description="specular exp")
        #angle2 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle2, description="angle2")
        ipywidgets.jslink((v, 'ambient_coefficient'), (ambient_coefficient, 'value'))
        ipywidgets.jslink((v, 'diffuse_coefficient'), (diffuse_coefficient, 'value'))
        ipywidgets.jslink((v, 'specular_coefficient'), (specular_coefficient, 'value'))
        ipywidgets.jslink((v, 'specular_exponent'), (specular_exponent, 'value'))
        widgets_bottom = [ipywidgets.HBox([ambient_coefficient, diffuse_coefficient]),
         ipywidgets.HBox([specular_coefficient, specular_exponent])]
    else:
        widgets_bottom = []
        v.ambient_coefficient = 1
        v.diffuse_coefficient = 0
        v.specular_coefficient = 0

    if 1:
        stereo = widgets.ToggleButton(value=v.stereo, description='stereo', icon='eye')
        fullscreen = widgets.ToggleButton(value=v.stereo, description='fullscreen', icon='arrows-alt')
        ipywidgets.jslink((v, 'stereo'), (stereo, 'value'))
        ipywidgets.jslink((v, 'fullscreen'), (fullscreen, 'value'))
        widgets_bottom += [ipywidgets.HBox([stereo,fullscreen])]

    return ipywidgets.VBox(
        [v.tf.control(), v,
         ] + widgets_bottom# , ipywidgets.HBox([angle1, angle2])
    )
def preview_parameters_get_store_parameters_buttons(step, index, parameters_update):
    print(f'Do you want to set the following new parameters: \n {parameters_update} \n specific for the following data?')
    # Define toggle button widgets for mouse-, session- and trial-specific parameter storing
    mouse_specific_widget = widgets.ToggleButton(value=True, description=f'Mouse: {index[0]}')
    session_specific_widget = widgets.ToggleButton(value=True, description=f'Session: {index[1]}')
    trial_name = src.pipeline.get_trial_name(index[2],index[3])
    trial_specific_widget = widgets.ToggleButton(value=True, description=f'Trial: {trial_name}')
    # Store the widgets in a list
    widget_list = [mouse_specific_widget, session_specific_widget, trial_specific_widget]
    # Define the updating function to enforce the rule: if parameters are stored 
    # level-specific for a certain level, they are specific for all upper levels as well
    def update_values(*args):
        for i, indexer in enumerate(src.pipeline.data_structure[:3]):
            value_list = [widget.value for widget in widget_list[i+1:]]
            if np.array(value_list).any():
                widget_list[i].value = True
    # Apply the update_values function as an observer for each widget
    for widget in widget_list: widget.observe(update_values, 'value')
    # Display the widgets
#    for widget in widget_list: display(widget)
    # Create a button for storing parameters
#    store_parameters = widgets.Button(description = 'Store parameters') ; display(store_parameters)
    # Define a wrapper function for the button
    def f_store_parameters(mouse_specific, session_specific, trial_specific):
        mouse = index[0] if mouse_specific else None
        session = index[1] if session_specific else None
        trial = index[2] if trial_specific else None
        is_rest = index[3] if trial_specific else None 
        src.pipeline.set_parameters(step, parameters_update, mouse, session, trial, is_rest, check = False)
    
    interact_manual(f_store_parameters, mouse_specific = mouse_specific_widget, session_specific = session_specific_widget,
                    trial_specific = trial_specific_widget)
    def prepare_widgets(self):

        gui = types.SimpleNamespace(
            apply_idf=ipywidgets.ToggleButton(
                value=False,
                description='TF-IDF',
                tooltip='Apply IDF (skikit-learn) or TF-IDF (gensim)',
                icon='check',
                layout=ipywidgets.Layout(width='115px')),
            method=ipywidgets.Dropdown(
                description='Engine',
                options=ENGINE_OPTIONS,
                value='gensim_lda',
                layout=ipywidgets.Layout(width='200px')),
            n_topics=ipywidgets.IntSlider(
                description='Topics',
                min=2,
                max=100,
                value=20,
                step=1,
                layout=ipywidgets.Layout(width='240px')),
            max_iter=ipywidgets.IntSlider(
                description='Iterations',
                min=100,
                max=6000,
                value=2000,
                step=10,
                layout=ipywidgets.Layout(width='240px')),
            show_trace=ipywidgets.ToggleButton(
                value=False,
                description='Show trace',
                disabled=False,
                icon='check',
                layout=ipywidgets.Layout(width='115px')),
            compute=ipywidgets.Button(description='Compute',
                                      button_style='Success',
                                      layout=ipywidgets.Layout(
                                          width='115px',
                                          background_color='blue')),
            output=ipywidgets.Output(layout={'border': '1px solid black'}),
            spinner=get_spinner_widget())

        boxes = [
            ipywidgets.VBox(
                [
                    gui.method,
                    gui.n_topics,
                    gui.max_iter,
                ],
                layout=ipywidgets.Layout(margin='0px 0px 0px 0px')),
            ipywidgets.VBox([
                gui.apply_idf,
                gui.show_trace,
                gui.compute,
                gui.spinner,
            ],
                            layout=ipywidgets.Layout(align_items='flex-start'))
        ]

        return gui, boxes
Exemple #8
0
def figure(key=None, width=400, height=500, lighting=True, controls=True, debug=False):
	"""Create a new figure (if no key is given) or return the figure associated with key

	:param key: Python object that identifies this figure
	:param width: pixel width of WebGL canvas
	:param height:  .. height ..
	:param lighting: use lighting or not
	:param controls: show controls or not
	:param debug: show debug buttons or not
	:return:
	"""
	if key is not None and key in current.figures:
		current.figure = current.figures[key]
		current.container = current.containers[key]
	else:
		current.figure = volume.VolumeRendererThree(data=None)
		current.container = ipywidgets.VBox()
		current.container.children = [current.figure]
		if key is not None:
			current.figures[key] = current.figure
			current.containers[key] = current.container
		if controls:
			stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
			fullscreen = ipywidgets.ToggleButton(value=current.figure.stereo, description='fullscreen',
												 icon='arrows-alt')
			l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
			l2 = ipywidgets.jslink((current.figure, 'fullscreen'), (fullscreen, 'value'))
			current.container.children += (ipywidgets.HBox([stereo, fullscreen]),)
		if debug:
			show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front"])
			current.container.children += (show,)
			ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
	return current.figure
Exemple #9
0
 def _button(row, clmn, lattice):
     h = self.Hcoor2H.get((row, clmn), None)
     h_id = "" if h is None else str(h.id)
     if lattice in ["square", "honeycomb"]:
         description = h_id
         button = widgets.ToggleButton(
             description=description,
             layout=widgets.Layout(width="30px", height="30px"),
             disabled=(h is None),
         )
         if lattice == "square":
             return button
         else:
             spacer = widgets.ToggleButton(
                 description="",
                 layout=widgets.Layout(width="30px", height="15px"),
                 disabled=True,
             )
             odd_clmn = not clmn % 2
             even_row = row % 2
             if (odd_clmn + even_row) % 2:
                 return widgets.VBox([button, spacer])
             else:
                 return widgets.VBox([spacer, button])
     else:
         raise TypeError
Exemple #10
0
    def __init__(
        self,
        *,
        default_corpus_path: str = None,
        default_corpus_filename: str = '',
        default_data_folder: str = None,
    ):

        super().__init__(default_corpus_path, default_corpus_filename,
                         default_data_folder)

        self._partition_key: widgets.Dropdown = widgets.Dropdown(
            description='',
            options={
                'Year': 'year',
                'Document': 'document_id'
            },
            value='document_id',
            layout=widgets.Layout(width='140px'),
            disabled=True,
        )
        self._context_width = widgets.IntSlider(
            description='',
            min=1,
            max=40,
            step=1,
            value=1,
            layout=default_layout,
            # tooltip=tooltips['_context_width'],
        )
        self._concept = widgets.Text(
            value='',
            placeholder='Use comma (,) as word delimiter',
            description='',
            disabled=False,
            layout=widgets.Layout(width='280px'),
            # tooltip=tooltips['_concept'],
        )
        self._ignore_concept = widgets.ToggleButton(
            value=False,
            description='Ignore concept',
            icon='',
            layout=button_layout,
            tooltips=
            "Remove word-pairs that include concept tokens from end result",
        )
        self._ignore_padding = widgets.ToggleButton(
            value=True,
            description='Ignore padding',
            icon='check',
            layout=button_layout,
            tooltips=
            "Remove word-pairs that include padding tokens from end result",
        )
        self._context_width_title = widgets.HTML("<b>Context distance</b>")
Exemple #11
0
 def __init__(self,
              tag,
              a_widget,
              b_widget,
              orientation='h',
              offwidget=None):
     self.tag = tag
     self.description = widget.Label(tag,
                                     layout=widget.Layout(width="135px"))
     # self.description = widget.HTML(
     # 	value=f'<div style="transform: rotate(-15deg);">{tag}</div>',
     # )
     self.a_widget = a_widget
     self.b_widget = b_widget
     if offwidget is None:
         self.offwidget = widget.Label("background")
     elif isinstance(offwidget, str):
         self.offwidget = widget.Label(offwidget)
     else:
         self.offwidget = offwidget
     self.offwidget.add_class("EMAT_NOSHOW")
     self.active_status_box = widget.ToggleButton(
         value=True,
         disabled=False,
         button_style='',  # 'success', 'info', 'warning', 'danger' or ''
         tooltip='Activate Parameter',
         icon='toggle-on',  # (FontAwesome names without the `fa-` prefix)
         layout=widget.Layout(width="40px"),
     )
     self.link_status_box = widget.ToggleButton(
         value=True,
         # description='Click me',
         disabled=False,
         button_style='',  # 'success', 'info', 'warning', 'danger' or ''
         tooltip='Link Values',
         icon='link',  # (FontAwesome names without the `fa-` prefix)
         layout=widget.Layout(width="40px"),
     )
     self.toggle_link()
     super().__init__(children=(
         self.description,
         self.active_status_box,
         self.a_widget,
         self.link_status_box,
         self.b_widget,
         self.offwidget,
     ))
     self.layout.display = 'flex'
     self.layout.align_items = 'stretch'
     if orientation == 'v':
         self.layout.flex_flow = 'column'
     self.active_status_box.observe(self.toggle_active)
     self.link_status_box.observe(self.toggle_link)
Exemple #12
0
def create_grid(matrizbadfinal,resultados):
    grid = widgets.GridspecLayout(matrizbadfinal.shape[0]+1, matrizbadfinal.shape[1]+1,max_width=5)
    for i in range(matrizbadfinal.shape[1]):
        grid[0,i+1] = widgets.Text(value=str(matrizbadfinal.columns[i]), disabled=True,layout=widgets.Layout(width='100px'))
    for j in range(matrizbadfinal.shape[0]):
        grid[j+1,0] = widgets.Text(value= str(matrizbadfinal.index[j]), disabled=True, layout=widgets.Layout(width='100px'))

    for i in range(matrizbadfinal.shape[0]):
        for j in range(matrizbadfinal.shape[1]):
            if i < resultados['index'].values[0] and j < resultados['columns'].values[0]:
                grid[i+1,j+1] = widgets.ToggleButton(description=str(np.round(matrizbadfinal.values[i,j]*100,1))+"%",value=True,layout=widgets.Layout(width='100px'))
            else:
                grid[i+1,j+1] = widgets.ToggleButton(description=str(np.round(matrizbadfinal.values[i,j]*100,1))+"%",value=False,layout=widgets.Layout(width='100px'))
    return grid
Exemple #13
0
    def __init__(
        self,
        compute_callback: Callable[["TokenCountsGUI", DocumentIndex],
                                   pd.DataFrame],
        load_document_index_callback: Callable[[pipeline.CorpusConfig],
                                               DocumentIndex],
        load_corpus_config_callback: Callable[[str], pipeline.CorpusConfig],
    ):

        self.compute_callback: Callable[["TokenCountsGUI", DocumentIndex],
                                        pd.DataFrame] = compute_callback
        self.load_document_index_callback: Callable[
            [pipeline.CorpusConfig],
            DocumentIndex] = load_document_index_callback
        self.load_corpus_config_callback: Callable[
            [str], pipeline.CorpusConfig] = load_corpus_config_callback

        self.document_index: DocumentIndex = None

        self._corpus_configs: widgets.Dropdown = widgets.Dropdown(
            description='', options=[], value=None, layout={'width': '200px'})
        self._normalize: widgets.ToggleButton = widgets.ToggleButton(
            description="Normalize",
            icon='check',
            value=False,
            layout=widgets.Layout(width='140px'))
        self._smooth: widgets.ToggleButton = widgets.ToggleButton(
            description="Smooth",
            icon='check',
            value=False,
            layout=widgets.Layout(width='140px'))
        self._grouping: widgets.Dropdown = widgets.Dropdown(
            options=TOKEN_COUNT_GROUPINGS,
            value='year',
            description='',
            disabled=False,
            layout=widgets.Layout(width='90px'),
        )
        self._status: widgets.Label = widgets.Label(
            layout=widgets.Layout(width='50%', border="0px transparent white"))
        self._categories: widgets.SelectMultiple = widgets.SelectMultiple(
            options=[],
            value=[],
            rows=12,
            layout=widgets.Layout(width='120px'),
        )

        self._tab: OutputsTabExt = OutputsTabExt(["Table", "Line", "Bar"],
                                                 layout={'width': '98%'})
    def __init__(self):
        """__init__ is the initiation function for the Storm_Selection_gui object. This
        initiation creates a dataframe for the storm data from the National Hurricane
        Center. In addition, this initiation creates widgets to select a specific storm
        from the National Hurricane Center database with both a widget for a year
        selection and also for a track button which actually retrieves the models
        and tracks for a given storm. """

        # Setting up storm object table
        fileLines = readUrlFile(
            'http://ftp.nhc.noaa.gov/atcf/index/storm_list.txt')
        self.storm_table = split_storm_info(fileLines)

        # Creation of widgets
        # Year Selector Slider (year_slider)
        self.year_slider = widgets.IntSlider(min=1851,
                                             max=2019,
                                             value=2019,
                                             description='Storm Year: ')
        widgets.interact(self.get_storms_slider, year_slider=self.year_slider)
        # Button to retrieve storm tracks (track_button)
        self.track_button = widgets.ToggleButton(
            value=False,
            description='Get Storm Tracks',
            disabled=False,
            button_style='info',
            tooltip='Description')
        widgets.interact(self.get_tracks, track_button=self.track_button)
Exemple #15
0
def fitline(prism, survey, dobj):
    def profiledata(Binc, Bdec, Bigrf, depth, susc, comp, irt, Q, rinc, rdec,
                    update):

        # Get the line extent from the 2D survey for now
        sim = Mag.Simulation()
        sim.prism = prism.result

        xyzLoc = survey.receiver_locations.copy()
        xyzLoc[:, 2] += depth

        rxLoc = mag.receivers.Point(xyzLoc)
        srcField = mag.sources.SourceField(receiver_list=[rxLoc],
                                           parameters=(Bigrf, -Binc, Bdec))
        survey2D = mag.Survey(srcField)
        sim.survey = survey2D

        sim.Q, sim.rinc, sim.rdec = Q, -rinc, rdec
        sim.uType, sim.mType = comp, irt
        sim.susc = susc

        # Compute fields from prism
        fields = sim.fields()

        dpred = np.zeros_like(fields[0])
        for b in fields:
            dpred += b

        dpred += +Bigrf
        a = np.r_[xyzLoc[:, 0].min(), 0]
        b = np.r_[xyzLoc[:, 0].max(), 0]
        return plotProfile(xyzLoc, dobj, a, b, 10, pred=dpred, dType="2D")

    Q = widgets.interactive(
        profiledata,
        Binc=widgets.FloatSlider(min=-90.0,
                                 max=90,
                                 step=5,
                                 value=90,
                                 continuous_update=False),
        Bdec=widgets.FloatSlider(min=-90.0,
                                 max=90,
                                 step=5,
                                 value=0,
                                 continuous_update=False),
        Bigrf=widgets.FloatSlider(min=54000.0,
                                  max=55000,
                                  step=10,
                                  value=54500,
                                  continuous_update=False),
        depth=widgets.FloatSlider(min=0.0, max=5.0, step=0.05, value=0.5),
        susc=widgets.FloatSlider(min=0.0, max=800.0, step=5.0, value=1.0),
        comp=widgets.ToggleButtons(options=["tf", "bx", "by", "bz"]),
        irt=widgets.ToggleButtons(options=["induced", "remanent", "total"]),
        Q=widgets.FloatSlider(min=0.0, max=10.0, step=0.1, value=0.0),
        rinc=widgets.FloatSlider(min=-180.0, max=180.0, step=1.0, value=0.0),
        rdec=widgets.FloatSlider(min=-180.0, max=180.0, step=1.0, value=0.0),
        update=widgets.ToggleButton(description="Refresh", value=False),
    )
    return Q
def display_visual(algorithm=None, problem=None):
        def slider_callback(iteration):
            # Non mostra il grafo alla prima iterazione
            try:
                show_map(all_node_colors[iteration])
            except:
                pass
        def visualize_callback(Visualize):
            if Visualize is True:
                button.value = False
                
                global all_node_colors
                
                iterations, all_node_colors, node = algorithm(problem)
                solution = node.solution()
                all_node_colors.append(final_path_colors(problem, solution))
                
                slider.max = len(all_node_colors) - 1
                
                for i in range(slider.max + 1):
                    slider.value = i
        
        slider = widgets.IntSlider(min=0, max=1, step=1, value=0)
        slider_visual = widgets.interactive(slider_callback, iteration = slider)
        display(slider_visual)

        button = widgets.ToggleButton(value = False)
        button_visual = widgets.interactive(visualize_callback, Visualize = button)
        display(button_visual)
Exemple #17
0
def binary_widget(nbits=5):
    nbits = max(min(10, nbits), 2) # Keep nbits between 2 and 10

    output = _pre()
    bits = ['0' for i in range(nbits)]
    button_list = [widgets.ToggleButton(description=str(2**i),
                                        layout=widgets.Layout(width='3em',height='3em'))
                   for i in reversed(range(nbits))]

    hbox = widgets.HBox(button_list)
    label1 = widgets.Label(value="Toggle the bits below to change the binary number.")
    label2 = widgets.Label(value="Think of a number between 0 and %i and try to write it down in binary." % ((2**nbits)-1))
    vbox = widgets.VBox([label1,label2,hbox])
    def on_btn_click(b):
        for b in range(nbits):
            if button_list[b].value:
                bits[b] = '1'
            else:
                bits[b] = '0'
        string = "".join(bits)
        output.value = "Binary" + " "*(nbits//2) + " Decimal\n " + string + " = " + str(int(string,2))

    for button in button_list: button.observe(on_btn_click)

    # Add output before button press
    string = "".join(bits)
    output.value = "Binary" + " "*(nbits//2) + " Decimal\n " + string + " = " + str(int(string,2))

    display(vbox)
    display(output.widget)
Exemple #18
0
                    def __init__(self):
                        # pylint: disable=E1101
                        anim_params = brayns.animation_parameters
                        self.button = widgets.ToggleButton(
                            value=anim_params.delta != 0,
                            icon='play' if anim_params.delta == 0 else 'pause')
                        self.button.layout = widgets.Layout(width='40px')

                        def _on_button_change(change):
                            self.button.icon = 'pause' if change[
                                'new'] else 'play'
                            result = brayns.set_animation_parameters(
                                delta=1 if change['new'] else 0)
                            if inspect.iscoroutine(result):
                                asyncio.ensure_future(result)

                        self.button.observe(_on_button_change, names='value')

                        self.slider = widgets.IntSlider(
                            min=anim_params.start,
                            max=anim_params.end,
                            value=anim_params.current)

                        def _on_value_change(change):
                            result = brayns.set_animation_parameters(
                                current=change['new'])
                            if inspect.iscoroutine(result):
                                asyncio.ensure_future(result)

                        self.value_change = _on_value_change

                        self.slider.observe(self.value_change, names='value')

                        self.box = widgets.HBox([self.button, self.slider])
                        display(self.box)
    def __init__(self):
        #compound type
        self._compound_type = widgets.Dropdown(
            options=['manual', 'element', 'oxide', 'salt', 'acid'],
            layout=widgets.Layout(flex='0 0 auto',
                                  width='100px',
                                  height=_element_height))

        self._button_volatile = widgets.ToggleButton(description='volatile',
                                                     value=False,
                                                     layout=widgets.Layout(
                                                         flex='0 0 auto',
                                                         width='80px'))

        self._button_del = widgets.Button(description='remove',
                                          layout=widgets.Layout(
                                              flex='0 0 auto', width='80px'))

        self._mass = widgets.Text(layout=widgets.Layout(flex='0 0 auto',
                                                        width='80px'),
                                  value='1.0')

        self._box = widgets.HBox(layout=widgets.Layout(
            width='800px', height='', flex_direction='row', display='flex'))

        self._head = (self._button_del, self._button_volatile,
                      widgets.Label('mass'), self._mass, self._compound_type)

        #monitor _compound_type
        self._compound_type.observe(self._populate)

        #init to manual
        self._compound_type.value = 'manual'
        self._populate(None)
Exemple #20
0
    def __init__(self, topics: pd.DataFrame, n_tokens: int = 500):

        self.n_tokens: int = n_tokens
        self.topics: pd.DataFrame = topics
        self.reduced_topics: pd.DataFrame = None

        self._count_slider: w.IntSlider = w.IntSlider(description="Tokens",
                                                      min=1,
                                                      max=n_tokens,
                                                      value=50,
                                                      continuous_update=False,
                                                      layout=dict(width="40%"))
        self._search_text: w.Text = w.Text(
            description="Find",
            placeholder="(enter at least three characters",
            layout=dict(width="40%"))
        self._download_button: w.Button = w.Button(description="Download",
                                                   layout=dict(width='100px'))
        self._prune_tokens: w.ToggleButton = w.ToggleButton(
            description="Prune",
            icon="check",
            value=True,
            layout=dict(width='100px'))
        self._output: w.Output = w.Output()
        self.js_download: Javascript = None
Exemple #21
0
    def __init__(self,
                 start_time_ms: Optional[int] = None,
                 stop_time_ms: Optional[int] = None,
                 run_title: Optional[str] = None):
        import ipywidgets as widgets
        self._stop_button = widgets.ToggleButton(description="Stop stream")
        self._stop_button.observe(self._on_button_clicked, "value")
        self._title = widgets.Label("-")
        self._start_time = widgets.Label("-")
        self._stop_time = widgets.Label("-")
        self._time_format = "%m/%d/%Y %H:%M:%S"

        if run_title is not None:
            self.set_title(run_title)
        if start_time_ms is not None:
            self.set_start_time(start_time_ms)
        if stop_time_ms is not None and stop_time_ms != 0:
            # 0 is the default in the run start messsage flatbuffer
            # if stop time field is not populated
            self.set_stop_time(stop_time_ms)

        display(
            widgets.HBox([
                self._stop_button,
                widgets.HBox([widgets.Label('Run title:'), self._title]),
                widgets.HBox([widgets.Label('Start time:'), self._start_time]),
                widgets.HBox([widgets.Label('Stop time:'), self._stop_time])
            ]))
    def update_table(change):
        edges, energy, relevance, description = obj.update_table()

        # header
        items = [
            ipywidgets.HTML(header.format('edge')),
            ipywidgets.HTML(header.format('onset energy (eV)')),
            ipywidgets.HTML(header.format('relevance')),
            ipywidgets.HTML(header.format('description'))
        ]

        # rows
        obj.btns = []
        for k, edge in enumerate(edges):
            if edge in obj.active_edges or \
                edge in obj.active_complementary_edges:
                btn_state = True
            else:
                btn_state = False

            btn = ipywidgets.ToggleButton(
                value=btn_state,
                description=edge,
                layout=ipywidgets.Layout(width='70px'))
            btn.observe(obj.update_active_edge, names='value')
            obj.btns.append(btn)

            wenergy = ipywidgets.HTML(entry.format(str(energy[k])))
            wrelv = ipywidgets.HTML(entry.format(str(relevance[k])))
            wdes = ipywidgets.HTML(entry.format(str(description[k])))
            items.extend([btn, wenergy, wrelv, wdes])

        gb.children = items
Exemple #23
0
    def __drawWidgets(self):
        nv = self.nv
        vars = self.vars
        steps = self.steps
        self.layout = ipywidgets.GridspecLayout(nv + 1, 3)
        for i, (pname, pstep) in enumerate(zip(vars, steps)):
            self.layout[i, 0] = ipywidgets.FloatText(
                description=pname,
                value=self.parameterobj.parameters.get(pname),
                step=pstep)
            self.layout[i, 0].observe(self.__parCallBack, names='value')
            self.layout[i, 1] = ipywidgets.ToggleButton(
                description="Vary " + pname, value=pname in self.getvars())
            self.layout[i, 1].observe(self.__fixVaryCallBack, names='value')

        self.layout[nv, 0] = ipywidgets.FloatText(
            description='fit_tolerance',
            value=self.parameterobj.parameters.get("fit_tolerance"),
            step=0,
        )
        self.layout[nv, 0].observe(self.__parCallBack, names='value')

        self.layout[nv, 1] = ipywidgets.Button(description="Run Fit (blocks)")
        self.layout[nv, 1].on_click(self.__fitCallBack)

        self.layout[0, 2] = ipywidgets.Button(description="Load parameters")
        self.layout[0, 2].on_click(self.__loadCallBack)

        self.layout[1, 2] = ipywidgets.Button(description="Save to a file")
        self.layout[1, 2].on_click(self.__saveCallBack)
Exemple #24
0
def recode_7corr_widget(**kwopts):
    default_opts = dict(
        description='Recode 7CORR',
        tooltip='Recode all treaties with cultural=yes as 7CORR',
        value=True,
        layout=widgets.Layout(width='120px'))
    return widgets.ToggleButton(**extend(default_opts, kwopts))
Exemple #25
0
 def timelineSelector(self,directoryName):
     info=self.timelineInfo(directoryName)
     lst=[widgets.Label(value="Fields:")]
     fieldsSelected=set()
     storeButton=widgets.Button(description="Store to",disabled=True)
     def make_field_toggle(fName):
         def f(name,value):
             if value:
                 fieldsSelected.add(fName)
             else:
                 try:
                     fieldsSelected.remove(fName)
                 except KeyError:
                     pass # this should not happen, but hey!
             if len(fieldsSelected)>0:
                 storeButton.disabled=False
             else:
                 storeButton.disabled=True
         return f
     for f in info["fields"]:
         w=widgets.ToggleButton(description=f)
         w.on_trait_change(make_field_toggle(f), 'value')
         lst.append(w)
     fields=widgets.Box(description="Fields",children=lst)
     fields.add_class("hbox")
     varName=widgets.Text(description="Variable Name")
     def varname_change(name,value):
         storeButton.description="Store to "+value
         if len(value)==0 or len(fieldsSelected)==0:
             storeButton.disabled=True
         else:
             dis=False
             if not value[0].isalpha():
                 dis=True
             storeButton.disabled=dis
     varName.on_trait_change(varname_change, 'value')
     def store_clicked(b):
         v=varName.value
         f=list(fieldsSelected)
         print_("Storing",f,"from",directoryName,"in",self.path,"to variable",v)
         name=self.__getObjectName(self)
         store=self.__getStorageName()
         cmd="%s.timeline('%s',%s)" % (name,directoryName,str(f))
         if store:
             sname,sval=store
             create_code_cell(
                 "%s=%s('%s',lambda:%s)" % (v,sname,v,cmd),
                 "below")
             val=sval(v,lambda:self.timeline(directoryName,f))
         else:
             create_code_cell(
                 "%s=%s" % (v,cmd),
                 "below")
             val=self.timeline(directoryName,f)
         get_ipython().push({v:val})
         varName.value=""
     storeButton.on_click(store_clicked)
     total=widgets.Box(children=[fields,varName,storeButton])
     total.add_class("vbox")
     display(total)
    def __init__(self, step):

        select_box = ipywidgets.Select(
            options=step.description.replace(", ", "\n").splitlines(),
            rows=3,
            disabled=False,
            layout=ipywidgets.Layout(width="200px"),
        )

        self.modify_button = ipywidgets.ToggleButton(
            layout=ipywidgets.Layout(height="25px", width="98%"))

        self.delete_button = ipywidgets.Button(
            description="Delete Step",
            layout=ipywidgets.Layout(height="25px",
                                     width="98%",
                                     visibility="hidden"),
            button_style="warning",
        )

        self.widget = ipywidgets.VBox(
            [self.modify_button, select_box, self.delete_button],
            layout=ipywidgets.Layout(min_width="200px"),
        )

        self.step = step
        self.modify_step_callback = CallbackManager()
        self.stop_modifying_callback = CallbackManager()
        self.delete_step_callback = CallbackManager()

        self.modify_button.observe(self._modify_button_on_click, names="value")
        self.delete_button.on_click(
            lambda _: self.delete_step_callback.send_callbacks(self.step))

        self._set_inactive_style()
Exemple #27
0
        def _(*_):
            self.buttons = [
                widgets.ToggleButton(description=label,
                                     tooltip=label,
                                     layout=widgets.Layout(margin='2',
                                                           icon='check',
                                                           width='100%',
                                                           min_width='160px'))
                for label in self._selection_obj._options_labels
            ]
            rows = []
            for i in range(0, len(self.buttons), self.num_per_row):
                if i < len(self.buttons) - num_per_row:
                    rows.append(
                        widgets.HBox(self.buttons[i:i + self.num_per_row]))
                else:
                    rows.append(widgets.HBox(self.buttons[i:]))

            self.children = [
                widgets.VBox(rows,
                             layout=widgets.Layout(display='flex',
                                                   flex_grown='column'))
            ]

            @monitor(self.buttons, 'value')
            def _(*_):
                for btn in self.buttons:
                    btn.button_style = 'info' if btn.value or btn.description in self.value else ''
                self.value = tuple(value for btn, value in zip(
                    self.buttons, self._selection_obj._options_values)
                                   if btn.value)
    def __init__(self, state: TopicModelContainer | dict):
        super().__init__(state=state)
        slider_opts = {
            'continuous_update': False,
            'layout': dict(width='140px'),
            'readout': False,
            'handle_color': 'lightblue',
        }
        timespan: tuple[int, int] = self.inferred_topics.year_period
        yearspan: tuple[int, int] = self.inferred_topics.startspan(10)

        self._threshold_label: w.HTML = w.HTML("<b>Threshold</b>")
        self._threshold: w.FloatSlider = w.FloatSlider(min=0.01, max=1.0, value=0.05, step=0.01, **slider_opts)
        self._max_count_label: w.HTML = w.HTML("<b>Max result count</b>")
        self._max_count: w.IntSlider = w.IntSlider(min=1, max=50000, value=500, **slider_opts)
        self._year_range_label: w.HTML = w.HTML("Years")
        self._year_range: w.IntRangeSlider = w.IntRangeSlider(
            min=timespan[0], max=timespan[1], step=1, value=yearspan, **slider_opts
        )
        self._output: w.Output = w.Output(layout={'width': '50%'})
        self._extra_placeholder: w.Box = None
        self._content_placeholder: w.Box = None
        self._compute: w.Button = w.Button(description='Show!', button_style='Success', layout={'width': '140px'})
        self._auto_compute: w.ToggleButton = w.ToggleButton(description="auto", value=False, layout={'width': '140px'})
        self._table_widget: TableWidget = None
        self.click_handler: Callable[[pd.Series, Any], None] = None
Exemple #29
0
def display_visual(graph_data, algorithm=None, problem=None):
    initial_node_colors = graph_data['node_colors']

    def slider_callback(iteration):
        # don't show graph for the first time running the cell calling this function
        try:
            show_map(graph_data, node_colors=all_node_colors[iteration])
        except:
            pass

    def visualize_callback(Visualize):
        if Visualize is True:
            button.value = False

            global all_node_colors

            iterations, all_node_colors, node = algorithm(problem)
            solution = node.solution()
            all_node_colors.append(
                final_path_colors(all_node_colors[0], problem, solution))

            slider.max = len(all_node_colors) - 1

            for i in range(slider.max + 1):
                slider.value = i
                #time.sleep(.5)

    slider = widgets.IntSlider(min=0, max=1, step=1, value=0)
    slider_visual = widgets.interactive(slider_callback, iteration=slider)
    display(slider_visual)

    button = widgets.ToggleButton(value=False)
    button_visual = widgets.interactive(visualize_callback, Visualize=button)
    display(button_visual)
Exemple #30
0
    def __init__(self, net_widget, interactions=None):
        self.key = "PPI"
        self.net = net_widget
        self.interactions = interactions
        self.is_on = w.ToggleButton(description="PPI",
                                    value=False,
                                    layout=w.Layout(width="15%",
                                                    height="40px"))
        self.s1 = w.Dropdown(description="Species 1",
                             options={
                                 "S{}".format(key): key
                                 for key in self.net.types["Complexable"]
                             })
        self.s2 = w.Dropdown(description="Species 2",
                             options={
                                 "S{}".format(key): key
                                 for key in self.net.types["Complexable"]
                             })
        self.custom_p = w.Checkbox(description="custom parameters",
                                   value=False,
                                   layout=w.Layout(width="23%", height="40px"))

        self.kp = w.FloatText(description="k+",
                              value=1,
                              step=0.0001,
                              layout=w.Layout(width="15%", height="40px"))
        self.km = w.FloatText(description="k-",
                              value=1,
                              step=0.0001,
                              layout=w.Layout(width="15%", height="40px"))

        self.update_param_state(False)
        self.update_inter_state(False)
        w.interactive(self.update_inter_state, button=self.is_on)
        w.interactive(self.update_param_state, button=self.custom_p)