Beispiel #1
0
def generate_pdp_feature_selection_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Feature 1 for ...'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='(optional) Feature 2 for ...'))

    for model in models:
        # Row 2 -> Row (2 + len(models))
        # if you change the description of this widget,
        # you have to also adjust it in the notebook function call.
        features = model.features_ohe.copy()
        features.insert(0, 'None')

        children.append(
            Select(description="... " + model.name,
                   options=model.features_ohe,
                   disabled=False))
        children.append(
            Select(description="... " + model.name,
                   options=features,
                   value='None',
                   disabled=False))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
Beispiel #2
0
 def widget_images(self):
     return interact(
         self.show_images, 
         size=FloatSlider(value=0.5, min=0, max=1, step=0.01, continuous_update=False, description="Size fraction"),
         show=Select(options={"Image": "image", "Difference": "difference"}, value="image", description='Show'),
         algorithm=Select(options=['None (exact)'] + list(self.ALGORITHMS.keys()), value='JPEG', description='Algorithm')
     )
Beispiel #3
0
    def set_up_read_selection_widgets(self):
        self.widgets.update({
            'batch':
            Select(options=self.batch_names,
                   continuous_update=False,
                   layout=Layout(height='200px', width='300px')),
            'sample':
            Select(options=[],
                   continuous_update=False,
                   layout=Layout(height='200px', width='300px')),
        })

        self.populate_samples({'name': 'initial'})
        self.widgets['batch'].observe(self.populate_samples, names='value')

        if self.by_outcome:
            self.populate_categories({'name': 'initial'})
            self.populate_subcategories({'name': 'initial'})
            self.widgets['sample'].observe(self.populate_categories,
                                           names='value')
            self.widgets['category'].observe(self.populate_subcategories,
                                             names='value')
            self.widgets['subcategory'].observe(self.populate_read_ids,
                                                names='value')
            selection_widget_keys = [
                'batch', 'sample', 'category', 'subcategory', 'read_id'
            ]
        else:
            self.widgets['sample'].observe(self.populate_read_ids,
                                           names='value')
            selection_widget_keys = ['batch', 'sample', 'read_id']

        self.populate_read_ids({'name': 'initial'})

        return selection_widget_keys
Beispiel #4
0
 def make_index(self):
     try:
         from ._catalogs import catalogs
     except:
         print("To build the index page, we need some catalogs.")
         catalogs = []
     self.selected_object = None
     self.title.value = "Sage Explorer"
     self.visualbox.children = [Title("Index Page")]
     self.tabs.remove_class('invisible')
     self.tabs.add_class('visible')
     self.gobutton.description = 'Go!'
     menus = []
     for label, catalog in catalogs:
         menu = Select(rows=12, options=make_catalog_menu_options(catalog))
         menus.append(menu)
     self.menus.children = menus
     for i, (label, _) in enumerate(catalogs):
         self.menus.set_title(i, label)
     def menu_on_change(change):
         self.selected_object = change.new
         self.display_new_value(self.selected_object.name)
         self.doctab.value = to_html(change.new.doc)
         self.gobutton.on_click(lambda b:self.set_value(self.selected_object.member))
     for menu in self.menus.children:
         menu.observe(menu_on_change, names='value')
Beispiel #5
0
    def test_duplicate(self):
        select = Select(options=['first', 1, 'dup', 'dup'])
        observations = []

        def f(change):
            observations.append(change.new)

        select.observe(f, 'index')
        select.index = 3
        assert select.index == 3
        assert select.value == 'dup'
        assert select.label == 'dup'
        assert observations == [3]
        select.index = 2
        assert select.index == 2
        assert select.value == 'dup'
        assert select.label == 'dup'
        assert observations == [3, 2]
        select.index = 0
        assert select.index == 0
        assert select.value == 'first'
        assert select.label == 'first'
        assert observations == [3, 2, 0]

        # picks the first matching value
        select.value = 'dup'
        assert select.index == 2
        assert select.value == 'dup'
        assert select.label == 'dup'
        assert observations == [3, 2, 0, 2]
Beispiel #6
0
    def new_child(self) -> DOMWidget:
        """
        Widget for creating new child for this `Tier`.
        """
        child = self.tier.child_cls
        options = child.get_templates()

        mapping = {path.name: path for path in options}

        selection = Select(
            options=mapping.keys(),
            description='Template')

        def create(name, template, description):
            with form.status:
                obj = child(*self.tier.identifiers, name)
                obj.setup_files(mapping[template])
                obj.description = description
                display(widgetify_html(obj._repr_html_()))

        form = InputSequence(create,
                             Text(description=f'Identifier', placeholder=f'{child.id_regex}'),
                             selection,
                             Textarea(description='Motivation'))

        return form.as_widget()
Beispiel #7
0
    def _fill_folder(self):
        atoms = Button(description=' Fill', icon='adjust', layout=_wlo)
        opt = ['Ball and Stick', 'Van Der Waals Spheres', 'Covalent Spheres']
        #'High Performance']#,'Stick']
        fill = Select(options=opt, value=opt[0], layout=_wlo)
        bond_r = FloatSlider(max=1.0, description='Bond Radius')

        def _atoms(c):
            for scn in self.active():
                scn.atom_3d = not scn.atom_3d

        def _fill(c):
            for scn in self.active():
                scn.fill_idx = c.new
            bond_r.disabled = True if c.new == 1 else False

        def _bond_r(c):
            for scn in self.active():
                scn.bond_r = c.new

        atoms.on_click(_atoms)
        fill.observe(_fill, names='index')
        bond_r.observe(_bond_r, names='value')
        content = _ListDict([('opt', fill), ('bond_r', bond_r)])
        return Folder(atoms, content)
Beispiel #8
0
def generate_pdp_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose a PDP method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in PDPType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
Beispiel #9
0
    def create(self, path="/", height="400px"):
        if self.running:
            print("dbfs browser already running. Use close() first")
            return
        self.path = path
        self.flist = Select(options=[],
                            disabled=False,
                            layout={"height": height})
        self.flist.observe(self.on_click, names="value")

        self.refresh = Button(icon="refresh", layout={"width": "40px"})
        self.refresh.on_click(self.on_refresh)
        self.path_view = Output()
        self.preview = Output(
            layout={
                "width": "800px",
                "height": height,
                "overflow": "scroll",
                "border": "1px solid gray",
            })

        self.up = Button(icon="arrow-up", layout={"width": "40px"})
        self.up.on_click(self.on_up)

        display(
            VBox([
                HBox([self.refresh, self.up, self.path_view]),
                HBox([self.flist, self.preview]),
            ]))

        self.update()
        self.running = True
Beispiel #10
0
 def _create_widget(self):
     if self.dropdown:
         return Dropdown(options=self.classes,
                         layout=self.layout,
                         disabled=self.disabled)
     return Select(options=self.classes,
                   layout=self.layout,
                   disabled=self.disabled)
 def create(self, width=120, height=200):
     self.height = height
     self.refresh = Button(icon="refresh", layout={"width": "40px"})
     self.refresh.on_click(self.on_refresh)
     self.list = Select(
         options=[], disabled=False, layout={"width": _px(width), "height": _px(height)}
     )
     self.list.observe(self.on_click, names="value")
     self.update()
Beispiel #12
0
def generate_local_interpretation_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose an interpretation method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in LocalInterpreterType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    # Row 3
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        RadioButtons(options=[elem.name for elem in ExampleType],
                     layout={'width': 'max-content'},
                     description='Example(s) type:',
                     disabled=False))

    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        IntSlider(
            value=1,
            min=1,
            max=10,
            step=1,
            description='Number of examples:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
        ))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
Beispiel #13
0
    def __init__(self, parent_widget=None):
        super().__init__(parent_widget=parent_widget)

        self.box_universe = self.db.read_boxes(scope=self.scope)

        self.library_list = Select(
            options=self.box_universe.fancy_names(),
            #value=' ',
            rows=10,
            description='',
            disabled=False)

        self.new_child_button = Button(
            description='New Child',
            disabled=False,
            button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Create a new child for the indicated selection',
            # icon='check'
        )
        self.new_child_button.on_click(self.open_new_child_interface)

        # self.load_box_button = Button(
        # 	description='Load '+CLUSTER,
        # 	disabled=False,
        # 	button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        # 	tooltip='Open the indicated selection in the Selectors editor',
        # 	# icon='check'
        # )
        # self.load_box_button.on_click(self.load_box_action)
        self.next_button.on_click(self.load_box_action)

        self.buttons = VBox([
            self.new_child_button,
            # self.load_box_button,
        ])

        self.popper = PseudoPopUpTextBox()
        self.main_window = HBox([
            self.library_list,
            self.buttons,
        ])

        self.make_stack(
            self.popper,
            self.main_window,
        )

        self.library_list.observe(self.on_change_library_list)
        self.popper.disappear()

        self.on_change_library_list(None)

        with self.header:
            display(HTML("<h1>Box Selection</h1>"))
 def test_index_trigger(self):
     select = Select(options=[1, 2, 3])
     observations = []
     def f(change):
         observations.append(change.new)
     select.observe(f, 'index')
     assert select.index == 0
     select.options = [4, 5, 6]
     assert select.index == 0
     assert select.value == 4
     assert select.label == '4'
     assert observations == [0]
Beispiel #15
0
    def __init__(self, rows=20, directory_only=False, ignore_dotfiles=True):
        self._callback = None
        self._directory_only = directory_only
        self._ignore_dotfiles = ignore_dotfiles
        self._empty_selection = True
        self._selected_dir = os.getcwd()
        self._item_layout = Layout(width='auto')
        self._nb_rows = rows
        self._file_selector = Select(options=self._get_selector_options(),
                                     rows=min(
                                         len(os.listdir(self._selected_dir)),
                                         self._nb_rows),
                                     layout=self._item_layout)
        self._open_button = Button(description='Open',
                                   layout=Layout(flex='auto 1 auto',
                                                 width='auto'))
        self._select_button = Button(description='Select',
                                     layout=Layout(flex='auto 1 auto',
                                                   width='auto'))
        self._cancel_button = Button(description='Cancel',
                                     layout=Layout(flex='auto 1 auto',
                                                   width='auto'))
        self._parent_button = Button(icon='chevron-up',
                                     layout=Layout(flex='auto 1 auto',
                                                   width='auto'))
        self._selection = Text(value=os.path.join(self._selected_dir,
                                                  self._file_selector.value),
                               disabled=True,
                               layout=Layout(flex='1 1 auto', width='auto'))
        self._filename = Text(value='',
                              layout=Layout(flex='1 1 auto', width='auto'))
        self._parent_button.on_click(self._parent_button_clicked)
        self._open_button.on_click(self._open_button_clicked)
        self._select_button.on_click(self._select_button_clicked)
        self._cancel_button.on_click(self._cancel_button_clicked)
        self._file_selector.observe(self._update_path)

        self._widget = VBox([
            HBox([
                self._parent_button,
                HTML(value='Look in:'),
                self._selection,
            ]),
            self._file_selector,
            HBox([
                HTML(value='File name'),
                self._filename,
                self._open_button,
                self._select_button,
                self._cancel_button,
            ]),
        ])
Beispiel #16
0
    def run(self, dfa):
        print('run')
        df_select = dfa

        # dfから先頭末尾の年を取得し、list化
        # year_list = ['2002', '2004', '2006']
        year_list = [str(n) for n in list(range(2002, 2006 + 1))]

        y1 = year_list
        y2 = year_list

        @interact(y1=Select(options=y1, rows=1, value=year_list[0]),
                  m1=Select(options=['04', '10'], rows=1),
                  y2=Select(options=y2, rows=1, value=year_list[-1]),
                  m2=Select(options=['03', '09'], rows=1))
        def function(y1, m1, y2, m2):
            print('function')

            start = y1 + '-' + m1 + '-01'
            if m2 == '03':
                end = y2 + '-' + m2 + '-31'
            elif m2 == '09':
                end = y2 + '-' + m2 + '-30'
            else:
                pass

            print(start)
            print(end)

            df_show = df_select[start:end]

            if len(df_show) == 0:
                print('エラーメッセージ')
                raise MyError()

            print(df_show)
            df_show.plot()
            df_show.plot()
    def set_up_read_selection_widgets(self):

        condition_options = [(', '.join(c) if isinstance(c, tuple) else c, c)
                             for c in self.group.conditions]
        self.widgets.update({
            'condition':
            Select(options=condition_options,
                   value=self.initial_condition,
                   layout=Layout(height='200px', width='300px')),
            'replicate':
            Select(options=[], layout=Layout(height='200px', width='150px')),
        })

        self.populate_replicates({'name': 'initial'})
        self.widgets['condition'].observe(self.populate_replicates,
                                          names='value')

        if self.by_outcome:
            self.populate_categories({'name': 'initial'})
            self.populate_subcategories({'name': 'initial'})

            self.widgets['replicate'].observe(self.populate_categories,
                                              names='value')
            self.widgets['category'].observe(self.populate_subcategories,
                                             names='value')
            self.widgets['subcategory'].observe(self.populate_read_ids,
                                                names='value')
            selection_widget_keys = [
                'condition', 'replicate', 'category', 'subcategory', 'read_id'
            ]
        else:
            self.widgets['replicate'].observe(self.populate_read_ids,
                                              names='value')
            selection_widget_keys = ['condition', 'replicate', 'read_id']

        self.populate_read_ids({'name': 'initial'})

        return selection_widget_keys
Beispiel #18
0
    def __init__(self, nl, **kwargs):
        self.nl = nl
        self.list = Select(options=self.nl.symbols)
        self.search_box = Text(placeholder="search")
        self.help = HTML()
        super().__init__(**kwargs)

        self.children = [VBox([self.search_box, self.list]), self.help]

        self.help.layout = Layout(flex="1 1 65%")

        self.list.observe(self.on_select_change, names="value")
        self.on_select_change(None)

        self.search_box.observe(self.on_search_change, names="value")
    def display_environment_maps(self, folder):
        """Display visual controls for setting environment map"""
        supported_extensions = ['jpg', 'jpeg', 'png']
        hdri_files = list()
        for extension in supported_extensions:
            hdri_files = hdri_files + glob.glob(folder + '/*.' + extension)
        hdri_files.sort()
        base_names = list()
        for hdri_file in hdri_files:
            base_names.append(os.path.basename(hdri_file))

        def update_envmap(value):
            filename = folder + '/' + value['new']
            self._client.set_environment_map(filename)

        cb_names = Select(description='Maps', options=base_names)
        cb_names.observe(update_envmap, 'value')
        display(cb_names)
Beispiel #20
0
    def __init__(self, storage, setup):
        self.storage = storage
        self.setup = setup

        self.nans = None

        self.play = Play()
        self.step_slider = IntSlider()
        self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps")
        self.product_select = Select()
        self.plots_box = Box()

        self.slider = {}
        self.lines = {'x': [{}, {}], 'y': [{}, {}]}
        for xy in ('x', 'y'):
            self.slider[xy] = IntRangeSlider(min=0, max=1, description=f'spectrum_{xy}',
                                             orientation='horizontal' if xy == 'x' else 'vertical')

        self.reinit({})
Beispiel #21
0
    def _make_widgets(self, rows):
        """
        Instantiate all widgets
        """

        # Experiment selector element
        self.model = Dropdown(
            options=(),
            layout={
                "padding": "0px 5px",
                "width": "initial"
            },
            description="",
        )
        # Variable search
        self.search = Text(
            placeholder="Search: start typing",
            layout={
                "padding": "0px 5px",
                "width": "auto",
                "overflow-x": "scroll"
            },
        )
        # Variable selection box
        self.selector = Select(
            options=(),  # sorted(self.variables.name, key=str.casefold),
            rows=rows,
            layout=self.search.layout,
        )
        # Variable info
        self.info = HTML(layout=self.search.layout)
        # Variable filtering elements
        self.filter_coords = Checkbox(
            value=True,
            indent=False,
            description="Hide coordinates",
        )
        self.filter_restarts = Checkbox(
            value=True,
            indent=False,
            description="Hide restarts",
        )
Beispiel #22
0
        def create(self):
            """Create the sidecar view"""
            self.sc = Sidecar(title="DBFS-%s" %
                              os.environ["DBJL_CLUSTER"].split("-")[-1])
            self.path = "/"
            self.flist = Select(options=[], rows=40, disabled=False)
            self.flist.observe(self.on_click, names="value")

            self.refresh = Button(description="refresh")
            self.refresh.on_click(self.on_refresh)
            self.output = Output()

            self.up = Button(description="up")
            self.up.on_click(self.on_up)

            with self.sc:
                display(
                    VBox([
                        HBox([self.up, self.refresh]), self.flist, self.output
                    ]))

            self.update()
Beispiel #23
0
    def _make_widgets(self, selvariables, **kwargs):
        """
        Instantiate all widgets
        """
        layout = {"padding": "0px 5px"}
        # Variable selector combo-widget. Pass only unique variable names. Variable
        # name is the only value used for filtering, so will pick up all matches
        self.selector = VariableSelector(selvariables.drop_duplicates("name"),
                                         **kwargs)

        # Button to add variable from selector to selected
        self.var_filter_add = Button(
            tooltip="Add selected variable to filter",
            icon="angle-double-right",
            layout={"width": "auto"},
        )
        # Button to add variable from selector to selected
        self.var_filter_sub = Button(
            tooltip="Remove selected variable from filter",
            icon="angle-double-left",
            layout={"width": "auto"},
        )
        self.button_box = VBox(
            [self.var_filter_add, self.var_filter_sub],
            layout={
                "padding": "100px 5px",
                "height": "100%"
            },
        )
        # Selected variables for filtering with header widget
        self.var_filter_label = HTML("Filter variables:", layout=layout)
        self.var_filter_selected = Select(
            options=[],
            rows=10,
            layout=layout,
        )
        self.filter_box = VBox(
            [self.var_filter_label, self.var_filter_selected], layout=layout)
        def update(self):
            """Update the view when an element was selected"""
            tables = {}
            for obj in self.spark.sql("show tables").rdd.collect():
                db = obj[0]
                table = obj[1]
                temp = obj[2]
                if temp and db == "":
                    db = "temp"
                if tables.get(db, None) is None:
                    tables[db] = []
                if temp:
                    tables[db].append("%s (temp)" % table)
                else:
                    tables[db].append(table)

            for db in sorted(tables.keys()):
                select = Select(options=[""] + sorted(tables[db]), disabled=False)
                select.observe(self.on_click(db, self), names="value")
                self.selects.append(select)
            self.accordion.children = self.selects
            for i, db in enumerate(sorted(tables.keys())):
                self.accordion.set_title(i, db)
Beispiel #25
0
        cmd("files-cp input.tgz agave://${STORAGE_MACHINE}/inputs/${INPUT_DIR}/")
        submitJob(nodes, procs[0], cur_model, jobNameText.value, machines.value, queues.value)
        
runBtn.on_click(runfun_btn_clicked)

runBox = VBox(run_items)

##################################### Run tab end #################################################



################################# Output tab ###################################

jobListBtn = Button(description='List all jobs', button_style='primary', layout= Layout(width = '115px'))

jobSelect = Select(layout = Layout(height = '150px', width='100%'))

jobOutputBtn = Button(description='List job output', button_style='primary', layout= Layout(width = '115px'))

abortBtn = Button(description='Abort', button_style='danger', layout= Layout(width = 'auto'))

outputSelect = Select(layout = Layout(height = '150px', width='100%'))

downloadOpBtn = Button(description='Download', button_style='primary', layout= Layout(width = '115px'))

jobHisBtn = Button(description='Job history', button_style='primary', layout= Layout(width = '115px'))

jobHisSelect = Select(layout = Layout(height = '336px', width='100%'))

def jobList_btn_clicked(a):
    with logOp:
    def __init__(self,
                 path=os.getcwd(),
                 filename='',
                 title='',
                 select_desc='Select',
                 change_desc='Change',
                 show_hidden=False,
                 select_default=False,
                 use_dir_icons=False,
                 **kwargs):
        """Initialize FileChooser object."""
        self._default_path = path.rstrip(os.path.sep)
        self._default_filename = filename
        self._selected_path = None
        self._selected_filename = None
        self._show_hidden = show_hidden
        self._select_desc = select_desc
        self._change_desc = change_desc
        self._callback = None
        self._use_dir_icons = use_dir_icons

        # Widgets
        self._pathlist = Dropdown(description="",
                                  layout=Layout(width='auto',
                                                grid_area='pathlist'))
        self._filename = Text(placeholder='output filename',
                              layout=Layout(width='auto',
                                            grid_area='filename'))
        self._dircontent = Select(rows=8,
                                  layout=Layout(width='auto',
                                                grid_area='dircontent'))
        self._cancel = Button(description='Cancel',
                              layout=Layout(width='auto', display='none'))
        self._select = Button(description=self._select_desc,
                              layout=Layout(width='auto'))

        self._title = HTML(value=title)

        if title == '':
            self._title.layout.display = 'none'

        # Widget observe handlers
        self._pathlist.observe(self._on_pathlist_select, names='value')
        self._dircontent.observe(self._on_dircontent_select, names='value')
        self._filename.observe(self._on_filename_change, names='value')
        self._select.on_click(self._on_select_click)
        self._cancel.on_click(self._on_cancel_click)

        # Selected file label
        self._label = HTML(value=self._LBL_TEMPLATE.format(
            self._LBL_NOFILE, 'black'),
                           placeholder='',
                           description='')

        # Layout
        self._gb = GridBox(
            children=[self._pathlist, self._filename, self._dircontent],
            layout=Layout(display='none',
                          width='500px',
                          grid_gap='0px 0px',
                          grid_template_rows='auto auto',
                          grid_template_columns='60% 40%',
                          grid_template_areas='''
                    'pathlist filename'
                    'dircontent dircontent'
                    '''))
        buttonbar = HBox(children=[self._select, self._cancel, self._label],
                         layout=Layout(width='auto'))

        # Call setter to set initial form values
        self._set_form_values(self._default_path, self._default_filename)

        # Use the defaults as the selected values
        if select_default:
            self._apply_selection()

        # Call VBox super class __init__
        super().__init__(children=[
            self._title,
            self._gb,
            buttonbar,
        ],
                         layout=Layout(width='auto'),
                         **kwargs)
 def test_construction(self):
     select = Select(options=['a', 'b', 'c'])
    def __init__(self,
                 ed: ExplorerData,
                 box_universe,
                 box_name,
                 parent_widget=None):
        super().__init__(parent_widget=parent_widget)
        self.data = ed
        self._box_universe = box_universe
        self._box_name = box_name

        self._suspend_updates = False

        try:

            clusterdef = ChainedBox(self._box_universe, self._box_name)

            clusterdef_relevant = clusterdef.relevant_and_demanded_features
            clusterdef_demanded = clusterdef.demanded_features

            self.checkers = []

            for i in self.data.all_performance_measures:
                controller = Checkbox(
                    value=i in clusterdef_relevant,
                    description=i,
                    disabled=i in clusterdef_demanded,
                    style={'description_width': 'initial'},
                    tooltip=i
                    if i not in clusterdef_demanded else _demanded_tooltip,
                )
                self.checkers.append(controller)

            for i in self.data.all_strategy_names:
                controller = Checkbox(
                    value=i in clusterdef_relevant,
                    description=i,
                    disabled=i in clusterdef_demanded,
                    style={'description_width': 'initial'},
                    tooltip=i
                    if i not in clusterdef_demanded else _demanded_tooltip,
                )
                self.checkers.append(controller)

            for i in self.data.all_risk_factors:
                controller = Checkbox(
                    value=i in clusterdef_relevant,
                    description=i,
                    disabled=i in clusterdef_demanded,
                    style={'description_width': 'initial'},
                    tooltip=i
                    if i not in clusterdef_demanded else _demanded_tooltip,
                )
                self.checkers.append(controller)

            for s in range(len(self.checkers)):
                self.checkers[s].observe(self.toggle_check)

            self.ui_risks = VBox([
                ch for ch in self.checkers
                if ch.description in self.data.all_risk_factors
            ], )

            self.ui_strategies = VBox([
                ch for ch in self.checkers
                if ch.description in self.data.all_strategy_names
            ], )

            self.ui_perform = VBox([
                ch for ch in self.checkers
                if ch.description in self.data.all_performance_measures
            ], )

            self.accordion = Accordion(
                children=[self.ui_strategies, self.ui_risks, self.ui_perform],
                layout=Layout(width='600px', ))
            self.accordion.set_title(0, 'Policy Levers')
            self.accordion.set_title(1, 'Exogenous Uncertainties')
            self.accordion.set_title(2, 'Performance Measures')

            self.accordion_filter = Text(value='.*',
                                         placeholder='.*',
                                         description='Filter:',
                                         disabled=False)
            self.accordion_filter.observe(self.filter_checkboxes)

            self.current_relevant_attributes = Select(
                options=[],
                # value='OSX',
                rows=30,
                description='',
                disabled=False)

            # self.load_current_relevant_attributes_button = Button(
            # 	description=f"Next",
            # 	disabled=False,
            # 	button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            # 	tooltip='Load',
            # 	# icon='check'
            # )
            # self.load_current_relevant_attributes_button.on_click(
            # 	self.load_selected_features_into_thresholds
            # )

            self.next_button.on_click(
                self.load_selected_features_into_thresholds)

            # self.stack = VBox([
            # 	self.header_area,
            # 	HBox([
            # 		VBox([
            # 			self.accordion_filter,
            # 			self.accordion,
            # 		]),
            # 		VBox([
            # 			HTML_widget(value=f"<b>{RELEVANT}</b>", placeholder=f"These things will be loaded"),
            # 			self.current_relevant_attributes,
            # 			self.load_current_relevant_attributes_button,
            # 		]),
            # 	]),
            # 	self.footer,
            # ])

            self.make_stack(
                HBox([
                    VBox([
                        self.accordion_filter,
                        self.accordion,
                    ]),
                    VBox([
                        HTML_widget(
                            value=f"<b>{RELEVANT}</b>",
                            placeholder=f"These things will be loaded"),
                        self.current_relevant_attributes,
                        # self.load_current_relevant_attributes_button,
                    ]),
                ]), )

            self.set_header(clusterdef.names)
            self.recompile_list_of_active_features(
                None)  # initial interactive plots

        except:
            logger.exception("error in initialize_sliders")
            raise
    def display_palette_for_models(self):
        """Display visual controls for color palettes applied to models"""
        def set_colormap(model_id, colormap_name, shading_mode):
            material_ids = self._be.get_material_ids(model_id)['ids']
            nb_materials = len(material_ids)

            palette = sns.color_palette(colormap_name, nb_materials)
            self._be.set_materials_from_palette(
                model_ids=[model_id],
                material_ids=material_ids,
                palette=palette,
                specular_exponent=specular_exponent_slider.value,
                shading_mode=shading_mode,
                opacity=opacity_slider.value,
                refraction_index=refraction_index_slider.value,
                reflection_index=reflection_index_slider.value,
                glossiness=glossiness_slider.value,
                user_parameter=user_param_slider.value,
                emission=emission_slider.value,
                chameleon_mode=chameleon_combobox.index)
            self._client.set_renderer(accumulation=True)

        # Models
        model_names = list()
        for model in self._client.scene.models:
            model_names.append(model['name'])
        model_combobox = Select(options=model_names,
                                description='Models:',
                                disabled=False)

        # Shading modes
        shading_combobox = Select(options=SHADING_MODES,
                                  description='Shading:',
                                  disabled=False)

        # Colors
        palette_combobox = Select(options=COLOR_MAPS,
                                  description='Palette:',
                                  disabled=False)

        # Chameleon modes
        chameleon_combobox = Select(options=CHAMELEON_MODES,
                                    description='Chameleon:',
                                    disabled=False)

        # Events
        def update_materials_from_palette(value):
            """Update materials when palette is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         value['new'], shading_combobox.index)

        def update_materials_from_shading_modes(_):
            """Update materials when shading is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         palette_combobox.value, shading_combobox.index)

        def update_materials_from_chameleon_modes(_):
            """Update materials when chameleon mode is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         palette_combobox.value, shading_combobox.index)

        shading_combobox.observe(update_materials_from_shading_modes, 'value')
        palette_combobox.observe(update_materials_from_palette, 'value')
        chameleon_combobox.observe(update_materials_from_chameleon_modes,
                                   'value')

        horizontal_box_list = HBox(
            [model_combobox, shading_combobox, palette_combobox])

        opacity_slider = FloatSlider(description='Opacity',
                                     min=0,
                                     max=1,
                                     value=1)
        opacity_slider.observe(update_materials_from_shading_modes)
        refraction_index_slider = FloatSlider(description='Refraction',
                                              min=1,
                                              max=5,
                                              value=1)
        refraction_index_slider.observe(update_materials_from_shading_modes)
        reflection_index_slider = FloatSlider(description='Reflection',
                                              min=0,
                                              max=1,
                                              value=0)
        reflection_index_slider.observe(update_materials_from_shading_modes)
        glossiness_slider = FloatSlider(description='Glossiness',
                                        min=0,
                                        max=1,
                                        value=1)
        glossiness_slider.observe(update_materials_from_shading_modes)
        specular_exponent_slider = FloatSlider(description='Specular exponent',
                                               min=1,
                                               max=100,
                                               value=1)
        specular_exponent_slider.observe(update_materials_from_shading_modes)
        user_param_slider = FloatSlider(description='User param',
                                        min=0,
                                        max=100,
                                        value=1)
        user_param_slider.observe(update_materials_from_shading_modes)
        emission_slider = FloatSlider(description='Emission',
                                      min=0,
                                      max=100,
                                      value=0)
        emission_slider.observe(update_materials_from_shading_modes)

        cast_simulation_checkbox = Checkbox(description='Simulation',
                                            value=False)
        cast_simulation_checkbox.observe(update_materials_from_shading_modes)

        horizontal_box_detail1 = HBox(
            [opacity_slider, refraction_index_slider, reflection_index_slider])
        horizontal_box_detail2 = HBox(
            [glossiness_slider, specular_exponent_slider, user_param_slider])
        horizontal_box_detail3 = HBox(
            [emission_slider, cast_simulation_checkbox, chameleon_combobox])
        vertical_box = VBox([
            horizontal_box_list, horizontal_box_detail1,
            horizontal_box_detail2, horizontal_box_detail3
        ],
                            layout=DEFAULT_GRID_LAYOUT)
        display(vertical_box)
Beispiel #30
0
    def __init__(self):

        self.physicell_vars = Select(
            # options=['--- microenv ---','--- cell var ---'],
            options=[],
            #     value='OSX',
            rows=10,
            description='PhysiCell:',
            disabled=False)
        self.sbml_vars = Select(
            options=[],
            #     value='OSX',
            rows=10,
            description='SBML:',
            disabled=False)

        gen_button_layout = {'width': '20%'}
        self.generate = Button(
            description='Generate',  #style={'description_width': 'initial'},
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Generate code to map two quantities.',
            disabled=False,
            layout=gen_button_layout
            # layout=Layout(width='490px')
        )
        empty_btn = Button(disabled=True, layout=Layout(width='270px'))
        empty_btn.style.button_color = 'white'

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='700px')
        row1 = [empty_btn, self.generate]
        box1 = Box(children=row1, layout=box_layout)

        self.code = Textarea(value='code goes here...',
                             placeholder='placeholder',
                             description='Code:',
                             disabled=False,
                             layout=Layout(width='700px', height='300px'))

        def generate_code_cb(b):
            # validate selections as valid
            self.code.value = "// " + str(
                self.physicell_vars.value) + " --> " + str(
                    self.sbml_vars.value)
            self.code.value += "\n..."
            str1 = """
    static int idx_sbml_oxygen = 3;
    static int idx_substrate_oxygen = microenvironment.find_density_index( "oxygen" ); 

    int index_voxel = microenvironment.nearest_voxel_index(pCell->position);
    double oxy_val = microenvironment(vi)[idx_substrate_oxygen];

    rrc::RRVectorPtr vptr;
    rrc::RRCDataPtr result;  // start time, end time, and number of points
    vptr = rrc::getFloatingSpeciesConcentrations(pCell->phenotype.molecular.model_rr);
    """
            self.code.value += str1
            self.code.value += "\n..."
            self.code.value += "\n// " + str(
                self.sbml_vars.value) + " --> " + str(
                    self.physicell_vars.value)
            str2 = """
    static int idx_sbml_oxygen = 3;
    static int idx_substrate_oxygen = microenvironment.find_density_index( "oxygen" ); 

    int index_voxel = microenvironment.nearest_voxel_index(pCell->position);
    double oxy_val = microenvironment(vi)[idx_substrate_oxygen];

    rrc::RRVectorPtr vptr;
    rrc::RRCDataPtr result;  // start time, end time, and number of points
    vptr = rrc::getFloatingSpeciesConcentrations(pCell->phenotype.molecular.model_rr);

    """
            self.code.value += str2
            self.code.value += "\n..."

        self.generate.on_click(generate_code_cb)

        map_tables = HBox([
            self.physicell_vars,
            self.sbml_vars,
        ])

        # self.tab = VBox([map_tables, self.generate, self.code])
        self.tab = VBox([map_tables, box1, self.code])