コード例 #1
0
 def create_input_widget(self):
     """
     Creates and returns the relevant user-input ipywidget.
     """
     return widgets.Combobox(placeholder=self._tooltip,
                             continuous_update=False,
                             options=self._options)
コード例 #2
0
ファイル: old.py プロジェクト: tonyluo98/SEEK-project
    def person_tab(self):
        '''
        Creates tab relating to searching for a person
        '''
        #Get the list of users sorted in alphbetical order and removes
        #duplicates
        user_list_alphabet_order = []
        user_list_alphabet_order = list(self.list_of_user_names)
        #removes duplicates
        user_list_alphabet_order = list(
            dict.fromkeys(user_list_alphabet_order))
        #sort alphabetically
        user_list_alphabet_order.sort()
        #add empty string for when the widget is empty
        user_list_alphabet_order.append('')

        self.people_search_ID_widget = widgets.Combobox(
            # value='',
            placeholder='Enter ID',
            options=[],
            description='ID :',
            ensure_option=False,
            disabled=False)
        #Handles update to ID widget
        self.people_search_ID_widget.observe(self.change_made_people_search_ID)

        self.name_search_widget = widgets.Combobox(
            # value='',
            placeholder='Enter Name',
            options=user_list_alphabet_order,
            description='Name :',
            ensure_option=False,
            disabled=False)

        #Handles update to name widget
        self.name_search_widget.observe(self.change_made_name_search)

        people_search_widget_list = [
            self.name_search_widget, self.people_search_ID_widget
        ]

        #Formats the widgets into a column
        people_search_container = widgets.VBox(
            [people_search_widget_list[0], people_search_widget_list[1]])

        return people_search_container
コード例 #3
0
ファイル: widget.py プロジェクト: flekschas/jupyter-scatter
    def color_widgets(self):
        color_by_widget = widgets.RadioButtons(
            options=[('Point color', 'none'),
                     ('Category (using colormap)', 'category'),
                     ('Value (using colormap)', 'value')],
            value='none' if self.color_by is None else self.color_by)

        colormap_widget = widgets.Combobox(
            placeholder='Choose a Matplotlib colormap',
            options=list(plt.colormaps()),
            ensure_option=True,
            disabled=self.color_by is None,
        )

        color_widget = widgets.ColorPicker(value=to_hex(self.color),
                                           disabled=False)

        def color_by_change_handler(change):
            if change.new == 'none':
                self.color_by = None
                self.color = color_widget.value

                colormap_widget.disabled = True
                color_widget.disabled = False

            else:
                if change.new == 'category':
                    colormap_widget.options = [
                        'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',
                        'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',
                        'tab20c'
                    ]
                else:
                    colormap_widget.options = [
                        'greys', 'viridis', 'plasma', 'inferno', 'magma',
                        'cividis', 'coolwarm', 'RdGy'
                    ]

                self.color_by = change.new
                if colormap_widget.value:
                    self.use_cmap(colormap_widget.value)

                colormap_widget.disabled = False
                color_widget.disabled = True

        def colormap_change_handler(change):
            self.use_cmap(change.new)

        def color_change_handler(change):
            self.color = change.new

        color_by_widget.observe(color_by_change_handler, names='value')
        colormap_widget.observe(colormap_change_handler, names='value')
        color_widget.observe(color_change_handler, names='value')

        return (with_left_label('Color by', color_by_widget),
                with_left_label('Colormap', colormap_widget),
                with_left_label('Point color', color_widget))
コード例 #4
0
ファイル: inputs.py プロジェクト: scipp/scippwidgets
 def __init__(self,
              function_arg_name: str,
              validator: Callable[[str], str] = lambda input: input,
              **kwargs):
     self._name = function_arg_name
     self._widget = widgets.Combobox(**kwargs)
     self._validator = validator
     if 'placeholder' not in kwargs:
         self._widget.placeholder = function_arg_name
コード例 #5
0
ファイル: widget.py プロジェクト: tonyluo98/SEEK-project
 def combobox(self, ph, options, desc, bool_option, bool_active):
     '''
     RETURNS Combobox
     '''
     widget = widgets.Combobox(
         # value='',
         placeholder=ph,
         options=options,
         description=desc,
         ensure_option=bool_option,
         disabled=bool_active)
     return widget
コード例 #6
0
ファイル: core.py プロジェクト: LiaoWenyun/Query_Builder
    def __get_service(self):
        service_combobox_list = ['https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/',
                                'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/youcat/',
                                'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/']
        self.delete_button = widgets.Button(
            description="Delete",
            icon='',
            style=widgets.ButtonStyle(button_color='#E58975'),
            layout=widgets.Layout(height = "25px",
                                  width='70px'))
        self.delete_button.on_click(self.__button_clicked)
        
        self.query_button = widgets.Button(
            description="Query",
            icon='',
            style=widgets.ButtonStyle(button_color='#E58975'),
            layout=widgets.Layout(height = "25px",
                                  width='70PX'))
        self.query_button.on_click(self.__query_clicked)
        
        self.clear_button = widgets.Button(
            description="Clear",
            icon='',
            style=widgets.ButtonStyle(button_color='#E58975'),
            layout=widgets.Layout(height = "25px",
                                  width='70px'))
        self.clear_button.on_click(self.__button_clicked)
        self.clear_button.click()
        self.buttons_ui = widgets.VBox([self.delete_button,
                                        self.clear_button,
                                        self.query_button],
                                       layout=widgets.Layout(top='8px',
                                                             height='90px',
                                                             width='100px'))
        self.output_ui = widgets.HBox([self.out, self.buttons_ui])

        self.service_combobox = widgets.Combobox(
            value='https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/',
            placeholder='',
            options=service_combobox_list,
            description='Service',
            continuous_update=False,
            layout=widgets.Layout(flex='1 1 auto',
                                  width='auto'),
            style={'description_width': 'initial'})
        
        self.tables = widgets.interactive_output(
            self.__get_table,
            {'service': self.service_combobox})
        
        display(self.query_out, self.service_combobox, self.tables, self.output_ui)
コード例 #7
0
ファイル: widget.py プロジェクト: flekschas/jupyter-scatter
    def color_map_widget(self):
        widget = widgets.Combobox(
            placeholder='Choose a Matplotlib colormap',
            options=list(plt.colormaps()),
            ensure_option=True,
            disabled=True,
        )

        def change_handler(change):
            self.use_cmap(change.new)

        widget.observe(change_handler, names='value')

        return with_left_label('Color map', widget)
コード例 #8
0
 def jobs_combobox(self) -> widgets.Combobox:
     """Create the Job search Combobox"""
     layout = widgets.Layout(
         display="flex", justify_content="flex-start", width=f"{JOBS_CB_WIDTH}px",
         border=f"solid 1px {CarbonColors.BLACK}"
     )
     jobs_combobox = widgets.Combobox(
         placeholder="Job ID",
         options=self.job_ids,
         ensure_option=True,
         disabled=False,
         layout=layout,
     )
     jobs_combobox.observe(self.update_job_selector_combobox)
     return jobs_combobox
コード例 #9
0
ファイル: inputs.py プロジェクト: scipp/scippwidgets
 def __init__(self,
              func_arg_names: Sequence[str] = ('x', 'dim'),
              data_name: str = 'data',
              **kwargs):
     self._scope = get_notebook_global_scope()
     self._func_arg_names = func_arg_names
     self._scipp_obj_input = widgets.Text(placeholder=data_name,
                                          continuous_update=False,
                                          **kwargs)
     self._dimension_input = widgets.Combobox(placeholder='dim',
                                              continuous_update=False,
                                              **kwargs)
     self._scipp_obj_input.observe(self._handle_scipp_obj_change, names='value')
     self._widget = widgets.HBox([self._scipp_obj_input, self._dimension_input])
     self._validators = (self._scipp_obj_validator, self._dims_validator)
     self._allowed_dims = []
コード例 #10
0
ファイル: core.py プロジェクト: opencadc/notebook-ui
 def __get_service(self):
     service_combobox_list = [
         'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/',
         'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/youcat/',
         'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/'
     ]
     self.service_combobox = widgets.Combobox(
         value='https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/',
         options=service_combobox_list,
         description='SERVICE',
         continuous_update=False,
         layout=widgets.Layout(left='-15px', width='780px'))
     output_schema = widgets.interactive_output(
         self.__get_schema, {'service': self.service_combobox})
     display(self.service_combobox)
     display(output_schema)
コード例 #11
0
ファイル: inputs.py プロジェクト: scipp/scippwidgets
 def __init__(self,
              function_arg_name: str,
              validator: Callable[[Any], Any] = lambda input: input,
              **kwargs):
     """
     :param function_arg_name: Name of function argument this
         input corresponds to.
     :param widget_type: Type of widget to construct for this input.
     :param validator: Validator function.
     :param kwargs: kwargs to pass to widget constructor.
     :type widget_type:  ipywidget
     """
     self._name = function_arg_name
     self._widget = widgets.Combobox(**kwargs)
     self.scope = get_notebook_global_scope()
     self._validator = lambda input: validator(_wrapped_eval(input, self.scope))
     if 'placeholder' not in kwargs:
         self._widget.placeholder = function_arg_name
コード例 #12
0
    def __get_service(self):
        service_combobox_list = [
            'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/',
            'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/youcat/',
            'https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/'
        ]

        self.service_combobox = widgets.Combobox(
            value='https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/',
            options=service_combobox_list,
            description='Service',
            continuous_update=False,
            layout=widgets.Layout(flex='1 1 auto', width='auto'),
            style={'description_width': 'initial'})

        output_schema = widgets.interactive_output(
            self.__get_schema, {'service': self.service_combobox})
        display(widgets.HBox([self.service_combobox, self.schema_dropdown]))
        display(output_schema)
コード例 #13
0
 def _repr_ipyw_(self):
     import ipywidgets as ipw
     wname=ipw.Text(value=self.name, layout=ipw.Layout(width='35%'))
     wname=ipw.Combobox(value=self.name,
                        options=[ni for ni, oi in self._parent.model.script_module.__dict__.items()
                                 if type(oi).__name__ in ['Layer', 'Stack', 'Instrument']])
     wname.change_item='name'
     wval=ipw.FloatText(value=self.value, layout=ipw.Layout(width='20%'))
     wval.change_item='value'
     wfit=ipw.Checkbox(value=self.fit, indent=False, layout=ipw.Layout(width='5%'))
     wfit.change_item='fit'
     wmin=ipw.FloatText(value=self.min, layout=ipw.Layout(width='20%'))
     wmin.change_item='min'
     wmax=ipw.FloatText(value=self.max, layout=ipw.Layout(width='20%'))
     wmax.change_item='max'
     entries=[wname, wval, wfit, wmin, wmax]
     wname.others=entries[1:]
     for entr in entries:
         entr.observe(self._ipyw_change, names='value')
     return ipw.HBox(entries)
コード例 #14
0
ファイル: qtplotter.py プロジェクト: cover-me/qtplotter
 def create_ui(self):
     x,y,w = self.x,self.y,self.w
     x0 = x[0]
     y0 = y[:,0]
     xmin,xmax,dx = x[0,0],x[0,-1],x[0,1]-x[0,0]
     ymin,ymax,dy = y[0,0],y[-1,0],y[1,0]-y[0,0]
     wmin,wmax = np.min(w),np.max(w)
     dw = (wmax-wmin)/20
     
     ## Tab of tools
     self.s_xpos = widgets.FloatSlider(value=(xmin+xmax)/2,min=xmin,max=xmax,step=dx,description='x')
     self.s_ypos = widgets.FloatSlider(value=(ymin+ymax)/2,min=ymin,max=ymax,step=dy,description='y')
     vb1 = widgets.VBox([self.s_xpos,self.s_ypos])
     self.s_gamma = widgets.IntSlider(value=0,min=-100,max=100,step=10,description='gamma')
     self.s_vlim = widgets.FloatRangeSlider(value=[wmin,wmax], min=wmin, max=wmax, step=dw, description='vlim')
     self.c_cmap = widgets.Combobox(value='', placeholder='Choose or type', options=plt.colormaps(), description='cmap:', ensure_option=False, disabled=False)
     vb2 = widgets.VBox([self.s_gamma,self.s_vlim,self.c_cmap])
     self.b_expMTX = widgets.Button(description='To mtx')
     self.html_exp = widgets.HTML()
     vb3 = widgets.VBox([self.b_expMTX,self.html_exp])
     self.t_tools = widgets.Tab(children=[vb1,vb2,vb3])
     [self.t_tools.set_title(i,j) for i,j in zip(range(3), ['linecuts','color','export'])]
     self.t_tools.layout.display = 'block'
     ## A toggle button
     self.tb_showtools = widgets.ToggleButton(value=True, description='', tooltip='Toggle Tools', icon='minus-circle')
     self.tb_showtools.layout.width='50px'
     ## Top layer ui
     ui = widgets.Box([self.t_tools,self.tb_showtools])
     self.out = widgets.Output()        
     if 'gamma' in self.kw:
         self.s_gamma.value = self.kw['gamma']
     if 'vlim' in self.kw:
         self.s_vlim.value = self.kw['vlim']
     if 'cmap' in self.kw:
         self.c_cmap.value = self.kw['cmap']
         
     if Player.PLAYER_STATIC:
         from IPython.core.display import HTML
         display(HTML('<button style="border:none;" title="For interaction, run the cell first.">+...</button>'))
     else:
         display(ui,self.out)
コード例 #15
0
ファイル: gui.py プロジェクト: eschmidt42/bundestag
    def init_widgets(self):
        # prints out the current selection of MdB, party and timespan
        self.selection_widget = widgets.Label()

        # widget to render figures in
        self.display_widget = widgets.Output()

        # submit button
        self.submit_widget = widgets.Button(description="Submit")
        self.submit_widget.on_click(self.on_click)

        # widgets to set MdB, party, timespan
        self.name_widget = widgets.Combobox(
            placeholder="Choose an MdB",
            options=tuple(self.mdbs),
            description="MdB:",
            ensure_option=True,
        )

        self.start_widget = widgets.DatePicker(description="Start date")
        self.end_widget = widgets.DatePicker(description="End date")
コード例 #16
0
                                                value=1,
                                                layout={'width': '500px'})

block_end_slider = ipywidgets.SelectionSlider(options=[False] +
                                              list(range(1, 34 + 1)),
                                              description='block end',
                                              value=False,
                                              layout={'width': '500px'})

trial_start_slider = ipywidgets.SelectionSlider(options=list(range(1, 10 + 1)),
                                                description='trial',
                                                value=1)

trial_end_slider = ipywidgets.SelectionSlider(options=[False] +
                                              list(range(1, 10 + 1)),
                                              description='trial end',
                                              value=False)

lighter_slider = ipywidgets.IntSlider(value=4, min=1, max=5)

color = ipywidgets.Combobox(value='royalblue',
                            placeholder='Type Blue or Green to see options',
                            options=plot.CMAP['Control']['colornames'] +
                            plot.CMAP['ASD']['colornames'],
                            description='color',
                            ensure_option=True)

linestyle = ipywidgets.Dropdown(
    value='solid',
    options=['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'])
コード例 #17
0
    def __build(self):
        """
        This function is used to build all widgets of the UI.
        """

        # Section: "Dataset Selection"
        # ============================================================================================================ #
        label = ipywidgets.Label(
            value="$\\textbf{•}$ $\\textbf{Dataset Selection}$")
        self._widget_list.append(label)
        label = ipywidgets.Label(
            value=
            "Please, select a $\\texttt{.csv}$ file from the following list." +
            " (Only $\\texttt{.csv}$ files stored inside $\\texttt{./data}$ directory are"
            + " displayed).")

        self._widget_dataset_file_select = ipywidgets.Select(
            description="Current Selected Dataset:",
            style={'description_width': 'initial'},
            layout=ipywidgets.Layout(width='90%'),
            continuous_update=False)

        self._widget_list.append(
            ipywidgets.VBox([label, self._widget_dataset_file_select]))

        # Section: "Plot Options"
        # ============================================================================================================ #
        label = ipywidgets.Label(
            value="$\\textbf{•}$ $\\textbf{Plot Options}$")
        self._widget_list.append(label)
        label = ipywidgets.Label(
            value=
            "You can customize your $\\textit{Plot}$ using following $\\textit{Widgets}$ "
            +
            "(Available $\\textit{Widgets}$ depend on $\\textit{Current Selected Dataset}$)"
        )
        self._widget_list.append(label)

        self._widget_month_combobox = ipywidgets.Combobox(
            placeholder="Select/Type 'Month'...",
            options=calendar.month_name[1:],
            description='Month:',
            layout=ipywidgets.Layout(width='350px'),
            continuous_update=False)

        self._widget_state_combobox = ipywidgets.Combobox(
            placeholder="Select/Type 'State'...",
            description='State:',
            layout=ipywidgets.Layout(width='350px'),
            continuous_update=False)

        self._widget_city_combobox = ipywidgets.Combobox(
            placeholder="Select/Type 'City'...",
            description='City:',
            layout=ipywidgets.Layout(width='350px'),
            continuous_update=False,
        )

        self._widget_month_checkbox = ipywidgets.Checkbox(
            description="Enable 'Month Filter'",
            layout=ipywidgets.Layout(width='350px'))

        self._widget_display_univariate_regression_line_checkbox = ipywidgets.Checkbox(
            description="Plot 'Regression Line'",
            layout=ipywidgets.Layout(width='350px'))

        grid = ipywidgets.GridspecLayout(3, 2)
        grid[0, 0] = self._widget_month_combobox
        grid[1, 0] = self._widget_state_combobox
        grid[2, 0] = self._widget_city_combobox

        grid[0, 1] = self._widget_month_checkbox
        grid[1, 1] = self._widget_display_univariate_regression_line_checkbox

        self._widget_list.append(grid)

        self._widget_time_int_range_slider = ipywidgets.IntRangeSlider(
            step=1,
            description="Plot's 'Time Range'",
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
            style={'description_width': 'initial'},
            layout=ipywidgets.Layout(width='90%'),
        )

        self._widget_list.append(self._widget_time_int_range_slider)

        label = ipywidgets.Label(
            value=
            "Using following $\\textit{Widget}$, you can select one or more " +
            "$\\textit{fields}$ to customize your $\\textit{Plot}$" +
            " (Hold $\\texttt{CTRL}$ and click to select more $\\textit{fields}$!)"
        )

        self._widget_list.append(label)

        self._widget_active_columns_select_multiple = ipywidgets.SelectMultiple(
            rows=10,
            description='Active Columns:',
            disabled=False,
            style={'description_width': 'initial'},
            layout=ipywidgets.Layout(width='90%'),
        )

        self._widget_list.append(self._widget_active_columns_select_multiple)

        # Section 'Dataset Indo'
        # ============================================================================================================ #
        label = ipywidgets.Label(
            value="$\\textbf{•}$ $\\textbf{Dataset Info}$")
        self._widget_list.append(label)
        label = ipywidgets.Label(
            value=
            "Here are displayed several info about $\\textit{Current Selected Dataset}$ "
            +
            "(Displayed data depend on current selected $\\textit{Plot Options}$)"
        )
        self._widget_list.append(label)

        self._widget_states_summary_label = ipywidgets.Label()
        self._widget_cities_summary_label = ipywidgets.Label()
        self._widget_how_many_cities_inside_state_label = ipywidgets.Label()
        self._widget_state_flag_image_HTML = ipywidgets.HTML()

        box = ipywidgets.VBox([
            self._widget_states_summary_label,
            self._widget_cities_summary_label,
            self._widget_how_many_cities_inside_state_label
        ])

        box = ipywidgets.HBox([self._widget_state_flag_image_HTML, box])

        self._widget_list.append(box)

        # Section: "Plot Button"
        # ============================================================================================================ #
        label = ipywidgets.Label(
            value="$\\textbf{•}$ $\\textbf{Plot Section}$")
        self._widget_list.append(label)
        self._widget_plot_button = ipywidgets.Button(description='Plot',
                                                     disabled=False,
                                                     button_style='success',
                                                     icon='line-chart')

        self._widget_list.append(self._widget_plot_button)

        # Section: "ERROR Label"
        # ============================================================================================================ #
        self._widget_error_label = ipywidgets.Label(value="")
        self._widget_list.append(self._widget_error_label)

        # Section: "Display Univariate Regression Line"
        # ============================================================================================================ #
        self._widget_univariate_regression_line_info_HTMLMath = ipywidgets.HTMLMath(
            value="",
            style={'description_width': 'initial'},
        )
        self._widget_list.append(
            self._widget_univariate_regression_line_info_HTMLMath)
コード例 #18
0
    def __init__(self,path_or_url,**kw):
        # data
        self.path = path_or_url
        x,y,w,labels = read2d(path_or_url,**kw)
        if 'labels' not in kw:
            kw['labels'] = labels
        
        if len(y)==1:#1d data
            x = np.vstack([x,x,x])
            y = np.vstack([y-.5,y,y+.5])
            w = np.vstack([w,w,w])

        self.x = x
        self.y = y
        self.w = w
        self.kw = kw

        # UI
        x0 = x[0]
        y0 = y[:,0]
        xmin,xmax,dx = x[0,0],x[0,-1],x[0,1]-x[0,0]
        ymin,ymax,dy = y[0,0],y[-1,0],y[1,0]-y[0,0]
        wmin,wmax = np.min(w),np.max(w)
        dw = (wmax-wmin)/20
        
        ## Tab of tools
        self.s_xpos = widgets.FloatSlider(value=(xmin+xmax)/2,min=xmin,max=xmax,step=dx,description='x')
        self.s_ypos = widgets.FloatSlider(value=(ymin+ymax)/2,min=ymin,max=ymax,step=dy,description='y')
        vb1 = widgets.VBox([self.s_xpos,self.s_ypos])
        self.s_gamma = widgets.IntSlider(value=0,min=-100,max=100,step=10,description='gamma')
        self.s_vlim = widgets.FloatRangeSlider(value=[wmin,wmax], min=wmin, max=wmax, step=dw, description='vlim')
        self.c_cmap = widgets.Combobox(value='', placeholder='Choose or type', options=plt.colormaps(), description='cmap:', ensure_option=False, disabled=False)
        vb2 = widgets.VBox([self.s_gamma,self.s_vlim,self.c_cmap])
        self.b_expMTX = widgets.Button(description='To mtx')
        self.html_exp = widgets.HTML()
        vb3 = widgets.VBox([self.b_expMTX,self.html_exp])
        self.t_tools = widgets.Tab(children=[vb1,vb2,vb3])
        [self.t_tools.set_title(i,j) for i,j in zip(range(3), ['linecuts','color','export'])]
        self.t_tools.layout.display = 'none'
        ## A toggle button
        self.tb_showtools = widgets.ToggleButton(value=False, description='...', tooltip='Toggle Tools', icon='plus-circle')
        self.tb_showtools.layout.width='50px'
        ## Top layer ui
        ui = widgets.Box([self.t_tools,self.tb_showtools])
        self.out = widgets.Output()

        if 'gamma' in kw:
            self.s_gamma.value = kw['gamma']
        if 'vlim' in kw:
            self.s_vlim.value = kw['vlim']
        if 'cmap' in kw:
            self.c_cmap.value = kw['cmap']

        display(ui,self.out)
        self.draw(None)
        if mpl.get_backend() == 'module://ipympl.backend_nbagg':#ipympl backend. Not good at this moment. But faster
            self.s_gamma.observe(self.on_gamma_change,'value')
            self.s_vlim.observe(self.on_vlim_change,'value')
            self.c_cmap.observe(self.on_cmap_change,'value')
            self.s_xpos.observe(self.on_xpos_change,'value')
            self.s_ypos.observe(self.on_ypos_change,'value')
            self.fig.canvas.mpl_connect('button_press_event', self.on_mouse_click)
        else:# inline mode
            self.s_gamma.observe(self.draw,'value')
            self.s_vlim.observe(self.draw,'value')
            self.c_cmap.observe(self.draw,'value')
            self.s_xpos.observe(self.draw,'value')
            self.s_ypos.observe(self.draw,'value')
        self.tb_showtools.observe(self.on_showtools_change,'value')
        self.b_expMTX.on_click(self.exportMTX)
コード例 #19
0
             description='String:',
             disabled=False)

# ### Textarea

widgets.Textarea(value='Hello World',
                 placeholder='Type something',
                 description='String:',
                 disabled=False)

# ### Combobox

widgets.Combobox(
    # value='John',
    placeholder='Choose Someone',
    options=['Paul', 'John', 'George', 'Ringo'],
    description='Combobox:',
    ensure_option=True,
    disabled=False)

# ### Password
#
# The `Password` widget hides user input on the screen. **This widget is not a secure way to collect sensitive information because:**
#
# + The contents of the `Password` widget are transmitted unencrypted.
# + If the widget state is saved in the notebook the contents of the `Password` widget is stored as plain text.

widgets.Password(value='password',
                 placeholder='Enter password',
                 description='Password:',
                 disabled=False)
コード例 #20
0
def build_plots_jupyter(output, stat_global, stat_per_asset):
    print("Build plots...")
    log_info("---")

    def display_scrollable_output_table(output):
        output = output.to_pandas()
        tail_r=10
        tail_c=10

        def show_table(row_offset, column_offset):
            try:
                from IPython.display import display
                display(output.iloc[row_offset:row_offset + tail_r, column_offset:column_offset + tail_c])
            except:
                log_info(output.iloc[row_offset:row_offset + tail_r, column_offset:column_offset + tail_c])

        if is_interact():
            try:
                from ipywidgets import interact, interactive, fixed, interact_manual, Layout, IntSlider
                import ipywidgets as widgets

                interact(show_table,
                         row_offset=IntSlider(
                             max(0, len(output) - tail_r), 0, max(0, len(output) - tail_r), 1,
                             layout=Layout(width='90%')
                         ),
                         column_offset=IntSlider(
                             0, 0, max(0, len(output.columns) - tail_c), 1,
                             layout=Layout(width='90%')
                         )
                         )
            except:
                show_table(len(output) - tail_r, 0)
        else:
            show_table(len(output) - tail_r, 0)

    def display_scrollable_stats_table(stat):
        stat = stat.to_pandas()
        tail=10
        def show_table(offset):
            try:
                from IPython.display import display
                display(stat[offset:offset+tail])
            except:
                log_info(stat[offset:offset + tail])
        if is_interact():
            try:
                from ipywidgets import interact, interactive, fixed, interact_manual, Layout, IntSlider
                import ipywidgets as widgets

                interact(show_table,
                         offset=IntSlider(
                             max(0, len(stat)-tail), 0, max(0, len(stat)-tail), 1,
                             layout=Layout(width='90%')
                         )
                    )
            except:
                show_table(len(stat)-tail)
        else:
            show_table(len(stat)-tail)

    def show_asset_stat(asset):
        if asset in stat_per_asset.asset.values.tolist():
            out = output.sel(asset=[asset])
            stat = stat_per_asset.sel(asset=asset)
        else:
            out = output
            stat = stat_global
        log_info("Output:")
        display_scrollable_output_table(out)
        log_info("Stats:")
        display_scrollable_stats_table(stat)
        make_major_plots(stat)
        log_info("---")

    if is_interact():
        try:
            from ipywidgets import interact, interactive, fixed, interact_manual
            import ipywidgets as widgets

            log_info("Select the asset (or leave blank to display the overall stats):")
            interact(show_asset_stat, asset=widgets.Combobox(options=[''] + output.asset.values.tolist()))
        except:
            show_asset_stat('')
    else:
        show_asset_stat('')
コード例 #21
0
def entry_gui():

    style = {'description_width': 'initial'}
    sm_layout = widgets.Layout(flex='1 1 1%', width='auto')

    exp_name = widgets.Text(placeholder='pxxxx',
                            description='Exp. Name:',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    op_name = widgets.Text(placeholder='Name(s)',
                           description='Operator Name(s):',
                           continuous_update=True,
                           disabled=False,
                           style=style)

    hyd_start = widgets.Text(placeholder='xxx.x',
                             description='Hyd. Start:',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    hyd_end = widgets.Text(placeholder='xxx.x',
                           description='Hyd. End:',
                           continuous_update=True,
                           disabled=False,
                           style=style)

    pick_date = widgets.DatePicker(description='Exp. Date:',
                                   disabled=False,
                                   style=style)

    names = widgets.VBox(children=[exp_name, op_name], layout=sm_layout)
    dates = widgets.VBox(children=[pick_date, hyd_start, hyd_end],
                         layout=sm_layout)

    pre_layout = widgets.Layout(display='flex',
                                flex_flow='row',
                                align_items='stretch',
                                border='2px solid grey',
                                padding='10px',
                                width='75%',
                                grid_gap='60px 60px')

    preamble = widgets.GridBox(children=[names, dates], layout=pre_layout)

    area = widgets.Text(placeholder='m^2',
                        description='Contact Area (m^2)',
                        value='',
                        continuous_update=True,
                        disabled=False,
                        style=style)

    block_thck = widgets.Text(placeholder='mm',
                              description='Sample Block Thickness (no gouge)',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    layer_thck = widgets.Text(placeholder='mm',
                              description='Layer Thickness',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    layer_thck_ld = widgets.Text(placeholder='mm',
                                 description='Under Load',
                                 continuous_update=True,
                                 disabled=False,
                                 style=style)

    material = widgets.Text(placeholder='Anhydrite, Westerly Granite',
                            description='Material',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    part_size = widgets.Text(placeholder='Size Distribution',
                             description='Particle Size, Distribution',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    mat_layout = widgets.Layout(display='flex',
                                flex_flow='row',
                                align_items='stretch',
                                border='2px solid grey',
                                padding='10px',
                                width='75%',
                                grid_gap='60px 60px')

    mat_col1 = widgets.VBox(children=[area, block_thck, layer_thck],
                            layout=widgets.Layout(flex='1 1 1%', width='auto'))
    mat_col2 = widgets.VBox(children=[material, part_size],
                            layout=widgets.Layout(flex='1 1 1%', width='auto'))
    material_block = widgets.GridBox(children=[mat_col1, mat_col2],
                                     layout=mat_layout)

    h_lc_title = widgets.Label('Horizontal Load Cell')

    h_lc_picker = widgets.Dropdown(
        options=['44mm Solid Horiz', '44mm Solid Vert', 'None'],
        value='44mm Solid Horiz',
        description='Horiz. Load Cell:',
        disabled=False,
        style=style)

    h_lc_calib = widgets.Text(placeholder='mV/kN',
                              description='Calibration (mV/kN):',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    h_lc_stress = widgets.Text(placeholder='MPa',
                               description='Target Stress(es) (MPa):',
                               continuous_update=True,
                               disabled=False,
                               style=style)

    h_lc_ini_V = widgets.Text(placeholder='Volt',
                              description='H. Init. Volt.:',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    h_load_v = widgets.Label(value='Volt. @ Load = ')

    def hor_handle_change(change):
        if str(change.new) == '' or str(change.new) == '--' or str(
                change.new) == '-':
            h_load_v.value = 'Volt. @ Load = N/A'
        else:
            _, targ_volt = calc_stress(h_lc_calib, area, h_lc_stress,
                                       h_lc_ini_V)
            h_load_v.value = 'Volt. @ Load = ' + targ_volt

    h_lc_ini_V.observe(hor_handle_change, names='value')

    # ---------------------------------------------------------------------------------------------------------
    # ---------------------------------------------------------------------------------------------------------

    v_lc_title = widgets.Label('Vertical Load Cell')

    v_lc_picker = widgets.Dropdown(
        options=['44mm Solid Vert', '44mm Solid Vert', 'None'],
        value='44mm Solid Vert',
        description='Vert. Load Cell:',
        disabled=False,
        style=style)

    v_lc_calib = widgets.Text(placeholder='mV/kN',
                              description='Calibration (mV/kN):',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    v_lc_stress = widgets.Text(placeholder='MPa',
                               description='Target Stress(es) (MPa):',
                               continuous_update=True,
                               disabled=False,
                               style=style)

    v_lc_ini_V = widgets.Text(placeholder='Volt',
                              description='V. Init. Volt.:',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    v_load_v = widgets.Label(value='Volt. @ Load = ')

    def ver_handle_change(change):
        if str(change.new) == '' or str(change.new) == '--' or str(
                change.new) == '-':
            v_load_v.value = 'Volt. @ Load = N/A'
        else:
            _, targ_volt = calc_stress(v_lc_calib, area, v_lc_stress,
                                       v_lc_ini_V)
            v_load_v.value = 'Volt. @ Load = ' + targ_volt

    v_lc_ini_V.observe(ver_handle_change, names='value')

    # ---------------------------------------------------------------------------------------------------------
    # VESSEL PRESSURES -- Pc, PpA, PpB
    # ---------------------------------------------------------------------------------------------------------

    #     ves_grid = widgets.GridspecLayout(6, 3)

    pore_fluid = widgets.Text(value='DI H2O',
                              placeholder='DI H2O',
                              description='Pore Fluid',
                              continuous_update=True,
                              disabled=False,
                              style=style)

    vessel_title = widgets.Label('Confining Pressure')

    pc_gain = widgets.Text(value='0.1456',
                           placeholder='0.1456 V/MPa',
                           description='Pc Gain (V/MPa):',
                           continuous_update=True,
                           disabled=False,
                           style=style)

    pc_press = widgets.Text(placeholder='MPa',
                            description='Target Stress(es) (MPa):',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    pc_ini_V = widgets.Text(placeholder='Volt',
                            description='V. Init. Volt.:',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    pc_load_v = widgets.Label(value='Volt. @ Load = ')

    def pc_handle_change(change):
        if str(change.new) == '' or str(change.new) == '--' or str(
                change.new) == '-':
            pc_load_v.value = 'Volt. @ Load = N/A'
        else:
            targ_volt = calc_press(pc_gain, pc_press, pc_ini_V)
            pc_load_v.value = 'Volt. @ Load = ' + targ_volt

    pc_ini_V.observe(pc_handle_change, names='value')

    pc_items = widgets.VBox(
        children=[vessel_title, pc_gain, pc_press, pc_ini_V, pc_load_v])

    ppa_gain = widgets.Text(placeholder='Ppa Gain (V/MPa)',
                            description='Ppa Gain (V/MPa):',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    ppa_press = widgets.Text(placeholder='MPa',
                             description='PpA Press. (MPa)',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    ppa_ini_V = widgets.Text(placeholder='Volt',
                             description='V. Init. Volt.:',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    ppa_load_v = widgets.Label(value='Volt. @ Load = ')

    def ppa_handle_change(change):
        if str(change.new) == '' or str(change.new) == '--' or str(
                change.new) == '-':
            ppa_load_v.value = 'Volt. @ Load = N/A'
        else:
            targ_volt = calc_press(ppa_gain, ppa_press, ppa_ini_V)
            ppa_load_v.value = 'Volt. @ Load = ' + targ_volt

    ppa_ini_V.observe(ppa_handle_change, names='value')

    ppa_items = widgets.VBox(
        children=[vessel_title, ppa_gain, ppa_press, ppa_ini_V, ppa_load_v])

    ppb_gain = widgets.Text(placeholder='PpB Gain (V/MPa)',
                            description='PpB Gain (V/MPa):',
                            continuous_update=True,
                            disabled=False,
                            style=style)

    ppb_press = widgets.Text(placeholder='MPa',
                             description='PpB Press. (MPa)',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    ppb_ini_V = widgets.Text(placeholder='Volt',
                             description='V. Init. Volt.:',
                             continuous_update=True,
                             disabled=False,
                             style=style)

    ppb_load_v = widgets.Label(value='Volt. @ Load = ')

    def ppb_handle_change(change):
        if str(change.new) == '' or str(change.new) == '--' or str(
                change.new) == '-':
            ppb_load_v.value = 'Volt. @ Load = N/A'
        else:
            targ_volt = calc_press(ppb_gain, ppb_press, ppb_ini_V)
            ppb_load_v.value = 'Volt. @ Load = ' + targ_volt

    ppb_ini_V.observe(ppb_handle_change, names='value')

    ppb_items = widgets.VBox(children=[
        pore_fluid, vessel_title, ppb_gain, ppb_press, ppb_ini_V, ppb_load_v
    ])

    layout_args = {
        'flex_flow': 'row',
        'padding': '10px',
        'width': '75%',
        'grid_gap': '60px'
    }

    layout2 = widgets.Layout(display='flex',
                             **layout_args,
                             border='2px solid royalblue')

    horizontal = widgets.VBox(children=[
        h_lc_title, h_lc_picker, h_lc_calib, h_lc_stress, h_lc_ini_V, h_load_v
    ],
                              layout=widgets.Layout(flex='1 1 0%',
                                                    width='auto'))
    vertical = widgets.VBox(children=[
        v_lc_title, v_lc_picker, v_lc_calib, v_lc_stress, v_lc_ini_V, v_load_v
    ],
                            layout=widgets.Layout(flex='1 1 0%', width='auto'))

    layout = widgets.Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            border='2px solid grey',
                            padding='10px',
                            width='75%')

    hor_vert = widgets.GridBox(children=[horizontal, vertical], layout=layout)

    use_vessel = widgets.RadioButtons(options=['yes', 'no'],
                                      description='Use Vessel?',
                                      value='no',
                                      disabled=False)

    def vessel_input(a):
        pore_press = widgets.Label('')
        if a == 'yes':
            pore_press = widgets.GridBox(
                children=[pc_items, ppa_items, ppb_items], layout=layout2)
        return display(pore_press)

    vessel_params = widgets.interactive_output(vessel_input, {'a': use_vessel})

    data_logger = widgets.Dropdown(options=['8 channel', '16 channel'],
                                   value='8 channel',
                                   description='Data Logger Used:',
                                   disabled=False,
                                   style=style)

    h_dcdt = widgets.Combobox(options=['short rod', 'long rod', 'None'],
                              placeholder='Horiz. DCDT',
                              ensure_option=True,
                              description='Horiz. DCDT:',
                              disabled=False,
                              style=style)

    h_dcdt_calib = widgets.Text(placeholder='mm/V',
                                description='Horiz. DCDT calib.:',
                                continuous_update=True,
                                disabled=False,
                                style=style)

    v_dcdt = widgets.Combobox(options=['Trans-Tek2', 'None'],
                              placeholder='Vert. DCDT',
                              ensure_option=True,
                              description='Vert. DCDT:',
                              disabled=False,
                              style=style)

    v_dcdt_calib = widgets.Text(placeholder='mm/V',
                                description='Vert. DCDT calib.:',
                                continuous_update=True,
                                disabled=False,
                                style=style)

    layout = widgets.Layout(display='flex',
                            flex_flow='row',
                            border='2px solid grey',
                            padding='10px',
                            grid_gap='5px 100px',
                            width='75%')

    hdcdt = widgets.VBox(children=[h_dcdt, h_dcdt_calib],
                         layout=widgets.Layout(flex='1 1 1%', width='auto'))
    vdcdt = widgets.VBox(children=[v_dcdt, v_dcdt_calib],
                         layout=widgets.Layout(flex='1 1 1%', width='auto'))
    dcdts = widgets.GridBox(children=[data_logger, hdcdt, vdcdt],
                            layout=layout)

    style2 = {'width': 'initial'}
    purpose = widgets.Textarea(placeholder='Purpose/Description',
                               description='Purpose/Description',
                               continuous_update=True,
                               disabled=False,
                               style=style,
                               layout=widgets.Layout(flex='1 1 1%',
                                                     width='auto'))

    ac_blocks = widgets.Text(placeholder='',
                             description='Acoustics blocks used',
                             continuous_update=True,
                             disabled=False,
                             style=style,
                             layout=widgets.Layout(flex='1 1 1%',
                                                   width='auto'))

    temp = widgets.Text(placeholder='Temperature (C)',
                        description='Temperture',
                        continuous_update=True,
                        disabled=False,
                        style=style,
                        layout=widgets.Layout(flex='1 1 1%', width='auto'))

    humid = widgets.Text(placeholder='Rel. Humid. (%)',
                         description='Relative Humidity',
                         continuous_update=True,
                         disabled=False,
                         style=style,
                         layout=widgets.Layout(flex='1 1 1%', width='auto'))

    temp_humid = widgets.HBox([ac_blocks, temp, humid])

    notes = widgets.Textarea(placeholder='Experiment Notes',
                             description='Experiment Notes',
                             continuous_update=True,
                             disabled=False,
                             style=style,
                             layout=widgets.Layout(flex='1 1 1%',
                                                   width='auto'))
    layout = widgets.Layout(display='flex',
                            flex_flow='column',
                            align_items='stretch',
                            border='2px solid grey',
                            padding='10px',
                            width='75%')
    exp_info = widgets.GridBox(children=[purpose, temp_humid, notes],
                               layout=layout)

    # ---------------------------------------------------------------------------------------------------------
    # PID SETTINGS
    # ---------------------------------------------------------------------------------------------------------

    use_pid = widgets.RadioButtons(options=['yes', 'no'],
                                   description='Record PID?',
                                   value='no',
                                   disabled=False)

    layout = widgets.Layout(display='inline_flex',
                            align_items='center',
                            align_content='center',
                            border='2px solid grey',
                            padding='10px',
                            width='75%')

    pid_grid = widgets.GridspecLayout(4, 4, layout=layout)
    pid_grid_args = {'continuous_update': True, 'disabled': False}

    pid_grid[0, 0:2] = widgets.Label('Hor. Servo Settings')

    pid_grid[1, 0] = widgets.Text(placeholder='',
                                  description='P',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[2, 0] = widgets.Text(placeholder='',
                                  description='I',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[3, 0] = widgets.Text(placeholder='',
                                  description='D',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[1, 1] = widgets.Text(placeholder='',
                                  description='Datten',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[2, 1] = widgets.Text(placeholder='',
                                  description='Feedback',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[3, 1] = widgets.Text(placeholder='',
                                  description='E-gain',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[0, 2::] = widgets.Label('Vert. Servo Settings')

    pid_grid[1, 2] = widgets.Text(placeholder='',
                                  description='P',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[2, 2] = widgets.Text(placeholder='',
                                  description='I',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[3, 2] = widgets.Text(placeholder='',
                                  description='D',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[1, 3] = widgets.Text(placeholder='',
                                  description='Datten',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[2, 3] = widgets.Text(placeholder='',
                                  description='Feedback',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    pid_grid[3, 3] = widgets.Text(placeholder='',
                                  description='E-gain',
                                  layout=widgets.Layout(width='150px'),
                                  **pid_grid_args)

    def pid_input(a):
        pid_set = widgets.Label('')
        if a == 'yes':
            pid_set = pid_grid
        return display(pid_set)

    pid_params = widgets.interactive_output(pid_input, {'a': use_pid})

    # ---------------------------------------------------------------------------------------------------------
    # OUTPUT
    # ---------------------------------------------------------------------------------------------------------

    outputs = [
        exp_name, op_name, hyd_start, hyd_end, pick_date, area, block_thck,
        layer_thck, layer_thck_ld, material, part_size, h_lc_picker,
        h_lc_calib, h_lc_stress, h_lc_ini_V, v_lc_picker, v_lc_calib,
        v_lc_stress, v_lc_ini_V, pore_fluid, ppa_gain, ppa_press, ppa_ini_V,
        ppa_load_v, ppb_gain, ppb_press, ppb_ini_V, ppb_load_v, pc_gain,
        pc_press, pc_ini_V, pc_load_v, use_vessel, vessel_params, data_logger,
        h_dcdt, h_dcdt_calib, v_dcdt, v_dcdt_calib, layout, purpose, ac_blocks,
        temp, humid, notes, layout
    ]

    gui = display(preamble, material_block, hor_vert, use_vessel,
                  vessel_params, dcdts, exp_info, use_pid, pid_params)

    return gui, outputs
コード例 #22
0
    def __build(self):
        """
        This function is used to build all widgets of the UI.
        """

        # Section: "Plot Current Selected Dataset"
        # ============================================================================================================ #
        label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Current Selected Dataset}$: "
                                       + "$\\texttt{GlobalLandTemperaturesByCountry.csv}$ ")
        self._widget_list.append(label)

        # Section: "Plot Options"
        # ============================================================================================================ #
        label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Comparison Options}$")
        self._widget_list.append(label)

        label = ipywidgets.Label(
            value="You can customize your $\\textit{Comparison}$ using following $\\textit{Widgets}$")
        self._widget_list.append(label)

        self._widget_month_combobox = ipywidgets.Combobox(
            placeholder="Select/Type 'Month'...",
            options=calendar.month_name[1:],
            description='Month:',
            layout=ipywidgets.Layout(width='350px'),
            continuous_update=False
        )

        self._widget_month_checkbox = ipywidgets.Checkbox(
            description="Enable 'Month Filter'",
            layout=ipywidgets.Layout(width='350px')
        )

        grid = ipywidgets.GridspecLayout(1, 2)
        grid[0, 0] = self._widget_month_combobox
        grid[0, 1] = self._widget_month_checkbox

        self._widget_list.append(grid)

        self._widget_time_int_range_slider = ipywidgets.IntRangeSlider(
            step=1,
            description="Plot's 'Time Range'",
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
            style={'description_width': 'initial'},
            layout=ipywidgets.Layout(width='90%'),
        )

        self._widget_list.append(self._widget_time_int_range_slider)

        self._widget_active_columns_select = ipywidgets.Select(
            rows=10,
            description='Active Column:',
            disabled=False,
            style={'description_width': 'initial'},
            layout=ipywidgets.Layout(width='90%'),
        )

        self._widget_list.append(self._widget_active_columns_select)

        # Section: "State Selection"
        # ============================================================================================================ #

        label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{State Selection}$")
        self._widget_list.append(label)

        label = ipywidgets.Label(value="In order to compare regression lines, use the following combobox to select "
                                       " a $\\textit{State}$, then click on $\\textit{'Add State'}$ button to insert it "
                                       + "into the list below.")
        self._widget_list.append(label)
        label = ipywidgets.Label(
            value="We will compare regression lines of all $\\textit{States}$ that appear in that list!")
        self._widget_list.append(label)

        label = ipywidgets.Label(
            value="You can remove a $\\textit{States}$ selecting it and clicking $\\textit{'Remove State'}$ button!")
        self._widget_list.append(label)

        self._widgets_state_for_comparison_combobox = ipywidgets.Combobox(
            placeholder='Select a state...',
            layout=ipywidgets.Layout(width='500px'),
            continuous_update=False,
        )

        self._widgets_state_list_comparison_select = ipywidgets.Select(
            options=[],
            disabled=False,
            layout=ipywidgets.Layout(width='500px'),
            style={'description_width': 'initial'}
        )

        self._widgets_remove_state_comparison_list_button = ipywidgets.Button(
            description="Remove 'State'",
            disabled=False,
            button_style="danger",
            icon="minus"
        )

        self._widgets_insert_state_comparison_list_button = ipywidgets.Button(
            description="Add 'State'",
            disabled=False,
            button_style="success",
            icon="plus"
        )

        items = [self._widgets_insert_state_comparison_list_button, self._widgets_state_for_comparison_combobox,
                 self._widgets_remove_state_comparison_list_button, self._widgets_state_list_comparison_select]

        self._widget_list.append(ipywidgets.GridBox(items,
                                                    layout=ipywidgets.Layout(grid_template_columns="repeat(2, 170px)")))

        # Section: "Comparison Button"
        # ============================================================================================================ #
        label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Comparison Section}$")
        self._widget_list.append(label)
        self._widget_compare_button = ipywidgets.Button(description='Compare!',
                                                        disabled=False,
                                                        button_style='success',
                                                        icon='star')

        self._widget_list.append(self._widget_compare_button)

        # Section: "ERROR Label"
        # ============================================================================================================ #
        self._widget_error_label = ipywidgets.Label(value="")
        self._widget_list.append(self._widget_error_label)
    def __init__(self, path_or_url, **kw):
        # data
        self.path = path_or_url
        x, y, w, labels = read2d(path_or_url, **kw)
        if 'labels' not in kw:
            kw['labels'] = labels

        self.x = x
        self.y = y
        self.w = w
        self.kw = kw

        x0 = x[0]
        y0 = y[:, 0]
        xmin, xmax, dx = x[0, 0], x[0, -1], x[0, 1] - x[0, 0]
        ymin, ymax, dy = y[0, 0], y[-1, 0], y[1, 0] - y[0, 0]
        wmin, wmax = np.min(w), np.max(w)
        dw = (wmax - wmin) / 20

        # UI
        self.s_xpos = widgets.FloatSlider(value=(xmin + xmax) / 2,
                                          min=xmin,
                                          max=xmax,
                                          step=dx,
                                          description='x')
        self.s_ypos = widgets.FloatSlider(value=(ymin + ymax) / 2,
                                          min=ymin,
                                          max=ymax,
                                          step=dy,
                                          description='y')
        vb1 = widgets.VBox([self.s_xpos, self.s_ypos])
        self.s_gamma = widgets.IntSlider(value=0,
                                         min=-100,
                                         max=100,
                                         step=10,
                                         description='gamma')
        self.s_vlim = widgets.FloatRangeSlider(value=[wmin, wmax],
                                               min=wmin,
                                               max=wmax,
                                               step=dw,
                                               description='limit')
        self.c_cmap = widgets.Combobox(value='',
                                       placeholder='Choose or type',
                                       options=plt.colormaps(),
                                       description='colormap:',
                                       ensure_option=False,
                                       disabled=False)
        vb2 = widgets.VBox([self.s_gamma, self.s_vlim, self.c_cmap])
        self.b_expMTX = widgets.Button(description='To mtx')
        self.html_exp = widgets.HTML()
        vb3 = widgets.VBox([self.b_expMTX, self.html_exp])
        ui = widgets.Tab(children=[vb1, vb2, vb3])
        [
            ui.set_title(i, j)
            for i, j in zip(range(3), ['linecuts', 'color', 'export'])
        ]
        display(ui)

        # figure
        fig, axs = plt.subplots(1, 2,
                                figsize=(6.5, 2.5))  #main plot and h linecut
        fig.canvas.header_visible = False
        fig.canvas.toolbar_visible = False
        fig.canvas.resizable = False

        plt.subplots_adjust(wspace=0.4, bottom=0.2)
        axs[1].yaxis.tick_right()
        axs[1].tick_params(axis='x', colors='tab:orange')
        axs[1].tick_params(axis='y', colors='tab:orange')
        axv = fig.add_axes(axs[1].get_position(),
                           frameon=False)  #ax vertical linecut
        axv.xaxis.tick_top()
        axv.tick_params(axis='x', colors='tab:blue')
        axv.tick_params(axis='y', colors='tab:blue')
        self.fig = fig
        self.ax = axs[0]
        self.axv = axv
        self.axh = axs[1]

        # plot 2D data
        g = self.s_gamma.value
        v0, v1 = self.s_vlim.value
        self.kw['gamma'], self.kw['vmin'], self.kw['vmax'] = g, v0, v1
        Painter.plot2d(self.x,
                       self.y,
                       self.w,
                       fig=self.fig,
                       ax=self.ax,
                       **self.kw)

        self.im = [
            obj for obj in self.ax.get_children()
            if isinstance(obj, mpl.image.AxesImage)
            or isinstance(obj, mpl.collections.QuadMesh)
        ][0]

        # vlinecut
        xpos = self.s_xpos.value
        indx = np.abs(x0 - xpos).argmin()  # x0 may be a non uniform array
        [self.linev1] = axs[0].plot(x[:, indx], y0, 'tab:blue')
        [self.linev2] = axv.plot(w[:, indx], y0, 'tab:blue')
        self.indx = indx

        # hlinecut
        ypos = self.s_ypos.value
        indy = np.abs(y0 - ypos).argmin()
        [self.lineh1] = axs[0].plot(x0, y[indy, :], 'tab:orange')
        [self.lineh2] = axs[1].plot(x0, w[indy, :], 'tab:orange')
        self.indy = indy

        self.s_gamma.observe(self.on_gamma_change, 'value')
        self.s_vlim.observe(self.on_vlim_change, 'value')
        self.c_cmap.observe(self.on_cmap_change, 'value')
        self.s_xpos.observe(self.on_xpos_change, 'value')
        self.s_ypos.observe(self.on_ypos_change, 'value')
        self.fig.canvas.mpl_connect('button_press_event', self.on_mouse_click)
        self.b_expMTX.on_click(self.exportMTX)
コード例 #24
0
#いずれかがfloatならfloat
interact(f, x=(0.0, 10.0, 0.01))


#初期値
@interact(x=(0.0, 20.0, 0.5))
def h(x=5.5):
    return x


#ドロップダウンメニュー

interact(f, x=['apples', 'oranges'])
interact(f, x=[('one', 10), ('two', 20)])
interact(f,
         x=widgets.Combobox(options=["Chicago", "New York", "Washington"],
                            value="Chicago"))
"""#interactive : 再利用できるウィジェット"""

from IPython.display import display


def f(a, b):
    display(a + b)
    return a + b


w = interactive(f, a=10, b=20)
type(w)

w.children