Пример #1
0
def tradeoffs_setup(lock=True):
	box1 = IntText(value = 20, description='Euler steps')
	if lock:
		box2 = BoundedFloatText(value = 2.2, description='predict value', max=6)
	else:
		box2 = BoundedFloatText(value = 2.2, description='predict value')
	return box1, box2
Пример #2
0
    def create_check_radio_boxes(self):
        labels = dict()
        for k_name, v in self.properties_and_values.items():

            if len(v) == 3:
                label = v[2]
            elif MetaPropertiesType.TEXT.value == v[0].value and len(v) == 2:
                label = v[1]
            else:
                label = k_name

            labels[k_name] = label

            if MetaPropertiesType.UNIQUE.value == v[0].value:  # radiobutton
                self.radiobuttons[k_name] = RadioButtons(name=k_name, options=v[1],
                                                         disabled=False,
                                                         indent=False)
            elif MetaPropertiesType.COMPOUND.value == v[0].value:  # checkbox
                self.checkboxes[k_name] = [Checkbox(False, indent=False, name=k_name,
                                                    description=prop_name) for prop_name in v[1]]
            elif MetaPropertiesType.CONTINUE.value == v[0].value:
                self.bounded_text[k_name] = BoundedFloatText(value=v[1][0], min=v[1][0], max=v[1][1])

            elif MetaPropertiesType.TEXT.value == v[0].value:
                self.box_text[k_name] = Textarea(disabled=False)

        return labels
Пример #3
0
def plot_growth_interactive():
    #     interact(plot_growth, mass_ratio=FloatSlider(min=0.005, max=0.1, step=.002, description='$m/M$', value = 0.001))
    interact(plot_growth,
             mass_ratio=BoundedFloatText(min=0.001,
                                         max=0.1,
                                         step=0.001,
                                         description='$m/M$',
                                         value=0.001))
Пример #4
0
def test_player_link_to_ipywidgets():
    traj = pt.datafiles.load_tz2()
    view = nv.show_pytraj(traj)

    int_text = IntText(2)
    float_text = BoundedFloatText(40, min=10)
    HBox([int_text, float_text])
    link((int_text, 'value'), (view.player, 'step'))
    link((float_text, 'value'), (view.player, 'delay'))

    assert view.player.step == 2
    assert view.player.delay == 40

    float_text.value = 100
    assert view.player.delay == 100

    float_text.value= 0.00
    # we set min=10
    assert view.player.delay == 10
def test_player_link_to_ipywidgets():
    traj = pt.datafiles.load_tz2()
    view = nv.show_pytraj(traj)

    int_text = IntText(2)
    float_text = BoundedFloatText(40, min=10)
    HBox([int_text, float_text])
    link((int_text, 'value'), (view.player, 'step'))
    link((float_text, 'value'), (view.player, 'delay'))

    nt.assert_equal(view.player.step, 2)
    nt.assert_equal(view.player.delay, 40)

    float_text.value = 100
    nt.assert_equal(view.player.delay, 100)

    float_text.value = 0.00
    # we set min=10
    nt.assert_equal(view.player.delay, 10)
Пример #6
0
    def vis(self, oracle=False, oracle_res=4):
        """
        optionally save all predicted files through output writer
        """
        assert not self.mp_distributed
        from panoptic.vis import Visualizer
        from ipywidgets import interactive, BoundedIntText, BoundedFloatText
        from IPython.display import display

        model, loader = self.model, self.val_loader
        dset, pcv = loader.dataset, model.pcv
        vis_engine = Visualizer(cfg, dset.meta, pcv)
        vis_engine.display_stdout_and_err_in_curr_cell()

        def logic(inx, hmap_thresh):
            _, segments_info, img, pan_gt_mask = dset.pan_getitem(inx)
            if oracle:
                sem_pd, vote_pd = gt_tsr_res_reduction(
                    oracle_res, self.gt_prod_handle,
                    dset.meta, pcv, pan_gt_mask, segments_info
                )
            else:
                # sem_pd, _ = gt_tsr_res_reduction(
                #     oracle_res, self.gt_prod_handle,
                #     dset.meta, pcv, pan_gt_mask, segments_info
                # )
                sem_pd, vote_pd = model.infer(
                    dset[inx][0].unsqueeze(0).cuda(), softmax_normalize=True
                )

            # img = _downsample_PIL(img)  # rtchange
            if cfg.data.dataset.params['caffe_mode']:
                img = np.array(img)[:, :, ::-1]
            pan_gt_mask = _downsample_PIL(pan_gt_mask)
            vis_engine.vis(
                img, pan_gt_mask, segments_info, sem_pd, vote_pd,
                self.gt_prod_handle, model.criteria, hmap_thresh
            )

        wdgt = interactive(
            logic,
            inx=BoundedIntText(
                min=0, max=len(dset) - 1, step=1
            ),
            hmap_thresh=BoundedFloatText(
                value=cfg.pcv.hmap_thresh, min=0, max=1000.0, step=0.2,
                description='ws_thresh'
            )
        )
        wdgt.children[-1].layout.height = '1300px'
        display(wdgt)
        return vis_engine
Пример #7
0
    def __init__(self, signal_components: dict):
        """
            Summary:
                Object constructor.                
        """

        super().__init__(signal_components, "butter_smoother")

        wbft_fc = BoundedFloatText(description="fc:",
                                   value=0.05,
                                   min=0,
                                   max=0.5,
                                   step=0.01,
                                   disabled=False)

        self.add_options([wbft_fc])
Пример #8
0
class Foreground(object):
    style = {'description_width': '200px'}
    layout = {'width': '300px'}

    widgets = {
        'foreground': BoundedFloatText(value=1, min=0, max=1e6, step=0.1, description='foreground counts (elec/s/pix)'),
    }

    params = ('foreground', )

    def __init__(self):
        """ """
        for key, widget in self.widgets.items():
            widget.style = self.style
            widget.layout = self.layout

        self.widget = VBox([self.widgets['foreground']])
Пример #9
0
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True):
    """
    This function adds the ability to interactively adjust all of the
    plotting.make_plot() arguments.

    Parameters
    ----------
    sa_dict : dict
              a dictionary with all the sensitivity analysis results.
    demo    : bool, optional
              plot only few outcomes for demo purpose.

    Returns
    -------
    Interactive widgets to control plot
    """
    min_val_box = BoundedFloatText(value=0.01,
                                   min=0,
                                   max=1,
                                   description='Min value:')
    top_box = IntText(value=20, description='Show top:')
    stacks = Checkbox(
        description='Show stacked plots:',
        value=True,
    )
    error_bars = Checkbox(description='Show error bars:', value=True)
    log_axis = Checkbox(description='Use log axis:', value=True)

    # get a list of all the parameter options
    key = sa_dict.keys()[0]
    param_options = list(sa_dict[key][0].Parameter.values)
    highlighted = SelectMultiple(description="Choose parameters to highlight",
                                 options=param_options,
                                 value=[])

    return interact(plot_all_outputs,
                    sa_dict=fixed(sa_dict),
                    demo=fixed(demo),
                    min_val=min_val_box,
                    top=top_box,
                    stacked=stacks,
                    error_bars=error_bars,
                    log_axis=log_axis,
                    highlighted_parameters=highlighted,
                    __manual=manual)
Пример #10
0
def travel_time_fun():
    center = [-43.51876443245584, 172.66858981519297]
    m = GroundwaterMap(basemap=basemaps.Esri.WorldImagery,
                       center=center,
                       zoom=14)
    t = IntSlider(value=100,
                  description=r'$t_t$ [day]',
                  min=10,
                  max=365,
                  step=20,
                  continuous_update=False,
                  layout=Layout(max_width='250px'))
    Q = FloatSlider(value=100,
                    description=r'pumping [L/s]',
                    min=0,
                    max=200,
                    step=20,
                    continuous_update=False,
                    layout=Layout(max_width='250px'))
    q = FloatSlider(value=1.5,
                    description=r'$dh/dx$ [m/km]',
                    min=0.5,
                    max=3,
                    step=0.5,
                    continuous_update=False,
                    layout=Layout(max_width='270px'))
    th = BoundedFloatText(value=135,
                          min=0,
                          max=180,
                          description='flow dir. [$^{\circ}$]',
                          layout=Layout(max_width='150px'))
    m.add_well(center)
    m.configure(widgets={
        't': t,
        'Q': Q,
        'q': q,
        'th': th
    },
                func=partial(m.travel_time, 1.e-4, 0.03, 10.))
    return VBox([m, HBox([Q, t, q, th])])
Пример #11
0
    def __init__(self, signal_components: dict, parent=None):
        """
        Summary:
            Object constructor.
        
        Arguments :
            signal_components - dictionary with the signal/components names
        """
        super().__init__(signal_components, peak_detector_widget._type, parent)

        # Add specific options
        wbit_aggregate = BoundedIntText(description="aggregate:",
                                        value=0,
                                        min=0,
                                        step=1,
                                        disabled=False)

        wcb_filter_by_angle = Checkbox(value=False,
                                       description='filter_by_angle:',
                                       disabled=False)

        wbit_min_duration = BoundedIntText(description="min_duration:",
                                           value=-1,
                                           min=-1,
                                           step=1,
                                           disabled=False)

        wbit_min_increase = BoundedFloatText(description="min_increase:",
                                             value=-1,
                                             min=-1,
                                             step=1,
                                             disabled=False)

        self.add_options([
            wbit_min_duration, wbit_min_increase, wcb_filter_by_angle,
            wbit_aggregate
        ])
Пример #12
0
    def __init__(self):

        #        micron_units = HTMLMath(value=r"$\mu M$")
        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)
        #        micron_units = Label('microns')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        # tab_height = '400px'
        tab_height = '500px'
        #        tab_layout = Layout(width='900px',   # border='2px solid black',
        #        tab_layout = Layout(width='850px',   # border='2px solid black',
        #                            height=tab_height, overflow_y='scroll',)
        #        np_tab_layout = Layout(width='800px',  # border='2px solid black',
        #                               height='350px', overflow_y='scroll',)

        # my_domain = [0,0,-10, 2000,2000,10, 20,20,20]  # [x,y,zmin,  x,y,zmax, x,y,zdelta]
        #        label_domain = Label('Domain ($\mu M$):')
        label_domain = Label('Domain (micron):')
        stepsize = 10
        self.xmin = FloatText(
            step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(
            step=stepsize,
            description='Ymin',
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(
            step=stepsize,
            description='Zmin',
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(
            step=stepsize,
            description='Xmax',
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(
            step=stepsize,
            description='Ymax',
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(
            step=stepsize,
            description='Zmax',
            layout=Layout(width=constWidth),
        )
        #            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',  # '∆x',  # Mac: opt-j for delta
            layout=Layout(width=constWidth),
        )
        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            layout=Layout(width=constWidth),
        )
        """
        self.tdelta = BoundedFloatText(
            min=0.01,
            description='$Time_{delta}$',
            layout=Layout(width=constWidth),
        )
        """
        """
        self.toggle2D = Checkbox(
            description='2-D',
            layout=Layout(width=constWidth),
        )
        def toggle2D_cb(b):
            if (self.toggle2D.value):
                #zmin.disabled = zmax.disabled = zdelta.disabled = True
                zmin.disabled = True
                zmax.disabled = True
                zdelta.disabled = True
            else:
                zmin.disabled = False
                zmax.disabled = False
                zdelta.disabled = False
            
        self.toggle2D.observe(toggle2D_cb)
        """

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            description='# threads',
            layout=Layout(width=constWidth),
        )

        # self.toggle_prng = Checkbox(
        #     description='Seed PRNG', style={'description_width': 'initial'},  # e.g. 'initial'  '120px'
        #     layout=Layout(width=constWidth),
        # )
        # self.prng_seed = BoundedIntText(
        #     min = 1,
        #     description='Seed',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        # def toggle_prng_cb(b):
        #     if (toggle_prng.value):
        #         self.prng_seed.disabled = False
        #     else:
        #         self.prng_seed.disabled = True

        # self.toggle_prng.observe(toggle_prng_cb)
        #prng_row = HBox([toggle_prng, prng_seed])

        self.toggle_svg = Checkbox(
            description='Cells',  # SVG
            layout=Layout(width='150px'))  # constWidth = '180px'
        # self.svg_t0 = BoundedFloatText (
        #     min=0,
        #     description='$T_0$',
        #     layout=Layout(width=constWidth),
        # )
        self.svg_interval = BoundedIntText(
            min=1,
            max=
            99999999,  # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True

        self.toggle_svg.observe(toggle_svg_cb)

        self.toggle_mcds = Checkbox(
            #     value=False,
            description='Subtrates',  # Full
            layout=Layout(width='180px'),
        )
        # self.mcds_t0 = FloatText(
        #     description='$T_0$',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        self.mcds_interval = BoundedIntText(
            min=0,
            max=99999999,
            description='every',
            #            disabled=True,
            layout=Layout(width='160px'),
        )

        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                # self.mcds_t0.disabled = False #False
                self.mcds_interval.disabled = False
            else:
                # self.mcds_t0.disabled = True
                self.mcds_interval.disabled = True

        self.toggle_mcds.observe(toggle_mcds_cb)

        #svg_output_row = HBox([toggle_svg, svg_t0, svg_interval])
        #mat_output_row = HBox([toggle_mcds, mcds_t0, mcds_interval])
        #        svg_mat_output_row = HBox([self.toggle_svg, self.svg_interval, self.toggle_mcds, self.mcds_interval])
        svg_mat_output_row = HBox([
            Label('Plots:'), self.toggle_svg,
            HBox([self.svg_interval, Label('min')]), self.toggle_mcds,
            HBox([self.mcds_interval, Label('min')])
        ])
        #write_config_row = HBox([write_config_button, write_config_file])
        #run_sim_row = HBox([run_button, run_command_str, kill_button])
        # run_sim_row = HBox([run_button, run_command_str])
        # run_sim_row = HBox([run_button.w])  # need ".w" for the custom RunCommand widget

        label_blankline = Label('')
        # toggle_2D_seed_row = HBox([toggle_prng, prng_seed])  # toggle2D

        box_layout = Layout(border='1px solid')
        # box_layout = Layout(border='1px solid', height='500px')
        #        domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout)
        domain_box = VBox([label_domain, x_row, y_row], layout=box_layout)
        self.tab = VBox([
            domain_box,
            #                         label_blankline,
            HBox([self.tmax, Label('min')]),
            self.omp_threads,
            svg_mat_output_row,
            #                         HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]),
        ])  # output_dir, toggle_2D_seed_
Пример #13
0
    plt.scatter(corrupted[apples][:, 0],
                corrupted[apples][:, 1],
                color="red",
                alpha=0.7)
    plt.scatter(corrupted[pears][:, 0],
                corrupted[pears][:, 1],
                color="green",
                alpha=0.7)
    ax_2.set_xlabel("yellowness")
    ax_2.set_ylabel("symmetry")

    plt.show()


@interact(b=BoundedFloatText(value=str(g_bias),
                             min=min_b,
                             max=max_b,
                             description="Enter $b$:"),
          w1=BoundedFloatText(value="0",
                              min=min_w1,
                              max=max_w1,
                              description="Enter $w_1$:"),
          w2=BoundedFloatText(value="0",
                              min=min_w2,
                              max=max_w2,
                              description="Enter $w_2$:"),
          learning_rate=Dropdown(
              options=["0.01", "0.05", "0.1", "0.5", "1", "5", "10"],
              value="0.01",
              description="Learning rate: "))
def learning_curve_for_starting_point(b, w1, w2, learning_rate=0.1):
    w = np.array([b, w1, w2]).reshape(X_corrupted.shape[1], 1)
Пример #14
0
    def _create_input_widgets(self) -> None:
        self._input["smiles"] = Text(description="SMILES", continuous_update=False)
        self._input["smiles"].observe(self._show_mol, names="value")
        display(self._input["smiles"])
        self._output["smiles"] = Output(
            layout={"border": "1px solid silver", "width": "50%", "height": "180px"}
        )
        display(self._output["smiles"])

        self._input["stocks"] = [
            Checkbox(
                value=True,
                description=key,
                style={"description_width": "initial"},
                layout={"justify": "left"},
            )
            for key in self.finder.stock.items
        ]

        list_ = [Label("Limit atom occurrences")]
        self._input["stocks_atom_count_on"] = []
        self._input["stocks_atom_count"] = []
        current_criteria = self.finder.stock.stop_criteria.get("counts", {})
        for atom in ["C", "O", "N"]:
            chk_box = Checkbox(
                value=atom in current_criteria,
                description=atom,
                layout={"justify": "left", "width": "80px"},
                style={"description_width": "initial"},
            )
            self._input["stocks_atom_count_on"].append(chk_box)
            inpt = BoundedIntText(
                value=current_criteria.get(atom, 0),
                min=0,
                layout={"width": "80px"},
            )
            self._input["stocks_atom_count"].append(inpt)
            list_.append(HBox([chk_box, inpt]))
        box_stocks = VBox(
            [Label("Stocks")] + self._input["stocks"] + list_,
            layout={"border": "1px solid silver"},
        )

        self._input["policy"] = widgets.Dropdown(
            options=self.finder.expansion_policy.items,
            description="Expansion Policy:",
            style={"description_width": "initial"},
        )

        self._input["filter"] = widgets.Dropdown(
            options=["None"] + self.finder.filter_policy.items,
            description="Filter Policy:",
            style={"description_width": "initial"},
        )

        max_time_box = self._make_slider_input("time_limit", "Time (min)", 1, 120)
        self._input["time_limit"].value = self.finder.config.time_limit / 60
        max_iter_box = self._make_slider_input(
            "iteration_limit", "Max Iterations", 100, 2000
        )
        self._input["iteration_limit"].value = self.finder.config.iteration_limit
        self._input["return_first"] = widgets.Checkbox(
            value=self.finder.config.return_first,
            description="Return first solved route",
        )
        vbox = VBox(
            [
                self._input["policy"],
                self._input["filter"],
                max_time_box,
                max_iter_box,
                self._input["return_first"],
            ]
        )
        box_options = HBox([box_stocks, vbox])

        self._input["C"] = FloatText(description="C", value=self.finder.config.C)
        self._input["max_transforms"] = BoundedIntText(
            description="Max steps for substrates",
            min=1,
            max=6,
            value=self.finder.config.max_transforms,
            style={"description_width": "initial"},
        )
        self._input["cutoff_cumulative"] = BoundedFloatText(
            description="Policy cutoff cumulative",
            min=0,
            max=1,
            value=self.finder.config.cutoff_cumulative,
            style={"description_width": "initial"},
        )
        self._input["cutoff_number"] = BoundedIntText(
            description="Policy cutoff number",
            min=1,
            max=1000,
            value=self.finder.config.cutoff_number,
            style={"description_width": "initial"},
        )
        self._input["filter_cutoff"] = BoundedFloatText(
            description="Filter cutoff",
            min=0,
            max=1,
            value=self.finder.config.filter_cutoff,
            style={"description_width": "initial"},
        )
        self._input["exclude_target_from_stock"] = widgets.Checkbox(
            value=self.finder.config.exclude_target_from_stock,
            description="Exclude target from stock",
        )
        box_advanced = VBox(
            [
                self._input["C"],
                self._input["max_transforms"],
                self._input["cutoff_cumulative"],
                self._input["cutoff_number"],
                self._input["filter_cutoff"],
                self._input["exclude_target_from_stock"],
            ]
        )

        children = [box_options, box_advanced]
        tab = widgets.Tab()
        tab.children = children
        tab.set_title(0, "Options")
        tab.set_title(1, "Advanced")
        display(tab)
Пример #15
0
class Galaxy(object):
    """ """

    style = {'description_width': '200px'}
    layout = {'width': '300px'}

    widgets = {
        'redshift':
        BoundedFloatText(value=1,
                         min=0,
                         max=10,
                         step=0.1,
                         description="Redshift"),
        'bulge_scale':
        BoundedFloatText(value=0.5,
                         min=0,
                         max=10,
                         step=0.1,
                         description="Bulge scale (arcsec)"),
        'disk_scale':
        BoundedFloatText(value=0.3,
                         min=0,
                         max=10,
                         step=0.1,
                         description="Disk scale (arcsec)"),
        'bulge_fraction':
        BoundedFloatText(value=.5,
                         min=0,
                         max=1,
                         step=0.1,
                         description="Bulge fraction"),
        'axis_ratio':
        BoundedFloatText(value=1,
                         min=0.01,
                         max=1,
                         step=0.1,
                         description="Axis ratio"),
        'pa':
        BoundedFloatText(value=0,
                         min=-180,
                         max=180,
                         step=10,
                         description="Position angle"),
        'iso':
        Checkbox(value=True, description="Isotropize"),
        'half_light_radius':
        HBox([Label("Half-light radius (arcsec): "),
              Label(value="0")]),
        'velocity_dispersion':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description="Velocity dispersion (km/s)"),
        'flux_ha':
        BoundedFloatText(
            value=2,
            min=0,
            max=1000,
            step=0.1,
            description='Flux H$\\alpha$ 6565 ($10^{-16}$ erg/cm2/s):'),
        'n2_ha_ratio':
        BoundedFloatText(value=0,
                         min=0,
                         max=10,
                         step=0.1,
                         description='NII/H$\\alpha$:'),
        'flux_n2a':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux NIIa 6550 ($10^{-16}$ erg/cm2/s):'),
        'flux_n2b':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux NIIb 6585 ($10^{-16}$ erg/cm2/s):'),
        'flux_hb':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux Hb 4863 ($10^{-16}$ erg/cm2/s):'),
        'flux_o3a':
        BoundedFloatText(
            value=0,
            min=0,
            max=1000,
            step=0.1,
            description='Flux OIIIa 4960 ($10^{-16}$ erg/cm2/s):'),
        'flux_o3b':
        BoundedFloatText(
            value=0,
            min=0,
            max=1000,
            step=0.1,
            description='Flux OIIIb 5008 ($10^{-16}$ erg/cm2/s):'),
        'flux_s2a':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux SIIa 6718 ($10^{-16}$ erg/cm2/s):'),
        'flux_s2b':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux SIIb 6733 ($10^{-16}$ erg/cm2/s):'),
        'flux_o2':
        BoundedFloatText(value=0,
                         min=0,
                         max=1000,
                         step=0.1,
                         description='Flux OII 3727 ($10^{-16}$ erg/cm2/s):'),
        'flux_s3a':
        BoundedFloatText(
            value=0,
            min=0,
            max=1000,
            step=0.1,
            description='Flux SIIIa 9069 ($10^{-16}$ erg/cm2/s):'),
        'flux_s3b':
        BoundedFloatText(
            value=0,
            min=0,
            max=1000,
            step=0.1,
            description='Flux SIIIb 9531 ($10^{-16}$ erg/cm2/s):'),
    }

    params = ('redshift', 'bulge_scale', 'disk_scale', 'bulge_fraction',
              'axis_ratio', 'pa', 'iso', 'velocity_dispersion', 'flux_ha',
              'flux_n2a', 'flux_n2b', 'flux_hb', 'flux_o3a', 'flux_o3b',
              'flux_s2a', 'flux_s2b', 'flux_o2', 'flux_s3a', 'flux_s3b')

    def __init__(self):
        for key, widget in self.widgets.items():
            widget.style = self.style
            widget.layout = self.layout

        self.widgets['bulge_scale'].observe(self.compute_radius, names='value')
        self.widgets['disk_scale'].observe(self.compute_radius, names='value')
        self.widgets['bulge_fraction'].observe(self.compute_radius,
                                               names='value')
        self.widgets['axis_ratio'].observe(self.compute_radius, names='value')

        self.widgets['flux_ha'].observe(self.flux_ha_change, names='value')
        self.widgets['n2_ha_ratio'].observe(self.n2_ha_ratio_change,
                                            names='value')
        self.widgets['flux_n2a'].observe(self.flux_n2a_change, names='value')
        self.widgets['flux_n2b'].observe(self.flux_n2b_change, names='value')
        self.widgets['flux_s2a'].observe(self.flux_s2a_change, names='value')
        self.widgets['flux_s2b'].observe(self.flux_s2b_change, names='value')
        self.widgets['flux_o3a'].observe(self.flux_o3a_change, names='value')
        self.widgets['flux_o3b'].observe(self.flux_o3b_change, names='value')

        self.compute_radius()

        title = HTML("<h2>Galaxy</h2>")
        n2box = HBox([
            self.widgets['n2_ha_ratio'], self.widgets['flux_n2a'],
            self.widgets['flux_n2b']
        ])
        s2box = HBox([self.widgets['flux_s2a'], self.widgets['flux_s2b']])
        o3box = HBox([self.widgets['flux_o3a'], self.widgets['flux_o3b']])
        hbbox = HBox([self.widgets['flux_hb']])
        o2box = HBox([self.widgets['flux_o2']])
        s3box = HBox([self.widgets['flux_s3a'], self.widgets['flux_s3b']])

        elements = []
        elements += [self.widgets['redshift']]

        sizebox = VBox([
            self.widgets['bulge_scale'], self.widgets['disk_scale'],
            self.widgets['bulge_fraction'], self.widgets['axis_ratio'],
            self.widgets['pa'], self.widgets['iso']
        ])
        elements += [
            HTML("<b>Size</b>"),
            HBox([sizebox, self.widgets['half_light_radius']])
        ]
        elements += [
            HTML("<b>Emission lines</b>"), self.widgets['velocity_dispersion'],
            self.widgets['flux_ha'], n2box, s2box, hbbox, o3box, o2box, s3box
        ]

        self.widget = VBox(elements)

    def compute_radius(self, change=None):
        """ """
        radius = bulgy_disk_radius(
            np.array([self.widgets['bulge_scale'].value]),
            np.array([self.widgets['disk_scale'].value]),
            np.array([self.widgets['bulge_fraction'].value]),
            np.array([self.widgets['axis_ratio'].value]), 0.5)[0]
        self.widgets['half_light_radius'].children[1].value = "%3.2f" % radius

    def n2_ha_ratio_change(self, change):
        y = self.widgets['n2_ha_ratio'].value * self.widgets['flux_ha'].value
        self.widgets['flux_n2a'].value = y / 4.
        self.widgets['flux_n2b'].value = y * 3 / 4.

    flux_ha_change = n2_ha_ratio_change

    def flux_n2b_change(self, change):
        self.widgets['flux_n2a'].value = self.widgets['flux_n2b'].value / 3.
        self.widgets['n2_ha_ratio'].value = (
            self.widgets['flux_n2a'].value +
            self.widgets['flux_n2b'].value) / self.widgets['flux_ha'].value

    def flux_n2a_change(self, change):
        self.widgets['flux_n2b'].value = self.widgets['flux_n2a'].value * 3.
        self.widgets['n2_ha_ratio'].value = (
            self.widgets['flux_n2a'].value +
            self.widgets['flux_n2b'].value) / self.widgets['flux_ha'].value

    def flux_s2b_change(self, change):
        self.widgets['flux_s2a'].value = self.widgets['flux_s2b'].value

    def flux_s2a_change(self, change):
        self.widgets['flux_s2b'].value = self.widgets['flux_s2a'].value

    def flux_o3b_change(self, change):
        self.widgets['flux_o3a'].value = self.widgets['flux_o3b'].value / 3.

    def flux_o3a_change(self, change):
        self.widgets['flux_o3b'].value = self.widgets['flux_o3a'].value * 3.

    def flux_s3b_change(self, change):
        self.widgets['flux_s3a'].value = self.widgets['flux_s3b'].value
Пример #16
0
class Analysis(object):
    style = {'description_width': '200px'}
    layout = {'width': '400px'}

    widgets = {
        'zmeas_template_file':
        Dropdown(options=get_template_files(),
                 description='Spec templates file'),
        'extraction_sigma':
        BoundedFloatText(value=2,
                         min=0,
                         max=100,
                         step=0.1,
                         description='Extraction kernel width (pixels)'),
        'zmin':
        BoundedFloatText(value=0,
                         min=0,
                         max=10,
                         step=0.1,
                         description='Redshift grid min'),
        'zmax':
        BoundedFloatText(value=3,
                         min=0,
                         max=10,
                         step=0.1,
                         description='Redshift grid max'),
        'zstep':
        BoundedFloatText(value=0.001,
                         min=0,
                         max=0.01,
                         step=0.0005,
                         description='Redshift grid step'),
        'templ_res':
        BoundedIntText(value=5,
                       min=1,
                       max=100,
                       step=1,
                       description='Resolution parameter'),
        'ztol':
        BoundedFloatText(value=0.01,
                         min=0.0001,
                         max=1,
                         step=0.0005,
                         description='Redshift error tolerance'),
        'output':
        Output(layout={'width': '800px'}),
    }

    params = ('zmeas_template_file', 'extraction_sigma', 'zmin', 'zmax',
              'zstep', 'ztol', 'templ_res')

    def __init__(self):
        """ """
        for key, widget in self.widgets.items():
            widget.style = self.style
            widget.layout = self.layout
        self.widgets['output'].layout = {'width': '800px'}

        self.widgets['zmeas_template_file'].observe(self.show_template_table,
                                                    names='value')

        elements = []
        elements += [
            HTML('<b>Extraction</b>'), self.widgets['extraction_sigma']
        ]
        elements += [
            HTML('<b>Redshift measurement</b>'),
            self.widgets['zmeas_template_file'], self.widgets['zmin'],
            self.widgets['zmax'], self.widgets['zstep'],
            self.widgets['templ_res'], self.widgets['ztol']
        ]

        bot = VBox(
            [HTML('<b>Spec templates table</b>'), self.widgets['output']],
            layout={
                'width': '800px',
                'display': 'flex'
            })

        top = VBox(elements, layout={'width': '800px', 'display': 'flex'})

        self.widget = VBox([top, bot], layout={'width': '800px'})

        self.show_template_table()

    def show_template_table(self, change=None):
        with self.widgets['output']:
            clear_output()
            display(Label(self.widgets['zmeas_template_file'].value))
            self.template_path = os.path.join(
                TEMPLATE_DIR, self.widgets['zmeas_template_file'].value)
            table = pandas.read_csv(self.template_path, sep=",")
            display(table)
 def __init__(self, name, init_value, max_value=100):
     self.label = Label(value=name,  layout=Layout(width='120px'))
     self.float_text = BoundedFloatText(min=0, max=max_value, value=init_value, layout=Layout(width='120px'))
     super().__init__(children=[self.label, self.float_text])
Пример #18
0
    def load_UI(self):
        '''Setting up the interactive visualization tool'''

        # UI elements
        range_slider = IntRangeSlider(value=[1, self.time_window],
                                      min=1,
                                      max=self.time_window,
                                      description="Range: ",
                                      continuous_update=False)
        view_ftr_i = IntSlider(min=1,
                               max=self.num_features,
                               default_value=2,
                               description="View Feature: ",
                               continuous_update=False)
        self.modify_ftr_i = IntSlider(min=1,
                                      max=self.num_features,
                                      default_value=2,
                                      description="Mod Feature: ",
                                      continuous_update=False)
        uniform_slider = FloatSlider(value=0,
                                     min=-1,
                                     max=1,
                                     step=0.05,
                                     description='Value:',
                                     continuous_update=False)
        radio_button_uni = RadioButtons(options=[('Positive Weights', 1),
                                                 ('Negative Weights', -1)],
                                        description='Affect:')
        select_target = BoundedFloatText(
            value=(self.min_target + self.max_target) / 2,
            min=self.min_target,
            max=self.max_target,
            layout={'width': '150px'})
        radio_button_xyz7 = RadioButtons(options=[
            ('Present (' + str(self.forecast_window) + '-last values)', 0),
            ('Future (' + str(self.forecast_window) + '-next values)', 1)
        ],
                                         description='Affect:')
        enable_iPCA = Checkbox(value=False, description='Enable iPCA')
        iml_method = ToggleButtons(options=['LioNets', 'Lime'])
        self.forecast = Dropdown(options=[('Neural', 6), ('Static', 7),
                                          ('N-Beats', 8)],
                                 description="Forecast: ")
        mod = Dropdown(options=[('Original', 0), ('Uniform', 1),
                                ('Mean (Local)', 2), ('Mean (Global)', 3),
                                ('Zeros', 4), ('Noise', 5),
                                ('Forecast (Neural)', 6),
                                ('Forecast (Static)', 7),
                                ('Forecast (N-Beats)', 8),
                                ('Forecast (XYZ7)', 9)],
                       description="Mods: ")
        jsdlink((self.modify_ftr_i, 'value'), (view_ftr_i, 'value'))

        # UI layout
        interpretable_settings = HBox(
            [Label('Interpretation method:'), iml_method, enable_iPCA])
        enable_iPCA.layout.margin = '0 0 0 -50px'
        interpretable_settings.layout.margin = '20px 0 20px 0'
        standard_settings = VBox([self.modify_ftr_i, view_ftr_i])
        xyz7_settings = VBox([
            HBox([Label('Desired Target:'), select_target]), radio_button_xyz7
        ])
        xyz7_settings.layout.margin = '0 0 0 30px'
        self.opt1_settings = VBox([mod])
        self.opt2_settings = VBox([mod, range_slider])
        self.opt3_settings = HBox([
            VBox([mod, range_slider]),
            VBox([uniform_slider, radio_button_uni])
        ])
        self.opt4_settings = HBox([VBox([mod, self.forecast]), xyz7_settings])
        self.mod_settings = VBox([])
        ui = VBox([
            interpretable_settings,
            HBox([standard_settings, self.mod_settings])
        ])

        # Starting the interactive tool
        inter = interactive_output(
            self.plot_feature, {
                'ftr_i': view_ftr_i,
                'mod_ftr_i': self.modify_ftr_i,
                'mod': mod,
                'rng_sldr': range_slider,
                'uni_sldr': uniform_slider,
                'rd_btn_uni': radio_button_uni,
                'select_target': select_target,
                'rd_btn_xyz7': radio_button_xyz7,
                'forecast_optns': self.forecast,
                'iml_method': iml_method,
                'enable_ipca': enable_iPCA
            })
        display(ui, inter)
Пример #19
0
    def _create_input_widgets(self):
        self._input["smiles"] = Text(description="SMILES", continuous_update=False)
        self._input["smiles"].observe(self._show_mol, names="value")
        display(self._input["smiles"])
        self._output["smiles"] = Output(
            layout={"border": "1px solid silver", "width": "50%", "height": "180px"}
        )
        display(self._output["smiles"])

        self._input["stocks"] = [
            Checkbox(value=True, description=key, layout={"justify": "left"})
            for key in self.finder.stock.available_stocks()
        ]
        box_stocks = VBox(
            [Label("Stocks")] + self._input["stocks"],
            layout={"border": "1px solid silver"},
        )

        self._input["policy"] = widgets.Dropdown(
            options=self.finder.policy.available_policies(),
            description="Neural Policy:",
            style={"description_width": "initial"},
        )

        max_time_box = self._make_slider_input("time_limit", "Time (min)", 1, 120)
        self._input["time_limit"].value = self.finder.config.time_limit / 60
        max_iter_box = self._make_slider_input(
            "iteration_limit", "Max Iterations", 100, 2000
        )
        self._input["iteration_limit"].value = self.finder.config.iteration_limit
        self._input["return_first"] = widgets.Checkbox(
            value=self.finder.config.return_first,
            description="Return first solved route",
        )
        vbox = VBox(
            [
                self._input["policy"],
                max_time_box,
                max_iter_box,
                self._input["return_first"],
            ]
        )
        box_options = HBox([box_stocks, vbox])

        self._input["C"] = FloatText(description="C", value=self.finder.config.C)
        self._input["max_transforms"] = BoundedIntText(
            description="Max steps for substrates",
            min=1,
            max=6,
            value=self.finder.config.max_transforms,
            style={"description_width": "initial"},
        )
        self._input["cutoff_cumulative"] = BoundedFloatText(
            description="Policy cutoff cumulative",
            min=0,
            max=1,
            value=self.finder.config.cutoff_cumulative,
            style={"description_width": "initial"},
        )
        self._input["cutoff_number"] = BoundedIntText(
            description="Policy cutoff number",
            min=1,
            max=1000,
            value=self.finder.config.cutoff_number,
            style={"description_width": "initial"},
        )
        self._input["exclude_target_from_stock"] = widgets.Checkbox(
            value=self.finder.config.exclude_target_from_stock,
            description="Exclude target from stock",
        )
        box_advanced = VBox(
            [
                self._input["C"],
                self._input["max_transforms"],
                self._input["cutoff_cumulative"],
                self._input["cutoff_number"],
                self._input["exclude_target_from_stock"],
            ]
        )

        children = [box_options, box_advanced]
        tab = widgets.Tab()
        tab.children = children
        tab.set_title(0, "Options")
        tab.set_title(1, "Advanced")
        display(tab)
Пример #20
0
    def __init__(self, controller: TwittipediaController):

        self.controller = controller

        title = HTML(value="<h1>Twittipedia</h1>",
                     description="",
                     disabled=False)

        # Twitter

        twitter_title = HTML(value="<b>Tweets</b>",
                             description="",
                             disabled=False)

        self.query_field = Text(value="",
                                placeholder="Search or enter username",
                                description="",
                                disabled=False,
                                layout=dict(width="auto"))
        self.query_field.observe(self._query_field_changed, names="value")

        self.number_of_tweets_field = BoundedIntText(
            value=DEFAULT_NUMBER_OF_TWEETS,
            min=1,
            max=100,
            step=1,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.number_of_tweets_field.observe(
            self._number_of_tweets_field_changed, names="value")
        number_of_tweets_label = Label(value="most recent tweets",
                                       disabled=False,
                                       layout=dict(width="auto"))
        number_of_tweets_field_with_label = HBox(
            (self.number_of_tweets_field, number_of_tweets_label))

        self.search_tweets_button = Button(description="Search Tweets",
                                           disabled=True,
                                           button_style="primary",
                                           tooltip="",
                                           icon="",
                                           layout=dict(width="auto"))
        self.load_tweets_from_user_button = Button(
            description="Load Tweets from User",
            disabled=True,
            button_style="",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.twitter_search_buttons = [
            self.load_tweets_from_user_button, self.search_tweets_button
        ]

        for button in self.twitter_search_buttons:
            button.on_click(self._twitter_search_button_pressed)

        twitter_search_buttons_box = Box(self.twitter_search_buttons,
                                         layout=dict(
                                             justify_content="flex-end",
                                             flex_flow="row wrap",
                                         ))

        self.reset_and_clear_tweets_button = Button(
            description="Reset and Clear Tweets",
            disabled=True,
            button_style="danger",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.reset_and_clear_tweets_button.on_click(
            self._reset_and_clear_tweets_button_pressed)

        self.twitter_buttons = self.twitter_search_buttons \
            + [self.reset_and_clear_tweets_button]
        twitter_buttons_box = Box(
            (self.reset_and_clear_tweets_button, twitter_search_buttons_box),
            layout=dict(
                justify_content="space-between",
                flex_flow="row wrap",
            ))

        twitter_box = VBox(
            (twitter_title, self.query_field,
             number_of_tweets_field_with_label, twitter_buttons_box))

        # Wikipedia search

        wikipedia_title = HTML(value="<b>Wikipedia Search</b>",
                               description="",
                               disabled=False)

        self.wikipedia_options = []

        self.term_frequency_scaling_parameter_field = BoundedFloatText(
            value=DEFAULT_TERM_FREQUENCY_SCALING_PARAMETER_VALUE,
            min=0,
            max=100,
            step=0.1,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.term_frequency_scaling_parameter_field.observe(
            self._term_frequency_scaling_parameter_field_changed,
            names="value")
        self.wikipedia_options.append({
            "label": "$k_1$${{}}=$",
            "field": self.term_frequency_scaling_parameter_field,
            "explanation": "$k_1 \ge 0$"
        })

        self.document_length_scaling_parameter_field = BoundedFloatText(
            value=DEFAULT_DOCUMENT_LENGTH_SCALING_PARAMETER_VALUE,
            min=0,
            max=1,
            step=0.01,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.document_length_scaling_parameter_field.observe(
            self._document_length_scaling_parameter_field_changed,
            names="value")
        self.wikipedia_options.append({
            "label": "$b$${{}}=$",
            "field": self.document_length_scaling_parameter_field,
            "explanation": "$0 \le b$${} \le 1$"
        })

        wikipedia_options_box = Box(
            (VBox([
                Label(value=option["label"])
                for option in self.wikipedia_options
            ],
                  layout=dict(align_items="flex-end")),
             VBox([option["field"] for option in self.wikipedia_options], ),
             VBox([
                 Label(value="(" + option["explanation"] + ")")
                 for option in self.wikipedia_options
             ])))

        self.search_wikipedia_button = Button(
            description="Search Wikipedia with Tweets",
            disabled=True,
            button_style="primary",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.search_wikipedia_button.on_click(
            self._search_wikipedia_button_pressed)

        self.reset_and_clear_wikipedia_results_button = Button(
            description="Reset and Clear Results",
            disabled=True,
            button_style="danger",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.reset_and_clear_wikipedia_results_button.on_click(
            self._reset_and_clear_wikipedia_results_button_pressed)

        self.wikipedia_buttons = [
            self.reset_and_clear_wikipedia_results_button,
            self.search_wikipedia_button
        ]

        wikipedia_buttons_box = Box(self.wikipedia_buttons,
                                    layout=dict(
                                        justify_content="space-between",
                                        flex_flow="row wrap",
                                    ))

        wikipedia_box = VBox(
            (wikipedia_title, wikipedia_options_box, wikipedia_buttons_box))

        # Result views

        results_title = HTML(value="<b>Results</b>",
                             description="",
                             disabled=True)

        self.results_box = VBox([DEFAULT_RESULTS_WIDGET])
        self.results = None

        # Together

        self.buttons = self.twitter_buttons + self.wikipedia_buttons

        search_box = VBox((twitter_box, wikipedia_box),
                          # layout=dict(max_width="600px")
                          )

        results_box = VBox((results_title, self.results_box))

        self.widget = VBox((title, search_box, results_box))

        self._reset_and_clear_tweets()
Пример #21
0
class TwittipediaView:
    def __init__(self, controller: TwittipediaController):

        self.controller = controller

        title = HTML(value="<h1>Twittipedia</h1>",
                     description="",
                     disabled=False)

        # Twitter

        twitter_title = HTML(value="<b>Tweets</b>",
                             description="",
                             disabled=False)

        self.query_field = Text(value="",
                                placeholder="Search or enter username",
                                description="",
                                disabled=False,
                                layout=dict(width="auto"))
        self.query_field.observe(self._query_field_changed, names="value")

        self.number_of_tweets_field = BoundedIntText(
            value=DEFAULT_NUMBER_OF_TWEETS,
            min=1,
            max=100,
            step=1,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.number_of_tweets_field.observe(
            self._number_of_tweets_field_changed, names="value")
        number_of_tweets_label = Label(value="most recent tweets",
                                       disabled=False,
                                       layout=dict(width="auto"))
        number_of_tweets_field_with_label = HBox(
            (self.number_of_tweets_field, number_of_tweets_label))

        self.search_tweets_button = Button(description="Search Tweets",
                                           disabled=True,
                                           button_style="primary",
                                           tooltip="",
                                           icon="",
                                           layout=dict(width="auto"))
        self.load_tweets_from_user_button = Button(
            description="Load Tweets from User",
            disabled=True,
            button_style="",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.twitter_search_buttons = [
            self.load_tweets_from_user_button, self.search_tweets_button
        ]

        for button in self.twitter_search_buttons:
            button.on_click(self._twitter_search_button_pressed)

        twitter_search_buttons_box = Box(self.twitter_search_buttons,
                                         layout=dict(
                                             justify_content="flex-end",
                                             flex_flow="row wrap",
                                         ))

        self.reset_and_clear_tweets_button = Button(
            description="Reset and Clear Tweets",
            disabled=True,
            button_style="danger",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.reset_and_clear_tweets_button.on_click(
            self._reset_and_clear_tweets_button_pressed)

        self.twitter_buttons = self.twitter_search_buttons \
            + [self.reset_and_clear_tweets_button]
        twitter_buttons_box = Box(
            (self.reset_and_clear_tweets_button, twitter_search_buttons_box),
            layout=dict(
                justify_content="space-between",
                flex_flow="row wrap",
            ))

        twitter_box = VBox(
            (twitter_title, self.query_field,
             number_of_tweets_field_with_label, twitter_buttons_box))

        # Wikipedia search

        wikipedia_title = HTML(value="<b>Wikipedia Search</b>",
                               description="",
                               disabled=False)

        self.wikipedia_options = []

        self.term_frequency_scaling_parameter_field = BoundedFloatText(
            value=DEFAULT_TERM_FREQUENCY_SCALING_PARAMETER_VALUE,
            min=0,
            max=100,
            step=0.1,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.term_frequency_scaling_parameter_field.observe(
            self._term_frequency_scaling_parameter_field_changed,
            names="value")
        self.wikipedia_options.append({
            "label": "$k_1$${{}}=$",
            "field": self.term_frequency_scaling_parameter_field,
            "explanation": "$k_1 \ge 0$"
        })

        self.document_length_scaling_parameter_field = BoundedFloatText(
            value=DEFAULT_DOCUMENT_LENGTH_SCALING_PARAMETER_VALUE,
            min=0,
            max=1,
            step=0.01,
            description="",
            disabled=False,
            layout=dict(width="auto"))
        self.document_length_scaling_parameter_field.observe(
            self._document_length_scaling_parameter_field_changed,
            names="value")
        self.wikipedia_options.append({
            "label": "$b$${{}}=$",
            "field": self.document_length_scaling_parameter_field,
            "explanation": "$0 \le b$${} \le 1$"
        })

        wikipedia_options_box = Box(
            (VBox([
                Label(value=option["label"])
                for option in self.wikipedia_options
            ],
                  layout=dict(align_items="flex-end")),
             VBox([option["field"] for option in self.wikipedia_options], ),
             VBox([
                 Label(value="(" + option["explanation"] + ")")
                 for option in self.wikipedia_options
             ])))

        self.search_wikipedia_button = Button(
            description="Search Wikipedia with Tweets",
            disabled=True,
            button_style="primary",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.search_wikipedia_button.on_click(
            self._search_wikipedia_button_pressed)

        self.reset_and_clear_wikipedia_results_button = Button(
            description="Reset and Clear Results",
            disabled=True,
            button_style="danger",
            tooltip="",
            icon="",
            layout=dict(width="auto"))
        self.reset_and_clear_wikipedia_results_button.on_click(
            self._reset_and_clear_wikipedia_results_button_pressed)

        self.wikipedia_buttons = [
            self.reset_and_clear_wikipedia_results_button,
            self.search_wikipedia_button
        ]

        wikipedia_buttons_box = Box(self.wikipedia_buttons,
                                    layout=dict(
                                        justify_content="space-between",
                                        flex_flow="row wrap",
                                    ))

        wikipedia_box = VBox(
            (wikipedia_title, wikipedia_options_box, wikipedia_buttons_box))

        # Result views

        results_title = HTML(value="<b>Results</b>",
                             description="",
                             disabled=True)

        self.results_box = VBox([DEFAULT_RESULTS_WIDGET])
        self.results = None

        # Together

        self.buttons = self.twitter_buttons + self.wikipedia_buttons

        search_box = VBox((twitter_box, wikipedia_box),
                          # layout=dict(max_width="600px")
                          )

        results_box = VBox((results_title, self.results_box))

        self.widget = VBox((title, search_box, results_box))

        self._reset_and_clear_tweets()

    def _disable_twitter_buttons(self):
        for button in self.twitter_buttons:
            button.disabled = True

    def _enable_twitter_buttons(self):
        for button in self.twitter_buttons:
            button.disabled = False

    def _disable_twitter_search_buttons(self):
        for button in self.twitter_search_buttons:
            button.disabled = True

    def _enable_twitter_search_buttons(self):
        for button in self.twitter_search_buttons:
            button.disabled = False

    def _disable_wikipedia_buttons(self):
        for button in self.wikipedia_buttons:
            button.disabled = True

    def _enable_wikipedia_buttons(self):
        for button in self.wikipedia_buttons:
            button.disabled = False

    def _disable_all_buttons(self):
        for button in self.buttons:
            button.disabled = True

    def _enable_all_buttons(self):
        for button in self.buttons:
            button.disabled = False

    def _reset_and_clear_tweets(self):
        self.query_field.value = ""
        self.number_of_tweets_field.value = \
            DEFAULT_NUMBER_OF_TWEETS
        self.results_box.children = [DEFAULT_RESULTS_WIDGET]
        self._disable_twitter_buttons()
        self.search_wikipedia_button.disabled = True
        self._reset_and_clear_wikipedia_results()

    def _reset_and_clear_wikipedia_results(self):
        self.term_frequency_scaling_parameter_field.value = \
            DEFAULT_TERM_FREQUENCY_SCALING_PARAMETER_VALUE
        self.document_length_scaling_parameter_field.value = \
            DEFAULT_DOCUMENT_LENGTH_SCALING_PARAMETER_VALUE
        self._clear_wikipedia_results()
        self.reset_and_clear_wikipedia_results_button.disabled = True

    def _clear_wikipedia_results(self):
        if isinstance(self.results, list):
            for result in self.results:
                if "articles" in result:
                    result["articles"].value = ""

    def _query_field_changed(self, notification):

        if notification.type == "change":

            query = notification.new

            if query:
                self.reset_and_clear_tweets_button.disabled = False
                self.search_tweets_button.disabled = False
            else:
                self.reset_and_clear_tweets_button.disabled = True
                self.search_tweets_button.disabled = True

            is_username, username = check_twitter_username(query)

            if is_username:
                self.load_tweets_from_user_button.disabled = False
            else:
                self.load_tweets_from_user_button.disabled = True

    def _number_of_tweets_field_changed(self, notification):

        if notification.type == "change":

            number_of_tweets = notification.new

            if number_of_tweets == DEFAULT_NUMBER_OF_TWEETS:
                self.reset_and_clear_tweets_button.disabled = True
            else:
                self.reset_and_clear_tweets_button.disabled = False

    def _term_frequency_scaling_parameter_field_changed(self, notification):

        if notification.type == "change":

            term_frequency_scaling_parameter = notification.new

            if term_frequency_scaling_parameter == \
                DEFAULT_TERM_FREQUENCY_SCALING_PARAMETER_VALUE:

                self.reset_and_clear_wikipedia_results_button.disabled = True
            else:
                self.reset_and_clear_wikipedia_results_button.disabled = False

    def _document_length_scaling_parameter_field_changed(self, notification):

        if notification.type == "change":

            document_length_scaling_parameter = notification.new

            if document_length_scaling_parameter == \
                DEFAULT_DOCUMENT_LENGTH_SCALING_PARAMETER_VALUE:

                self.reset_and_clear_wikipedia_results_button.disabled = True
            else:
                self.reset_and_clear_wikipedia_results_button.disabled = False

    def _twitter_search_button_pressed(self, button):

        query = self.query_field.value
        count = self.number_of_tweets_field.value

        if button is self.search_tweets_button:
            twitter_method = "search"
            query_string = f"Searching for recent tweets matching \"{query}\"..."

        elif button is self.load_tweets_from_user_button:
            twitter_method = "user_timeline"
            username = query.lstrip("@")
            query_string = f"Loading tweets from @{username}..."

        self.results_box.children = [HTML(f"<i>{query_string}</i>")]

        self._disable_all_buttons()

        self.controller.search_tweets(query=query,
                                      twitter_method=twitter_method,
                                      count=count)

        self._enable_twitter_buttons()

    def _reset_and_clear_tweets_button_pressed(self, button):
        self._reset_and_clear_tweets()

    def _reset_and_clear_wikipedia_results_button_pressed(self, button):
        self._reset_and_clear_wikipedia_results()

    def _search_wikipedia_button_pressed(self, button):

        k_1 = self.term_frequency_scaling_parameter_field.value
        b = self.document_length_scaling_parameter_field.value

        self._disable_all_buttons()

        self.controller.search_wikipedia(k_1=k_1, b=b)

        self._enable_all_buttons()

    def show_tweets(self, tweets):

        self.results = []

        for tweet in tweets:

            result = {
                "tweet": Output(layout=dict(width="50%")),
                "articles": HTML(layout=dict(width="50%"))
            }
            self.results.append(result)

            with result["tweet"]:
                display(IPHTML(tweet.as_html(hide_thread=True)))

        self.results_box.children = [
            HBox((result["tweet"], result["articles"]))
            for result in self.results
        ]

        display(
            IPHTML(
                '<script id="twitter-wjs" type="text/javascript" async defer src="//platform.twitter.com/widgets.js"></script>'
            ))
        self.search_wikipedia_button.disabled = False

    def show_articles_for_tweet_number(self, i, formatted_results):
        if isinstance(self.results, list) \
            and i < len(self.results) \
            and "articles" in self.results[i] \
            and isinstance(self.results[i]["articles"], HTML):
            self.results[i]["articles"].value = formatted_results
Пример #22
0
class Survey(object):
    style = {'description_width': '200px'}
    layout = {'width': '350px'}

    widgets = {
        'config':
        Dropdown(options=configurations.keys(), description='Configurations:'),
        'exp_time':
        BoundedFloatText(value=565,
                         min=0,
                         max=1e6,
                         step=5,
                         description='Exposure time (sec)'),
        'nexp_red':
        BoundedIntText(value=4,
                       min=0,
                       max=1000,
                       step=1,
                       description='Number of red exposures'),
        'nexp_blue':
        BoundedIntText(value=0,
                       min=0,
                       max=1000,
                       step=1,
                       description='Number of blue exposures'),
    }

    params = ('exp_time', 'nexp_red', 'nexp_blue')

    def __init__(self):
        """ """
        self._set_custom = True
        for key, widget in self.widgets.items():
            widget.style = self.style
            widget.layout = self.layout

        self.update(**configurations[self.widgets['config'].value])
        self.widgets['config'].observe(self.change_config, names='value')

        for key, widget in self.widgets.items():
            if key in ['config']:
                continue
            widget.observe(self.modify, names='value')

        elements = [
            self.widgets['config'],
            HTML('<b>Exposure</b>'), self.widgets['exp_time'],
            self.widgets['nexp_red'], self.widgets['nexp_blue']
        ]

        self.widget = VBox(elements)

    def update(self, **kwargs):
        """ """
        for key, value in kwargs.items():
            if key in self.widgets:
                self.widgets[key].value = value

    def change_config(self, change):
        """ """
        self._set_custom = False
        key = change['new']
        self.update(**configurations[key])
        self._set_custom = True

    def modify(self, change):
        """ """
        if not self._set_custom:
            return
        self.widgets['config'].value = 'custom'
Пример #23
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        label_domain = Label('Domain (micron):')
        stepsize = 10
        self.xmin = FloatText(
            step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(
            step=stepsize,
            description='Ymin',
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(
            step=stepsize,
            description='Zmin',
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(
            step=stepsize,
            description='Xmax',
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(
            step=stepsize,
            description='Ymax',
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(
            step=stepsize,
            description='Zmax',
            layout=Layout(width=constWidth),
        )
        #            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',  # '∆x',  # Mac: opt-j for delta
            layout=Layout(width=constWidth),
        )
        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            layout=Layout(width=constWidth),
        )

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            description='# threads',
            layout=Layout(width=constWidth),
        )
        self.toggle_svg = Checkbox(
            description='Cells',  # SVG
            layout=Layout(width='150px'))  # constWidth = '180px'
        self.svg_interval = BoundedIntText(
            min=1,
            max=
            99999999,  # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True

        self.toggle_svg.observe(toggle_svg_cb)

        self.toggle_mcds = Checkbox(
            description='Subtrates',  # Full
            layout=Layout(width='180px'),
        )
        self.mcds_interval = BoundedIntText(
            min=0,
            max=99999999,
            description='every',
            layout=Layout(width='160px'),
        )

        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                self.mcds_interval.disabled = False
            else:
                self.mcds_interval.disabled = True

        self.toggle_mcds.observe(toggle_mcds_cb)

        svg_mat_output_row = HBox([
            Label('Plots:'), self.toggle_svg,
            HBox([self.svg_interval, Label('min')]), self.toggle_mcds,
            HBox([self.mcds_interval, Label('min')])
        ])

        label_blankline = Label('')

        label_substrates = Label('Substrates:')
        self.substrate = []
        self.diffusion_coef = []
        self.decay_rate = []

        width_cell_params_units = '510px'
        width_cell_params_units = '380px'
        disable_substrates_flag = False

        self.substrate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    disabled=True,
                    value=38,
                    description='o2: ',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.substrate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    disabled=True,
                    value=1,
                    description='Glc: ',
                    layout=Layout(width=constWidth),
                ),
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.substrate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    disabled=True,
                    value=7.25,
                    description='H+: ',
                    layout=Layout(width=constWidth),
                ),
                Label('pH')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.substrate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    disabled=True,
                    value=1.0,
                    description='ECM: ',
                    layout=Layout(width=constWidth),
                ),
            ],
                 layout=Layout(width=width_cell_params_units)))

        width_cell_params_units = '450px'
        width_cell_params_units = '400px'
        self.diffusion_coef.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    max=999999,
                    step=10.0,
                    description='diffusion coef',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('micron^2/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.diffusion_coef.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    max=999999,
                    step=10.0,
                    description='diffusion coef',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('micron^2/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.diffusion_coef.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    max=999999,
                    step=10.0,
                    description='diffusion coef',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('micron^2/min')
            ],
                 layout=Layout(width=width_cell_params_units)))

        width_cell_params_units = '400px'
        width_cell_params_units = '380px'
        self.decay_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.01,
                    description='decay rate',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.decay_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.00001,
                    description='decay rate',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.decay_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.01,
                    description='decay rate',
                    disabled=disable_substrates_flag,
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))

        box_layout = Layout(border='1px solid')
        domain_box = VBox([label_domain, x_row, y_row, z_row],
                          layout=box_layout)
        substrates_box = VBox([
            label_substrates,
            HBox([
                self.substrate[0], self.diffusion_coef[0], self.decay_rate[0]
            ]),
            HBox([
                self.substrate[1], self.diffusion_coef[1], self.decay_rate[1]
            ]),
            HBox([
                self.substrate[2], self.diffusion_coef[2], self.decay_rate[2]
            ])
        ],
                              layout=box_layout)

        self.tab = VBox([
            domain_box,
            HBox([self.tmax, Label('min')]),
            self.omp_threads,
            svg_mat_output_row,
        ])  # output_dir, toggle_2D_seed_
Пример #24
0
class Instrument(object):
    """ """
    style = {'description_width': '150px'}
    layout = {'width': '250px'}

    widgets = {
        'config':
        Dropdown(options=configurations.keys(), description='Configurations:'),
        'collecting_surface_area':
        BoundedFloatText(value=10000,
                         min=0,
                         max=1e6,
                         step=10,
                         description='Collecting area (cm2)'),
        'pix_size':
        BoundedFloatText(value=0.3,
                         min=0,
                         max=10,
                         step=0.1,
                         description='Pixel size (arcsec)'),
        'pix_disp':
        BoundedFloatText(value=13.4,
                         min=0,
                         max=100,
                         step=0.1,
                         description='Dispersion (A/pixel)'),
        'psf_amp':
        BoundedFloatText(value=0.781749,
                         min=0,
                         max=1,
                         step=0.05,
                         description='PSF amplitude'),
        'psf_sig1':
        BoundedFloatText(value=0.84454,
                         min=0,
                         max=20,
                         step=0.1,
                         description='PSF sigma 1 (pixels)'),
        'psf_sig2':
        BoundedFloatText(value=3.6498,
                         min=0,
                         max=20,
                         step=0.1,
                         description='PSF sigma 2 (pixels)'),
        'readnoise':
        BoundedFloatText(value=8.87,
                         min=0,
                         max=100,
                         step=0.1,
                         description='read noise (electrons)'),
        'darkcurrent':
        BoundedFloatText(value=0.019,
                         min=0,
                         max=100,
                         step=0.1,
                         description='dark current (elec/s/pix)'),
        'transmission_red':
        Dropdown(options=get_transmission_files(),
                 description='Red grism transmission'),
        'transmission_blue':
        Dropdown(options=get_transmission_files(),
                 description='Blue grism transmission'),
        'radius1':
        Label(),
        'radius2':
        Label(),
    }

    params = ('collecting_surface_area', 'pix_size', 'pix_disp', 'psf_amp',
              'psf_sig1', 'psf_sig2', 'readnoise', 'darkcurrent',
              'transmission_red', 'transmission_blue')

    def __init__(self):
        self._set_custom = True

        for key, widget in self.widgets.items():
            widget.style = self.style
            widget.layout = self.layout

        self.update(**configurations[self.widgets['config'].value])

        self.widgets['config'].observe(self.change_config, names='value')
        self.widgets['transmission_red'].observe(self.plot_transmission,
                                                 names='value')
        self.widgets['transmission_blue'].observe(self.plot_transmission,
                                                  names='value')

        self.widgets['psf_amp'].observe(self.plot_psf, names='value')
        self.widgets['psf_sig1'].observe(self.plot_psf, names='value')
        self.widgets['psf_sig2'].observe(self.plot_psf, names='value')

        for key, widget in self.widgets.items():
            if key in ['config', 'transmission_red', 'transmission_blue']:
                continue
            widget.observe(self.modify, names='value')

        self.figs = [go.FigureWidget(), go.FigureWidget()]
        self.figs[0].update_layout(xaxis_title='Wavelength (microns)',
                                   yaxis_title='Throughput',
                                   width=500,
                                   height=200,
                                   margin=dict(l=0, r=0, t=0, b=0, pad=0),
                                   autosize=True)
        self.figs[1].update_layout(xaxis_title='Radius (pixels)',
                                   yaxis_title='PSF',
                                   width=500,
                                   height=200,
                                   margin=dict(l=0, r=0, t=0, b=0, pad=0),
                                   autosize=True)

        title = HTML('<h2>Instrument<h2>')
        elements = []
        elements.append(self.widgets['config'])
        elements += [
            HTML('<b>Optics</b>'), self.widgets['collecting_surface_area'],
            self.widgets['pix_size'], self.widgets['pix_disp'],
            self.widgets['transmission_red'], self.widgets['transmission_blue']
        ]
        elements += [
            HTML('<b>PSF</b>'), self.widgets['psf_amp'],
            self.widgets['psf_sig1'], self.widgets['psf_sig2']
        ]
        elements += [
            HTML('<b>Detector</b>'), self.widgets['readnoise'],
            self.widgets['darkcurrent']
        ]
        self.widget = HBox([
            VBox(elements),
            VBox(self.figs +
                 [self.widgets['radius1'], self.widgets['radius2']])
        ])

        self.plot_transmission()
        self.plot_psf()

    def update(self, **kwargs):
        """ """
        for key, value in kwargs.items():
            if key in self.widgets:
                self.widgets[key].value = value

    def change_config(self, change):
        """ """
        self._set_custom = False
        key = change['new']
        self.update(**configurations[key])
        self._set_custom = True

    def modify(self, change):
        """ """
        if not self._set_custom:
            return
        self.widgets['config'].value = 'custom'

    def plot_transmission(self, change=None):
        """ """
        if change:
            self.widgets['config'].value = 'custom'

        colors = {'transmission_red': 'red', 'transmission_blue': 'blue'}

        fig = self.figs[0]
        fig.data = []

        for key in ['transmission_red', 'transmission_blue']:

            if not self.widgets[key].value:
                continue

            if self.widgets[key].value == 'none':
                continue

            path = os.path.join(TRANSMISSION_DIR, self.widgets[key].value)
            if not os.path.exists(path):
                continue
            x, y = np.loadtxt(path, unpack=True)

            sel, = np.where(y > (y.max() / 10.))
            a = max(0, sel[0] - 10)
            b = min(len(x), sel[-1] + 10)
            x = x[a:b]
            y = y[a:b]

            fig.add_scatter(x=x / 1e4,
                            y=y,
                            name=self.widgets[key].value,
                            line_color=colors[key])

    def plot_psf(self, change=None):
        """ """
        if change:
            self.widgets['config'].value = 'custom'

        sig1 = self.widgets['psf_sig1'].value
        sig2 = self.widgets['psf_sig2'].value
        amp = self.widgets['psf_amp'].value

        PSF = psf.PSF_model(amp, sig1, sig2)

        r1 = PSF.radius(0.5)
        r2 = PSF.radius(0.8)
        self.widgets['radius1'].value = "PSF 50%%-radius: %3.2f pixels" % r1
        self.widgets['radius2'].value = "PSF 80%%-radius: %3.2f pixels" % r2

        x = np.linspace(0, np.ceil(PSF.radius(0.95)), 100)
        y = np.array(PSF.prof(x))
        yinteg = np.array(PSF.evaluate(x))

        fig = self.figs[1]
        fig.data = []
        fig.add_scatter(x=x, y=y / y.max(), name='Profile')
        fig.add_scatter(x=x, y=yinteg, name='Integrated')

    def get_lambda_range(self, key, thresh=2):
        """"""
        path = os.path.join(TRANSMISSION_DIR, self.widgets[key].value)
        x, y = np.loadtxt(path, unpack=True)
        sel = y > (y.max() * 1. / thresh)
        x = x[sel]
        return x.min(), x.max()

    def get_config_list(self):
        """ """
        config_list = []
        for key in 'transmission_red', 'transmission_blue':
            if not self.widgets[key].value or self.widgets[key].value == 'none':
                continue
            config = {}
            config['collecting_surface_area'] = self.widgets[
                'collecting_surface_area'].value
            config['pix_size'] = self.widgets['pix_size'].value
            config['pix_disp'] = [1, self.widgets['pix_disp'].value, 1]
            config['psf_amp'] = self.widgets['psf_amp'].value
            config['psf_sig1'] = self.widgets['psf_sig1'].value
            config['psf_sig2'] = self.widgets['psf_sig2'].value
            config['readnoise'] = self.widgets['readnoise'].value
            config['darkcurrent'] = self.widgets['darkcurrent'].value
            config['transmission_path'] = os.path.join(TRANSMISSION_DIR,
                                                       self.widgets[key].value)
            config['lambda_range'] = self.get_lambda_range(key)
            config_list.append(config)
        return config_list
Пример #25
0
    def create_param_widget(self, param, value):
        from ipywidgets import Layout, HBox
        children = (HBox(),)
        if isinstance(value, bool):
            from ipywidgets import Label, ToggleButton
            p = Label(value=param, layout=Layout(width='10%'))
            t = ToggleButton(description=str(value), value=value)

            def on_bool_change(change):
                t.description = str(change['new'])
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            t.observe(on_bool_change, names='value')

            children = (p, t)

        elif isinstance(value, float):
            from ipywidgets import FloatSlider, FloatText, BoundedFloatText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedFloatText(value=0, min=1e-10,
                                 layout=Layout(flex='0 1 auto', width='10%'),
                                 font_weight='bold')
            a = FloatText(value=2 * value,
                          layout=Layout(flex='0 1 auto', width='10%'))
            f = FloatSlider(value=value, min=b.value, max=a.value,
                            step=np.abs(a.value - b.value) * 0.01,
                            layout=Layout(flex='1 1 auto', width='60%'))
            l = FloatText(value=f.value,
                          layout=Layout(flex='0 1 auto', width='10%'),
                          disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)

        elif isinstance(value, int):
            from ipywidgets import IntSlider, IntText, BoundedIntText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedIntText(value=0, min=1e-10,
                               layout=Layout(flex='0 1 auto', width='10%'),
                               font_weight='bold')
            a = IntText(value=2 * value,
                        layout=Layout(flex='0 1 auto', width='10%'))
            f = IntSlider(value=value, min=b.value, max=a.value,
                          step=1,
                          layout=Layout(flex='1 1 auto', width='60%'))
            l = IntText(value=f.value,
                        layout=Layout(flex='0 1 auto', width='10%'),
                        disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = 1

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = 1

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)
        container = HBox(children)
        return container
Пример #26
0
    def __init__(self):
        constWidth = '180px'
        #width_cell_params_units = '240px'
        width_cell_params_units = '270px'

        self.cell_name = Text(
            value='untreated cancer',
            disabled=False,
            description='Cell line name',
            style={'description_width': 'initial'},
        )

        #-------------------------------
        label_cycle = Label('Cycle:')
        self.max_birth_rate = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.0001,
                    description='max birth rate',
                    style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_proliferation_saturation = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='o2: prolif sat',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_proliferation_threshold = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='prolif thresh',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_reference = HBox([
            BoundedFloatText(
                min=0,
                step=0.1,
                description='ref',
                layout=Layout(width=constWidth),
            ),
            Label('mmHg')
        ],
                                 layout=Layout(width=width_cell_params_units))
        self.glucose_proliferation_reference = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='Glc: prolif ref',
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        self.glucose_proliferation_saturation = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='prolif sat',
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        self.glucose_proliferation_threshold = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='prolif thresh',
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        label_necrosis = Label('Necrosis:')
        self.max_necrosis_rate = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.001,
                    description='max rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_necrosis_threshold = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='o2: thresh',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_necrosis_max = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='max',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        label_apoptosis = Label('Apoptosis:')
        self.apoptosis_rate = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.00001,
                    description='rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        # TODO: enforce sum=1
        label_metabolism = Label('Metabolism (must sum to 1):')
        # TODO: assert these next 2 values sum to 1.0
        self.relative_aerobic_effects = HBox(
            [
                BoundedFloatText(
                    min=0,
                    max=1,
                    step=0.1,
                    disabled=True,
                    description=
                    'Aerobic',  #style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        self.relative_glycolytic_effects = HBox(
            [
                BoundedFloatText(
                    min=0,
                    max=1,
                    step=0.1,
                    disabled=True,
                    description=
                    'Glycolytic',  #style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        label_motility = Label('Motility:')
        self.is_motile = Checkbox(
            description='motile',
            disabled=False,
            layout=Layout(width=constWidth),
        )
        self.bias = HBox(
            [
                BoundedFloatText(
                    max=1,
                    step=0.01,
                    description=
                    'bias',  # style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        #        speed_units = HTMLMath(value=r"$\frac{\mu M^2}{min}$")
        speed_units = Label(
            'micron/min')  # use "option m" (Mac, for micro symbol)
        self.speed = HBox([
            BoundedFloatText(
                min=0,
                step=0.1,
                description='speed',
                layout=Layout(width=constWidth),
            ), speed_units
        ],
                          layout=Layout(width=width_cell_params_units))
        self.persistence_time = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='persistence time',
                    layout=Layout(width=constWidth),
                ),
                Label('min')
            ],
            layout=Layout(width=width_cell_params_units))

        # constWidt = '180px'
        self.gradient_substrate_index = BoundedIntText(
            min=0,
            value=0,
            disabled=False,
            description='substrate index',
            style={'description_width': 'initial'},
            layout=Layout(width='160px'),
        )
        self.negative_taxis = RadioButtons(
            options={
                "grad": 0,
                "-grad": 1
            },  # {u"\u2207" : 0, "-" +  u"\u2207" : 1},
            value=0,
            disabled=True,
            description='',
        )

        self.is_motile.observe(self.is_motile_cb)

        #-------------------------------
        label_mechanics = Label('Mechanics:')
        self.max_relative_adhesion_distance = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,  #max=1,  
                    description=
                    'Max adhesion distance',  # style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        self.adhesion_strength = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,  #max=1,  
                    description=
                    'Adhesion strength',  # style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))
        self.repulsion_strength = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,  #max=1,  
                    description=
                    'Repulsion strength',  # style={'description_width': 'initial'},
                    layout=Layout(width=constWidth),
                ),
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        label_hypoxia = Label('Hypoxia:')
        self.o2_hypoxic_threshold = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='o2: threshold',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_hypoxic_response = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='response',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))
        self.o2_hypoxic_saturation = HBox(
            [
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='saturation',
                    layout=Layout(width=constWidth),
                ),
                Label('mmHg')
            ],
            layout=Layout(width=width_cell_params_units))

        #-------------------------------
        label_secretion = Label('Secretion:')
        self.uptake_rate = []
        self.secretion_rate = []
        self.saturation_density = []

        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='o2: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.01,
                    description='Glc: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='H+: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='ECM: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='NP1: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))
        self.uptake_rate.append(
            HBox([
                BoundedFloatText(
                    min=0,
                    step=0.1,
                    description='NP2: uptake rate',
                    layout=Layout(width=constWidth),
                ),
                Label('1/min')
            ],
                 layout=Layout(width=width_cell_params_units)))

        for idx in range(6):
            self.secretion_rate.append(
                HBox([
                    BoundedFloatText(
                        min=0,
                        step=0.1,
                        description='secretion rate',
                        layout=Layout(width=constWidth),
                    ),
                    Label('1/min')
                ],
                     layout=Layout(width=width_cell_params_units)))
            self.saturation_density.append(
                HBox([
                    BoundedFloatText(
                        min=0,
                        step=0.1,
                        description='saturation',
                        layout=Layout(width=constWidth),
                    ),
                ],
                     layout=Layout(width=width_cell_params_units)))

        row1 = HBox([self.max_birth_rate])
        row2 = HBox([
            self.o2_proliferation_saturation, self.o2_proliferation_threshold,
            self.o2_reference
        ])
        row2b = HBox([
            self.glucose_proliferation_reference,
            self.glucose_proliferation_saturation,
            self.glucose_proliferation_threshold
        ])
        row3 = HBox([self.max_necrosis_rate])
        row4 = HBox([self.o2_necrosis_threshold, self.o2_necrosis_max])

        row_secretion = []
        for idx in range(2):
            row_secretion.append(
                HBox([
                    self.uptake_rate[idx], self.secretion_rate[idx],
                    self.saturation_density[idx]
                ]))

        # row12 = HBox([self.uptake_rate[1], self.secretion_rate[1], self.saturation_density[1] ])
        # row13 = HBox([self.uptake_rate3, self.secretion_rate3, self.saturation_density3 ])
        # row14 = HBox([self.uptake_rate4, self.secretion_rate4, self.saturation_density4 ])
        # row15 = HBox([self.uptake_rate5, self.secretion_rate5, self.saturation_density5 ])
        # row16 = HBox([self.uptake_rate6, self.secretion_rate6, self.saturation_density6 ])

        box_layout = Layout(border='1px solid')
        cycle_box = VBox([label_cycle, row1, row2, row2b], layout=box_layout)
        necrosis_box = VBox([label_necrosis, row3, row4], layout=box_layout)
        apoptosis_box = VBox(
            [label_apoptosis, HBox([self.apoptosis_rate])], layout=box_layout)
        metabolism_box = VBox([
            label_metabolism,
            HBox([
                self.relative_aerobic_effects, self.relative_glycolytic_effects
            ])
        ],
                              layout=box_layout)
        motility_box = VBox([
            HBox([
                label_motility,
                self.is_motile,
                self.gradient_substrate_index,
                self.negative_taxis,
            ]),
            HBox([self.bias, self.speed, self.persistence_time]),
        ],
                            layout=box_layout)
        mechanics_box = VBox([
            label_mechanics,
            HBox([
                self.max_relative_adhesion_distance, self.adhesion_strength,
                self.repulsion_strength
            ])
        ],
                             layout=box_layout)
        hypoxia_box = VBox([
            label_hypoxia,
            HBox([
                self.o2_hypoxic_threshold, self.o2_hypoxic_response,
                self.o2_hypoxic_saturation
            ])
        ],
                           layout=box_layout)
        secretion_box = VBox([
            label_secretion,
            HBox([
                self.uptake_rate[0], self.secretion_rate[0],
                self.saturation_density[0]
            ]),
            HBox([
                self.uptake_rate[1], self.secretion_rate[1],
                self.saturation_density[1]
            ]),
            HBox([
                self.uptake_rate[2], self.secretion_rate[2],
                self.saturation_density[2]
            ]),
            HBox([
                self.uptake_rate[3], self.secretion_rate[3],
                self.saturation_density[3]
            ]),
            HBox([
                self.uptake_rate[4], self.secretion_rate[4],
                self.saturation_density[4]
            ]),
            HBox([
                self.uptake_rate[5], self.secretion_rate[5],
                self.saturation_density[5]
            ])
        ],
                             layout=box_layout)

        self.tab = VBox([
            self.cell_name,
            cycle_box,
            necrosis_box,
            apoptosis_box,
            metabolism_box,
            motility_box,
            mechanics_box,
            hypoxia_box,
            secretion_box,
        ])  #,row13,row14,row15,row16])
Пример #27
0
class ConfigTab(object):
    def __init__(self):

        #        micron_units = HTMLMath(value=r"$\mu M$")
        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)
        #        micron_units = Label('microns')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        # tab_height = '400px'
        tab_height = '500px'
        #        tab_layout = Layout(width='900px',   # border='2px solid black',
        #        tab_layout = Layout(width='850px',   # border='2px solid black',
        #                            height=tab_height, overflow_y='scroll',)
        #        np_tab_layout = Layout(width='800px',  # border='2px solid black',
        #                               height='350px', overflow_y='scroll',)

        # my_domain = [0,0,-10, 2000,2000,10, 20,20,20]  # [x,y,zmin,  x,y,zmax, x,y,zdelta]
        #        label_domain = Label('Domain ($\mu M$):')
        label_domain = Label('Domain (micron):')
        stepsize = 10
        disable_domain = False
        self.xmin = FloatText(
            step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(
            step=stepsize,
            description='Ymin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(
            step=stepsize,
            description='Zmin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(
            step=stepsize,
            description='Xmax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(
            step=stepsize,
            description='Ymax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(
            step=stepsize,
            description='Zmax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        #            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',  # '∆x',  # Mac: opt-j for delta
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        """
        self.tdelta = BoundedFloatText(
            min=0.01,
            description='$Time_{delta}$',
            layout=Layout(width=constWidth),
        )
        """
        """
        self.toggle2D = Checkbox(
            description='2-D',
            layout=Layout(width=constWidth),
        )
        def toggle2D_cb(b):
            if (self.toggle2D.value):
                #zmin.disabled = zmax.disabled = zdelta.disabled = True
                zmin.disabled = True
                zmax.disabled = True
                zdelta.disabled = True
            else:
                zmin.disabled = False
                zmax.disabled = False
                zdelta.disabled = False
            
        self.toggle2D.observe(toggle2D_cb)
        """

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            max=4,
            description='# threads',
            layout=Layout(width=constWidth),
        )

        # self.toggle_prng = Checkbox(
        #     description='Seed PRNG', style={'description_width': 'initial'},  # e.g. 'initial'  '120px'
        #     layout=Layout(width=constWidth),
        # )
        # self.prng_seed = BoundedIntText(
        #     min = 1,
        #     description='Seed',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        # def toggle_prng_cb(b):
        #     if (toggle_prng.value):
        #         self.prng_seed.disabled = False
        #     else:
        #         self.prng_seed.disabled = True

        # self.toggle_prng.observe(toggle_prng_cb)
        #prng_row = HBox([toggle_prng, prng_seed])

        self.toggle_svg = Checkbox(
            description='Cells',  # SVG
            layout=Layout(width='150px'))  # constWidth = '180px'
        # self.svg_t0 = BoundedFloatText (
        #     min=0,
        #     description='$T_0$',
        #     layout=Layout(width=constWidth),
        # )
        # self.svg_interval = BoundedIntText(
        self.svg_interval = BoundedFloatText(
            min=1,
            max=
            99999999,  # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )
        # self.mcds_interval = BoundedIntText(
        self.mcds_interval = BoundedFloatText(
            min=1,
            max=99999999,
            description='every',
            #            disabled=True,
            layout=Layout(width='160px'),
        )

        # don't let this be > mcds interval
        def svg_interval_cb(b):
            if (self.svg_interval.value > self.mcds_interval.value):
                self.svg_interval.value = self.mcds_interval.value

        self.svg_interval.observe(
            svg_interval_cb)  # BEWARE: when fill_gui, this sets value = 1 !

        # don't let this be < svg interval
        def mcds_interval_cb(b):
            if (self.mcds_interval.value < self.svg_interval.value):
                self.mcds_interval.value = self.svg_interval.value

        self.mcds_interval.observe(
            mcds_interval_cb)  # BEWARE: see warning above

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True

        self.toggle_svg.observe(toggle_svg_cb)

        self.toggle_mcds = Checkbox(
            #     value=False,
            description='Subtrates',  # Full
            layout=Layout(width='180px'),
        )

        # self.mcds_t0 = FloatText(
        #     description='$T_0$',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                # self.mcds_t0.disabled = False #False
                self.mcds_interval.disabled = False
            else:
                # self.mcds_t0.disabled = True
                self.mcds_interval.disabled = True

        self.toggle_mcds.observe(toggle_mcds_cb)

        svg_mat_output_row = HBox([
            Label('Plots:'), self.toggle_svg,
            HBox([self.svg_interval, Label('min')]), self.toggle_mcds,
            HBox([self.mcds_interval, Label('min')])
        ])

        # to sync, do this
        # svg_mat_output_row = HBox( [Label('Plots:'), self.svg_interval, Label('min')])

        #write_config_row = HBox([write_config_button, write_config_file])
        #run_sim_row = HBox([run_button, run_command_str, kill_button])
        # run_sim_row = HBox([run_button, run_command_str])
        # run_sim_row = HBox([run_button.w])  # need ".w" for the custom RunCommand widget

        label_blankline = Label('')
        # toggle_2D_seed_row = HBox([toggle_prng, prng_seed])  # toggle2D

        box_layout = Layout(border='1px solid')
        #        domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout)
        domain_box = VBox([label_domain, x_row, y_row], layout=box_layout)
        self.tab = VBox([
            domain_box,
            #                         label_blankline,
            HBox([self.tmax, Label('min')]),
            self.omp_threads,
            svg_mat_output_row,
            #                         HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]),
        ])  # output_dir, toggle_2D_seed_
#                         ], layout=tab_layout)  # output_dir, toggle_2D_seed_

# Populate the GUI widgets with values from the XML

    def fill_gui(self, xml_root):
        self.xmin.value = float(xml_root.find(".//x_min").text)
        self.xmax.value = float(xml_root.find(".//x_max").text)
        self.xdelta.value = float(xml_root.find(".//dx").text)

        self.ymin.value = float(xml_root.find(".//y_min").text)
        self.ymax.value = float(xml_root.find(".//y_max").text)
        self.ydelta.value = float(xml_root.find(".//dy").text)

        self.zmin.value = float(xml_root.find(".//z_min").text)
        self.zmax.value = float(xml_root.find(".//z_max").text)
        self.zdelta.value = float(xml_root.find(".//dz").text)

        self.tmax.value = float(xml_root.find(".//max_time").text)

        self.omp_threads.value = int(xml_root.find(".//omp_num_threads").text)

        if xml_root.find(".//full_data//enable").text.lower() == 'true':
            self.toggle_mcds.value = True
        else:
            self.toggle_mcds.value = False
        # self.mcds_interval.value = int(xml_root.find(".//full_data//interval").text)
        self.mcds_interval.value = float(
            xml_root.find(".//full_data//interval").text)

        # NOTE: do this *after* filling the mcds_interval, directly above, due to the callback/constraints on them
        if xml_root.find(".//SVG//enable").text.lower() == 'true':
            self.toggle_svg.value = True
        else:
            self.toggle_svg.value = False
        # self.svg_interval.value = int(xml_root.find(".//SVG//interval").text)
        self.svg_interval.value = float(xml_root.find(".//SVG//interval").text)

    # Read values from the GUI widgets and generate/write a new XML
    def fill_xml(self, xml_root):
        # print('config.py fill_xml() !!!!!')
        # TODO: verify template .xml file exists!

        # TODO: verify valid type (numeric) and range?
        xml_root.find(".//x_min").text = str(self.xmin.value)
        xml_root.find(".//x_max").text = str(self.xmax.value)
        xml_root.find(".//dx").text = str(self.xdelta.value)
        xml_root.find(".//y_min").text = str(self.ymin.value)
        xml_root.find(".//y_max").text = str(self.ymax.value)
        xml_root.find(".//dy").text = str(self.ydelta.value)
        xml_root.find(".//z_min").text = str(self.zmin.value)
        xml_root.find(".//z_max").text = str(self.zmax.value)
        xml_root.find(".//dz").text = str(self.zdelta.value)

        xml_root.find(".//max_time").text = str(self.tmax.value)

        xml_root.find(".//omp_num_threads").text = str(self.omp_threads.value)

        xml_root.find(".//SVG").find(".//enable").text = str(
            self.toggle_svg.value)
        xml_root.find(".//SVG").find(".//interval").text = str(
            self.svg_interval.value)
        xml_root.find(".//full_data").find(".//enable").text = str(
            self.toggle_mcds.value)
        xml_root.find(".//full_data").find(".//interval").text = str(
            self.mcds_interval.value)

        #    user_details = ET.SubElement(root, "user_details")
        #    ET.SubElement(user_details, "PhysiCell_settings", name="version").text = "devel-version"
        #    ET.SubElement(user_details, "domain")
        #    ET.SubElement(user_details, "xmin").text = "-100"

        #    tree = ET.ElementTree(root)
        #    tree.write(write_config_file.value)
        #    tree.write("test.xml")

        # TODO: verify can write to this filename
#        tree.write(write_config_file.value)

    def get_num_svg_frames(self):
        if (self.toggle_svg.value):
            return int(self.tmax.value / self.svg_interval.value)
        else:
            return 0

    def get_num_substrate_frames(self):
        if (self.toggle_mcds.value):
            return int(self.tmax.value / self.mcds_interval.value)
        else:
            return 0
Пример #28
0
#svg_tab = widgets.VBox([svg_dir, svg_anim], layout=tab_layout)
#---------------------

#============ Cells tab ===================
cell_name = widgets.Text(
    value='untreated cancer',
    description='Cell line name', style={'description_width': 'initial'},
)
#-------
label_cycle = widgets.Label('Cycle:')   # no worky:  ,style={'font_weight': 'bold'})

# NOTE: by adopting the 
cell0_max_birth_rate = HBox([BoundedFloatText (
    min=0,
    #value = 0.0079,
    description='Max birth rate', style={'description_width': 'initial'},
    layout = Layout(width = constWidth3),
    ), min_inv_units], layout=Layout(width='300px'))


width_cell_params_units = '230px'
cell0_o2_prolif_sat = HBox([BoundedFloatText (
    min=0,
    description='$O_2$: Prolif sat',
    layout = Layout(width = constWidth),
    ), mmHg_units], layout=Layout(width=width_cell_params_units))
cell0_o2_prolif_thresh = HBox([BoundedFloatText (
    min=0,
    description='Prolif thresh',
    layout = Layout(width = constWidth),
    ), mmHg_units], layout=Layout(width=width_cell_params_units))
Пример #29
0
class ConfigTab(object):

    # def __init__(self):
    def __init__(self, xml_root):
        
#        micron_units = HTMLMath(value=r"$\mu M$")
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)
#        micron_units = Label('microns')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        # tab_height = '400px'
        tab_height = '500px'
#        tab_layout = Layout(width='900px',   # border='2px solid black',
#        tab_layout = Layout(width='850px',   # border='2px solid black',
#                            height=tab_height, overflow_y='scroll',)
#        np_tab_layout = Layout(width='800px',  # border='2px solid black',
#                               height='350px', overflow_y='scroll',)

        # my_domain = [0,0,-10, 2000,2000,10, 20,20,20]  # [x,y,zmin,  x,y,zmax, x,y,zdelta]
#        label_domain = Label('Domain ($\mu M$):')
        label_domain = Label('Domain (micron):')
        stepsize = 10
        disable_domain = False
        self.xmin = FloatText(step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(step=stepsize,
            description='Ymin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(step=stepsize,
            description='Zmin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(step=stepsize,
            description='Xmax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(step=stepsize,
            description='Ymax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(step=stepsize,
            description='Zmax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.toggle_virtual_walls = Checkbox(
            description='Virtual walls',
            layout=Layout(width='350px') )

#            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',   # '∆x',  # Mac: opt-j for delta
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        """
        self.tdelta = BoundedFloatText(
            min=0.01,
            description='$Time_{delta}$',
            layout=Layout(width=constWidth),
        )
        """

        """
        self.toggle2D = Checkbox(
            description='2-D',
            layout=Layout(width=constWidth),
        )
        def toggle2D_cb(b):
            if (self.toggle2D.value):
                #zmin.disabled = zmax.disabled = zdelta.disabled = True
                zmin.disabled = True
                zmax.disabled = True
                zdelta.disabled = True
            else:
                zmin.disabled = False
                zmax.disabled = False
                zdelta.disabled = False
            
        self.toggle2D.observe(toggle2D_cb)
        """

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            max=4,
            description='# threads',
            layout=Layout(width=constWidth),
        )

        # self.toggle_prng = Checkbox(
        #     description='Seed PRNG', style={'description_width': 'initial'},  # e.g. 'initial'  '120px'
        #     layout=Layout(width=constWidth),
        # )
        # self.prng_seed = BoundedIntText(
        #     min = 1,
        #     description='Seed', 
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        # def toggle_prng_cb(b):
        #     if (toggle_prng.value):
        #         self.prng_seed.disabled = False
        #     else:
        #         self.prng_seed.disabled = True
            
        # self.toggle_prng.observe(toggle_prng_cb)
        #prng_row = HBox([toggle_prng, prng_seed])

        self.toggle_svg = Checkbox(
            description='Cells',    # SVG
            layout=Layout(width='150px') )  # constWidth = '180px'
        # self.svg_t0 = BoundedFloatText (
        #     min=0,
        #     description='$T_0$',
        #     layout=Layout(width=constWidth),
        # )
        self.svg_interval = BoundedFloatText(
            min=0.001,
            max=99999999,   # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )
        self.mcds_interval = BoundedFloatText(
            min=0.001,
            max=99999999,
            description='every',
#            disabled=True,
            layout=Layout(width='160px'),
        )

        # don't let this be > mcds interval
        def svg_interval_cb(b):
            if (self.svg_interval.value > self.mcds_interval.value):
                self.svg_interval.value = self.mcds_interval.value

        self.svg_interval.observe(svg_interval_cb)  # BEWARE: when fill_gui, this sets value = 1 !

        # don't let this be < svg interval
        def mcds_interval_cb(b):
            if (self.mcds_interval.value < self.svg_interval.value):
                self.mcds_interval.value = self.svg_interval.value

        self.mcds_interval.observe(mcds_interval_cb)   # BEWARE: see warning above

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False 
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True
            
        self.toggle_svg.observe(toggle_svg_cb)


        self.toggle_mcds = Checkbox(
        #     value=False,
            description='Subtrates',   # Full
            layout=Layout(width='180px'),
        )
        # self.mcds_t0 = FloatText(
        #     description='$T_0$',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                # self.mcds_t0.disabled = False #False
                self.mcds_interval.disabled = False
            else:
                # self.mcds_t0.disabled = True
                self.mcds_interval.disabled = True
            
        self.toggle_mcds.observe(toggle_mcds_cb)
       
        svg_mat_output_row = HBox([Label('Plots:'),self.toggle_svg, HBox([self.svg_interval,Label('min')]), 
            self.toggle_mcds, HBox([self.mcds_interval,Label('min')])  ])

        # to sync, do this
        # svg_mat_output_row = HBox( [Label('Plots:'), self.svg_interval, Label('min')]) 

        #write_config_row = HBox([write_config_button, write_config_file])
        #run_sim_row = HBox([run_button, run_command_str, kill_button])
        # run_sim_row = HBox([run_button, run_command_str])
        # run_sim_row = HBox([run_button.w])  # need ".w" for the custom RunCommand widget

        label_blankline = Label('')
        # toggle_2D_seed_row = HBox([toggle_prng, prng_seed])  # toggle2D

        def upload_done_cb(w, name):
            # Do something with the files here...
            # We just print their names
            print("%s uploaded" % name)

            # reset clears and re-enables the widget for more uploads
            # You may want to do this somewhere else, depending on your GUI
            w.reset()

        if (hublib_flag):
            self.csv_upload= FileUpload(
                '',
                'Upload cells positions (.csv) from your local machine',
                dir='data',
                cb=upload_done_cb,
                maxsize='1M',
                # layout=Layout(width='350px') 
            )
        self.toggle_cells_csv = Checkbox(
            description='Enable .csv',
            layout=Layout(width='280px') )
            # layout=Layout(width='350px') )

        def toggle_cells_csv_cb(b):  # why can't I disable this widget?!
            # print('---- toggle_cells_csv_cb')
            if (hublib_flag):
                if (self.toggle_cells_csv.value):
                    # self.csv_upload.w.disabled = False
                    self.csv_upload.visible = True
                else:
                    self.csv_upload.visible = False
            
        self.toggle_cells_csv.observe(toggle_cells_csv_cb)

        box_layout = Layout(border='1px solid')
        if (hublib_flag):
            upload_cells_hbox = HBox([self.csv_upload.w, self.toggle_cells_csv] , layout=Layout(border='1px solid', width='420px'))
        else:
            upload_cells_hbox = HBox([self.toggle_cells_csv] , layout=Layout(border='1px solid', width='420px'))


#        domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout)
        uep = xml_root.find(".//options//virtual_wall_at_domain_edge")
        if uep:
            domain_box = VBox([label_domain,x_row,y_row, self.toggle_virtual_walls], layout=box_layout)
        else:
            domain_box = VBox([label_domain,x_row,y_row], layout=box_layout)

        uep = xml_root.find(".//options//virtual_wall_at_domain_edge")
        if uep:
            self.tab = VBox([domain_box,
                         HBox([self.tmax, Label('min')]), self.omp_threads,  
                         svg_mat_output_row,
                        label_blankline, 
                        #  HBox([self.csv_upload.w, self.toggle_cells_csv]),
                         upload_cells_hbox,
#                         HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]),
#                         ], layout=tab_layout)  # output_dir, toggle_2D_seed_
                         ])  
        else:
            self.tab = VBox([domain_box,
                         HBox([self.tmax, Label('min')]), self.omp_threads,  
                         svg_mat_output_row,
                         ])  

    # Populate the GUI widgets with values from the XML
    def fill_gui(self, xml_root):
        self.xmin.value = float(xml_root.find(".//x_min").text)
        self.xmax.value = float(xml_root.find(".//x_max").text)
        self.xdelta.value = float(xml_root.find(".//dx").text)
    
        self.ymin.value = float(xml_root.find(".//y_min").text)
        self.ymax.value = float(xml_root.find(".//y_max").text)
        self.ydelta.value = float(xml_root.find(".//dy").text)
    
        self.zmin.value = float(xml_root.find(".//z_min").text)
        self.zmax.value = float(xml_root.find(".//z_max").text)
        self.zdelta.value = float(xml_root.find(".//dz").text)

        uep = xml_root.find(".//options//virtual_wall_at_domain_edge")
        if uep and (uep.text.lower() == 'true'):
            self.toggle_virtual_walls.value = True
        else:
            self.toggle_virtual_walls.value = False
        

        self.tmax.value = float(xml_root.find(".//max_time").text)
        
        self.omp_threads.value = int(xml_root.find(".//omp_num_threads").text)
        
        if xml_root.find(".//full_data//enable").text.lower() == 'true':
            self.toggle_mcds.value = True
        else:
            self.toggle_mcds.value = False
        self.mcds_interval.value = float(xml_root.find(".//full_data//interval").text)

        # NOTE: do this *after* filling the mcds_interval, directly above, due to the callback/constraints on them
        if xml_root.find(".//SVG//enable").text.lower() == 'true':
            self.toggle_svg.value = True
        else:
            self.toggle_svg.value = False
        self.svg_interval.value = float(xml_root.find(".//SVG//interval").text)

        # if xml_root.find(".//initial_conditions//cell_positions").attrib["enabled"].lower() == 'true':
        uep = xml_root.find(".//initial_conditions//cell_positions")
        if uep:
            if uep.attrib["enabled"].lower() == 'true':
                self.toggle_cells_csv.value = True
            else:
                self.toggle_cells_csv.value = False

            self.toggle_cells_csv.description = xml_root.find(".//initial_conditions//cell_positions//filename").text


    # Read values from the GUI widgets and generate/write a new XML
    def fill_xml(self, xml_root):
        # print('config.py fill_xml() !!!!!')
        # TODO: verify template .xml file exists!

        # TODO: verify valid type (numeric) and range?
        xml_root.find(".//x_min").text = str(self.xmin.value)
        xml_root.find(".//x_max").text = str(self.xmax.value)
        xml_root.find(".//dx").text = str(self.xdelta.value)
        xml_root.find(".//y_min").text = str(self.ymin.value)
        xml_root.find(".//y_max").text = str(self.ymax.value)
        xml_root.find(".//dy").text = str(self.ydelta.value)
        xml_root.find(".//z_min").text = str(self.zmin.value)
        xml_root.find(".//z_max").text = str(self.zmax.value)
        xml_root.find(".//dz").text = str(self.zdelta.value)

        if xml_root.find(".//options//virtual_wall_at_domain_edge"):
            xml_root.find(".//options//virtual_wall_at_domain_edge").text = str(self.toggle_virtual_walls.value).lower()

        xml_root.find(".//max_time").text = str(self.tmax.value)

        xml_root.find(".//omp_num_threads").text = str(self.omp_threads.value)

        xml_root.find(".//SVG").find(".//enable").text = str(self.toggle_svg.value)
        xml_root.find(".//SVG").find(".//interval").text = str(self.svg_interval.value)
        xml_root.find(".//full_data").find(".//enable").text = str(self.toggle_mcds.value)
        xml_root.find(".//full_data").find(".//interval").text = str(self.mcds_interval.value)

# uep.find('.//cell_definition[1]//phenotype//mechanics//options//set_absolute_equilibrium_distance').attrib['enabled'] = str(self.bool1.value)
        # xml_root.find(".//initial_conditions//cell_positions").attrib["enabled"] = str(self.toggle_cells_csv.value)
        uep = xml_root.find(".//initial_conditions//cell_positions")
        if uep:
            uep.attrib["enabled"] = str(self.toggle_cells_csv.value)

        #    user_details = ET.SubElement(root, "user_details")
        #    ET.SubElement(user_details, "PhysiCell_settings", name="version").text = "devel-version"
        #    ET.SubElement(user_details, "domain")
        #    ET.SubElement(user_details, "xmin").text = "-100"

        #    tree = ET.ElementTree(root)
        #    tree.write(write_config_file.value)
        #    tree.write("test.xml")

        # TODO: verify can write to this filename
#        tree.write(write_config_file.value)

    def get_num_svg_frames(self):
        if (self.toggle_svg.value):
            return int(self.tmax.value/self.svg_interval.value)
        else:
            return 0

    def get_num_substrate_frames(self):
        if (self.toggle_mcds.value):
            return int(self.tmax.value/self.mcds_interval.value)
        else:
            return 0
Пример #30
0
    def build_options(self):
        grid = GridspecLayout(10, 2)
        options_map = {}
        style = {'description_width': '60%', 'width': 'auto'}

        # feature
        feature = Combobox(description='Feature to plot:',
                           style=style,
                           options=list(self.feature_names),
                           ensure_option=True,
                           value=self.feature_names[0])
        options_map['feature'] = feature

        # num_grid_points
        num_grid_points = BoundedIntText(
            value=10,
            min=1,
            max=999999,
            step=1,
            description='Number of grid points:',
            style=style,
            description_tooltip='Number of grid points for numeric feature')
        options_map['num_grid_points'] = num_grid_points

        # grid_type
        grid_type = Dropdown(
            description='Grid type:',
            options=['percentile', 'equal'],
            style=style,
            description_tooltip='Type of grid points for numeric feature')
        options_map['grid_type'] = grid_type

        # cust_range
        cust_range = Checkbox(description='Custom grid range', value=False)
        options_map['cust_range'] = cust_range

        # range_min
        range_min = FloatText(
            description='Custom range minimum:',
            style=style,
            description_tooltip=
            'Percentile (when grid_type="percentile") or value (when grid_type="equal") '
            'lower bound of range to investigate (for numeric feature)\n'
            ' - Enabled only when custom grid range is True and variable with grid points is None',
            disabled=True)
        options_map['range_min'] = range_min

        # range_max
        range_max = FloatText(
            description='Custom range maximum:',
            style=style,
            description_tooltip=
            'Percentile (when grid_type="percentile") or value (when grid_type="equal") '
            'upper bound of range to investigate (for numeric feature)\n'
            ' - Enabled only when custom grid range is True and variable with grid points is None',
            disabled=True)
        options_map['range_max'] = range_max

        # cust_grid_points
        cust_grid_points = UpdatingCombobox(
            options_keys=self.globals_options,
            description='Variable with grid points:',
            style=style,
            description_tooltip=
            'Name of variable (or None) with customized list of grid points for numeric feature',
            value='None',
            disabled=True)
        cust_grid_points.lookup_in_kernel = True
        options_map['cust_grid_points'] = cust_grid_points

        # set up disabling of range inputs, when user doesn't want custom range
        def disable_ranges(change):
            range_min.disabled = not change['new']
            range_max.disabled = not change['new']
            cust_grid_points.disabled = not change['new']
            # but if the cust_grid_points has a value filled in keep range_max and range_min disabled
            if cust_grid_points.value != 'None':
                range_max.disabled = True
                range_min.disabled = True

        cust_range.observe(disable_ranges, names=['value'])

        # set up disabling of range_max and range_min if user specifies custom grid points
        def disable_max_min(change):
            if change['new'] == 'None':
                range_max.disabled = False
                range_min.disabled = False
            else:
                range_max.disabled = True
                range_min.disabled = True

        cust_grid_points.observe(disable_max_min, names=['value'])

        # set up links between upper and lower ranges
        def set_ranges(change):
            if grid_type.value == 'percentile':
                if change['owner'] == range_min or change[
                        'owner'] == num_grid_points:
                    range_max.value = max(
                        range_max.value,
                        range_min.value + num_grid_points.value)
                if change['owner'] == range_max:
                    range_min.value = min(
                        range_min.value,
                        range_max.value - num_grid_points.value)
            else:
                if change['owner'] == range_min:
                    range_max.value = max(range_max.value, range_min.value)
                if change['owner'] == range_max:
                    range_min.value = min(range_min.value, range_max.value)

        range_min.observe(set_ranges, names=['value'])
        range_max.observe(set_ranges, names=['value'])
        num_grid_points.observe(set_ranges, names=['value'])

        # center
        center = Checkbox(description='Center the plot', value=True)
        options_map['center'] = center

        # plot_pts_dist
        plot_pts_dist = Checkbox(description='Plot data points distribution',
                                 value=True)
        options_map['plot_pts_dist'] = plot_pts_dist

        # x_quantile
        x_quantile = Checkbox(description='X-axis as quantiles', value=False)
        options_map['x_quantile'] = x_quantile

        # show_percentile
        show_percentile = Checkbox(description='Show precentile buckets',
                                   value=False)
        options_map['show_percentile'] = show_percentile

        # lines
        lines = Checkbox(description='Plot lines - ICE plot', value=False)
        options_map['lines'] = lines

        # frac_to_plot
        frac_to_plot = BoundedFloatText(
            description='Lines to plot:',
            value=1,
            description_tooltip=
            'How many lines to plot, can be a integer or a float.\n'
            ' - integer values higher than 1 are interpreted as absolute amount\n'
            ' - floats are interpreted as fraction (e.g. 0.5 means half of all possible lines)',
            style=style,
            disabled=True)
        options_map['frac_to_plot'] = frac_to_plot

        # cluster
        cluster = Checkbox(description='Cluster lines',
                           value=False,
                           disabled=True)
        options_map['cluster'] = cluster

        # n_cluster_centers
        n_cluster_centers = BoundedIntText(
            value=10,
            min=1,
            max=999999,
            step=1,
            description='Number of cluster centers:',
            style=style,
            description_tooltip='Number of cluster centers for lines',
            disabled=True)
        options_map['n_cluster_centers'] = n_cluster_centers

        # cluster method
        cluster_method = Dropdown(
            description='Cluster method',
            style=style,
            options={
                'KMeans': 'accurate',
                'MiniBatchKMeans': 'approx'
            },
            description_tooltip='Method to use for clustering of lines',
            disabled=True)
        options_map['cluster_method'] = cluster_method

        # set up disabling of lines related options
        def disable_lines(change):
            frac_to_plot.disabled = not change['new']
            cluster.disabled = not change['new']
            n_cluster_centers.disabled = not (change['new'] and cluster.value)
            cluster_method.disabled = not (change['new'] and cluster.value)

        lines.observe(disable_lines, names=['value'])

        # set up disabling of clustering options
        def disable_clustering(change):
            n_cluster_centers.disabled = not (cluster.value and change['new'])
            cluster_method.disabled = not (cluster.value and change['new'])

        cluster.observe(disable_clustering, names=['value'])

        grid[0, :] = feature
        grid[1, 0] = num_grid_points
        grid[1, 1] = grid_type
        grid[2, 0] = cust_range
        grid[2, 1] = cust_grid_points
        grid[3, 0] = range_min
        grid[3, 1] = range_max
        grid[4, 0] = center
        grid[4, 1] = plot_pts_dist
        grid[5, 0] = x_quantile
        grid[5, 1] = show_percentile
        grid[6, :] = lines
        grid[7, :] = frac_to_plot
        grid[8, :] = cluster
        grid[9, 0] = n_cluster_centers
        grid[9, 1] = cluster_method

        return options_map, grid
Пример #31
0
    def __init__(self, xml_root):
        
#        micron_units = HTMLMath(value=r"$\mu M$")
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)
#        micron_units = Label('microns')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        # tab_height = '400px'
        tab_height = '500px'
#        tab_layout = Layout(width='900px',   # border='2px solid black',
#        tab_layout = Layout(width='850px',   # border='2px solid black',
#                            height=tab_height, overflow_y='scroll',)
#        np_tab_layout = Layout(width='800px',  # border='2px solid black',
#                               height='350px', overflow_y='scroll',)

        # my_domain = [0,0,-10, 2000,2000,10, 20,20,20]  # [x,y,zmin,  x,y,zmax, x,y,zdelta]
#        label_domain = Label('Domain ($\mu M$):')
        label_domain = Label('Domain (micron):')
        stepsize = 10
        disable_domain = False
        self.xmin = FloatText(step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(step=stepsize,
            description='Ymin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(step=stepsize,
            description='Zmin',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(step=stepsize,
            description='Xmax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(step=stepsize,
            description='Ymax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(step=stepsize,
            description='Zmax',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.toggle_virtual_walls = Checkbox(
            description='Virtual walls',
            layout=Layout(width='350px') )

#            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',   # '∆x',  # Mac: opt-j for delta
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            disabled = disable_domain,
            layout=Layout(width=constWidth),
        )
        """
        self.tdelta = BoundedFloatText(
            min=0.01,
            description='$Time_{delta}$',
            layout=Layout(width=constWidth),
        )
        """

        """
        self.toggle2D = Checkbox(
            description='2-D',
            layout=Layout(width=constWidth),
        )
        def toggle2D_cb(b):
            if (self.toggle2D.value):
                #zmin.disabled = zmax.disabled = zdelta.disabled = True
                zmin.disabled = True
                zmax.disabled = True
                zdelta.disabled = True
            else:
                zmin.disabled = False
                zmax.disabled = False
                zdelta.disabled = False
            
        self.toggle2D.observe(toggle2D_cb)
        """

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            max=4,
            description='# threads',
            layout=Layout(width=constWidth),
        )

        # self.toggle_prng = Checkbox(
        #     description='Seed PRNG', style={'description_width': 'initial'},  # e.g. 'initial'  '120px'
        #     layout=Layout(width=constWidth),
        # )
        # self.prng_seed = BoundedIntText(
        #     min = 1,
        #     description='Seed', 
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        # def toggle_prng_cb(b):
        #     if (toggle_prng.value):
        #         self.prng_seed.disabled = False
        #     else:
        #         self.prng_seed.disabled = True
            
        # self.toggle_prng.observe(toggle_prng_cb)
        #prng_row = HBox([toggle_prng, prng_seed])

        self.toggle_svg = Checkbox(
            description='Cells',    # SVG
            layout=Layout(width='150px') )  # constWidth = '180px'
        # self.svg_t0 = BoundedFloatText (
        #     min=0,
        #     description='$T_0$',
        #     layout=Layout(width=constWidth),
        # )
        self.svg_interval = BoundedFloatText(
            min=0.001,
            max=99999999,   # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )
        self.mcds_interval = BoundedFloatText(
            min=0.001,
            max=99999999,
            description='every',
#            disabled=True,
            layout=Layout(width='160px'),
        )

        # don't let this be > mcds interval
        def svg_interval_cb(b):
            if (self.svg_interval.value > self.mcds_interval.value):
                self.svg_interval.value = self.mcds_interval.value

        self.svg_interval.observe(svg_interval_cb)  # BEWARE: when fill_gui, this sets value = 1 !

        # don't let this be < svg interval
        def mcds_interval_cb(b):
            if (self.mcds_interval.value < self.svg_interval.value):
                self.mcds_interval.value = self.svg_interval.value

        self.mcds_interval.observe(mcds_interval_cb)   # BEWARE: see warning above

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False 
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True
            
        self.toggle_svg.observe(toggle_svg_cb)


        self.toggle_mcds = Checkbox(
        #     value=False,
            description='Subtrates',   # Full
            layout=Layout(width='180px'),
        )
        # self.mcds_t0 = FloatText(
        #     description='$T_0$',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                # self.mcds_t0.disabled = False #False
                self.mcds_interval.disabled = False
            else:
                # self.mcds_t0.disabled = True
                self.mcds_interval.disabled = True
            
        self.toggle_mcds.observe(toggle_mcds_cb)
       
        svg_mat_output_row = HBox([Label('Plots:'),self.toggle_svg, HBox([self.svg_interval,Label('min')]), 
            self.toggle_mcds, HBox([self.mcds_interval,Label('min')])  ])

        # to sync, do this
        # svg_mat_output_row = HBox( [Label('Plots:'), self.svg_interval, Label('min')]) 

        #write_config_row = HBox([write_config_button, write_config_file])
        #run_sim_row = HBox([run_button, run_command_str, kill_button])
        # run_sim_row = HBox([run_button, run_command_str])
        # run_sim_row = HBox([run_button.w])  # need ".w" for the custom RunCommand widget

        label_blankline = Label('')
        # toggle_2D_seed_row = HBox([toggle_prng, prng_seed])  # toggle2D

        def upload_done_cb(w, name):
            # Do something with the files here...
            # We just print their names
            print("%s uploaded" % name)

            # reset clears and re-enables the widget for more uploads
            # You may want to do this somewhere else, depending on your GUI
            w.reset()

        if (hublib_flag):
            self.csv_upload= FileUpload(
                '',
                'Upload cells positions (.csv) from your local machine',
                dir='data',
                cb=upload_done_cb,
                maxsize='1M',
                # layout=Layout(width='350px') 
            )
        self.toggle_cells_csv = Checkbox(
            description='Enable .csv',
            layout=Layout(width='280px') )
            # layout=Layout(width='350px') )

        def toggle_cells_csv_cb(b):  # why can't I disable this widget?!
            # print('---- toggle_cells_csv_cb')
            if (hublib_flag):
                if (self.toggle_cells_csv.value):
                    # self.csv_upload.w.disabled = False
                    self.csv_upload.visible = True
                else:
                    self.csv_upload.visible = False
            
        self.toggle_cells_csv.observe(toggle_cells_csv_cb)

        box_layout = Layout(border='1px solid')
        if (hublib_flag):
            upload_cells_hbox = HBox([self.csv_upload.w, self.toggle_cells_csv] , layout=Layout(border='1px solid', width='420px'))
        else:
            upload_cells_hbox = HBox([self.toggle_cells_csv] , layout=Layout(border='1px solid', width='420px'))


#        domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout)
        uep = xml_root.find(".//options//virtual_wall_at_domain_edge")
        if uep:
            domain_box = VBox([label_domain,x_row,y_row, self.toggle_virtual_walls], layout=box_layout)
        else:
            domain_box = VBox([label_domain,x_row,y_row], layout=box_layout)

        uep = xml_root.find(".//options//virtual_wall_at_domain_edge")
        if uep:
            self.tab = VBox([domain_box,
                         HBox([self.tmax, Label('min')]), self.omp_threads,  
                         svg_mat_output_row,
                        label_blankline, 
                        #  HBox([self.csv_upload.w, self.toggle_cells_csv]),
                         upload_cells_hbox,
#                         HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]),
#                         ], layout=tab_layout)  # output_dir, toggle_2D_seed_
                         ])  
        else:
            self.tab = VBox([domain_box,
                         HBox([self.tmax, Label('min')]), self.omp_threads,  
                         svg_mat_output_row,
                         ])