Example #1
0
def test_default_values():
    @annotate(n=10, f=(0, 10.), g=5, h=OrderedDict([('a',1), ('b',2)]), j=['hi', 'there'])
    def f(n, f=4.5, g=1, h=2, j='there'):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSlider,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSlider,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSlider,
            value=5,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options=(('a', 1), ('b', 2)),
            value=2
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=(('hi', 'hi'), ('there', 'there')),
            value='there'
        ),
    )
def test_default_values():
    @annotate(n=10, f=(0, 10.), g=5, h={'a': 1, 'b': 2}, j=['hi', 'there'])
    def f(n, f=4.5, g=1, h=2, j='there'):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSlider,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSlider,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSlider,
            value=5,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options={'a': 1, 'b': 2},
            value=2
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=['hi', 'there'],
            value='there'
        ),
    )
def test_interact_manual_nocall():
    callcount = 0
    def calltest(testarg):
        callcount += 1
    c = interactive(calltest, testarg=5, __manual=True)
    c.children[0].value = 10
    nt.assert_equal(callcount, 0)
Example #4
0
def test_mapping():
    from collections import Mapping, OrderedDict
    class TestMapping(Mapping):
        def __init__(self, values):
            self.values = values
        def __getitem__(self):
            raise NotImplementedError
        def __len__(self):
            raise NotImplementedError
        def __iter__(self):
            raise NotImplementedError
        def items(self):
            return self.values

    items = [(3, 300), (1, 100), (2, 200)]
    first = items[0][1]
    values = TestMapping(items)
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    d['options'] = tuple(zip(d['_options_labels'], d['_options_values']))
    check_widgets(c, lis=d)
Example #5
0
def interactive( animation, size = 320 ):
	basedir = mkdtemp()
	basename = join( basedir, 'graph' )
	steps = [ Image( path ) for path in render( animation.graphs(), basename, 'png', size ) ]
	rmtree( basedir )
	slider = widgets.IntSlider( min = 0, max = len( steps ) - 1, step = 1, value = 0 )
	return widgets.interactive( lambda n: steps[ n ], n = slider )
def test_list_tuple_3_int():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,-1))
    for min, max, step in [ (0,2,1), (1,10,2), (1,100,2), (-5,5,4), (-100,-20,4) ]:
        c = interactive(f, tup=(min, max, step), lis=[min, max, step])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.IntSlider,
            min=min,
            max=max,
            step=step,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)
Example #7
0
def test_list_tuple_invalid():
    for bad in [
        (),
    ]:
        with nt.assert_raises(ValueError):
            print(bad) # because there is no custom message in assert_raises
            c = interactive(f, tup=bad)
Example #8
0
def interactive_responseFct():
	app = interactive(plot_ResponseFct,h_boom = FloatSlider(min=h_boom, max = h_boom_max, step = 0.1, value = h_boom),
                  h_1 = FloatSlider(min=0., max=zmax,value=0.1, step = 0.1),
                  sigma_1 = FloatSlider(min=sigmin, max = sigmax,value=sigmin, step = sigmin),
                  sigma_2 = FloatSlider(min=sigmin, max = sigmax,value=sigmin, step = sigmin),
                  orientation=ToggleButtons(options=['vertical','horizontal']))
	return app
def display_vecs():
    def interactive_display(directionx=1.0, directiony=0.0):
        plt.figure(figsize=(8,8))
        vec = Vector(np.float64(3),np.float64(2))

        direction = Vector(directionx,directiony)
        normal = direction/direction.norm()

        normal_component = vec.dot(normal)
    
        remainder = vec - (normal*normal_component)
        tangent = remainder/remainder.norm()
    
        np_vec =np.array( [ [0,0,vec.x,vec.y]]) 
        np_components = np.array( [ [0,0,normal_component*normal.x, normal_component*normal.y], 
                                  [0,0,remainder.x,remainder.y]])

        X1,Y1,U1,V1 = zip(*np_vec)
        X2,Y2,U2,V2 = zip(*np_components)

        ax = plt.gca()
        ax.quiver(X1,Y1,U1,V1,angles='xy',scale_units='xy',scale=1, color='r')
        ax.quiver(X2,Y2,U2,V2,angles='xy',scale_units='xy',scale=1, linestyle='--', color='b')

        ax.set_xlim([-5,5])
        ax.set_ylim([-5,5])
        plt.draw()
        plt.show() 

    return interactive(interactive_display, directionx=(-1,1,0.1), directiony=(-1,1,0.1))
Example #10
0
def test_list_tuple_2_float():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1.0,1.0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(0.5,-0.5))
    for min, max in [ (0.5, 1.5), (1.1,10.2), (1,2.2), (-5.,5), (-20,-19.) ]:
        c = interactive(f, tup=(min, max), lis=[min, max])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.FloatSlider,
            min=min,
            max=max,
            step=.1,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)
Example #11
0
    def interactive(self):
        """
        Generates a jupyter widgets UI for exploring a spectra.
        """
        import ipywidgets as wid
        from IPython.display import display

        is_nm = self.freq_unit is "nm"
        if is_nm:
            ph.vis_mode()
        else:
            ph.ir_mode()
        ds = self.dataset
        x = ds.wavelengths if is_nm else ds.wavenumbers
        # fig, ax = plt.subplots()
        wl_slider = wid.FloatSlider(
            None,
            min=x.min(),
            max=x.max(),
            step=1,
            description="Freq (%s)" % self.freq_unit,
        )

        def func(x):

            # ax.cla()
            self.trans([x])
            # plt.show()

        ui = wid.interactive(func, x=wl_slider, continuous_update=False)
        display(ui)
        return ui
Example #12
0
def test_default_description():
    c = interactive(f, b='text')
    w = c.children[0]
    check_widget(w,
        cls=widgets.Text,
        value='text',
        description='b',
    )
Example #13
0
def setup_conditional_sampler(x, y, yerr, kernel):
    # Pre-compute a bunch of things for speed.
    xs = np.linspace(-20, 20, 100)
    rxx = np.abs(x[:, None] - x[None, :])
    rss = np.abs(xs[:, None] - xs[None, :])
    rxs = np.abs(x[None, :] - xs[:, None])
    ye2 = yerr ** 2

    model = SillyTransitModel(*true_parameters)

    # This function samples from the conditional distribution and
    # plots those samples.
    def sample_conditional(amp, ell,
                           depth=np.exp(true_parameters[0]),
                           duration=np.exp(true_parameters[1]),
                           time=true_parameters[2]):
        rng = np.random.RandomState(123)

        # Compute the covariance matrices.
        Kxx = kernel([amp, ell], rxx)
        Kxx[np.diag_indices_from(Kxx)] += ye2
        Kss = kernel([amp, ell], rss)
        Kxs = kernel([amp, ell], rxs)

        # Compute the residuals.
        model.set_parameter_vector([np.log(depth), np.log(duration), time])
        resid = y - model.get_value(x)

        # Compute the likelihood.
        factor = cho_factor(Kxx, overwrite_a=True)
        ld = 2*np.sum(np.log(np.diag(factor[0])))
        a = cho_solve(factor, resid)
        ll = -0.5 * (np.dot(resid, a) + ld)

        # Compute the predictive mean.
        model_xs = model.get_value(xs)
        mu = np.dot(Kxs, a) + model_xs

        # Compute the predictive covariance.
        cov = Kss - np.dot(Kxs, np.linalg.solve(Kxx, Kxs.T))
        cov[np.diag_indices_from(cov)] += 1e-9

        # Sample and display the results.
        y0 = rng.multivariate_normal(mu, cov, 6)
        plt.errorbar(x, y, yerr=yerr, fmt=".k", capsize=0)
        plt.plot(xs, y0.T, "k", alpha=0.5)
        plt.plot(xs, model_xs, ":r")
        plt.ylim(-250, 100)
        plt.xlim(-20, 20)
        plt.title("lnlike = {0}".format(ll))
        plt.show()

    w = interactive(sample_conditional,
                    amp=(10.0, 500.0), ell=(0.5, 10.0),
                    depth=(10.0, 500.0),
                    duration=(0.1, 2.0),
                    time=(-5.0, 5.0))
    return w
Example #14
0
def test_interact_noinspect():
    a = u'hello'
    c = interactive(print, a=a)
    w = c.children[0]
    check_widget(w,
        cls=widgets.Text,
        description='a',
        value=a,
    )
Example #15
0
def test_single_value_string():
    a = u'hello'
    c = interactive(f, a=a)
    w = c.children[0]
    check_widget(w,
        cls=widgets.Text,
        description='a',
        value=a,
    )
Example #16
0
def test_fixed():
    c = interactive(f, a=widgets.fixed(5), b='text')
    nt.assert_equal(len(c.children), 2)
    w = c.children[0]
    check_widget(w,
        cls=widgets.Text,
        value='text',
        description='b',
    )
Example #17
0
def test_single_value_bool():
    for a in (True, False):
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(w,
            cls=widgets.Checkbox,
            description='a',
            value=a,
        )
Example #18
0
def test_list_tuple_3_float():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,0.0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(-1,-2,1.))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2.,-1.))
    for min, max, step in [ (0.,2,1), (1,10.,2), (1,100,2.), (-5.,5.,4), (-100,-20.,4.) ]:
        c = interactive(f, tup=(min, max, step), lis=[min, max, step])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.FloatSlider,
            min=min,
            max=max,
            step=step,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)
Example #19
0
def test_get_interact_value():
    from ipywidgets.widgets import ValueWidget
    from traitlets import Unicode
    class TheAnswer(ValueWidget):
        description = Unicode()
        def get_interact_value(self):
            return 42
    w = TheAnswer()
    c = interactive(lambda v: v, v=w)
    c.update()
    nt.assert_equal(c.result, 42)
 def __init__(self, feature = 'total_enrollment'):
     self.feature = feature
     self.all_years_data = self.norm_numeric()
     self.trans_x = self.PCA_fit()
     self.widget_keys =  self.make_keys_for_interactive_widget()
     self.w = interactive(self.plot_in_transformed_dimensions,
                          feature=widgets.Dropdown(options = self.widget_keys, description='Group schools by feature:', value="total_enrollment"))
     self.w.border_color = 'red'
     self.w.border_style = 'dotted'
     self.w.border_width = 3
     display(self.w)
Example #21
0
def test_list_tuple_str():
    values = ['hello', 'there', 'guy']
    first = values[0]
    c = interactive(f, tup=tuple(values), lis=list(values))
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        options=values
    )
    check_widgets(c, tup=d, lis=d)
 def __init__(self, feature = 'Total', year = 2012):
     self.feature = feature
     self.year = year
     self.all_years_data = self.read_and_merge_data()
     self.basemap, self.ax, self.fig = self.make_NYC_basemap()
     self.color_bar = self.create_color_bar(feature = 'Total', year = 2012)
     self.features_for_widget = self.features_for_interaction()
     w = interactive(self.interactive_update, Expenditure = self.features_for_widget, Year={'2010':2010, '2011':2011, '2012':2012})
     w.border_color = 'red'
     w.border_style = 'dotted'
     w.border_width = 3
     display(w)
Example #23
0
    def interact(self):
        def _interact(count, field):
            self.view(count, field, show_table=False)

        return display(
            show_grid(self.timings, self.remote_js),
            interactive(
                _interact,
                count=IntSlider(min=5, max=100, step=5, value=35),
                field=('cumtime', 'tottime', 'ncalls'),
            ),
        )
def test_get_interact_value():
    from ipywidgets.widgets import ValueWidget
    from traitlets import Unicode
    class TheAnswer(ValueWidget):
        _model_name = Unicode('TheAnswer')
        description = Unicode()
        def get_interact_value(self):
            return 42
    w = TheAnswer()
    c = interactive(lambda v: v, v=w)
    c.update()
    assert c.result == 42
Example #25
0
 def __init__(self):
     self.all_years_data = self.read_all_years_data()
     self.expenditure_options = self.build_expenditure_dicts()
     self.groupby_options = self.build_groupby_dicts()
     w = interactive(self.make_boxplot,
                     expenditure=widgets.Dropdown(options=self.expenditure_options,value='Total',description='Expenditure category:'),
                     groupby_feature=widgets.Dropdown(options=self.groupby_options,value='Title_1',description='Group schools by feature:'),
                     normalized=widgets.Checkbox(description='Plot expenditure as percent of total:', value=False))
     w.border_color = 'red'
     w.border_style = 'dotted'
     w.border_width = 3
     display(w)
Example #26
0
def test_iterable_tuple():
    values = [(3, 300), (1, 100), (2, 200)]
    first = values[0][1]
    c = interactive(f, lis=iter(values))
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        _options_labels=("3", "1", "2"),
        _options_values=(300, 100, 200),
    )
    d['options'] = tuple(zip(d['_options_labels'], d['_options_values']))
    check_widgets(c, lis=d)
Example #27
0
def test_single_value_float():
    for a in (2.25, 1.0, -3.5):
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(w,
            cls=widgets.FloatSlider,
            description='a',
            value=a,
            min= -a if a > 0 else 3*a,
            max= 3*a if a > 0 else -a,
            step=0.1,
            readout=True,
        )
Example #28
0
def test_single_value_dict():
    for d in [
        dict(a=5),
        dict(a=5, b='b', c=dict),
    ]:
        c = interactive(f, d=d)
        w = c.children[0]
        check_widget(w,
            cls=widgets.Dropdown,
            description='d',
            options=d,
            value=next(iter(d.values())),
        )
Example #29
0
def test_list_str():
    values = ['hello', 'there', 'guy']
    first = values[0]
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        _options_labels=tuple(values),
        _options_values=tuple(values),
    )
    d['options'] = tuple(zip(d['_options_labels'], d['_options_values']))
    check_widgets(c, lis=d)
Example #30
0
def test_list_int():
    values = [3, 1, 2]
    first = values[0]
    c = interactive(f, lis=values)
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.Dropdown,
        value=first,
        _options_labels=tuple(str(v) for v in values),
        _options_values=tuple(values),
    )
    d['options'] = tuple(zip(d['_options_labels'], d['_options_values']))
    check_widgets(c, lis=d)
Example #31
0
 def __init__(self, queries, kustodatabase, render):
     today = date.today()
     tomorrow = today + timedelta(days=1)
     self.render = render
     self.links = []
     self.kustodatabase = kustodatabase
     self.queries = queries
     self.clusterDnsNameText = widgets.Text(description="ClusterName:",
                                            placeholder="Cluster Dns Name")
     self.searchTimeBeginPicker = widgets.DatePicker(description="Start:",
                                                     value=today)
     self.searchTimeEndPicker = widgets.DatePicker(description="End:",
                                                   value=tomorrow)
     self.__interactive = widgets.interactive(
         lambda clusterDnsName, searchTimeBegin, searchTimeEnd: self.search(
             clusterDnsName, searchTimeBegin, searchTimeEnd), {
                 'manual': True,
                 'manual_name': "Search"
             },
         clusterDnsName=self.clusterDnsNameText,
         searchTimeBegin=self.searchTimeBeginPicker,
         searchTimeEnd=self.searchTimeEndPicker)
     self.ui = widgets.HBox(self.__interactive.children)
Example #32
0
def FieldsApp():
    Q1 = interactive(
        csem_fields_app,
        rho0=FloatText(value=1e8, description="$\\rho_{0} \ (\Omega m)$"),
        rho1=FloatText(value=0.3, description="$\\rho_{1} \ (\Omega m)$"),
        rho2=FloatText(value=1.0, description="$\\rho_{2} \ (\Omega m)$"),
        rho3=FloatText(value=100.0, description="$\\rho_{3} \ (\Omega m)$"),
        rho4=FloatText(value=1.0, description="$\\rho_{4} \ (\Omega m)$"),
        zsrc=FloatText(value=-950.0, description="src height (m)"),
        rv_rh=FloatText(value=1.0,
                        description="$\\rho_{2 \ v} / \\rho_{2 \ h}$"),
        dz1=FloatText(value=1000.0, description="dz1 (m)"),
        dz2=FloatText(value=1000.0, description="dz2 (m)"),
        dz3=FloatText(value=200.0, description="dz3 (m)"),
        frequency=FloatText(value=0.5, description="f (Hz)"),
        Field=ToggleButtons(options=["E", "H", "P"], value="E"),
        Plane=ToggleButtons(options=["XZ", "YZ"], value="XZ"),
        Fixed=widgets.widget_bool.Checkbox(value=False),
        vmin=FloatText(value=None),
        vmax=FloatText(value=None),
        __manual=True,
    )
    return Q1
Example #33
0
def test_default_out_of_bounds():
    @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
    def f(f='hi', h=5, j='other'):
        pass

    c = interactive(f)
    check_widgets(
        c,
        f=dict(
            cls=widgets.FloatSlider,
            value=5.,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options={'a': 1},
            value=1,
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=['hi', 'there'],
            value='hi',
        ),
    )
Example #34
0
def test_single_value_int():
    for a in (1, 5, -3, 0):
        if not a:
            expected_min = 0
            expected_max = 1
        elif a > 0:
            expected_min = -a
            expected_max = 3*a
        else:
            expected_min = 3*a
            expected_max = -a
        c = interactive(f, a=a)
        nt.assert_equal(len(c.children), 2)
        w = c.children[0]
        check_widget(w,
            cls=widgets.IntSlider,
            description='a',
            value=a,
            min=expected_min,
            max=expected_max,
            step=1,
            readout=True,
        )
Example #35
0
def test_single_value_float():
    for a in (2.25, 1.0, -3.5, 0.0):
        if not a:
            expected_min = 0.0
            expected_max = 1.0
        elif a > 0:
            expected_min = -a
            expected_max = 3 * a
        else:
            expected_min = 3 * a
            expected_max = -a
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(
            w,
            cls=widgets.FloatSlider,
            description='a',
            value=a,
            min=expected_min,
            max=expected_max,
            step=0.1,
            readout=True,
        )
Example #36
0
    def global_walk_missed_gts_wdgt(self):
        def logic(seq_inx):
            print("INFO: mark widget boundary")
            image_id = list(self.imgId_to_unmatched_gtAnn.keys())[seq_inx]
            im = self.read_img(
                self.coco_eval.cocoDt.imgs[image_id]['file_name'])
            unmatched_gts = self.imgId_to_unmatched_gtAnn[image_id]
            print("total {} unmatched objects in {} images".format(
                len(self.unmatched_gt_ids),
                len(self.imgId_to_unmatched_gtAnn.keys())))
            print("image id: {}".format(image_id))
            print("{} unmatched objects in this image".format(
                len(unmatched_gts)))
            plot_image_with_anns(im, detections=(), gtruths=unmatched_gts)
            return image_id

        interface = interactive(logic,
                                seq_inx=widgets.BoundedIntText(
                                    min=0,
                                    max=len(self.imgId_to_unmatched_gtAnn) - 1,
                                    step=1))
        interface.catId = self.catId
        return interface
Example #37
0
def plot_measures(data_path):

    dd_style = {'description_width': 'initial'}

    w = ipywidgets.Dropdown(options=[
        'dikeraising_evr_smooth', 'dikeraising_lrg_smooth',
        'groynelowering_evr_smooth', 'groynelowering_lrg_smooth',
        'lowering_evr_natural', 'lowering_evr_smooth', 'lowering_lrg_natural',
        'lowering_lrg_smooth', 'minemblowering_evr_smooth',
        'minemblowering_lrg_smooth', 'sidechannel_evr_natural',
        'sidechannel_evr_smooth', 'sidechannel_lrg_natural',
        'sidechannel_lrg_smooth', 'smoothing_evr_natural',
        'smoothing_evr_smooth', 'smoothing_lrg_natural', 'smoothing_lrg_smooth'
    ],
                            value='lowering_evr_smooth',
                            description='Select measure:',
                            style=dd_style)

    res = interactive(_plot_datasets,
                      data_path=fixed(data_path),
                      measure_dir=w)

    display(res)
Example #38
0
    def interactive_plot(*args, **kwargs):
        dct, *args = args  # arg0 must be dict of line data to plot
        kwargs["legend"] = False  # Turn off legend

        handles = []

        def plot_these(**labels):
            included = {k: v for k, v in dct.items() if labels[k]}
            hh = plotter(included, *args, **kwargs)
            if not handles:
                handles.extend(hh)

        widget = interactive(plot_these, **{label: True for label in dct})
        widget.update()
        # Could end function here. The rest is adjustments.

        # Place checkmarks to the right
        *checkmarks, figure = widget.children
        widget = HBox([figure, VBox(checkmarks)])
        ip_disp.display(widget)

        # Narrower checkmark boxes
        widget.children[1].layout.width = "15ex"
        for CX in widget.children[1].children:
            CX.layout.width = '10ex'
            CX.style.description_width = '0ex'

        # Hack to color borders of checkmarks.
        # Did not find how to color background/face.
        # Anyways, there is no general/good way to style widgets, ref:
        # https://github.com/jupyter-widgets/ipywidgets/issues/710#issuecomment-409448282
        import matplotlib as mpl
        for cm, lh in zip(checkmarks, handles):
            c = mpl.colors.to_hex(lh.get_color(), keep_alpha=False)
            cm.layout.border = "solid 5px" + c

        return widget
Example #39
0
    def single_img_widget(self):
        mode_options = ['bulk', 'walk']

        def logic(image_id, cat_name, mode):
            print("INFO: mark widget boundary")
            if image_id not in self.coco_eval.cocoGt.imgs:
                raise ValueError("{} not a valid id".format(image_id))
            catId = self.catsName_to_jsonId[cat_name]
            if mode == mode_options[0]:
                wdgt = self.make_widget(imgIds=[image_id],
                                        catId=catId).single_img_bulk_wdgt()
            elif mode == mode_options[1]:
                wdgt = self.make_widget(imgIds=[image_id],
                                        catId=catId).walk_dts_wdgt()
            display(wdgt)

        # since the wdgt is initially at global
        assert self.global_wdgt_in_display is not None
        default_id = self.global_wdgt_in_display.result
        image_id_button = widgets.IntText(value=default_id,
                                          description='img id')
        category_button = self.make_category_button()
        category_button.options = self._get_relevant_category_names(default_id)
        category_button.value = self.global_cat_button.value

        def update_cat_of_interest(*args):
            category_button.options = self._get_relevant_category_names(
                image_id_button.value)

        image_id_button.observe(update_cat_of_interest, 'value')

        interface = interactive(
            logic,
            image_id=image_id_button,
            cat_name=category_button,
            mode=widgets.ToggleButtons(options=mode_options))
        return interface
Example #40
0
def images_colorscale_sliders(axs_list, scale_step_size=0, display=True):
    """Creates ipywidget sliders to scale the 0th image for each axes in axs_list.

    Args:
        axs_list: List of matplotlib axes objects containing images.
        scale_step_size: The step size for the sliders to use. If set to 0 (default), then an automatic step_size will be picked.
        display: Specifies whether the ipywsliders will be displayed or returned.

    Returns:
        ipywidgets object: If display is False. If display is True, the widgets will be directly diplayed.
    """
    import IPython.display

    ias = []
    for ax in axs_list:
        scale_min, scale_max = ax.images[0].get_clim()
        if scale_step_size == 0:
            scale_step_size_curr = np.abs(scale_min - scale_max) / 100
            scale_step_size_curr = 10**(np.floor(
                np.log10(scale_step_size_curr)))
        ia = ipywidgets.interactive(images_colorscale,
                                    min=ipywidgets.widgets.FloatSlider(
                                        min=scale_min,
                                        max=scale_max + scale_step_size_curr,
                                        step=scale_step_size_curr,
                                        value=scale_min),
                                    max=ipywidgets.widgets.FloatSlider(
                                        min=scale_min,
                                        max=scale_max + scale_step_size_curr,
                                        step=scale_step_size_curr,
                                        value=scale_max),
                                    axs_list=ipywidgets.widgets.fixed([ax]))
        ias.append(ia)
    if display:
        IPython.display.display(ipywidgets.HBox(ias))
    else:
        return ias
Example #41
0
 def generate_widgets(self):
     self.button_decomposition_interact = interactive(
         self.decomposition_interact_button, {
             'manual': True,
             'manual_name': 'Decompose'
         })
     decomposition_items = [
         ipywidgets.Box([self.rank_display, self.decomposition_method_list],
                        layout=form_item_layout),
         ipywidgets.Box([
             Label(
                 value=
                 'The number of components should be no more than the number of samples'
             )
         ]), self.show_components, self.show_loadings,
         self.dataset_normalization, self.show_normalized_loadings,
         self.show_normalized_component, self.show_normalized_score,
         self.button_decomposition_interact
     ]
     # parameter optimization
     # correlation analysis
     tab = ipywidgets.Tab()
     tab.children = [ipywidgets.Box(decomposition_items)]
     return decomposition_items
Example #42
0
    def iplot(self, *args, plot_func=None, n: int = -1, **kwargs) -> None:
        """
        Plot simulation interactively. All other arguments forwarded to PlutoData.plot()
        No return, because it would interfere with interactive output in Jupyter Notebook
        """

        # Use widget to choose timestep if inside Jupyter Notebook
        try:
            get_ipython
            import ipywidgets as widgets

            if plot_func is None:

                def handler(i):
                    self[i].plot(*args, **kwargs)
                    plt.show()

            else:

                def handler(i):
                    plot_func(self[i])

            plot = widgets.interactive(
                handler,
                i=widgets.IntSlider(min=0,
                                    max=len(self) - 1,
                                    value=self._index(n)),
            )
            plot.children[0].description = "Step"
            plot.children[0].layout.width = "40%"
            display(plot)

        except NameError:
            raise RuntimeError(
                "Code has to be run in Jupyter Notebook for interactive plotting"
            )
Example #43
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)
Example #44
0
def time_plot_i(max_time=(1.0, 100.0), x0=(-100, 100), v0=(-100, 100),
                m=(1.0, 100.0), c=(0.0, 1.0, .02), k=(1.0, 100.0)):
    """Interactive single degree of freedom free reponse plot in iPython.

    ``time_plot_i`` is only functional in a
    `Jupyter notebook <http://jupyter.org>`_.

    Parameters
    ----------
    m, c, k:  floats, optional
        mass, damping coefficient, stiffness
    x0, v0:  floats, optional
        initial displacement, initial velocity
    max_time: float, optional
        end time for :math:`x(t)`

    """
    if _in_ipynb():
        w = interactive(_time_plot, max_time=max_time, v0=v0, m=m,
                        c=c, x0=x0, k=k)
        display(w)
    else:
        print('time_plot_i can only be used in an iPython notebook.')
    '''
Example #45
0
    def __init__(self, targets):
        super().__init__(targets)
        self.obj_type = ToggleButtons(
            options=['unclassified', 'SN II', 'SN IIP', 'SN Ia'],
            description='Type:',
            disabled=False,
            button_style='')
        self.max_alt = FloatSlider(
            value=30.,
            min=0.,
            max=90.,
            step=2.,
            description='Max alt cut:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )
        self.mag_cut = FloatSlider(
            value=17.8,
            min=10.,
            max=22.,
            step=0.25,
            description='Max mag cut:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )

        self.interactive = interactive(self.filter_targets,
                                       obj_type=self.obj_type,
                                       max_alt=self.max_alt,
                                       mag_cut=self.mag_cut)
Example #46
0
    def showLogging(self, **kwargs):
        """ showLogging """

        for m_name, m_level in kwargs.items():
            self.levels[m_name] = m_level

        controls = {}

        style = {'description_width': 'initial'}

        for m_name in self.modules.keys():
            controls[m_name] = widgets.Dropdown(options=[*self.types],
                                                value=self.levels.get(
                                                    m_name, 'Warning'),
                                                description=m_name,
                                                style=style,
                                                disabled=False)

        print("")
        print("Debugging level")
        display(interactive(self._set_debug, **controls))
        print("")

        return
Example #47
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
Example #48
0
    def root_wdgt(self):
        """
        root widget delegates to either global or image
        """
        self.summarize()
        modes = ['Global', 'Single-Image']

        def logic(mode):
            # cache the widget later
            if mode == modes[0]:
                if self.global_walk is None:
                    self.global_walk = self.global_walk_specifier()
                ipy_display(self.global_walk)
            elif mode == modes[1]:
                self.image_view = self.single_image_selector()
                # if self.image_view is None:
                #     self.image_view = self.single_image_selector()
                # ipy_display(self.image_view)

        UI = interactive(logic,
                         mode=widgets.ToggleButtons(options=modes,
                                                    value=modes[0]))
        UI.children[-1].layout.height = '1000px'
        ipy_display(UI)
Example #49
0
def qw_init_box(qw):

    title_text = 'Please fill quantum well and calculation parameters.'
    title_html = HTML(
        value='<{size}>{text}</{size}>'.format(text=title_text, size='h3'))

    desc_w = 'w = Width of quantum well (nm)'
    desc_E_w = 'E_w = Lowest energy level of a quantum well (eV)'
    desc_E_b = 'E_b = Energy level of barrier material (eV)'
    desc_Me_w = 'Me_w = Effective electron mass in quantum well'
    desc_Me_b = 'Me_b = Effective electron mass in barrier'
    desc_n = 'n = Number of finite elements to break calculation into, per 1 QW width (larger n -> longer run time, default is 100)'
    desc_bound = 'bound = Thickness of barrier material to pad when perform calculation, in a QW width unit (larger bound -> longer run time, default is 6)'

    desc_text = f'{desc_w}<br>{desc_E_w}<br>{desc_E_b}<br>{desc_Me_w}<br>{desc_Me_b}<br>{desc_n}<br>{desc_bound}'
    desc_html = HTML(value=desc_text)

    qw_init = interactive(qw.e_solver, {
        'manual': True,
        'manual_name': 'Run State Solver'
    },
                          w='E.g. 5.60',
                          E_w='e.g. 0',
                          E_b='e.g. 0.23',
                          Me_w='e.g. 0.067 (GaAs)',
                          Me_b='e.g. 0.092 (AlGaAs)',
                          n=widgets.IntSlider(min=30,
                                              max=500,
                                              step=10,
                                              value=100),
                          bound=widgets.IntSlider(min=3,
                                                  max=10,
                                                  step=1,
                                                  value=6))

    return VBox((title_html, desc_html, qw_init))
 def run(self):
     w1 = widgets.interactive(self.vis_child, **self.params)
     display(w1)
Example #51
0
    def run_widget(self,
                   df,
                   df_features):
        """


        Args:
            df: pd.Dataframe
                A pandas dataframe object

            df_features: DataFrameType
                DataFrameTypes object; organizes feature types into groups.

        Returns:
            Returns a UI widget to create a JSON file for cleaning.
        """
        self.__feature_option_dict = dict()

        self.__selected_options = {feature_name: "None"
                                   for feature_name in
                                   df_features.string_features()}

        feature_cleaning_options = {feature_name: ["None"]
                                    for feature_name in
                                    df_features.string_features()}

        self.__feature_options_w = {key: widgets.Select(
            options=feature_cleaning_options[key],
            layout=Layout(width='50%',
                          height='300px'))
            for key in feature_cleaning_options}

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

        self.__update_widgets()

        # ---
        self.__file_name_w = widgets.Text(
            value='Default Data Cleaning',
            placeholder='Replace Value',
            description='File Name:',
            disabled=False,
            visible=False,
            layout=Layout(left='590px')
        )

        # ---
        self.__submit_button = widgets.Button(
            description='Create JSON File from options',
            color="#ff1122",
            layout=Layout(left='100px',
                          bottom="5px",
                          width='40%', ))

        self.__input_w = widgets.Text(
            value='',
            placeholder='Replace Value',
            description='Input:',
            disabled=False,
            visible=False,
            layout=Layout(width='50%')
        )

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

        self.__input_w.observe(self.__validate_save_input_w)

        # Setup and display full UI
        self.__full_widgets_ui = widgets.interactive(
            self.__save_option,
            Features=self.__features_w,
            Options=self.__options_w,
            Text_Input=self.__input_w,
        )

        display(self.__full_widgets_ui)
Example #52
0
    def __init__(self, *args):
        
        self.dt = 0.01; 
        self.f1 = 1.;
        self.f2 = 1.; 
        self.f3 = 1.;
        self.d1 = .1; 
        self.d2 = .5; 
        self.d3 = 1.; 
        self.noise = 0.2; 
        self.eig_lines = None;
        self.eig_dots = None;
        self.ax = None

        ### Make slider for frequency content
        layout = widgets.Layout(width='300px')

        self.freqs = widgets.interactive(self.save_freq, {'manual': True}, 
                                     f1 = widgets.IntSlider(min=1, max=20, step=1, layout=layout),
                                     f2 = widgets.IntSlider(min=1, max=20, step=1, layout=layout),
                                     f3 = widgets.IntSlider(min=1, max=20, step=1, layout=layout),
                                     style={'description_width': 'initial'})
        
        # self.decays = widgets.interactive(self.save_decay, {'manual': True}, 
        #                              d1 = widgets.FloatSlider(min=0.01, max=1., step=.01, layout=layout),
        #                              d2 = widgets.FloatSlider(min=0.01, max=1., step=.01, layout=layout),
        #                              d3 = widgets.FloatSlider(min=0.01, max=1., step=.01, layout=layout),
        #                              style={'description_width': 'initial'})
        
        self.noise_wid = widgets.interactive(self.save_noise, {'manual': True},
            noise = widgets.FloatSlider(.2, min=0.1, max=1., step=.01, layout=layout),
            style = {'description_width': 'initial'})

        self.ylim_wid = widgets.interactive(self.set_ylim_eig,
            ymax = widgets.FloatSlider(1., min=0.1, max=5., step=.01, layout=layout),
            style = {'description_width': 'initial'})

        self.r2 = widgets.HTMLMath()

        ### Eigenvalue spec plot ####
        self.out1 = widgets.Output()
        with self.out1:
            fig1, axes1 = plt.subplots(figsize=(6, 4))
            #self.format_ax1(axes1)
            plt.show(fig1)
        self.fig1 = fig1 
        self.axes1 = axes1

        # ### Data ####
        self.out2 = widgets.Output()
        with self.out2:
            fig2, axes2 = plt.subplots(ncols = 3, nrows = 3, figsize=(16, 6))
            #self.format_ax2(axes2)
            plt.show(fig2)
        self.fig2 = fig2 
        self.axes2 = axes2

        ### First row; 
        self.grandchild1 = [self.noise_wid, self.ylim_wid, self.r2]
        self.grand_row = widgets.VBox(self.grandchild1)

        self.children1 = [self.freqs, self.grand_row, self.out1]
Example #53
0
g = go.Figure()
g.add_trace(trace)
g = go.FigureWidget(g)


def upate(lambdai, lambdaf):
    lambdas = [lambdai, lambdaf]
    new_line = utils.FCR_bac[lambdas]
    new_line.integ_sigma(t=np.linspace(0, 5, 500))
    g.data[0].x, g.data[0].y = new_line.t, new_line.sigma_t


slid1 = widgets.FloatSlider(value=0.1, min=0.001, max=3., step=0.01)
slid2 = widgets.FloatSlider(value=1.2, min=0.001, max=3., step=0.01)
container = widgets.HBox([slid1, slid2])
widgets.interactive(upate, lambdai=slid1, lambdaf=slid2)
final = widgets.VBox([container, g])
display(final)

#%%
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import EllipseSelector


def onselect(eclick, erelease):
    "eclick and erelease are matplotlib events at press and release."
    print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
    print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
    print('used button  : ', eclick.button)
Example #54
0
 def view():
     display(
         interactive(self.pairwise_plot,
                     y=self.volatility_indices,
                     x=self.volatility_indices))
Example #55
0
 def view():
     display(interactive(ta, y=list(self.prs.keys())))
Example #56
0
 def view():
     display(
         interactive(self.pairwise_plot,
                     y=self.forex_major,
                     x=self.forex_major))
Example #57
0
    def __init__(self):
        
        self.output_dir = '.'
        # self.output_dir = 'tmpdir'

        self.figsize_width_substrate = 15.0  # allow extra for colormap
        self.figsize_height_substrate = 12.5
        self.figsize_width_svg = 12.0
        self.figsize_height_svg = 12.0

        # self.fig = plt.figure(figsize=(7.2,6))  # this strange figsize results in a ~square contour plot

        self.first_time = True
        self.modulo = 1

        self.use_defaults = True

        self.svg_delta_t = 1
        self.substrate_delta_t = 1
        self.svg_frame = 1
        self.substrate_frame = 1

        self.customized_output_freq = False
        self.therapy_activation_time = 1000000
        self.max_svg_frame_pre_therapy = 1000000
        self.max_substrate_frame_pre_therapy = 1000000

        self.svg_xmin = 0

        # Probably don't want to hardwire these if we allow changing the domain size
        # self.svg_xrange = 2000
        # self.xmin = -1000.
        # self.xmax = 1000.
        # self.ymin = -1000.
        # self.ymax = 1000.
        # self.x_range = 2000.
        # self.y_range = 2000.

        self.show_nucleus = True
        self.show_edge = True

        # initial value
        self.field_index = 4
        # self.field_index = self.mcds_field.value + 4

        self.skip_cb = False

        # define dummy size of mesh (set in the tool's primary module)
        self.numx = 0
        self.numy = 0

        self.title_str = ''

        tab_height = '600px'
        tab_height = '500px'
        constWidth = '180px'
        constWidth2 = '150px'
        tab_layout = Layout(width='900px',   # border='2px solid black',
                            height=tab_height, ) #overflow_y='scroll')

        max_frames = 1   
        # self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)  
        # self.i_plot = interactive(self.plot_plots, frame=(0, max_frames), continuous_update=False)  
        self.i_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)  

        # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that)
        # NOTE: the Substrates Plot tab has an extra row of widgets at the top of it (cf. Cell Plots tab)
        svg_plot_size = '700px'
        svg_plot_size = '600px'
        svg_plot_size = '700px'
        svg_plot_size = '900px'
        self.i_plot.layout.width = svg_plot_size
        self.i_plot.layout.height = svg_plot_size

        self.fontsize = 20

            # description='# cell frames',
        self.max_frames = BoundedIntText(
            min=0, max=99999, value=max_frames,
            description='# frames',
           layout=Layout(width='160px'),
        )
        self.max_frames.observe(self.update_max_frames)

        # self.field_min_max = {'dummy': [0., 1., False]}
        # NOTE: manually setting these for now (vs. parsing them out of data/initial.xml)
        self.field_min_max = {'director signal':[0.,1.,False], 'cargo signal':[0.,1.,False] }
        # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below
        # self.field_dict = {0:'dummy'}
        self.field_dict = {0:'director signal', 1:'cargo signal'}

        self.mcds_field = Dropdown(
            options={'director signal': 0, 'cargo signal':1},
            value=0,
            #     description='Field',
           layout=Layout(width=constWidth)
        )
        # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value)
#        self.mcds_field.observe(self.mcds_field_cb)
        self.mcds_field.observe(self.mcds_field_changed_cb)

        self.field_cmap = Dropdown(
            options=['viridis', 'jet', 'YlOrRd'],
            value='YlOrRd',
            #     description='Field',
           layout=Layout(width=constWidth)
        )
#        self.field_cmap.observe(self.plot_substrate)
        self.field_cmap.observe(self.mcds_field_cb)

        self.cmap_fixed_toggle = Checkbox(
            description='Fix',
            disabled=False,
#           layout=Layout(width=constWidth2),
        )
        self.cmap_fixed_toggle.observe(self.mcds_field_cb)

#         def cmap_fixed_toggle_cb(b):
#             # self.update()
# #            self.field_min_max = {'oxygen': [0., 30.,True], 'glucose': [0., 1.,False]}
#             field_name = self.field_dict[self.mcds_field.value]
#             if (self.cmap_fixed_toggle.value):  
#                 self.field_min_max[field_name][0] = self.cmap_min.value
#                 self.field_min_max[field_name][1] = self.cmap_max.value
#                 self.field_min_max[field_name][2] = True
#             else:
#                 # self.field_min_max[field_name][0] = self.cmap_min.value
#                 # self.field_min_max[field_name][1] = self.cmap_max.value
#                 self.field_min_max[field_name][2] = False
#             self.i_plot.update()

        # self.cmap_fixed_toggle.observe(cmap_fixed_toggle_cb)

#         self.save_min_max= Button(
#             description='Save', #style={'description_width': 'initial'},
#             button_style='success',  # 'success', 'info', 'warning', 'danger' or ''
#             tooltip='Save min/max for this substrate',
#             disabled=True,
#            layout=Layout(width='90px')
#         )

#         def save_min_max_cb(b):
# #            field_name = self.mcds_field.options[]
# #            field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value)
#             field_name = self.field_dict[self.mcds_field.value]
# #            print(field_name)
# #            self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]}
#             self.field_min_max[field_name][0] = self.cmap_min.value
#             self.field_min_max[field_name][1] = self.cmap_max.value
# #            print(self.field_min_max)

#         self.save_min_max.on_click(save_min_max_cb)


        self.cmap_min = FloatText(
            description='Min',
            value=0,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_min.observe(self.mcds_field_cb)

        self.cmap_max = FloatText(
            description='Max',
            value=38,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_max.observe(self.mcds_field_cb)

        def cmap_fixed_toggle_cb(b):
            field_name = self.field_dict[self.mcds_field.value]
            # print(self.cmap_fixed_toggle.value)
            if (self.cmap_fixed_toggle.value):  # toggle on fixed range
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.field_min_max[field_name][0] = self.cmap_min.value
                self.field_min_max[field_name][1] = self.cmap_max.value
                self.field_min_max[field_name][2] = True
                # self.save_min_max.disabled = False
            else:  # toggle off fixed range
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.field_min_max[field_name][2] = False
                # self.save_min_max.disabled = True
#            self.mcds_field_cb()
            self.i_plot.update()

        self.cmap_fixed_toggle.observe(cmap_fixed_toggle_cb)

        field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed_toggle])

#        field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max])
        items_auto = [
            # self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'),
            self.cmap_min, 
            self.cmap_max,  
         ]
        box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch',
                    width='80%')
        field_cmap_row3 = Box(children=items_auto, layout=box_layout)

        # self.debug_str = Text(
        #     value='debug info',
        #     description='Debug:',
        #     disabled=True,
        #     layout=Layout(width='600px'),  #constWidth = '180px'
        # )

        #---------------------
        self.cell_nucleus_toggle = Checkbox(
            description='nuclei',
            disabled=False,
            value = self.show_nucleus,
#           layout=Layout(width=constWidth2),
        )
        def cell_nucleus_toggle_cb(b):
            # self.update()
            if (self.cell_nucleus_toggle.value):  
                self.show_nucleus = True
            else:
                self.show_nucleus = False
            self.i_plot.update()

        self.cell_nucleus_toggle.observe(cell_nucleus_toggle_cb)

        #----
        self.cell_edges_toggle = Checkbox(
            description='edges',
            disabled=False,
            value=self.show_edge,
#           layout=Layout(width=constWidth2),
        )
        def cell_edges_toggle_cb(b):
            # self.update()
            if (self.cell_edges_toggle.value):  
                self.show_edge = True
            else:
                self.show_edge = False
            self.i_plot.update()

        self.cell_edges_toggle.observe(cell_edges_toggle_cb)

        self.cells_toggle = Checkbox(
            description='Cells',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def cells_toggle_cb(b):
            # self.update()
            self.i_plot.update()
            if (self.cells_toggle.value):
                self.cell_edges_toggle.disabled = False
                self.cell_nucleus_toggle.disabled = False
            else:
                self.cell_edges_toggle.disabled = True
                self.cell_nucleus_toggle.disabled = True

        self.cells_toggle.observe(cells_toggle_cb)

        #---------------------
        self.substrates_toggle = Checkbox(
            description='Substrates',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def substrates_toggle_cb(b):
            if (self.substrates_toggle.value):  # seems bass-ackwards
                self.cmap_fixed_toggle.disabled = False
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.mcds_field.disabled = False
                self.field_cmap.disabled = False
            else:
                self.cmap_fixed_toggle.disabled = True
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.mcds_field.disabled = True
                self.field_cmap.disabled = True

        self.substrates_toggle.observe(substrates_toggle_cb)

        self.grid_toggle = Checkbox(
            description='grid',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def grid_toggle_cb(b):
            # self.update()
            self.i_plot.update()

        self.grid_toggle.observe(grid_toggle_cb)

#        field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max])

        # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout)
        # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames])  # mcds_dir
#        mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,])  # mcds_dir

#        self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout)

        help_label = Label('select slider: drag or left/right arrows')
        # row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black',
        row1a = Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        row1b = Box( [self.cells_toggle, self.cell_nucleus_toggle, self.cell_edges_toggle], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        row1 = HBox( [row1a, Label('.....'), row1b])

        row2a = Box([self.cmap_fixed_toggle, self.cmap_min, self.cmap_max], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex'))
        # row2b = Box( [self.substrates_toggle, self.grid_toggle], layout=Layout(border='1px solid black',
        row2b = Box( [self.substrates_toggle, ], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        # row2 = HBox( [row2a, self.substrates_toggle, self.grid_toggle])
        row2 = HBox( [row2a, Label('.....'), row2b])

        if (hublib_flag):
            self.download_button = Download('mcds.zip', style='warning', icon='cloud-download', 
                                                tooltip='Download data', cb=self.download_cb)

            self.download_svg_button = Download('svg.zip', style='warning', icon='cloud-download', 
                                            tooltip='You need to allow pop-ups in your browser', cb=self.download_svg_cb)
            download_row = HBox([self.download_button.w, self.download_svg_button.w, Label("Download all cell plots (browser must allow pop-ups).")])

            # box_layout = Layout(border='0px solid')
            controls_box = VBox([row1, row2])  # ,width='50%', layout=box_layout)
            self.tab = VBox([controls_box, self.i_plot, download_row])
            # self.tab = VBox([controls_box, self.debug_str, self.i_plot, download_row])
        else:
            # self.tab = VBox([row1, row2])
            self.tab = VBox([row1, row2, self.i_plot])
Example #58
0
    def param(self):
        """ Interface de paramétrage.
        
            Cette fonction affiche dans une cellule de dialogue les paramètres
            courants et offre la possibilité de les modifier graphiquement.
        """
        def update_parameters(width, sigma, max_order, retry, percentile,
                              sample, split):

            self.feature_params['range_width'] = eval(width)
            self.feature_params['range_sigma'] = eval(sigma)
            self.feature_params['max_order'] = max_order

            self.learn_params['retry_number'] = retry
            self.learn_params['retry_percentile'] = percentile
            self.learn_params['samples_percent'] = sample
            self.learn_params['min_samples_split'] = split

        # =================================================================
        # Widgets pour les indicateurs.
        wfrw = widgets.Textarea(description="Range",
                                value=repr(self.feature_params['range_width']),
                                placeholder='____________________')
        wfrs = widgets.Textarea(description="Sigma",
                                value=repr(self.feature_params['range_sigma']),
                                placeholder='____________________')
        wfmo = widgets.IntText(description="Max Order",
                               value=self.feature_params['max_order'])

        fbox = widgets.VBox([
            widgets.Label("Feature parameters (.feature_params):"),
            widgets.HBox([wfrw, wfrs]),
            widgets.HBox([wfmo])
        ])

        # =================================================================
        # Widgets pour l'apprentissage.
        wtrn = widgets.IntText(description="Retry",
                               value=self.learn_params['retry_number'])
        wtrp = widgets.IntText(description="Percentile",
                               value=self.learn_params['retry_percentile'])
        wtsp = widgets.FloatText(description="Sample",
                                 value=self.learn_params['samples_percent'])
        wtss = widgets.FloatText(description="Split",
                                 value=self.learn_params['min_samples_split'])

        lbox = widgets.VBox([
            widgets.Label(value="Learning parameters (.learn_params):"),
            widgets.HBox([wtrn, wtrp]),
            widgets.HBox([wtsp, wtss])
        ])

        out = widgets.interactive(update_parameters,
                                  width=wfrw,
                                  sigma=wfrs,
                                  max_order=wfmo,
                                  retry=wtrn,
                                  percentile=wtrp,
                                  sample=wtsp,
                                  split=wtss)

        return widgets.VBox([fbox, lbox])
Example #59
0
def get_dicom_form(conf: ConfigurationAggregator, image):
    name = widgets.Text(
        value=conf.name,
        placeholder='Type something',
        description=' ',
        disabled=False
    )

    id = widgets.Text(
        value=conf.id,
        placeholder='Type something',
        description=' ',
        disabled=False
    )

    destination = widgets.Text(
        value=conf.destination,
        placeholder='Type something',
        description=' ',
        disabled=False
    )

    file_name = widgets.Text(
        value=conf.file_name,
        placeholder='Type something',
        description=' ',
        disabled=False
    )

    process_button = widgets.Button(
        description='Save',
        disabled=False,
        tooltip='Click me',
        icon='fa-arrow-right'
    )
    form_item_layout = Layout(
        display='flex',
        flex_flow='row',
        justify_content='space-between',
    )

    def process(_):
        pixel_array = array(image)
        file_name = '{}.dcm'.format(conf.file_name)
        write_dicom(file_name, pixel_array, conf.name, conf.id, conf.destination)

    process_button.on_click(process)

    form_items = [
        Box([Label(value='Name'), interactive(conf.set_name, x=name)], layout=form_item_layout),
        Box([Label(value='ID'), interactive(conf.set_id, x=id)], layout=form_item_layout),
        Box([Label(value='Description'), interactive(conf.set_destination, x=destination)], layout=form_item_layout),
        Box([Label(value='File name'), interactive(conf.set_file_name, x=file_name)], layout=form_item_layout),
        Box([process_button], layout=form_item_layout)
    ]

    form = Box(form_items, layout=Layout(
        display='flex',
        flex_flow='column',
        align_items='stretch',
        width='50%'
    ))

    return form
Example #60
0
def display_visual(graph_data, user_input, algorithm=None, problem=None):
    initial_node_colors = graph_data['node_colors']
    if user_input == False:
        def slider_callback(iteration):
            # don't show graph for the first time running the cell calling this function
            try:
                show_map(graph_data, node_colors=all_node_colors[iteration])
            except:
                pass
        def visualize_callback(Visualize):
            if Visualize is True:
                button.value = False
                
                global all_node_colors
                
                iterations, all_node_colors, node = algorithm(problem)
                solution = node.solution()
                all_node_colors.append(final_path_colors(all_node_colors[0], problem, solution))
                
                slider.max = len(all_node_colors) - 1
                
                for i in range(slider.max + 1):
                    slider.value = i
                     #time.sleep(.5)
        
        slider = widgets.IntSlider(min=0, max=1, step=1, value=0)
        slider_visual = widgets.interactive(slider_callback, iteration=slider)
        display(slider_visual)

        button = widgets.ToggleButton(value=False)
        button_visual = widgets.interactive(visualize_callback, Visualize=button)
        display(button_visual)
    
    if user_input == True:
        node_colors = dict(initial_node_colors)
        if isinstance(algorithm, dict):
            assert set(algorithm.keys()).issubset({"Breadth First Tree Search",
                                                       "Depth First Tree Search", 
                                                       "Breadth First Search", 
                                                       "Depth First Graph Search", 
                                                       "Best First Graph Search",
                                                       "Uniform Cost Search", 
                                                       "Depth Limited Search",
                                                       "Iterative Deepening Search",
                                                       "Greedy Best First Search",
                                                       "A-star Search",
                                                       "Recursive Best First Search"})

            algo_dropdown = widgets.Dropdown(description="Search algorithm: ",
                                             options=sorted(list(algorithm.keys())),
                                             value="Breadth First Tree Search")
            display(algo_dropdown)
        elif algorithm is None:
            print("No algorithm to run.")
            return 0
        
        def slider_callback(iteration):
            # don't show graph for the first time running the cell calling this function
            try:
                show_map(graph_data, node_colors=all_node_colors[iteration])
            except:
                pass
            
        def visualize_callback(Visualize):
            if Visualize is True:
                button.value = False
                
                problem = GraphProblem(start_dropdown.value, end_dropdown.value, romania_map)
                global all_node_colors
                
                user_algorithm = algorithm[algo_dropdown.value]
                
                iterations, all_node_colors, node = user_algorithm(problem)
                solution = node.solution()
                all_node_colors.append(final_path_colors(all_node_colors[0], problem, solution))

                slider.max = len(all_node_colors) - 1
                
                for i in range(slider.max + 1):
                    slider.value = i
                    #time.sleep(.5)
                         
        start_dropdown = widgets.Dropdown(description="Start city: ",
                                          options=sorted(list(node_colors.keys())), value="Arad")
        display(start_dropdown)

        end_dropdown = widgets.Dropdown(description="Goal city: ",
                                        options=sorted(list(node_colors.keys())), value="Fagaras")
        display(end_dropdown)
        
        button = widgets.ToggleButton(value=False)
        button_visual = widgets.interactive(visualize_callback, Visualize=button)
        display(button_visual)
        
        slider = widgets.IntSlider(min=0, max=1, step=1, value=0)
        slider_visual = widgets.interactive(slider_callback, iteration=slider)
        display(slider_visual)