示例#1
0
def smooth_savitzky_golay_ipy(obj, **kwargs):
    wdict = {}
    window_length = OddIntSlider(value=3,
                                 step=2,
                                 min=3,
                                 max=max(int(obj.axis.size * 0.25), 3))
    polynomial_order = ipywidgets.IntSlider(value=3,
                                            min=1,
                                            max=window_length.value - 1)

    # Polynomial order must be less than window length

    def update_bound(change):
        polynomial_order.max = change.new - 1

    window_length.observe(update_bound, "value")
    differential_order = ipywidgets.IntSlider(value=0, min=0, max=10)
    color = ipywidgets.ColorPicker()
    close = ipywidgets.Button(
        description="Close",
        tooltip=
        "Close widget and remove the smoothed line from the signal figure.")
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Perform the operation using the selected range.")
    link((obj, "polynomial_order"), (polynomial_order, "value"))
    link((obj, "window_length"), (window_length, "value"))
    link((obj, "differential_order"), (differential_order, "value"))
    # Differential order must be less or equal to polynomial_order
    link((polynomial_order, "value"), (differential_order, "max"))
    link((obj, "line_color_ipy"), (color, "value"))
    box = ipywidgets.VBox([
        labelme("Window length", window_length),
        labelme("polynomial order", polynomial_order),
        labelme("Differential order", differential_order),
        labelme("Color", color),
        ipywidgets.HBox((apply, close))
    ])

    wdict["window_length"] = window_length
    wdict["polynomial_order"] = polynomial_order
    wdict["differential_order"] = differential_order
    wdict["color"] = color
    wdict["close_button"] = close
    wdict["apply_button"] = apply

    def on_apply_clicked(b):
        obj.apply()

    apply.on_click(on_apply_clicked)

    def on_close_clicked(b):
        obj.close()
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
示例#2
0
    def _appearance_tab(self):
        """Defining the appearance tab."""

        # 1. Supercell
        def change_supercell(_=None):
            self.supercell = [
                _supercell[0].value, _supercell[1].value, _supercell[2].value
            ]

        _supercell = [
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
        ]
        for elem in _supercell:
            elem.observe(change_supercell, names='value')
        supercell_selector = ipw.HBox([ipw.HTML(description="Super cell:")] +
                                      _supercell)

        # 2. Choose background color.
        background_color = ipw.ColorPicker(description="Background")
        link((background_color, 'value'), (self._viewer, 'background'))
        background_color.value = 'white'

        # 3. Center button.
        center_button = ipw.Button(description="Center")
        center_button.on_click(lambda c: self._viewer.center())

        return ipw.VBox([supercell_selector, background_color, center_button])
示例#3
0
    def __init__(self, state, **kwargs):
        super(Color, self).__init__(**kwargs)
        self.state = state

        self.widget_color = widgets.ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'), color2hex)

        cmap_mode_options = type(self.state).cmap_mode.get_choice_labels(self.state)
        self.widget_cmap_mode = widgets.RadioButtons(options=cmap_mode_options, description='cmap mode')
        link((self.state, 'cmap_mode'), (self.widget_cmap_mode, 'value'))

        self.widget_cmap_att = LinkedDropdown(self.state, 'cmap_att',
                                              ui_name='color attribute',
                                              label='color attribute')

        self.widget_cmap_vmin = widgets.FloatText(description='color min')
        self.widget_cmap_vmax = widgets.FloatText(description='color max')
        self.widget_cmap_v = widgets.VBox([self.widget_cmap_vmin, self.widget_cmap_vmax])
        link((self.state, 'cmap_vmin'), (self.widget_cmap_vmin, 'value'), lambda value: value or 0)
        link((self.state, 'cmap_vmax'), (self.widget_cmap_vmax, 'value'), lambda value: value or 1)

        self.widget_cmap = widgets.Dropdown(options=colormaps, description='colormap')
        link((self.state, 'cmap'), (self.widget_cmap, 'label'), lambda cmap: colormaps.name_from_cmap(cmap), lambda name: colormaps[name])

        dlink((self.widget_cmap_mode, 'value'), (self.widget_color.layout, 'display'),     lambda value: None if value == cmap_mode_options[0] else 'none')
        dlink((self.widget_cmap_mode, 'value'), (self.widget_cmap.layout, 'display'),     lambda value: None if value == cmap_mode_options[1] else 'none')
        dlink((self.widget_cmap_mode, 'value'), (self.widget_cmap_att.layout, 'display'), lambda value: None if value == cmap_mode_options[1] else 'none')
        dlink((self.widget_cmap_mode, 'value'), (self.widget_cmap_v.layout, 'display'), lambda value: None if value == cmap_mode_options[1] else 'none')
        self.children = (self.widget_cmap_mode, self.widget_color, self.widget_cmap_att, self.widget_cmap_v, self.widget_cmap)
示例#4
0
    def change_colors(self, colordict: dict = None):
        """Change the model colors either by providing a color dictionary or,
        if not, by using a color pick widget.

        Args:
            colordict (dict, optional): dict with surface names mapped to hex color codes, e.g. {'layer1':'#6b0318'}
            if None: opens jupyter widget to change colors interactively. Defaults to None.
        """
        assert ipywidgets_import, 'ipywidgets not imported. Make sure the library is installed.'

        if colordict:
            self.update_colors(colordict)
        else:
            items = [
                widgets.ColorPicker(description=surface, value=color)
                for surface, color in self.colordict.items()
            ]
            colbox = widgets.VBox(items)
            print('Click to select new colors.')
            display(colbox)

            def on_change(v):
                self.colordict[v['owner'].description] = v['new']  # update colordict
                self._set_colors()

            for cols in colbox.children:
                cols.observe(on_change, 'value')
示例#5
0
    def dashboard(self):
        "Create linked widgets for wireframe parameters."
        children = []

        w = widgets.Checkbox(value=self.enable, description="Enable")
        widgets.jslink((w, "value"), (self, "enable"))
        children.append(w)

        w = widgets.FloatSlider(value=self.size,
                                min=0.005,
                                max=0.1,
                                step=0.005,
                                readout_format=".3f",
                                description="Width")
        widgets.jslink((w, "value"), (self, "size"))
        children.append(w)

        w = widgets.ColorPicker(value=self.color, description="Color")
        widgets.jslink((w, "value"), (self, "color"))
        children.append(w)

        w = widgets.FloatSlider(value=self.opacity,
                                min=0.0,
                                max=1.0,
                                step=0.01,
                                description="Opacity")
        widgets.jslink((w, "value"), (self, "opacity"))
        children.append(w)

        return widgets.VBox(children=children)
示例#6
0
 def make_keep_button(self):
     """
     Dynamically create a new "keep" button, when a line is saved, as the
     old "keep" button gets converted to a "remove" button.
     """
     drop = ipw.Dropdown(options=self.data_names,
                         description='',
                         layout={'width': 'initial'})
     lab = ipw.Label()
     but = ipw.Button(description="Keep",
                      disabled=False,
                      button_style="",
                      layout={'width': "70px"})
     # Generate a random color.
     # TODO: should we initialise the seed?
     col = ipw.ColorPicker(concise=True,
                           description='',
                           value=make_random_color(fmt='hex'),
                           layout={'width': "40px"})
     # Make a unique id
     self.counter += 1
     line_id = self.counter
     setattr(but, "id", line_id)
     setattr(col, "id", line_id)
     but.on_click(self.keep_remove_line)
     col.observe(self.update_line_color, names="value")
     self.keep_buttons[line_id] = {
         "dropdown": drop,
         "button": but,
         "colorpicker": col,
         "label": lab
     }
     self.update_widgets()
    def __init__(self):
        super().__init__()
        output = widgets.Output()

        self.x = np.linspace(0, 2 * np.pi, 100)
        initial_color = '#FF00DD'

        with output:
            self.fig, self.ax = plt.subplots(constrained_layout=True, figsize=(5, 3.5))
        self.line, = self.ax.plot(self.x, np.sin(self.x), initial_color)
        
        self.fig.canvas.toolbar_position = 'bottom'
        self.ax.grid(True)

        # define widgets
        int_slider = widgets.IntSlider(
            value=1, 
            min=0, 
            max=10, 
            step=1, 
            description='freq'
        )
        color_picker = widgets.ColorPicker(
            value=initial_color, 
            description='pick a color'
        )
        text_xlabel = widgets.Text(
            value='', 
            description='xlabel', 
            continuous_update=False
        )
        text_ylabel = widgets.Text(
            value='', 
            description='ylabel', 
            continuous_update=False
        )

        controls = widgets.VBox([
            int_slider, 
            color_picker, 
            text_xlabel, 
            text_ylabel
        ])
        controls.layout = make_box_layout()
        
        out_box = widgets.Box([output])
        output.layout = make_box_layout()

        # observe stuff
        int_slider.observe(self.update, 'value')
        color_picker.observe(self.line_color, 'value')
        text_xlabel.observe(self.update_xlabel, 'value')
        text_ylabel.observe(self.update_ylabel, 'value')
        
        text_xlabel.value = 'x'
        text_ylabel.value = 'y'
        
        # add to children
        self.children = [controls, output]
示例#8
0
    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))
    def run_widget(self, feature_value_color_dict):
        """
        df:
            A pandas dataframe object

        df_features:
            DataFrameTypes object; organizes feature types into groups.

        Returns:
            Returns a UI widget to create a JSON file for cleaning.
        """

        self.__feature_value_color_dict = copy.deepcopy(
            feature_value_color_dict)

        # Convert all
        for k, v in feature_value_color_dict.items():
            if not v:
                self.__feature_value_color_dict[k] = "#000000"

            if isinstance(v, str):
                del self.__feature_value_color_dict[k]

        feature_values = {
            feature_name: self.__feature_value_color_dict[feature_name]
            for feature_name in self.__feature_value_color_dict.keys()
        }

        self.__features_w = widgets.Select(options=list(feature_values.keys()),
                                           layout=Layout(width='50%',
                                                         height='175px'))

        self.__feature_values_w = {
            feature: widgets.Select(options=feature_values[feature].keys(),
                                    layout=Layout(width='50%', height='300px'))
            for feature in feature_values
        }

        self.__color_picker_w = widgets.ColorPicker(concise=False,
                                                    description='Pick a color',
                                                    disabled=False)

        self.__update_widgets()

        # Link functions with non-updateable widgets
        self.__features_w.observe(self.__select_feature, 'value')

        self.__color_picker_w.observe(self.__select_color, 'value')

        # Setup and display full UI
        self.__full_widgets_ui = widgets.interactive(
            self.__select_value,
            Features=self.__features_w,
            Values=self.__values_w,
            Color_Picker=self.__color_picker_w,
        )

        display(self.__full_widgets_ui)
示例#10
0
    def reticle_color_widget(self):
        widget = widgets.ColorPicker(value=to_hex(self.reticle_color))

        def change_handler(change):
            self.reticle_color = change.new

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

        return with_left_label('Reticle color', widget)
示例#11
0
    def color_hover_widget(self):
        widget = widgets.ColorPicker(value=to_hex(self.color_hover))

        def change_handler(change):
            self.color_hover = change.new

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

        return with_left_label('Point color hover', widget)
示例#12
0
    def background_color_widget(self):
        widget = widgets.ColorPicker(value=to_hex(self.background_color))

        def change_handler(change):
            self.background_color = change.new

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

        return with_left_label('Background color', widget)
示例#13
0
    def create_widgets(self):
        self.widget_visible = widgets.Checkbox(description='visible',
                                               value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))
        link((self.state, 'visible'), (self.bars, 'visible'))

        self.widget_color = widgets.ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'))

        return widgets.VBox([self.widget_visible, self.widget_color])
示例#14
0
def cq_interact(params):
    'builds dict of interaction widgets for each exposed parameter'
    interactions = {}
    display_options = {}
    for key in params:
        name = params[key].name
        val = params[key].default_value
        if isinstance(val, int):
            if isinstance(val, bool):
                interactions[name] = ipywidgets.Checkbox(
                    description=name,
                    value=val,
                    continuous_update=False
                    )
            else:
                interactions[name] = ipywidgets.IntText(
                    description=name,
                    value=val,
                    continuous_update=False
                    )
        elif isinstance(val, float):
            interactions[name] = ipywidgets.FloatText(
                description=name,
                value=val,
                continuous_update=False
                )
        else:
            interactions[name] = ipywidgets.Text(
                description=name,
                value=val,
                continuous_update=False
                )

    # add color, units, scale selection
    display_options['display_color'] = ipywidgets.ColorPicker(
        description='Color: ',
        value='#8dc63f',
        concise=False,
        continuous_update=False
        )
    display_options['display_units'] = ipywidgets.ToggleButtons(
        description='Units: ',
        options=['mm', 'in'],
        value='mm',
        continuous_update=False
        )
    display_options['display_scale'] = ipywidgets.FloatText(
        description='Scale: ',
        value=1.0,
        continuous_update=False
        )

    return interactions, display_options
示例#15
0
    def __init__(self, xp, yp, function):
        """Interface for iterativelive fitting a curve

        Parameters
        ----------
        xp: np.array
            An array of x-values


        yp: WavelengthSolution
            An array of y-values

        function:  ~astropy.modeling.models
            A 1D model describing the transformation between x and y

        Returns
        -------
        ws: WavelengthSolution
            A calibrated wavelength solution for the observed arc
        """

        self.xp = xp
        self.yp = yp
        self.function = function
        self.xpd = []  # saved deleted points
        self.ypd = []
        self.color = '#FF0011'

        # set up the information and control panel
        color_picker = widgets.ColorPicker(value=self.color,
                                           description='Color for Arc')
        color_picker.observe(self.set_line_color, 'value')

        self.check_residual = widgets.Checkbox(value=True,
                                               description='Display residual',
                                               disabled=False,
                                               indent=False)
        self.check_residual.observe(self.set_residual, 'value')

        self.w = widgets.HTML()
        self.w.value = 'Starting'

        controls = widgets.VBox([color_picker, self.check_residual, self.w])

        # Set up the initial plot
        self.fig, self.ax = plt.subplots(constrained_layout=True,
                                         figsize=(5, 3.5))
        self.fig.canvas.mpl_connect('key_press_event', self.on_key_press)

        self.draw_plot()

        display(controls)
示例#16
0
    def dashboard(self):
        "Create a linked color picker for this color."
        children = []

        w = widgets.FloatSlider(value=self.intensity, description="Intensity")
        widgets.jslink((w, "value"), (self, "intensity"))
        children.append(w)

        w = widgets.ColorPicker(value=self.color, description="Color")
        widgets.jslink((w, "value"), (self, "color"))
        children.append(w)

        return widgets.VBox(children=children)
示例#17
0
    def _appearance_tab(self):
        """Defining the appearance tab."""

        # 1. Supercell
        def change_supercell(_=None):
            self.supercell = [
                _supercell[0].value,
                _supercell[1].value,
                _supercell[2].value,
            ]

        _supercell = [
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
            ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}),
        ]
        for elem in _supercell:
            elem.observe(change_supercell, names="value")
        supercell_selector = ipw.HBox([ipw.HTML(description="Super cell:")] +
                                      _supercell)

        # 2. Choose background color.
        background_color = ipw.ColorPicker(description="Background")
        link((background_color, "value"), (self._viewer, "background"))
        background_color.value = "white"

        # 3. Camera switcher
        camera_type = ipw.ToggleButtons(
            options={
                "Orthographic": "orthographic",
                "Perspective": "perspective"
            },
            description="Camera type:",
            value=self._viewer.camera,
            layout={"align_self": "flex-start"},
            style={"button_width": "115.5px"},
            orientation="vertical",
        )

        def change_camera(change):

            self._viewer.camera = change["new"]

        camera_type.observe(change_camera, names="value")

        # 4. Center button.
        center_button = ipw.Button(description="Center molecule")
        center_button.on_click(lambda c: self._viewer.center())

        return ipw.VBox(
            [supercell_selector, background_color, camera_type, center_button])
示例#18
0
    def __init__(self, state, **kwargs):
        super(Color, self).__init__(**kwargs)
        self.state = state

        self.widget_color = widgets.ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'))

        cmap_mode_options = type(self.state).cmap_mode.get_choice_labels(
            self.state)
        self.widget_cmap_mode = widgets.RadioButtons(options=cmap_mode_options,
                                                     description='cmap mode')
        link((self.state, 'cmap_mode'), (self.widget_cmap_mode, 'value'))

        helper = self.state.cmap_att_helper
        self.widget_cmap_att = widgets.Dropdown(
            options=[k.label for k in helper.choices],
            value=self.state.cmap_att,
            description='color attr.')
        link_component_id_to_select_widget(self.state, 'cmap_att',
                                           self.widget_cmap_att)
        # on_change([(self.state, 'cmap', 'cmap_mode', 'cmap_vmin', 'cmap_vmax')])(self._update_cmap)

        self.widget_cmap_vmin = widgets.FloatText(description='color min')
        self.widget_cmap_vmax = widgets.FloatText(description='color max')
        self.widget_cmap_v = widgets.VBox(
            [self.widget_cmap_vmin, self.widget_cmap_vmax])
        link((self.state, 'cmap_vmin'), (self.widget_cmap_vmin, 'value'))
        link((self.state, 'cmap_vmax'), (self.widget_cmap_vmax, 'value'))

        self.widget_cmap = widgets.Dropdown(options=colormaps,
                                            description='colormap')
        link((self.state, 'cmap'), (self.widget_cmap, 'label'),
             lambda cmap: colormaps.name_from_cmap(cmap),
             lambda name: colormaps[name])

        dlink((self.widget_cmap_mode, 'value'),
              (self.widget_color.layout, 'display'), lambda value: None
              if value == cmap_mode_options[0] else 'none')
        dlink((self.widget_cmap_mode, 'value'),
              (self.widget_cmap.layout, 'display'), lambda value: None
              if value == cmap_mode_options[1] else 'none')
        dlink((self.widget_cmap_mode, 'value'),
              (self.widget_cmap_att.layout, 'display'), lambda value: None
              if value == cmap_mode_options[1] else 'none')
        dlink((self.widget_cmap_mode, 'value'),
              (self.widget_cmap_v.layout, 'display'), lambda value: None
              if value == cmap_mode_options[1] else 'none')
        self.children = (self.widget_cmap_mode, self.widget_color,
                         self.widget_cmap_att, self.widget_cmap_v,
                         self.widget_cmap)
示例#19
0
    def create_widgets(self):
        children = []
        self.widget_visible = widgets.Checkbox(description='visible', value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))
        link((self.state, 'visible'), (self.image_mark, 'visible'))

        self.widget_opacity = widgets.FloatSlider(min=0, max=1, step=0.01, value=self.state.alpha, description='opacity')
        link((self.state, 'alpha'), (self.widget_opacity, 'value'))
        link((self.state, 'alpha'), (self.image_mark, 'opacity'))

        children.extend([self.widget_visible, self.widget_opacity])

        if isinstance(self.layer, Subset):
            self.widget_color = widgets.ColorPicker(description='color')
            link((self.state, 'color'), (self.widget_color, 'value'))
            on_change([(self.state, 'color')])(self._update_cmap)
            children.extend([self.widget_color])
        else:
            self.widget_contrast = widgets.FloatSlider(min=0, max=4, step=0.01, value=self.state.contrast, description='contrast')
            link((self.state, 'contrast'), (self.widget_contrast, 'value'))

            self.widget_bias = widgets.FloatSlider(min=0, max=1, step=0.01, value=self.state.bias, description='bias')
            link((self.state, 'bias'), (self.widget_bias, 'value'))

            # TODO: refactor: this is a copy from state
            percentile_display = {100: 'Min/Max',
                          99.5: '99.5%',
                          99: '99%',
                          95: '95%',
                          90: '90%'}
                          #'Custom': 'Custom'} # TODO: support custom

            self.widget_percentile = widgets.Dropdown(options=[(percentile_display[k], k) for k in [100, 99.5, 99, 95, 90]],#, 'Custom']],
                                           value=self.state.percentile, description='limits')
            link((self.state, 'percentile'), (self.widget_percentile, 'value'))
            on_change([(self.state, 'bias', 'contrast', 'v_min', 'v_max')])(self._update_scale_image)

            self.widget_colormap = widgets.Dropdown(options=colormaps, value=colormaps[0][1], description='colormap')
            link((self.widget_colormap, 'label'), (self.state, 'cmap'))
            on_change([(self.state, 'cmap')])(self._update_cmap)
            self._update_cmap()

            children.extend([self.widget_percentile, self.widget_contrast, self.widget_bias, self.widget_colormap])

        return widgets.VBox(children)
示例#20
0
def smooth_butterworth(obj, **kwargs):
    wdict = {}
    cutoff = ipywidgets.FloatSlider(min=0.01, max=1.)
    order = ipywidgets.IntText()
    type_ = ipywidgets.Dropdown(options=("low", "high"))
    color = ipywidgets.ColorPicker()
    close = ipywidgets.Button(
        description="Close",
        tooltip=
        "Close widget and remove the smoothed line from the signal figure.")
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Perform the operation using the selected range.")
    link((obj, "cutoff_frequency_ratio"), (cutoff, "value"))
    link((obj, "type"), (type_, "value"))
    link((obj, "order"), (order, "value"))
    wdict["cutoff"] = cutoff
    wdict["order"] = order
    wdict["type"] = type_
    wdict["color"] = color
    wdict["close_button"] = close
    wdict["apply_button"] = apply
    box = ipywidgets.VBox([
        labelme("Cutoff frequency ration", cutoff),
        labelme("Type", type_),
        labelme("Order", order),
        ipywidgets.HBox((apply, close))
    ])

    def on_apply_clicked(b):
        obj.apply()

    apply.on_click(on_apply_clicked)

    def on_close_clicked(b):
        obj.close()
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
示例#21
0
def smooth_tv_ipy(obj, **kwargs):
    wdict = {}
    smoothing_parameter = ipywidgets.FloatSlider(min=0.1, max=1000)
    smoothing_parameter_max = ipywidgets.FloatText(
        value=smoothing_parameter.max)
    color = ipywidgets.ColorPicker()
    close = ipywidgets.Button(
        description="Close",
        tooltip=
        "Close widget and remove the smoothed line from the signal figure.")
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Perform the operation using the selected range.")
    link((obj, "smoothing_parameter"), (smoothing_parameter, "value"))
    link((smoothing_parameter_max, "value"), (smoothing_parameter, "max"))
    link((obj, "line_color_ipy"), (color, "value"))
    wdict["smoothing_parameter"] = smoothing_parameter
    wdict["smoothing_parameter_max"] = smoothing_parameter_max
    wdict["color"] = color
    wdict["close_button"] = close
    wdict["apply_button"] = apply
    box = ipywidgets.VBox([
        labelme("Weight", smoothing_parameter),
        labelme("Weight max", smoothing_parameter_max),
        labelme("Color", color),
        ipywidgets.HBox((apply, close))
    ])

    def on_apply_clicked(b):
        obj.apply()

    apply.on_click(on_apply_clicked)

    def on_close_clicked(b):
        obj.close()
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
示例#22
0
    def __init__(self, image,
                colors = ['Red','Green','Blue']):

        """Standard __init__ method.
        
        Parameters
        ----------
        image : numpy array
            image array
        colors : list of str
            list of colors to use a colormap for each channel
        
        Attributes
        ----------
            
        colormaps = dict
            dictionary of matplotlib ListedColormap
        
        """
        
        self.image = image
        self.colors = colors
        
        self.selected_contrast = [(0.0, 255.0) for i in range(3)]
        self.selected_colors = ['Red', 'Green', 'Blue']
        
        self.possible_colors = ['Red','Green','Blue','Cyan','Magenta']
        self.color_select = [ipw.Select(options = self.possible_colors, 
                                        value = self.possible_colors[i],
                                        rows = 8,
                                        layout={'width': '300px'}) for i in range(3)]
        
        self.def_colormaps()
        
        self.hist_button = ipw.Button(description = 'Create movie')
        self.hist_button.on_click(self.button_callback)
        self.out_movie = ipw.Output()
        
        self.colorpick = ipw.ColorPicker(description='Pick a color',style = {'description_width': '150px'})
        self.createLUT_button = ipw.Button(description = 'Create colormap',layout={'width': '300px'})
        self.createLUT_button.on_click(self.createLUT)
        self.colorname = ipw.Text(description='Name the color', style = {'description_width': '150px'})
示例#23
0
def smooth_lowess_ipy(obj, **kwargs):
    wdict = {}
    smoothing_parameter = ipywidgets.FloatSlider(min=0, max=1)
    number_of_iterations = ipywidgets.IntText()
    color = ipywidgets.ColorPicker()
    close = ipywidgets.Button(
        description="Close",
        tooltip=
        "Close widget and remove the smoothed line from the signal figure.")
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Perform the operation using the selected range.")
    link((obj, "smoothing_parameter"), (smoothing_parameter, "value"))
    link((obj, "number_of_iterations"), (number_of_iterations, "value"))
    link((obj, "line_color_ipy"), (color, "value"))
    box = ipywidgets.VBox([
        labelme("Smoothing parameter", smoothing_parameter),
        labelme("Number of iterations", number_of_iterations),
        labelme("Color", color),
        ipywidgets.HBox((apply, close))
    ])
    wdict["smoothing_parameter"] = smoothing_parameter
    wdict["number_of_iterations"] = number_of_iterations
    wdict["color"] = color
    wdict["close_button"] = close
    wdict["apply_button"] = apply

    def on_apply_clicked(b):
        obj.apply()

    apply.on_click(on_apply_clicked)

    def on_close_clicked(b):
        obj.close()
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
示例#24
0
def get_layer_widget(layer, plot_function=None):
    color = widgets.ColorPicker(concise=False,
                                description='Layer color',
                                value=layer.color,
                                disabled=False)
    alpha = widgets.FloatSlider(value=1.0,
                                min=0,
                                max=1.0,
                                continuous_update=False,
                                description='Opacity',
                                readout=True)
    logscale = widgets.Checkbox(value=False, description='Logarithmic scaling')

    def wrapper(**kwargs):
        layer.update(object_name=layer.object,
                     filter_name=layer.filter,
                     **kwargs)
        if (plot_function is not None) and (not skip_layer_plot):
            plot_function()

    w = interactive(wrapper, color=color, alpha=alpha, logscale=logscale)
    return w
示例#25
0
 def make_keep_button(self):
     drop = widgets.Dropdown(options=self.traces.keys(),
                             description='',
                             layout={'width': 'initial'})
     but = widgets.Button(description="Keep",
                          disabled=False,
                          button_style="",
                          layout={'width': "70px"})
     # Generate a random color. TODO: should we initialise the seed?
     col = widgets.ColorPicker(concise=True,
                               description='',
                               value='#%02X%02X%02X' %
                               (tuple(np.random.randint(0, 255, 3))),
                               disabled=False)
     # Make a unique id
     key = str(id(but))
     setattr(but, "id", key)
     setattr(col, "id", key)
     but.on_click(self.keep_remove_trace)
     col.observe(self.update_trace_color, names="value")
     self.keep_buttons[key] = [drop, but, col]
     return
示例#26
0
def interactive_rad(temp_pd, stations):
    """Interactive plotting of elevation-azimuth plots for a set of satellites and a set
    of stations
    
    Parameters
    ----------
    temp_pd : Pandas dataframe
        Output of aiub.import_RM_file function
    stations: pandas dataframe
        station dataframe as output of aiub.import_stations()
       
        
    Returns
    -------
    
    """

    all_dates = temp_pd.time_stamp.unique(
    )  #temp_pd.datetime.apply(lambda x: x.timestamp()).unique()
    #all_dates_read = temp_pd.datetime.unique()

    time_list = list(
        map(lambda x: datetime.datetime.fromtimestamp(x),
            temp_pd.time_stamp.unique()))
    all_dates_read = [
        str(tl.year) + '-' + str(tl.month) + '-' + str(tl.day) + '  ' +
        str(tl.hour) + ':' + str(tl.minute) for tl in time_list
    ]

    colors = ['red', 'blue', 'green', 'cyan', 'orange']
    items = [
        widgets.ColorPicker(description=temp_pd.satellite.unique()[i],
                            value=colors[i])
        for i in range(len(temp_pd.satellite.unique()))
    ]
    if len(items) < 5:
        items = items + [
            widgets.ColorPicker(description='None', value=colors[i])
            for i in range(5 - len(items))
        ]
    colwidget = widgets.VBox(items)

    #min_date_widget = widgets.IntSlider(min=0, max=len(all_dates)-1, step=1, value = 0, continuous_update = False)
    #max_date_widget = widgets.IntSlider(min=0, max=len(all_dates)-1, step=1, value = 0, continuous_update = False)

    style = {'description_width': '20%', 'readout_width': '20%'}
    min_date_widget = widgets.SelectionSlider(options=all_dates_read,
                                              style=style,
                                              description='Min Time',
                                              layout={'width': '400px'})
    max_date_widget = widgets.SelectionSlider(options=all_dates_read,
                                              style=style,
                                              description='Max Time',
                                              layout={'width': '400px'})

    sat_type = widgets.SelectMultiple(options=temp_pd.satellite.unique(),
                                      description='Select satellite types',
                                      value=[temp_pd.satellite.unique()[0]],
                                      disabled=False)

    station_widget = widgets.Dropdown(options=stations.statname.unique(),
                                      value=stations.iloc[0].statname,
                                      description='Select observation station',
                                      style={'description_width': '50%'},
                                      layout={'width': '400px'})

    d = {
        'data': widgets.fixed(temp_pd),
        'all_dates': widgets.fixed(all_dates),
        'all_dates_read': widgets.fixed(all_dates_read),
        'sat_type': sat_type,
        'date_min': min_date_widget,
        'date_max': max_date_widget,
        'stations': widgets.fixed(stations),
        'station_sel': station_widget
    }
    d2 = {'col' + str(ind): value for (ind, value) in enumerate(items)}
    d.update(d2)

    title_w = widgets.HTML(
        "<span style='float:left;font-size:2em;font-weight:bold'>Radial plot of satellite observation</span>"
    )
    time_title_w = widgets.HTML(
        "<span style='float:left;font-size:1em;font-weight:bold'>Pick time range for observations</span>"
    )
    w1 = widgets.HBox([sat_type, colwidget])
    w2 = widgets.HBox([station_widget])
    w3 = widgets.HBox([min_date_widget, max_date_widget])
    ui = widgets.VBox([title_w, w1, w2, time_title_w, w3],
                      layout=Layout(align_items='stretch'))

    out = widgets.interactive_output(plot_radial, d)
    display(ui, out)
# create some x data
x = np.linspace(0, 2 * np.pi, 100)

# default line color
initial_color = '#FF00DD'

with output:
    fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 4))
    # move the toolbar to the bottom
fig.canvas.toolbar_position = 'bottom'
ax.grid(True)    
line, = ax.plot(x, np.sin(x), initial_color)

# create some control elements
int_slider = widgets.IntSlider(value=1, min=0, max=10, step=1, description='freq')
color_picker = widgets.ColorPicker(value=initial_color, description='pick a color')
text_xlabel = widgets.Text(value='', description='xlabel', continuous_update=False)
text_ylabel = widgets.Text(value='', description='ylabel', continuous_update=False)
reset_button = widgets.Button(description="Reset values!", layout=Layout(align_self='flex-end')) #center flex-end flex-start
#reset_button.layout.align_self='center'

# callback functions
def update(change):
    """redraw line (update plot)"""
    line.set_ydata(np.sin(change.new * x))
    fig.canvas.draw()
    
def line_color(change):
    """set line color"""
    line.set_color(change.new)
    
示例#28
0
    def __init__(self,
                 arc,
                 ws,
                 line_list=None,
                 wavelength_range=None,
                 flatten_order=None):
        """Preform identification of a spectrum of an arc lamp and return the wavelength solution for that spectrum.

        Parameters
        ----------
        arc: Spectrum1D
            An uncalibrated Spectrum1D of an observation of an arc lamp


        ws: WavelengthSolution
            An initial wavelength solution for the arc

        line_list: Astropy.Table
            A list of lines in the observed arc

        wavelength_range: list
            An initial guess for the wavelength range of the observed arc to be used in creating
            the artificial spectrum of the arc.

        flatten_order: int, None
            If not none, the continuum of the arc observations will be removed.  A polynomial of
            this order will be fit to the continuum and subtracted.

        Returns
        -------
        ws: WavelengthSolution
            A calibrated wavelength solution for the observed arc
        """
        #super().__init__()
        #output = widgets.Output()

        self.arc = arc
        self.xarr = self.arc.spectral_axis.value
        if flatten_order:
            self.farr = flatspectrum(self.arc.spectral_axis.value,
                                     self.arc.flux,
                                     order=flatten_order)
        else:
            self.farr = self.arc.spectral_axis.value
        self.ws = ws
        self.orig_ws = copy.deepcopy(ws)
        self.arc_color = '#2d34ff'
        self.line_list = line_list
        self.xp = []
        self.wp = []
        self.xpd = []  # saved deleted points
        self.wpd = []
        # TODO: Need to add these values into the options
        self.textcolor = 'black'
        self.cdiff = 20
        self.sections = 6
        self.mdiff = 20
        self.wdiff = 20
        self.sigma = 5
        self.res = 2
        self.niter = 5
        self.ndstep = 20

        # make an artificial version of the line list for plotting
        self.line_spec = make_artificial_spectra(self.line_list,
                                                 wavelength_range,
                                                 wavelength_unit=u.angstrom,
                                                 flux_unit=u.electron,
                                                 sigma=self.sigma)

        # set up the information and control panel
        color_picker = widgets.ColorPicker(value=self.arc_color,
                                           description='Color for Arc')
        color_picker.observe(self.line_color, 'value')

        self.pixel_value = widgets.BoundedFloatText(min=0,
                                                    max=len(self.arc.data),
                                                    description='pixel',
                                                    disable=True)
        self.wavelength_value = widgets.FloatText(description='wavelength',
                                                  disable=True)

        self.add_point_button = widgets.Button(
            description='Add point',
            disabled=False,
            button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip=
            'Click button to add a point at this x value and wavelength value',
        )
        self.add_point_button.on_click(self.add_point)

        self.dispersion_unit = widgets.RadioButtons(
            options=['pixel', 'wavelength'],
            value='pixel',
            description='Dispersion:',
            disabled=False)
        self.dispersion_unit.observe(self.set_dispersion, 'value')

        self.display_artificial = widgets.Checkbox(
            value=True,
            description='Display line list',
            disabled=False,
            indent=False)
        self.display_artificial.observe(self.set_display_artifical, 'value')

        self.display_features = widgets.Checkbox(
            value=True,
            description='Display features',
            disabled=False,
            indent=False)
        self.display_features.observe(self.set_display_features, 'value')

        controls = widgets.VBox([
            color_picker, self.pixel_value, self.wavelength_value,
            self.add_point_button, self.dispersion_unit,
            self.display_artificial, self.display_features
        ])

        # Set up the initial plot
        self.fig, self.ax = plt.subplots(constrained_layout=True,
                                         figsize=(8, 5))
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)
        self.fig.canvas.mpl_connect('key_press_event', self.on_key_press)

        self.draw_plot()

        display(controls)
示例#29
0
文件: data.py 项目: aglavic/genx
    def _repr_ipyw_(self, add_header=True):
        import ipywidgets as ipw
        vlist = []
        if add_header:
            vlist.append(ipw.HTML("<h3>Dataset</h3>"))
            header = ipw.HBox([
                ipw.HTML('<b>%s</b>' % txt[0], layout=ipw.Layout(width=txt[1]))
                for txt in [('Name', '30ex'), ('show',
                                               '6ex'), ('use',
                                                        '6ex'), ('error',
                                                                 '6ex')]
            ])
            vlist.append(header)

        entries = []
        entries.append(ipw.Text(self.name, layout=ipw.Layout(width='30ex')))
        entries.append(
            ipw.Checkbox(self.show,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        entries.append(
            ipw.Checkbox(self.use,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        entries.append(
            ipw.Checkbox(self.use_error,
                         indent=False,
                         layout=ipw.Layout(width='6ex')))
        items = ['name', 'show', 'use', 'use_error']
        for j, entr in enumerate(entries):
            entr._child_val = items[j]
            entr.observe(self._ipyw_change, names='value')
        vlist.append(ipw.HBox(entries))
        cbox = ipw.VBox()
        plotbox = ipw.VBox()
        clist = []
        commands = ipw.Accordion(children=[cbox, plotbox],
                                 selected_index=None,
                                 layout=ipw.Layout(width='46x'))
        commands.set_title(0, 'Commands')
        commands.set_title(1, 'Plotting')
        vlist.append(commands)
        for col in ['x', 'y', 'error']:
            entr = ipw.Text(eval('self.%s_command' % col, globals(), locals()),
                            description=col)
            entr._command = col
            entr.observe(self._ipyw_command, names='value')
            clist.append(entr)
        for key, value in self.extra_commands.items():
            entr = ipw.Text(value, description=key)
            entr._command = key
            clist.append(entr)
            entr.observe(self._ipyw_command, names='value')
        cbox.children = tuple(clist)
        clist = []
        clist.append(
            ipw.ColorPicker(description="Sim Color",
                            value=c2html(self.sim_color)))
        clist[-1]._child_val = 'sim_color'
        clist[-1].observe(self._ipyw_change_color)
        clist.append(
            ipw.ColorPicker(description="Data Color",
                            value=c2html(self.data_color)))
        clist[-1]._child_val = 'data_color'
        clist[-1].observe(self._ipyw_change_color)

        plotbox.children = tuple(clist)
        return ipw.VBox(vlist)
示例#30
0
)
w_outputfolder_valid = widgets.Valid(value=True)
hboxoutputfolder = widgets.HBox([w_outputfolder, w_outputfolder_valid])


def output_folder_check(*args):
    if os.path.isdir(w_outputfolder.value) and w_outputfolder.value[-1] == "/":
        w_outputfolder_valid.value = True
    else:
        w_outputfolder_valid.value = False


w_outputfolder.observe(output_folder_check, 'value')

### Color Selectors ###
w_cp1 = widgets.ColorPicker(value="#0080ff", width="100px", concise=False)
w_cp2 = widgets.ColorPicker(value="#ff0000", width="100px", concise=False)
w_cp3 = widgets.ColorPicker(value="#00ff00", width="100px", concise=False)
w_cp4 = widgets.ColorPicker(value="#800080", width="100px", concise=False)

selectors_color = widgets.HBox([w_cp1, w_cp2, w_cp3, w_cp4])
selectors1 = widgets.HBox([
    w_labels,
    w_invert,
    w_legend,
    w_stagger,
    w_refseq,
    w_shadeBed,
    w_staticaxes,
    w_boundingbox,
])