コード例 #1
0
ファイル: measure.py プロジェクト: dgglab/QDotsPythonCode
def cut(image):
    """Interactive line cuts of 2D Images. Uses ipywidgets for interactivity.
    
    Args:
        image: Image to take line cuts of. The type should be a Holoviews Image.
    """

    #Defines a Holoviews Stream class for an x,y position
    class xy(hv.streams.Stream):
        x = param.Number(default=0.0, doc='An X position.')
        y = param.Number(default=0.0, doc='A Y position.')

    #Points for each axis
    x_axis = np.unique(image.dimension_values(0))
    y_axis = np.unique(image.dimension_values(1))

    #Create a slider widget to control x and y cut locations
    xw = widgets.SelectionSlider(options=[("%g" % i, i) for i in x_axis])
    yw = widgets.SelectionSlider(options=[("%g" % i, i) for i in y_axis])

    xyst = xy(x=x_axis[0], y=y_axis[0])

    #Define function that creates Holoviews Layout. This Layout contains
    #the original 2D image, lines going through the x,y point specified,
    #and the line cuts themselves
    def marker(x, y):
        x_dim = {image.kdims[0].label: x}
        y_dim = {image.kdims[1].label: y}
        crosssection1 = image.sample(**x_dim).opts(norm=dict(framewise=True))
        crosssection1y = image.sample(**y_dim).opts(norm=dict(framewise=True))
        return hv.Layout(image * hv.VLine(x) * hv.HLine(y) + crosssection1 +
                         crosssection1y).cols(2).opts(norm=dict(axiwise=True))

    #Create DynamicMap of above Layout such that the x,y positions can be

#streamed and updated
    dmap = hv.DynamicMap(marker, streams=[xyst])

    #Function that widget can call to update DynamicMap. When this Stream object
    #updates the x,y position via the Slider widget and then the event method
    #called, the DynamicMap recomputes marker based off this and thus updates
    #the line cut.
    def plot(x, y):
        xyst.event(x=x, y=y)

    hv.ipython.display(dmap)

    #Return statement is the syntax for interacting widgets (see ipywidget docs).
    return widgets.interact(
        plot,
        x=widgets.SelectionSlider(options=[("%g" % i, i) for i in x_axis],
                                  continuous_update=False),
        y=widgets.SelectionSlider(options=[("%g" % i, i) for i in y_axis]))
コード例 #2
0
def slider_interact(plot_function,
                    df,
                    options,
                    option_column,
                    initial_option=None,
                    option_label=None,
                    disabled=False,
                    button_style='',
                    **kwargs):
    if option_label is None:
        option_label = vh.labelfy(option_column)

    option_slider = widgets.SelectionSlider(
        options=options,
        value=options[0] if initial_option is None else initial_option,
        description=option_label,
        disabled=disabled,
        button_style=button_style)

    widgets.interact(plot_subset,
                     plot_function=widgets.fixed(plot_function),
                     df=widgets.fixed(df),
                     option=option_slider,
                     option_column=widgets.fixed(option_column),
                     kwargs=widgets.fixed(kwargs))
 def widget_dataset(self, dataset=None):
     """
     Parameters
     ----------
     dataset : str
         One of the keys of the instance attribute "datasets" such as "blobs",
         "circles", or "moons".
     Notes
     -----
     Displays the chosen dataset and calls other relevant widget methods.
     """
     if not dataset:
         return
     self.display = False
     self.split_data = False
     plt.close("all")
     self.fig_1, self.axs_1 = plt.subplots(1, 2, figsize=(8, 4))
     self.axs_1[1].axis("off")
     chosen_dataset = self.datasets[dataset]  # get_blobs
     ipywidgets.interact(chosen_dataset["widget"], **chosen_dataset["args"])
     ipywidgets.interact(
         self.choose_classifier,
         classifier=ipywidgets.Dropdown(
             options=["decision_tree", "logistic_regression"],
             value="decision_tree",
         ),
     )
     ipywidgets.interact(
         self.run_widget_dt,
         max_depth=ipywidgets.SelectionSlider(options=range(1, 20),
                                              value=1),
     )
コード例 #4
0
    def __init__(self,
                 filefilter,
                 processing=Generic2DPlotCtrl._idle,
                 **extra_kwargs):
        fp = filefilter + '/*.h5' if os.path.isdir(filefilter) else filefilter
        self.filter, self.flist, self.processing = fp, sorted(
            glob.glob(fp)), processing
        try:
            self.data = processing(osh5io.read_h5(self.flist[0]))
        except IndexError:
            raise IOError('No file found matching ' + fp)

        items_layout = Layout(flex='1 1 auto', width='auto')
        self.file_slider = widgets.SelectionSlider(options=self.flist,
                                                   description='filename:',
                                                   value=self.flist[0],
                                                   continuous_update=False,
                                                   layout=items_layout)
        self.time_label = widgets.Label(value=osh5vis.time_format(
            self.data.run_attrs['TIME'][0], self.data.run_attrs['TIME UNITS']),
                                        layout=items_layout)
        self.file_slider.observe(self.update_slice, 'value')

        super(DirSlicer, self).__init__(self.data,
                                        time_in_title=False,
                                        **extra_kwargs)
コード例 #5
0
ファイル: oscilloscope.py プロジェクト: zjarci/jupyter
        def __init__ (self, top, ch, input_range = 1.0):

            super().__init__(ch, input_range)
            self.top = top
            self.ch = ch

            self.reset()
            # decimation rate
            self.decimation = 1

            # trigger level [V] and edge
            self.level = [-0.1, +0.1]
            self.edge = 'pos'

            # control event mask
            self.sync_src = overlay.sync_src['osc0']
            self.trig_src = overlay.trig_src['osc0']
            # TODO: this default should be set in the oscilloscope application class

            # create widgets
            self.w_t_edge     = ipw.ToggleButtons    (value=self.edge, options=['pos', 'neg'], description='T edge')
            self.w_t_position = ipw.FloatRangeSlider (value=self.level, min=-1.0, max=+1.0, step=0.02, description='T position')
            self.w_y_position = ipw.FloatSlider      (value=self.y_position, min=-1.0, max=+1.0, step=0.01, description='Y position')
            self.w_y_scale    = ipw.SelectionSlider  (value=self.y_scale, options=self.y_scales, description='Y scale')

            # style widgets
            self.w_t_position.layout = ipw.Layout(width='100%')
            self.w_y_scale.layout    = ipw.Layout(width='100%')
            self.w_y_position.layout = ipw.Layout(width='100%')

            self.w_t_edge.observe     (self.clb_t_edge    , names='value')
            self.w_t_position.observe (self.clb_t_position, names='value')
            self.w_y_scale.observe    (self.clb_y_scale   , names='value')
            self.w_y_position.observe (self.clb_y_position, names='value')
コード例 #6
0
ファイル: editors.py プロジェクト: bmcs-group/bmcs_utils
    def render(self):
        if self.low_name:
            self.low = getattr(self.model, str(self.low_name))
        if self.high_name:
            self.high = getattr(self.model, str(self.high_name))
        if self.n_steps_name:
            self.n_steps = getattr(self.model, str(self.n_steps_name))
        step = (self.high - self.low) / self.n_steps

        round_value = self._get_round_value(self.low, self.high, self.n_steps)
        if not self.readout_format:
            self.readout_format = '.' + str(round_value) + 'f'

        # There's a bug in FloatSlider for very small step, see https://github.com/jupyter-widgets/ipywidgets/issues/259
        # it will be fixed in ipywidgets v8.0.0, but until then, the following fix will be used
        # with this implementation, entering the number manually in the readout will not work
        values = np.linspace(self.low, self.high, int(self.n_steps))
        values = np.round(values, round_value)

        # This is for SelectionSlider because 'value' must match exactly one of values array
        self.value = self._find_nearest(values, self.value)

        return ipw.SelectionSlider(
            options=values,
            value=self.value,
            tooltip=self.tooltip,
            continuous_update=self.continuous_update,
            description=self.label,
            disabled=self.disabled,
            readout=self.readout,
            style=style
        )
コード例 #7
0
def user_selection():
    global selected_persona, selected_percentile, selection_filter, variable_inputs

    selected_percentile = widgets.SelectionSlider(options=[
        '0', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%',
        '100%'
    ],
                                                  value='50%',
                                                  description='Percentile',
                                                  layout=Layout(
                                                      width='60%',
                                                      margin='30px 0 30px 0'))

    selected_persona = widgets.ToggleButtons(options=[
        'Boy', 'Teenage Boy', 'Young Man', 'Middle Aged Man', 'Old Man',
        'Girl', 'Teenage Girl', 'Young Woman', 'Middle Aged Woman', 'Old Woman'
    ],
                                             value='Young Woman',
                                             description='AGE:',
                                             layout=Layout(width='95%'))

    if (selected_persona.value == 'Boy'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('child')) & \
                              (data_dict.sex.str.contains('Male'))]
    elif (selected_persona.value == 'Girl'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('child')) & \
                              (data_dict.sex.str.contains('Female'))]

    elif (selected_persona.value == 'Teenage Boy'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('teenager')) & \
                              (data_dict.sex.str.contains('Male'))]
    elif (selected_persona.value == 'Teenage Girl'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('teenager')) & \
                              (data_dict.sex.str.contains('Female'))]

    elif (selected_persona.value == 'Young Man'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('young')) & \
                          (data_dict.sex.str.contains('Male'))]
    elif (selected_persona.value == 'Young Woman'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('young')) & \
                          (data_dict.sex.str.contains('Female'))]

    elif (selected_persona.value == 'Middle Aged Man'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('middle aged')) & \
                          (data_dict.sex.str.contains('Male'))]
    elif (selected_persona.value == 'Middle Aged Woman'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('middle aged')) & \
                          (data_dict.sex.str.contains('Female'))]

    elif (selected_persona.value == 'Old Man'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('old')) & \
                              (data_dict.sex.str.contains('Male'))]
    elif (selected_persona.value == 'Old Woman'):
        selection_filter = data_dict[(data_dict.age_category.str.contains('old')) & \
                              (data_dict.sex.str.contains('Female'))]

    list_of_variable_inputs = selection_filter["variables"].values[0:]
    variable_inputs = ', '.join(list_of_variable_inputs).replace(" ", "")
    variable_inputs = variable_inputs.split(',')
コード例 #8
0
            def joint_player(self):
                # no player for static view
                static = True
                for a in self.arg:
                    if not a.static:
                        static = False
                if static:
                    return

                # compute timeline
                timeline = []
                for v in self.arg:
                    p = v.ctrl.widgets["player"]
                    if p.timeline is not None:
                        timeline = timeline + p.timeline
                    timeline = list(set(timeline))
                    timeline.sort()
                self.timeline = timeline

                # init widgets
                self.player = widgets.Play(value=0, min=0,
                                           max=len(timeline) - 1,
                                           interval=150)
                self.slider = widgets.SelectionSlider(value=timeline[0],
                                                      options=timeline)
                self.speed = widgets.Dropdown(
                    options=[("1", 250), ("2", 200), ("3", 150), ("4", 100),
                             ("5", 50)],
                    value=150,
                    description="Speed:",
                    layout=widgets.Layout(
                        width="100px"
                    ),
                    style={
                        "description_width": "45px"
                    }
                )

                def on_slider_change(change):
                    t = change.new
                    self.player.value = self.timeline.index(t)
                    for v in self.arg:
                        p = v.ctrl.widgets["player"]
                        if p.slider is not None and t in p.slider.options:
                            p.slider.value = t

                self.slider.observe(on_slider_change, names="value")

                def on_player_change(change):
                    t = self.timeline[change.new]
                    self.slider.value = t
                    for v in self.arg:
                        p = v.ctrl.widgets["player"]
                        if p.slider is not None and t in p.slider.options:
                            p.slider.value = t

                self.player.observe(on_player_change, names="value")

                widgets.link((self.speed, "value"), (self.player, "interval"))
コード例 #9
0
ファイル: JupyterGUI.py プロジェクト: colbrydi/see-segment
def colorwidget(img, paramlist=None):
    """Display info to user on colorspace if paramlist is not empty."""
    if paramlist:
        seg = colorspace(paramlist=paramlist)
    else:
        seg = colorspace()

    print(f"seg.params = {seg.params}")
    widg = dict()
    widglist = []

    for ppp, ind in zip(seg.paramindexes, range(len(seg.paramindexes))):
        thislist = seg.params.ranges[ppp]
        name = ppp
        current_value = seg.params[ppp]
        if current_value not in thislist:
            # TODO: We should find the min distance between current_value and
            # this list and use that instead.
            current_value = thislist[0]

        thiswidg = widgets.SelectionSlider(
            options=tuple(thislist),
            disabled=False,
            description=name,
            value=current_value,
            continuous_update=False,
            orientation="horizontal",
            readout=True,
        )

        widglist.append(thiswidg)
        widg[ppp] = thiswidg

    def func(**kwargs):
        """Find mask and fitness for current algorithm. Show masked image."""
        for k in kwargs:
            seg.params[k] = kwargs[k]
        colorspace = seg.evaluate(img)

        # fit = Segmentors.FitnessFunction(mask, gmask)
        fig = showtwo(img, colorspace)
        showimage(
            img,
            ax=fig.gca(),
            color=seg.params["colorspace"],
            multichannel=seg.params["multichannel"],
            channel=seg.params["channel"],
        )
        # I like the idea of printing the sharepython but it should be below the figures.
        # print(seg.sharepython(img))

    #         plt.title('Fitness Value: ' + str(fit[0]))

    layout = widgets.Layout(grid_template_columns="1fr 1fr 1fr")
    u_i = widgets.GridBox(widglist, layout=layout)
    out = widgets.interactive_output(func, widg)
    display(u_i, out)

    return seg.params
コード例 #10
0
ファイル: oscilloscope.py プロジェクト: baj12/RedPitaya-1
        def __init__(self, top, ch, input_range=1.0):

            super().__init__(ch, input_range)
            self.top = top
            self.ch = ch

            self.reset()
            # TODO: for now bypass input filter
            self.filter_bypass = True
            # decimation rate
            self.decimation = 1

            # trigger level [V], edge and holdoff [periods]
            self.level = [-0.1, +0.1]
            self.edg = 'pos'
            self.holdoff = 0

            # trigger source mask
            #sh = 6*(ch+2)
            sh = 6 * (0 + 2)
            sh_t = 6 * (0 + 2)
            self.mask = [(0x1 << sh), (0x2 << sh), (0x4 << sh),
                         (0x8 << sh) | (0x10 << sh_t)]

            # create widgets
            self.w_t_edge = ipw.ToggleButtons(value=self.edge,
                                              options=['pos', 'neg'],
                                              description='T edge')
            self.w_t_position = ipw.FloatRangeSlider(value=self.level,
                                                     min=-1.0,
                                                     max=+1.0,
                                                     step=0.02,
                                                     description='T position')
            self.w_t_holdoff = ipw.FloatSlider(value=self.holdoff,
                                               min=0,
                                               max=1,
                                               step=0.1,
                                               description='T hold off')
            self.w_y_position = ipw.FloatSlider(value=self.y_position,
                                                min=-1.0,
                                                max=+1.0,
                                                step=0.01,
                                                description='Y position')
            self.w_y_scale = ipw.SelectionSlider(value=self.y_scale,
                                                 options=self.y_scales,
                                                 description='Y scale')

            # style widgets
            self.w_t_position.layout = ipw.Layout(width='100%')
            self.w_t_holdoff.layout = ipw.Layout(width='100%')
            self.w_y_scale.layout = ipw.Layout(width='100%')
            self.w_y_position.layout = ipw.Layout(width='100%')

            self.w_t_edge.observe(self.clb_t_edge, names='value')
            self.w_t_position.observe(self.clb_t_position, names='value')
            self.w_t_holdoff.observe(self.clb_t_holdoff, names='value')
            self.w_y_scale.observe(self.clb_y_scale, names='value')
            self.w_y_position.observe(self.clb_y_position, names='value')
コード例 #11
0
    def interact(self):
        """
        Display an interactive widget for choosing the profile.
        """
        # Setup the initial value options for the location
        dim = self.default_dimension
        dim2 = set(self.data.dims).difference({dim}).pop()
        options = self.data[dim2].values.tolist()[::self.profile_interval]
        mid = options[len(options)//2]

        # Make the slider for choosing the location
        slider_label = widgets.Label("at {} value".format(dim2))
        slider = widgets.SelectionSlider(options=options, value=mid,
                                         layout=widgets.Layout(width="350px"))
        # Make a menu for choosing the profile direction
        dimension_chooser = widgets.Dropdown(
            options=self.data.dims.keys(), value=dim,
            description="Profile along")

        def displayer(location, dimension):
            "Update and display the plot with given arguments"
            self.plot(location, dimension)
            display(self.fig)

        def handle_dimension_change(change):
            "Change the location options when dimension changes"
            dim2 = set(self.data.dims).difference({change.new}).pop()
            slider_label.value = "at {} value".format(dim2)
            options = self.data[dim2].values.tolist()[::self.profile_interval]
            slider.options = options
            slider.value = options[len(options)//2]

        # Connect the dimension change to the slider
        dimension_chooser.observe(handle_dimension_change, names='value')

        # Make the output display and connect it to the callback
        output = widgets.interactive_output(
            displayer, {'location': slider, 'dimension': dimension_chooser})

        # Make a title for the widget
        title = widgets.HTML(
            '<strong style="font-size: 1.5em;">Profile selector</strong>')

        # Layout the widgets
        layout = widgets.VBox(
            [title,
             widgets.HBox([dimension_chooser, slider_label, slider]),
             output],
            layout=widgets.Layout(align_items="center"))

        # For some reason, calling _figure_setup inserts a plot in the output
        # Call clear_output to get rid of it.
        with output:
            clear_output(wait=True)
            display(self.fig)

        return layout
コード例 #12
0
def _create_grouping_slider(value, target):
    return widgets.SelectionSlider(
        options=[freq_to_human_readable(freq) for freq in FREQUENCIES],
        value=value,
        description=f'Group {target} by:',
        disabled=False,
        continuous_update=True,
        orientation='horizontal',
        readout=True)
コード例 #13
0
ファイル: __init__.py プロジェクト: heatherguy/cube_browser
    def __init__(self, plots):
        """
        Compiles non-axis coordinates into sliders, the values from which are
        used to reconstruct plots upon movement of slider.

        Args:

        * plot
            cube_browser plot instance to display with slider.

        """
        if not isinstance(plots, Iterable):
            plots = [plots]
        self.plots = plots

        # Mapping of coordinate/alias name to axis.
        self._axis_by_name = {}
        # Mapping of cube-id to shared cache.
        self._cache_by_cube_id = {}
        # Mapping of plot-id to coordinate/alias name.
        self._names_by_plot_id = {}
        # Mapping of coordinate/alias name to plots.
        self._plots_by_name = {}
        self._build_mappings()

        self._slider_by_name = {}
        self._name_by_slider_id = {}
        if self._axis_by_name:
            name_len = max([len(name) for name in self._axis_by_name])
        children = []
        for axis in self._axis_by_name.values():
            if hasattr(axis, 'coord') and axis.coord.units.is_time_reference():
                pairs = [(axis.coord.units.num2date(axis.coord.points[i]), i)
                         for i in range(axis.size)]
            elif hasattr(axis, 'coord'):
                pairs = [(axis.coord.points[i], i) for i in range(axis.size)]
            else:
                pairs = [(i, i) for i in range(axis.size)]
            options = OrderedDict(pairs)
            slider = ipywidgets.SelectionSlider(options=options)
            slider.observe(self.on_change, names='value')
            self._slider_by_name[axis.name] = slider
            self._name_by_slider_id[id(slider)] = axis.name
            # Explicitly control the slider label in order to avoid
            # fix width widget description label wrapping issues.
            # XXX: Adjust px/em scale-factor dynamically based on font-size.
            scale_factor = .65
            width = u'{}em'.format(int(name_len * scale_factor))
            label = ipywidgets.Label(axis.name, padding=u'0.3em', width=width)
            hbox = ipywidgets.HBox(children=[label, slider])
            children.append(hbox)

        # Layout the sliders in a consitent order.
        self.form = ipywidgets.VBox()
        key = lambda hbox: hbox.children[0].value
        self.form.children = sorted(children, key=key)
コード例 #14
0
def slider(values, name, default=None):
    if default is None:
        default = values[0]
    return widgets.SelectionSlider(options=values,
                                   value=default,
                                   description=name,
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True)
コード例 #15
0
def get_widget(desc):
    w = widgets.SelectionSlider(options=desc['values'],
                                value=desc['default'],
                                description=desc['text'],
                                disabled=False,
                                continuous_update=False,
                                orientation='horizontal',
                                style={'description_width': '100px'},
                                readout=True)
    return w
コード例 #16
0
    def __init__(self, text="Upload Zip or Tar archive", node_class=None, **kwargs):
        """ Upload multiple structures and store them in AiiDA database.

        :param text: Text to display before upload button
        :type text: str
        :param node_class: AiiDA node class for storing the structure.
            Possible values: 'StructureData', 'CifData' or None (let the user decide).
            Note: If your workflows require a specific node class, better fix it here.
        """

        self.file_upload = FileUploadWidget(text)
        self.tmp_folder = None
        self.archive_name = ''
        # define the view part of the widget
        self.viewer = nglview.NGLWidget()
        self.selection_slider = ipw.SelectionSlider(
            options=[
                None,
            ],
            disabled=False,
            orientation='vertical',
            description='Browse structures:',
            readout=False,
            layout=Layout(width='50%'),
        )
        view = ipw.HBox([self.viewer, self.selection_slider])

        # define the action part of the widget
        self.btn_store_all = ipw.Button(description='Store all in AiiDA', disabled=True)
        self.btn_store_selected = ipw.Button(description='Store selected', disabled=True)
        self.structure_description = ipw.Text(placeholder="Description (optional)")
        self.data_format = ipw.RadioButtons(options=['StructureData', 'CifData'], description='Data type:')

        # if node_class is predefined, there is no need to select it afterwards
        if node_class is None:
            store = ipw.HBox(
                [self.btn_store_all, self.data_format, self.structure_description, self.btn_store_selected])
        else:
            store = ipw.HBox([self.btn_store_all, self.structure_description, self.btn_store_selected])
            self.data_format.value = node_class

        # define main data objects
        self.structure_ase = None  # contains the selected structure in the ase format
        self.structure_nodes = []  # a list that contains all stored structure objects
        self.structure_names = []  # list of uploaded structures

        # put all visual parts in children list and initialize the parent Vbox widget with it
        children = [self.file_upload, view, store]
        super(MultiStructureUploadWidget, self).__init__(children=children, **kwargs)

        # attach actions to the buttons
        self.file_upload.observe(self._on_file_upload, names='data')
        self.selection_slider.on_trait_change(self.change_structure, 'value')
        self.btn_store_all.on_click(self._on_click_store_all)
        self.btn_store_selected.on_click(self._on_click_store_selected)
 def __init__(self):
     self.datasets = {
         "blobs": {
             "widget": self.get_blobs,
             "args": {
                 "num_classes":
                 ipywidgets.SelectionSlider(options=[1, 2, 3, 4, 5],
                                            value=2),
                 "cluster_std":
                 ipywidgets.SelectionSlider(
                     options=[0.25, 0.5, 0.75, 1.0, 1.25, 1.5], value=1.0),
             },
         },
         "circles": {
             "widget": self.get_circles,
             "args": {
                 "noise":
                 ipywidgets.SelectionSlider(options=np.arange(0, 1, 0.05),
                                            value=0.1),
                 "scale_factor":
                 ipywidgets.SelectionSlider(
                     options=np.arange(0, 1, 0.1),
                     value=0.5,
                 ),
             },
         },
         "moons": {
             "widget": self.get_moons,
             "args": {},
         },
     }
     self.models_class = {
         "decision_tree": DecisionTreeClassifier,
         "logistic_regression": LogisticRegression,
     }
     self.scatter_count = 0
     self.clf_class = DecisionTreeClassifier
     self.classifier_string = "decision_tree"
     self.max_depth = 1
     self.display = False
     self.split_data = False
コード例 #18
0
    def getCreationPanel(self) -> ip.VBox:
        load: ip.Button = ip.Button(description="Create",
                                    layout=ip.Layout(flex='1 1 auto'),
                                    border='1px solid dimgrey')
        self._model_dims_selector: ip.SelectionSlider = ip.SelectionSlider(
            options=range(3, 50),
            description='Model Dimension:',
            value=self.model_dims,
            layout=ip.Layout(width="auto"),
            continuous_update=True,
            orientation='horizontal',
            readout=True,
            disabled=False)

        self._subsample_selector: ip.SelectionSlider = ip.SelectionSlider(
            options=range(1, 50),
            description='Subsample:',
            value=self.subsample,
            layout=ip.Layout(width="auto"),
            continuous_update=True,
            orientation='horizontal',
            readout=True,
            disabled=False)

        load.on_click(self.prepare_inputs)
        self._progress = ip.FloatProgress(value=0.0,
                                          min=0,
                                          max=1.0,
                                          step=0.01,
                                          description='Progress:',
                                          bar_style='info',
                                          orientation='horizontal',
                                          layout=ip.Layout(flex='1 1 auto'))
        button_hbox: ip.HBox = ip.HBox([load, self._progress],
                                       layout=ip.Layout(width="100%",
                                                        height="auto"))
        creationPanel: ip.VBox = ip.VBox(
            [self._model_dims_selector, self._subsample_selector, button_hbox],
            layout=ip.Layout(width="100%", height="100%"),
            border='2px solid firebrick')
        return creationPanel
コード例 #19
0
ファイル: PS1.py プロジェクト: ChampionApe/FinancialFriction
    def plot_interactive_sol(self):
        try:
            getattr(self, "sol_grid")
        except AttributeError:
            self.solgrid()

        def plot_from_dict(ph, B):
            contInvest.plot_instance(
                self.sol_grid[ph, B]['IR'], self.sol_base['IR'],
                self.sol_grid[ph, B]['Istar'], self.sol_base['Istar'],
                self.sol_grid[ph, B]['Sol'], self.sol_base['Sol'],
                self.grids['A'], self.sol_grid_ylim)

        prob = widgets.SelectionSlider(description="Probability, $p_H$",
                                       options=self.grids['pH'],
                                       style={'description_width': 'initial'})
        benefit = widgets.SelectionSlider(
            description="Private benefit, $B$",
            options=self.grids['B'],
            style={'description_width': 'initial'})
        widgets.interact(plot_from_dict, ph=prob, B=benefit)
コード例 #20
0
ファイル: PS2.py プロジェクト: ChampionApe/FinancialFriction
    def plot_interactive_ds(self):
        try:
            getattr(self, "ds_grid")
        except AttributeError:
            self.dsgrid()

        def plot_from_dict(n, lambda_):
            TwoAgent_GE.plot_ds_instance(self.ds_grid[n, lambda_]['d'],
                                         self.ds_base['d'],
                                         self.ds_grid[n, lambda_]['s'],
                                         self.ds_base['s'], self.grids['R'])

        nslider = widgets.SelectionSlider(
            description="Endowment, $n$",
            options=self.grids['n'],
            style={'description_width': 'initial'})
        lambda_slider = widgets.SelectionSlider(
            description="Borrowing constr., $\\lambda$",
            options=self.grids['lambda_'],
            style={'description_width': 'initial'})
        widgets.interact(plot_from_dict, n=nslider, lambda_=lambda_slider)
コード例 #21
0
ファイル: ui.py プロジェクト: hkejigu/ada-2018-uchicago
    def __init__(self, list_of_metrics):
        self.metric_dropdown = widgets.Dropdown(options=list_of_metrics,
                                                description='Metric')

        self.plot_toggle = widgets.ToggleButtons(
            options=['Count', 'Change'],
            value='Count',
            description='',
            disabled=False,
            button_style='',
            tooltips=['Display absolute counts', 'Display change over time'])

        options = [(" Q{} {} ".format(qtr, year), (qtr, year))
                   for year in range(2005, 2016) for qtr in range(1, 5)]
        self.time_slider = widgets.SelectionSlider(options=options,
                                                   description='Quarter',
                                                   disabled=False,
                                                   continuous_update=False,
                                                   layout=Layout(width='60%'))

        self.time_range_slider = widgets.SelectionRangeSlider(
            options=options,
            index=(0, len(options) - 1),
            description='Time Range',
            disabled=False,
            layout=Layout(width='60%'))
        self.time_range_slider.layout.visibility = 'hidden'

        self.generate_button = widgets.Button(description='Generate Plot',
                                              disabled=False,
                                              tooltip='Generate Plot')

        self.panel_items = [
            HBox([self.metric_dropdown]),
            HBox([self.plot_toggle]),
            VBox([self.time_slider, self.time_range_slider]),
            HBox([self.generate_button])
        ]

        self.input_panel = VBox(self.panel_items)

        self.output = Output()

        def on_value_change(change):
            if change['new'] == 'Count':
                self.time_range_slider.layout.visibility = 'hidden'
                self.time_slider.layout.visibility = 'visible'
            elif change['new'] == 'Change':
                self.time_slider.layout.visibility = 'hidden'
                self.time_range_slider.layout.visibility = 'visible'

        self.plot_toggle.observe(on_value_change, names='value')
コード例 #22
0
            def unit_player(self):
                # no player for static view
                if self.arg.static:
                    return

                # compute timeline
                layer, legend, profile = self.arg.get()
                temp_path = self.arg.temp_path
                file_list = self.arg.file_list
                timeline = [t.split(".")[0] for t in self.arg.file_list]
                timeline = [parser.parse(t) for t in timeline]
                self.timeline = timeline

                # init widgets
                self.player = widgets.Play(value=0, min=0,
                                           max=len(timeline) - 1,
                                           interval=150)
                self.slider = widgets.SelectionSlider(value=timeline[0],
                                                      options=timeline)
                self.speed = widgets.Dropdown(
                    options=[("1", 250), ("2", 200), ("3", 150), ("4", 100),
                             ("5", 50)],
                    value=150,
                    description="Speed:",
                    layout=widgets.Layout(
                        width="100px"
                    ),
                    style={
                        "description_width": "45px"
                    }
                )

                # slider change event
                def on_slider_change(change):
                    i = self.timeline.index(change.new)
                    self.player.value = i  # regarding change on player
                    img = os.path.join(temp_path, file_list[i])
                    layer.url = View.Layer.read_image(img)

                self.slider.observe(on_slider_change, names="value")

                # player change event
                def on_player_change(change):
                    t = self.timeline[change.new]
                    self.slider.value = t  # regarding change on slider
                    img = os.path.join(temp_path, file_list[change.new])
                    layer.url = View.Layer.read_image(img)

                self.player.observe(on_player_change, names="value")

                # speed change event
                widgets.link((self.speed, "value"), (self.player, "interval"))
コード例 #23
0
ファイル: JupyterGUI.py プロジェクト: syaffa/see-segment
def segmentwidget(img, gmask, params=None, alg=None):
    """Generate GUI. Produce slider for each parameter for the current segmentor.
     Show both options for the masked image.

    Keyword arguments:
    img -- original image
    gmask -- ground truth segmentation mask for the image
    params -- list of parameter options
    alg -- algorithm to search parameters over

    """
    if params is None and alg is None:
        alg = 'FB'
        params = [alg, 0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\
         (1, 1), 0, 'checkerboard', 'checkerboard', 0, 0, 0, 0, 0, 0]
    elif params is None and alg is not None:
        params = [alg, 0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\
         (1, 1), 0, 'checkerboard', 'checkerboard', 0, 0, 0, 0, 0, 0]
    elif params is not None and alg is not None:
        params[0] = alg
    seg = Segmentors.algoFromParams(params)
    widg = dict()
    widglist = []

    for ppp in seg.paramindexes:
        thislist = eval(seg.params.ranges[ppp])
        thiswidg = widgets.SelectionSlider(options=tuple(thislist),
                                           disabled=False,
                                           description=ppp,
                                           value=seg.params[ppp],
                                           continuous_update=False,
                                           orientation='horizontal',
                                           readout=True)
        widglist.append(thiswidg)
        widg[ppp] = thiswidg

    def func(img=img, mask=gmask, **kwargs):
        """Find mask and fitness for current algorithm. Show masked image."""
        print(seg.params["algorithm"])
        for k in kwargs:
            seg.params[k] = kwargs[k]
        mask = seg.evaluate(img)
        fit = Segmentors.FitnessFunction(mask, gmask)
        fig = showtwo(img, mask)
        plt.title('Fitness Value: ' + str(fit[0]))

    layout = widgets.Layout(grid_template_columns='1fr 1fr 1fr')
    u_i = widgets.GridBox(widglist, layout=layout)

    out = widgets.interactive_output(func, widg)
    display(u_i, out)
    return seg.params
コード例 #24
0
def interactive_plot(pathCDF):
    """ Interactive plot of all the variables of a NetCDF file.

    :param pathCDF: Path to the NetCDF file
    :type pathCDF: str
    :return: the interactive object for interactive plots
    :rtype: :class:`ipywidgets.widgets.interactive` object
    """
    resultsCDF = Dataset(pathCDF, 'r', format='NETCDF4', parallel=False)

    times = resultsCDF['t'][:].data
    times_ind = np.arange(len(times))

    disp_times = [
        '{}'.format(int(np.floor(times[k] // 3600))) +
        'h {}min'.format(int(np.floor(times[k] % 3600 // 60)))
        for k in times_ind
    ]

    vars_opts = list(resultsCDF.variables)
    cmap_opts = [
        'magma', 'Greys', 'hot', 'viridis', 'plasma', 'inferno', 'cividis'
    ]
    time_opts = [(disp_times[k], k) for k in times_ind]

    resultsCDF.close()

    vars_widg = widgets.ToggleButtons(options=vars_opts,
                                      value=vars_opts[0],
                                      description='variable :',
                                      disabled=False)

    time_widg = widgets.SelectionSlider(options=time_opts,
                                        value=0,
                                        description='t = ',
                                        continuous_update=False,
                                        disabled=False)

    cmap_widg = widgets.Select(options=cmap_opts,
                               value='magma',
                               description='colormap :',
                               disabled=False)

    inter = widgets.interactive(plot_data,
                                pathCDF=widgets.fixed(pathCDF),
                                cmap=cmap_widg,
                                variable=vars_widg,
                                time=time_widg)
    return inter
コード例 #25
0
ファイル: PS2.py プロジェクト: ChampionApe/FinancialFriction
    def plot_interactive_cequi(self):
        try:
            getattr(self, "c_grid")
        except AttributeError:
            self.capequigrid()

        def plot_from_dict(lambda_):
            TwoAgent_GE.plot_c_instance(self.c_grid[lambda_]['E'],
                                        self.c_base['E'], self.grids['n'])

        lambda_slider = widgets.SelectionSlider(
            description="Borrowing constr., $\\lambda$",
            options=self.grids['lambda_'],
            style={'description_width': 'initial'})
        widgets.interact(plot_from_dict, lambda_=lambda_slider)
コード例 #26
0
ファイル: PS2.py プロジェクト: ChampionApe/FinancialFriction
    def plot_interactive_pc(self):
        try:
            getattr(self, "I_grid")
        except AttributeError:
            self.pc_grid_of_I()

        def plot_from_dict(I):
            OptDebt.plot_pc_instance(self.I_grid[I]['I'], self.I_base['I'],
                                     self.grids['I'])

        I_slider = widgets.SelectionSlider(
            description="Investment cost, $I$",
            options=self.grids['I'],
            style={'description_width': 'initial'})
        widgets.interact(plot_from_dict, I=I_slider)
コード例 #27
0
def get_dates_widgets(options, index):
    monitoring_period_chooser = widgets.interactive(g,
         i=widgets.SelectionRangeSlider(
            options=options,
            index=index,
            description='Select the monitoring date range: ',
            style = {'description_width': 'initial'},
            orientation='horizontal',
            layout={'width': '800px',"height":"50px"}))

    history_period_chooser = widgets.interactive(g, 
         i=widgets.SelectionSlider(
            description="Start history period:", 
            options = options,
            style = {'description_width': 'initial'}))
    return monitoring_period_chooser, history_period_chooser
コード例 #28
0
def bar1():
    names = list(uploaded.keys())
    options = list()
    for name in names:
        options.append(tuple([name.split('.')[0], name]))
    interact(select_bar1,
             Name=widgets.Dropdown(
                 options=options,
                 value=names[0],
                 description='Employe:',
             ),
             Date=widgets.DatePicker(),
             ti=widgets.SelectionSlider(options=['Hourly', 'Quarterly'],
                                        value='Hourly',
                                        description='X-axis Interval: ',
                                        disabled=False))
コード例 #29
0
    def _common_control_generator(self):
        def unwrap_slider_val(callback):
            return lambda slider_val: callback(slider_val['new'])

        def update_nco(rf_block, nco_freq):
            mixer_cfg = rf_block.MixerSettings
            mixer_cfg['Freq'] = nco_freq
            rf_block.MixerSettings = mixer_cfg
            rf_block.UpdateEvent(xrfdc.EVENT_MIXER)

        def new_nco_slider(title):
            return ipw.FloatSlider(value=1000,
                                   min=620,
                                   max=1220,
                                   step=20,
                                   description=title,
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='.1f',
                                   style={'description_width': 'initial'})

        pow_slider = ipw.SelectionSlider(
            options=[0.1, 0.3, 0.6, 1],
            value=1,
            description='Transmit Power:',
            style={'description_width': 'initial'})
        pow_slider.observe(unwrap_slider_val(self.qpsk_tx.set_gain),
                           names='value')

        tx_nco_slider = new_nco_slider('TX Centre Frequency (MHz)')
        rx_nco_slider = new_nco_slider('RX Centre Frequency (MHz)')

        ipw.link((rx_nco_slider, 'value'), (tx_nco_slider, 'value'))
        tx_nco_slider.observe(
            unwrap_slider_val(lambda v: update_nco(self.dac_block, v)),
            names='value')
        rx_nco_slider.observe(
            unwrap_slider_val(lambda v: update_nco(self.adc_block, v)),
            names='value')

        control_widgets = ipw.Accordion(
            children=[ipw.VBox([pow_slider, tx_nco_slider, rx_nco_slider])])
        control_widgets.set_title(0, 'System Control')

        return control_widgets
コード例 #30
0
    def _create_widgets(self):
        """Create menu and parameter widgets"""

        self.widget_out = ipywidgets.Output(
            layout={'border': '1px solid black'})

        self._menu_widgets()
        widgets_params = {}
        for name, param in self.params.items():
            init_val = param[(len(param) - 1) // 2]
            w = ipywidgets.SelectionSlider(
                options=param,
                value=init_val,
                description=f'{name}:',
                continuous_update=self.continuous_update,
                readout=True)
            w.observe(self._update_display, names='value')
            widgets_params[name] = w

        self.widgets_params = widgets_params