Ejemplo n.º 1
0
def simulate_R0_unmitigated_plot(simulate_R0_unmitigated):
    w = interactive(simulate_R0_unmitigated,
                    R_0=widgets.FloatSlider(min=1,
                                            max=7,
                                            step=0.1,
                                            value=2,
                                            description='R0:',
                                            continuous_update=False),
                    column=widgets.Dropdown(options=[
                        'Infected (symptomatic)', 'Hospitalised', 'Critical',
                        'Deaths'
                    ],
                                            value='Infected (symptomatic)',
                                            description='Category:'))
    words = widgets.Label(
        'Impact of R0 value on the do nothing scenario outcomes')
    container = widgets.VBox([words, w])
    container.layout.width = '100%'
    container.layout.border = '2px solid grey'
    container.layout.justify_content = 'space-around'
    container.layout.align_items = 'center'
    return container
Ejemplo n.º 2
0
def rebinnable_interactive_histogram(series, initial_bin_width=10):
    figure_widget = go.FigureWidget(
        data=[go.Histogram(x=series, xbins={"size": initial_bin_width})])

    bin_slider = widgets.FloatSlider(
        value=initial_bin_width,
        min=1,
        max=30,
        step=1,
        description="Bin width:",
        readout_format=".0f",  # display as integer
    )

    histogram_object = figure_widget.data[0]

    def set_bin_size(change):
        histogram_object.xbins = {"size": change["new"]}

    bin_slider.observe(set_bin_size, names="value")

    output_widget = widgets.VBox([figure_widget, bin_slider])
    return output_widget
Ejemplo n.º 3
0
    def snapshot_slider(self, var: str = 'index') -> widgets.interactive:
        """Returns a slider that updates all Snapshot objects.

        Returns a slider from the ipywidgets library.

        Args:
            var: What variable the slider uses, either 'index' or 'time'.
        """
        if var.lower() == 'index':
            return widgets.interactive(self.set_snapshot_index,
                                       index=widgets.IntSlider(min=0,
                                                               max=len(self.times) - 1,
                                                               layout=widgets.Layout(width='100%'),
                                                               step=1))
        elif var.lower() == 'time':
            return widgets.interactive(self.set_snapshot_time,
                                       time=widgets.FloatSlider(min=self.times[0],
                                                                max=self.times[-1],
                                                                layout=widgets.Layout(width='100%'),
                                                                step=0.01))
        else:
            raise ValueError("var must be either 'index' or 'time'.")
Ejemplo n.º 4
0
    def __init__(self, format=None, *args, **kwargs):
        description = kwargs.pop('description', 'FloatSlider')
        min = kwargs.setdefault('min', 0.0)
        max = kwargs.setdefault('max', 10.0)
        self.formatstring = format
        self.header = ipy.HTML()
        self.readout = ipy.Text(width=100)
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **kwargs)
        self.minlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(
            self.formatstring.format(min)))
        self.maxlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(
            self.formatstring.format(max)))
        self.sliderbox = ipy.HBox([self.minlabel, self.slider, self.maxlabel])
        traitlets.link((self, 'description'), (self.header, 'value'))
        traitlets.link((self, 'value'), (self.slider, 'value'))
        self.description = description
        self.update_readout()
        super(ReadoutFloatSlider,
              self).__init__([self.header, self.readout, self.sliderbox])
Ejemplo n.º 5
0
    def get_widgets(self):
        """return the slider widget that are to be used

        :returns: widget_list: the list of widgets in order
                  widget_dict: a dictionary of the widget to be used in `interact

        :todo: make the sliders smaller: http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html
        """
        coeff = self.eigen_decomp.C
        widge_dict = {}
        widge_list = []
        for i in range(self.eigen_decomp.n):
            if coeff[i] > 0:
                r = [0, coeff[i] * 2]
            else:
                r = [coeff[i] * 2, 0]

            widge_list.append(widgets.FloatSlider(min=r[0],max=r[1],step=(r[1]-r[0])/10.,\
                                                  value=coeff[i],orientation='vertical',decription='v'+str(i)))
            widge_dict['c' + str(i)] = widge_list[-1]

        return widge_list, widge_dict
    def __init__(self, layer, map):
        self.layer = layer
        self.map = map

        visible = widgets.Checkbox(value=layer.visible,
                                   layout=initial_width,
                                   indent=False)
        widgets.jslink((visible, "value"), (layer, "visible"))
        self._widgets["visible"] = visible
        opacity = widgets.FloatSlider(
            value=layer.opacity,
            min=0,
            max=1,
            step=0.01,
            continuous_update=True,
            readout=False,
            layout=widgets.Layout(max_width="50px", min_width="20px"),
        )
        widgets.jslink((opacity, "value"), (layer, "opacity"))
        self._widgets["opacity"] = opacity

        super().__init__(layer, map)
Ejemplo n.º 7
0
def NumericalMethods():
    """
		Main function for called by notebook to produce plots and UI
	"""
    steps_sldr = widgets.IntSlider(value=3,
                                   description='Steps',
                                   min=0,
                                   max=50,
                                   continuos_update=False)
    h_sldr = widgets.FloatSlider(
        value=0.5,
        description='Step Size',
        min=0.1,
        max=1,
        step=0.1,
    )
    solver_drp = widgets.Dropdown(options=['Euler', 'Improved Euler'],
                                  description='Solver Type')
    eqn_drp = widgets.Dropdown(options=["dydx = -y +1", "dy/dx = cos(x)"],
                               description='Derivative')
    showSln_chk = widgets.Checkbox(value=False, description='Show Solution')
    grad_chk = widgets.Checkbox(value=False,
                                description='Show Next Gradient Evaluations')

    return widgets.VBox([
        widgets.VBox([
            widgets.HBox([h_sldr, eqn_drp, grad_chk]),
            widgets.HBox([steps_sldr, solver_drp, showSln_chk])
        ]),
        widgets.interactive_output(
            RunMethod, {
                'h': h_sldr,
                'steps': steps_sldr,
                'method': solver_drp,
                'eqnKey': eqn_drp,
                'showSln': showSln_chk,
                'showGrad': grad_chk
            })
    ])
Ejemplo n.º 8
0
 def single_img_bulk_wdgt(self):
     options = [
         'matched_gts', 'unmatched_gts', 'matched_dts', 'unmatched_dts'
     ]
     assert len(self.imgIds) == 1
     interface = interactive(self._single_img_bulk_wdgt_logic,
                             which_to_display=widgets.SelectMultiple(
                                 options=options,
                                 value=options,
                                 rows=4,
                             ),
                             dts_score_threshold=widgets.FloatSlider(
                                 value=0.0,
                                 min=0,
                                 max=1.0,
                                 step=0.05,
                                 description='dt score threshold: ',
                                 continuous_update=False,
                                 readout=True,
                                 readout_format='.2f',
                             ))
     return interface
Ejemplo n.º 9
0
def toon_voorspellingen():
    fig, big_axes = plt.subplots(figsize=(14, 5), nrows=2, ncols=1, sharex=True, sharey=True)
    fig.subplots_adjust(hspace=0.25)

    big_axes[0].set_title("Afbeeldingen met stoma")
    big_axes[1].set_title("Afbeeldingen zonder stoma")
    big_axes[0].set_axis_off()
    big_axes[1].set_axis_off()

    axes = []
    images = model['stoma_patches'] + model['no_stoma_patches']
    for i, image in enumerate(images):
        im = Image.open(os.path.join(image_dir, image['name']))
        ax = fig.add_subplot(2, 6, i + 1)
        ax.imshow(im)
        for spine in ax.spines.values():
            spine.set_linewidth(2)
        axes.append(ax)

        xlabel = "Pred: {:f}".format(float(image['prediction']))
        ax.set_xlabel(xlabel)

        ax.set_xticks([])
        ax.set_yticks([])

    plt.close()

    def change_threshold(thr=0.5):
        for i, image in enumerate(images):
            if (float(image['prediction']) < thr and image in model['stoma_patches']) or (float(image['prediction']) > thr and image in model['no_stoma_patches']):
                for spine in axes[i].spines.values():
                    spine.set_edgecolor('r')
            else:
                for spine in axes[i].spines.values():
                    spine.set_edgecolor('g')

        display(fig)

    widgets.interact(change_threshold, thr=widgets.FloatSlider(value=0.5, min=0.05, max=0.99, step=0.05, continuous_update=False))
Ejemplo n.º 10
0
	def control(self, max_opacity=0.2):
		import ipywidgets
		l1 = ipywidgets.FloatSlider(min=0, max=1, value=self.level1)
		l2 = ipywidgets.FloatSlider(min=0, max=1, value=self.level2)
		l3 = ipywidgets.FloatSlider(min=0, max=1, value=self.level3)
		o1 = ipywidgets.FloatSlider(min=0, max=max_opacity, step=0.001, value=self.opacity1)
		o2 = ipywidgets.FloatSlider(min=0, max=max_opacity, step=0.001, value=self.opacity2)
		o3 = ipywidgets.FloatSlider(min=0, max=max_opacity, step=0.001, value=self.opacity2)
		ipywidgets.jslink((self, 'level1'), (l1, 'value'))
		ipywidgets.jslink((self, 'level2'), (l2, 'value'))
		ipywidgets.jslink((self, 'level3'), (l3, 'value'))
		ipywidgets.jslink((self, 'opacity1'), (o1, 'value'))
		ipywidgets.jslink((self, 'opacity2'), (o2, 'value'))
		ipywidgets.jslink((self, 'opacity3'), (o3, 'value'))
		return ipywidgets.VBox(
			[ipywidgets.HBox([ipywidgets.Label(value="levels:"), l1, l2, l3]), ipywidgets.HBox([ipywidgets.Label(value="opacities:"), o1, o2, o3])]
		)
Ejemplo n.º 11
0
def plot_isosurface(data,
                    level=None,
                    color=default_color,
                    wireframe=True,
                    surface=True,
                    controls=True):
    from skimage import measure
    if level is None:
        level = np.median(data)
    verts, triangles = measure.marching_cubes(
        data, level)  #, spacing=(0.1, 0.1, 0.1))
    x, y, z = verts.T
    mesh = plot_trisurf(x, y, z, triangles=triangles, color=color)
    if controls:
        vmin, vmax = np.percentile(data, 1), np.percentile(data, 99)
        level_slider = ipywidgets.FloatSlider(value=level,
                                              min=vmin,
                                              max=vmax,
                                              icon='eye')
        recompute_button = ipywidgets.Button(description='update')
        controls = ipywidgets.HBox(children=[level_slider, recompute_button])
        current.container.children += (controls, )

        def recompute(*_ignore):
            level = level_slider.value
            recompute_button.description = "updating..."
            verts, triangles = measure.marching_cubes(
                data, level)  # , spacing=(0.1, 0.1, 0.1))
            x, y, z = verts.T
            with mesh.hold_sync():
                mesh.x = x
                mesh.y = y
                mesh.z = z
                mesh.triangles = triangles.astype(dtype=np.uint32)
                recompute_button.description = "update"

        recompute_button.on_click(recompute)
    return mesh
Ejemplo n.º 12
0
def poly_regression(func_to_fit=np.sqrt, x_range=(1, 50), num_points=None):
    global NUM_POINTS
    global l1, l2, x, y, y_hat, fig, ax, func
    func = func_to_fit
    if num_points is not None:
        NUM_POINTS = min(NUM_POINTS, num_points)
    fig = plt.figure(figsize=(8, 5))
    ax = fig.add_subplot(111)
    # fig, ax = plt.subplots()
    fig.tight_layout()
    plt.subplots_adjust(bottom=0.25)
    axcolor = "lightgoldenrodyellow"
    # noise = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    # degree = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
    # snoise = Slider(noise, "Noise", 0, 1.0, valinit=0.2)
    # sdegree = Slider(degree, "Degree", 1, 30, valinit=3, valstep=1)

    x = np.linspace(x_range[0], x_range[1], NUM_POINTS)
    y = get_noisy_func(x, 0.2, func)
    y_hat = get_polynomial_fit(x, y, 3)
    l1 = ax.scatter(x, y, alpha=0.8)
    l2 = ax.plot(x, y_hat, c="r", lw=3)

    # snoise.on_changed(lambda val: update_noise(sdegree.val, val))
    # sdegree.on_changed(update_degree)

    interact(update_degree,
             val=widgets.IntSlider(value=2, min=1, max=30, step=1))
    widgets.interact(
        lambda noise: update_noise(degree, noise, func),
        noise=widgets.FloatSlider(value=0.3, min=0, max=1, step=0.001),
    )
    # resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    # button = Button(resetax, "Reset", color=axcolor, hovercolor="0.975")
    # button.on_clicked(reset)

    plt.title("Polynomial Regression")
    plt.show()
Ejemplo n.º 13
0
    def __init__(self,
                 iquery,
                 description,
                 construct,
                 default=0,
                 max=1.0,
                 step=0.01):
        self._construct = construct
        self._iquery = iquery

        self._cost = widgets.FloatSlider(value=default,
                                         min=0,
                                         max=max,
                                         step=step,
                                         description=description,
                                         disabled=False)
        '''
		self._cost = widgets.BoundedFloatText(
			value=0,
			min=0,
			max=max,
			step=0.1,
			description=description,
			disabled=False)
		'''

        self._plot = widgets.Image(
            value=b'',
            format='png',
            width=300,
            height=400,
        )

        self.update_plot()
        self._cost.observe(self.on_changed, names='value')

        self._vbox = widgets.VBox([self._cost, self._plot],
                                  layout=widgets.Layout(border='solid'))
Ejemplo n.º 14
0
def figure(key=None, width=400, height=500, lighting=True, controls=True, controls_vr=False, debug=False, **kwargs):
    """Create a new figure (if no key is given) or return the figure associated with key

    :param key: Python object that identifies this figure
    :param width: pixel width of WebGL canvas
    :param height:  .. height ..
    :param lighting: use lighting or not
    :param controls: show controls or not
    :param controls_vr: show controls for VR or not
    :param debug: show debug buttons or not
    :return:
    """
    if key is not None and key in current.figures:
        current.figure = current.figures[key]
        current.container = current.containers[key]
    else:
        current.figure = volume.Figure(volume_data=None, width=width, height=height, **kwargs)
        current.container = ipywidgets.VBox()
        current.container.children = [current.figure]
        if key is not None:
            current.figures[key] = current.figure
            current.containers[key] = current.container
        if controls:
            stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
            fullscreen = ipywidgets.ToggleButton(value=current.figure.stereo, description='fullscreen',
                                                 icon='arrows-alt')
            l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
            l2 = ipywidgets.jslink((current.figure, 'fullscreen'), (fullscreen, 'value'))
            current.container.children += (ipywidgets.HBox([stereo, fullscreen]),)
        if controls_vr:
            eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')
            ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))
            current.container.children += (eye_separation,)
        if debug:
            show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front"])
            current.container.children += (show,)
            ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
    return current.figure
Ejemplo n.º 15
0
def phase_shift(holo, roi, phase=0):
    '''
    starts the quest for the global phase shift.
    Input:  the shifted, masked and propagated hologram
            coordinates of the ROI in the order [Xstart, Xstop, Ystart, Ystop]
    Returns the two sliders. When you are finished, you can save the positions of the sliders.
    -------
    author: KG 2019
    '''
    fig, axs = plt.subplots(1,2)
    def p(x):
        image = fth.reconstruct(holo*np.exp(1j*x))
        ax1 = axs[0].imshow(np.real(image[roi[2]:roi[3], roi[0]:roi[1]]), cmap='gray')
        #fig.colorbar(ax1, ax=axs[0], fraction=0.046, pad=0.04)
        axs[0].set_title("Real Part")
        ax2 = axs[1].imshow(np.imag(image[roi[2]:roi[3], roi[0]:roi[1]]), cmap='gray')
        #fig.colorbar(ax2, ax=axs[1], fraction=0.046, pad=0.04)
        axs[1].set_title("Imaginary Part")
        fig.tight_layout()
        print('REAL: max=%i, min=%i'%(np.max(np.real(image)), np.min(np.real(image))))
        print('IMAG: max=%i, min=%i'%(np.max(np.imag(image)), np.min(np.imag(image))))
        return

    layout = widgets.Layout(width='90%')
    style = {'description_width': 'initial'}
    slider_phase = widgets.FloatSlider(min=-np.pi, max=np.pi, step=0.001, value=phase, layout=layout, description='phase shift', style=style)

    widgets.interact(p, x=slider_phase)

    #input("Press the <ENTER> key to continue...")
    button = widgets.Button(description="Finished")
    display(button)
    
    def on_button_clicked(b):
        slider_phase.close()
        return
    button.on_click(on_button_clicked)
    return (slider_phase, button)
Ejemplo n.º 16
0
    def dynamic_plot(self, testing=False, step=None):
        """
        Generate a dynamic plot with a slider to control the time.

        Parameters
        ----------
        step : float
            For notebook mode, size of steps to allow in the slider. Defaults to 1/100th
            of the total time.
        testing : bool
            Whether to actually make the plot (turned off for unit tests)

        """
        if pybamm.is_notebook():  # pragma: no cover
            import ipywidgets as widgets

            step = step or self.max_t / 100
            widgets.interact(
                self.plot,
                t=widgets.FloatSlider(min=0, max=self.max_t, step=step, value=0),
                continuous_update=False,
            )
        else:
            import matplotlib.pyplot as plt
            from matplotlib.widgets import Slider

            # create an initial plot at time 0
            self.plot(0)

            axcolor = "lightgoldenrodyellow"
            ax_slider = plt.axes([0.315, 0.02, 0.37, 0.03], facecolor=axcolor)
            self.slider = Slider(
                ax_slider, "Time [{}]".format(self.time_unit), 0, self.max_t, valinit=0
            )
            self.slider.on_changed(self.slider_update)

            if not testing:  # pragma: no cover
                plt.show()
Ejemplo n.º 17
0
def simulate(iT=100,
             deta=0.8,
             dsigma=0.8,
             dbeta=0.0,
             dalpha=1.0,
             dphi=0.5,
             dlambda=0.0,
             dpstar=0.0,
             dy_pot=1.0,
             drstar=0.05,
             dpi_t=0.2,
             iShock=5):

    widgets.interact(
        simulate_,
        deta=widgets.fixed(deta),
        dsigma=widgets.fixed(dsigma),
        dbeta=widgets.fixed(dbeta),
        dalpha=widgets.fixed(dalpha),
        dphi=widgets.fixed(dphi),
        dlambda=widgets.fixed(dlambda),
        dpstar=widgets.fixed(dpstar),
        dy_pot=widgets.fixed(dy_pot),
        drstar=widgets.fixed(drstar),
        dpi_t=widgets.FloatSlider(
            # description="$\\pi$", min=0.01, max=5, step=0.01, value= dpi
            description="$\\tilde{\\pi}$",
            min=0.01,
            max=0.999,
            step=0.01,
            value=dpi_t,
            readout=True),
        # iShock= widgets.FloatSlider(
        #     description="Shock period", min=1, max=99, step=1, value= iShock
        # ),
        iShock=widgets.fixed(iShock),
        iT=widgets.fixed(iT),
    )
Ejemplo n.º 18
0
    def __init__(self, overtones, basis=lambda p: np.sin(tau * p)):
        if isinstance(overtones, int):
            overtones = [1 << i for i in range(overtones)]
        self.overtones = tuple(overtones)
        self.basis = basis
        self.sliders = []
        for overtone in self.overtones:
            self.sliders.append(
                widgets.FloatSlider(description="#{}".format(overtone),
                                    value=0,
                                    min=0,
                                    max=1,
                                    step=0.01,
                                    orientation="vertical"))
        self.offsets = np.zeros(len(overtones))
        self.randomizer = widgets.Button(description="Randomize phase")
        self.randomizer.on_click(lambda args: self.randomize_phase())

        self.el = widgets.VBox([
            widgets.Label("Overtones"),
            widgets.HBox(self.sliders),
            self.randomizer,
        ])
Ejemplo n.º 19
0
def test_create_facade(widgets_fix):
    # Composite widget with all components and default names
    p = pqef.ParameterWidget()
    f = pqef.create_facade(p)
    for name in pqef.ParameterCallbacksMixin.widget_names:
        assert f[name] is p.__dict__[name]

    # Composite widget with all components and custom names
    p = widgets_fix['CustomParm']()
    mapping = widgets_fix['mapping']
    f = pqef.create_facade(p, mapping=mapping)
    for name in pqef.ParameterCallbacksMixin.widget_names:
        assert f[name] is p.__dict__[mapping[name]]

    # Single widget with default target
    p = ipyw.FloatSlider()
    f = pqef.create_facade(p)
    assert f['value'] is p

    # Single widget with custom target
    p = ipyw.Checkbox(value=True)
    f = pqef.create_facade(p, 'vary')
    assert f['vary'] is p
Ejemplo n.º 20
0
def multi_pump_widget(aremote, pumps):
    # Multiple pump UI (i.e., one button to start multiple pumps simultaneously)
    pulses = ipw.IntSlider(min=0, max=125, value=25, description='Pulses')
    period = ipw.FloatSlider(min=0., max=125., value=1.,
                             description='Period (s)')
    button_pump = ipw.Button(description='Pump', tooltip='''\
    1) Use checkboxes to select one or more pumps.
    2) Select number of pulses.
    3) Click here to execute pulses.'''.strip())
    checkboxes = ipw.VBox([ipw.Checkbox(description=name_i, index=True)
                           for name_i in pumps])
    sliders = ipw.VBox([pulses, period])

    def on_multi_pump(pulses, period, *args, **kwargs):
        for c in checkboxes.children:
            if c.value:
                pump = pumps[c.description]
                do_pump(aremote, pump['addr'], pump['index'], pulses, period)

    button_pump.on_click(ft.partial(on_multi_pump, pulses, period))

    multi_pump_ui = ipw.HBox([checkboxes, sliders, button_pump])
    return multi_pump_ui
Ejemplo n.º 21
0
def sliders(
    field,
    datasetYamlPath="/global/u2/d/danieltm/ExaTrkX/eta-tracker/notebooks/datasetConfig.yaml"
):
    with open(datasetYamlPath, "r") as f:
        datasetConfig = yaml.safe_load(f)
    kwargs = {
        k: widgets.FloatSlider(
            value=v['default'],
            min=v['min'],
            max=v['max'],
            step=0.1,
            description='%s' % k,
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )
        for k, v in datasetConfig[field].items()
    }
    #     kwargs = {'w{}'.format(i):slider for i, slider in enumerate(weight_sliders)}
    return kwargs
Ejemplo n.º 22
0
 def __init__(self, dataset, *args, **kwargs):
     super(Nearest, self).__init__(*args, **kwargs)
     self.dataset = dataset
     feature_names = list(dataset.feature_names)
     self.x_name = feature_names[0]
     self.y_name = feature_names[1]
     sc = self.scatter_plot = js_proxy.ProxyWidget()
     xd = self.x_dropdown = widgets.Dropdown(
         options=list(feature_names), value=self.x_name)
     yd = self.y_dropdown = widgets.Dropdown(
         options=list(feature_names), value=self.y_name)
     bc = self.border_checkbox = widgets.Checkbox(description="border", value=True)
     ic = self.interior_checkbox = widgets.Checkbox(description="interior", value=True)
     tc = self.training_checkbox = widgets.Checkbox(description="training", value=True)
     tstc = self.test_checkbox = widgets.Checkbox(description="test", value=True)
     ns = self.n_slider = widgets.IntSlider(value=self.n_neighbors, min=1, max=20,
         description="neighbors", width="50px")
     ss = self.n_slider = widgets.FloatSlider(value=self.n_neighbors, min=0.2, max=0.5,
         description="test size", width="50px", step=0.1)
     traitlets.directional_link((ss, "value"), (self, "test_size"))
     traitlets.directional_link((xd, "value"), (self, "x_name"))
     traitlets.directional_link((yd, "value"), (self, "y_name"))
     traitlets.directional_link((bc, "value"), (self, "show_borders"))
     traitlets.directional_link((ic, "value"), (self, "prediction_grid"))
     traitlets.directional_link((ns, "value"), (self, "n_neighbors"))
     traitlets.directional_link((tc, "value"), (self, "show_training"))
     traitlets.directional_link((tstc, "value"), (self, "show_test"))
     xd.on_trait_change(self.redraw, "value")
     ss.on_trait_change(self.redraw, "value")
     yd.on_trait_change(self.redraw, "value")
     bc.on_trait_change(self.redraw, "value")
     tc.on_trait_change(self.redraw, "value")
     ic.on_trait_change(self.redraw, "value")
     tstc.on_trait_change(self.redraw, "value")
     ns.on_trait_change(self.redraw, "value")
     controls = widgets.VBox(children=[xd, yd, bc, ic, tc, tstc, ns, ss])
     self.assembly = widgets.HBox(children=[controls, sc])
Ejemplo n.º 23
0
    def iplot(self, name):
        #        allfields = list(self.field.keys())
        F = self.field[name]
        fieldmin = np.min(F)
        fieldmax = np.max(F)
        timeselector = widgets.FloatSlider(min=self.ts.times[0],
                                           max=self.ts.times[-1],
                                           step=(self.ts.times[1] -
                                                 self.ts.times[0]),
                                           value=self.ts.times[0])
        self.vrange = widgets.FloatRangeSlider(min=fieldmin,
                                               max=fieldmax,
                                               step=(fieldmax - fieldmin) / 10,
                                               value=(fieldmin, fieldmax))

        self._init_patch_plot = True
        self.plotwidget = interactive(
            self._plot_patch,
            F=fixed(F),
            name=fixed(name),
            time=timeselector,
            value_range=self.vrange,
        )
        display(self.plotwidget)
Ejemplo n.º 24
0
def _generate_widget(boundaries, description, width=0.8, step=0.001):
    bound_min, bound_max = boundaries
    if type(bound_min) == float or type(bound_max) == float:
        new_widget = widgets.FloatSlider(
            description=description,
            min=bound_min,
            max=bound_max,
            step=step,
            layout=widgets.Layout(width=f'{width*100}%'))
    elif type(bound_min) == int or type(bound_max) == int:
        new_widget = widgets.IntSlider(
            description=description,
            min=bound_min,
            max=bound_max,
            step=step,
            layout=widgets.Layout(width=f'{width*100}%'))
    elif type(bound_min) == bool or type(bound_max) == bool:
        new_widget = widgets.Checkbox(
            description=description,
            min=bound_min,
            max=bound_max,
            step=step,
            layout=widgets.Layout(width=f'{width*100}%'))
    return new_widget
Ejemplo n.º 25
0
def quick_sliders(obj, throttling=None, continuous_update=True, **kwargs):
    def create_callback(key):
        def callback(change):
            setattr(obj, key, change['new'])

        if throttling:
            return throttle(throttling)(callback)
        else:
            return callback

    sliders = []
    for key, value in kwargs.items():
        slider = widgets.FloatSlider(value=getattr(obj, key),
                                     min=value[0],
                                     max=value[1],
                                     step=value[2],
                                     description=key,
                                     continuous_update=continuous_update)

        slider.observe(create_callback(key), 'value')

        sliders += [slider]

    return sliders
Ejemplo n.º 26
0
def add_widgets(msg_instance, widget_dict, widget_list, prefix=''):
    """
    Adds widgets.
    
    @param msg_type The message type
    @param widget_dict The form list
    @param widget_list The widget list
    
    @return widget_dict and widget_list
    """
    # import only here so non ros env doesn't block installation
    from genpy import Message

    for idx, slot in enumerate(msg_instance.__slots__):
        attr = getattr(msg_instance, slot)
        s_t = msg_instance._slot_types[idx]
        w = None

        if s_t in ['float32', 'float64']:
            w = widgets.FloatSlider()
        if s_t in ['int8', 'uint8', 'int32', 'uint32', 'int64', 'uint64']:
            w = widgets.IntSlider()
        if s_t in ['string']:
            w = widgets.Text()

        if isinstance(attr, Message):
            widget_list.append(widgets.Label(value=slot))
            widget_dict[slot] = {}
            add_widgets(attr, widget_dict[slot], widget_list, slot)

        if w:
            widget_dict[slot] = w
            w_box = widgets.HBox([widgets.Label(value=slot), w])
            widget_list.append(w_box)

    return widget_dict, widget_list
Ejemplo n.º 27
0
def channel_properties():

    w = ipywidgets.IntSlider(value=default_width,
                             min=5,
                             max=max_channel_width,
                             step=5,
                             description='Width [m]')

    d = ipywidgets.FloatSlider(value=default_depth,
                               min=0,
                               max=5,
                               step=0.25,
                               description='Depth [m]')

    s = ipywidgets.IntSlider(value=default_slope,
                             min=1,
                             max=10,
                             step=1,
                             description='Slope [1:x]')

    res = interactive(_plot_channel, width=w, depth=d, slope=s)
    display(res)

    return res
Ejemplo n.º 28
0
    def interact(self):

        vec_row2 = []
        for sp in sorted(self.__scaling_parameters.keys()):
            (value, value_min, value_max, step) = self.__scaling_parameters[sp]
            vec_row2.append(ipyw.Label("%s: " % (sp)))
            new_slider = ipyw.FloatSlider(value=value, min=value_min, max=value_max, step=step)

            vec_row2.append(new_slider)
            self.__scaling_widgets[new_slider] = sp
            new_slider.observe(self.on_slider_change, names=['value'])

        display(
            ipyw.VBox([
                ipyw.HBox([ipyw.Label("%s: " % (self.separated_vars)), self.dd_filter, self.select_xscale,
                           self.select_yscale]),
                ipyw.HBox(vec_row2)
            ])
        )

        self.figure, self.axis = plt.subplots(1, 1, figsize=(8, 4))

        self.transform_data()
        self.draw()
Ejemplo n.º 29
0
def select_inj_site():
    global working
    working.replace('/', '\\')
    os.chdir(working)
    aa = ''
    p = Popen("python test2.py", stdout=PIPE, stderr=None, shell=True)
    for line in iter(p.stdout.readline, ""):
        #print(line)
        if "PRINTING COMPARTMENT" in str(line):
            break
    line = p.stdout.readline()
    #print(line)
    line = eval(line)
    x = line
    #print(line)
    result = []
    prefix = ''
    import re

    dot_ind = x[0].find('.')
    if dot_ind != -1:
        prefix = x[0][:dot_ind] + '.'

    for e in x:
        if e.find('.') != -1:
            e = e[e.find('.') + 1:]
        p = re.compile(r'\[\d+\]')
        test_str = e
        result.append([e for e in p.split(test_str) if e])
    result = [l[0] for l in result]

    newx = {i: result.count(i) for i in result}
    n = list(newx.keys())

    e = (widgets.FloatSlider(min=0, max=1, step=.01, value=0, description="Section Location (0-1)"));
    button = widgets.Button(description="Create Injection Site", width="100%")
    display(button)
    display(e);

    def f(c):
        global a, pop, has_subset;
        has_subset = False;
        try:
            po = a.close();
        except:
            pass

        pop = c
        if newx[c] - 1 != 0:
            a = (widgets.IntSlider(min=0, max=newx[c] - 1, description="Section subset", step=1, value=0));
            po = display(a);
            has_subset = True;

    o = widgets.interact(f, c=widgets.Dropdown(options=n, value=n[0], description='Section:', disabled=False));

    # button = widgets.Button(description="Create Injection Site", width="100%")
    def on_button_clicked2_7(b):
        linex = 'access %s' % (prefix + pop)

        if has_subset == True:
            linex = linex + ('[%s]' % a.value)
        replace_line('runModel.hoc', 29, linex + '\n')
        replace_line('runModel.hoc', 10, '   stLoc = %s \n' % e.value)
        # thefile.write(template.read())
        # thefile.close()
        print("Injection site successfully integrated")
        # print a.value, pop, e.value, has_subset

    button.on_click(on_button_clicked2_7)
			n = n+1

	df=pd.DataFrame(table, columns=['Square Number', 'total', 'last square'])
	df.set_index('Square Number', inplace=True)
	return df


# Adapted from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import ipywidgets as widgets

style = {'description_width' : 'initial'}

betaSlider = widgets.FloatSlider(value=0.3,min=0,max=1.0,step=0.1,description='Social distancing', style={'description_width' : '100px'}, layout=Layout(width='500px'))
daysSlider = widgets.FloatSlider(value=14,min=7,max=40,step=2.0,description='Days Contagious', style={'description_width' : '100px'}, layout=Layout(width='500px'))

def deriv(y, t, N, beta, gamma):
        S, I, R = y
        dSdt = -beta * S * I / N
        dIdt = beta * S * I / N - gamma * I
        dRdt = gamma * I 
        return dSdt, dIdt, dRdt

def updatePlot(beta, days):
    doPlot(1.0-beta, 1./days)
    
# beta is infection rate
# gamma is rate peple removed from infectred pool
def doPlot(beta, gamma):