def __init__(self, api, patients: Queryable = None):
        self.api = api
        self.tiles = list()
        self.hypercube = Hypercube()
        self.__linked_tile = None

        if isinstance(patients, Queryable):
            self.subject_set_id = api.create_patient_set(
                repr(patients), patients).get('id')
            counts = api.observations.counts_per_study_and_concept(
                subject_set_id=self.subject_set_id)
            self.nodes = filter_tree(api.tree_dict, counts)

        else:
            self.subject_set_id = None
            self.nodes = None

        self.out = widgets.Box()
        self.out.layout.flex_flow = 'row wrap'

        self.combination_out = widgets.Box()
        self.combination_out.layout.flex_flow = 'row wrap'

        self.cp = ConceptPicker(self.plotter, api, self.nodes)
        self.counter = widgets.IntProgress(value=10,
                                           min=0,
                                           max=10,
                                           step=1,
                                           orientation='horizontal')
Exemple #2
0
    def __init__(self, root_dir: path = None):
        self.root_dir: path = root_dir
        if self.root_dir is None:
            self.root_dir = path.join(path.sep, 'p', 'fastdata', 'slmet',
                                      'slmet111', 'met_data', 'ecmwf', 'era5',
                                      'nc')

        # filers and filter (multiple selection widget)
        self.dataset_files_selection: widgets.SelectMultiple = widgets.SelectMultiple(
        )
        self.filter_selection: widgets.SelectMultiple = widgets.SelectMultiple(
        )
        self.filter_specification_box: FilterBox = FilterBox()
        self.filter_specification: widgets.Box = widgets.Box([])

        self.datasets: List[DatasetFile] = []
        self.dataset_filters: List[DatasetFileFilter] = []

        self.recently_removed_datasets: List[List[DatasetFile]] = [[]]

        self.datebox_main: DateSelector = DateSelector()

        button_collect: widgets.Button = widgets.Button(
            description='Collect Datasets',
            disabled=False,
            button_style='success',
            # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Collects datasets within the given time interval',
            # icon='fa-bomb',
            style=style)

        def button_collect_clicked(collect_button: widgets.Button):
            self.datasets = []
            # check if dates are valid
            if self.datebox_main.evaluate_dates():
                # collect available datasets from specified start and end datetime objects
                if self.collect_datasets(
                        date_start=self.datebox_main.get_start_date(),
                        date_end=self.datebox_main.get_end_date()):
                    # if any datasets were found, initialize further widgets for filtering of selected files
                    self.init_dataset_specification()
                else:
                    notify('No datasets were found from ' +
                           str(self.datebox_main.get_start_date()) + ' to ' +
                           str(self.datebox_main.get_end_date()))

        button_collect.on_click(button_collect_clicked)

        self.date_selection_box: widgets.VBox = widgets.VBox(
            [self.datebox_main, button_collect],
            layout=widgets.Layout(display='flex',
                                  flex_flow='row wrap',
                                  justify_content='space-around',
                                  align_items='center'))
        self.dataset_specification_box: widgets.Box = widgets.Box()

        self.main_component: widgets.Accordion = widgets.Accordion(
            children=[self.date_selection_box])
        self.main_component.set_title(0, 'Selection Interval')
        self.main_component.selected_index = 0
    def create_ui(self, shared_slider):
        # Create the active UI components. Height and width are specified in 'em' units. This is
        # a html size specification, size relative to current font size.
        ui = None

        if shared_slider:
            # Validate that all the images have the same size along the axis which we scroll through
            sz = self.npa_list[0].shape[self.axis]
            for npa in self.npa_list:
                       if npa.shape[self.axis]!=sz:
                           raise ValueError('Not all images have the same size along the specified axis, cannot share slider.')

            slider = widgets.IntSlider(description='image slice:',
                                      min=0,
                                      max=sz-1,
                                      step=1,
                                      value = int((sz-1)/2),
                                      width='20em')
            slider.observe(self.on_slice_slider_value_change, names='value')
            self.slider_list = [slider]*len(self.npa_list)
            ui = widgets.Box(padding=7, children=[slider])
        else:
            self.slider_list = []
            for npa in self.npa_list:
                slider = widgets.IntSlider(description='image slice:',
                                           min=0,
                                           max=npa.shape[self.axis]-1,
                                           step=1,
                                           value = int((npa.shape[self.axis]-1)/2),
                                           width='20em')
                slider.observe(self.on_slice_slider_value_change, names='value')
                self.slider_list.append(slider)
            ui = widgets.Box(padding=7, children=self.slider_list)
        return ui
Exemple #4
0
    def __init__(self, element_list, description=None, size=5, style=0):
        if not isinstance(element_list, list):
            element_list = [element_list]

        box_layout = widgets.Layout(
            display='flex',
            flex_flow='column',
            align_items='flex-start',
            align_content='flex-start',
            #                                     justify_content='center',
            justify_content='space-around',
            border=border_list[2])
        frame = widgets.Box(children=element_list, layout=box_layout)

        if description is not None:
            caption = widgets.HTML(value="<font size=" + str(size) + "><B>" +
                                   description + "</B>")
            children = [caption, frame]
        else:
            children = [frame]

        box_layout = widgets.Layout(
            display='flex',
            flex_flow='column',
            align_items='center',
            justify_content='center',
            border=border_list[style],
        )
        self.frame = widgets.Box(children=children, layout=box_layout)
    def create_ui(self):
        # Create the active UI components. Height and width are specified in 'em' units. This is
        # a html size specification, size relative to current font size.
        self.viewing_checkbox = widgets.RadioButtons(description= 'Interaction mode:', 
                                                     options= ['edit', 'view'], 
                                                     value = 'edit')

        self.clearlast_button = widgets.Button(description= 'Clear Last', 
                                               width= '7em', 
                                               height= '3em')
        self.clearlast_button.on_click(self.clear_last)

        self.clearall_button = widgets.Button(description= 'Clear All', 
                                              width= '7em', 
                                              height= '3em') 
        self.clearall_button.on_click(self.clear_all)

        self.slice_slider = widgets.IntSlider(description='image z slice:',
                                              min=0,
                                              max=self.npa.shape[0]-1, 
                                              step=1, 
                                              value = int((self.npa.shape[0]-1)/2),
                                              width='20em')
        self.slice_slider.observe(self.on_slice_slider_value_change, names='value')
        
        # Layout of UI components. This is pure ugliness because we are not using a UI toolkit. Layout is done
        # using the box widget and padding so that the visible UI components are spaced nicely.
        bx0 = widgets.Box(padding=7, children=[self.slice_slider])
        bx1 = widgets.Box(padding=7, children = [self.viewing_checkbox])
        bx2 = widgets.Box(padding = 15, children = [self.clearlast_button])
        bx3 = widgets.Box(padding = 15, children = [self.clearall_button])
        return widgets.HBox(children=[widgets.HBox(children=[bx1, bx2, bx3]),bx0])
Exemple #6
0
    def layout(self):
        self._plot_container = ipywidgets.Box()
        # Define a container for the main controls in the browse interface.
        children = [fp.box for fp in self.file_pickers]
        self.ftabs = ipywidgets.Tab(children=children)
        children = [self._load_button, self._file_tab_button]
        self.bbox = ipywidgets.HBox(children=children)
        children = [self.ftabs, self.bbox]
        self._file_picker_tabs = ipywidgets.Box(children=children)

        pcc_children = [pc.box for pc in self.plot_controls]
        self._plot_control_container = ipywidgets.Tab(children=pcc_children)

        acc_children = [
            self._file_picker_tabs, self._subplots,
            self._plot_control_container
        ]
        self._accord = ipywidgets.Accordion(children=acc_children)
        self._accord.set_title(0, 'Files')
        self._accord.set_title(1, 'SubPlots')
        self._accord.set_title(2, 'Plots')

        # Display the browse interface.
        IPython.display.display(self._accord)
        IPython.display.display(self._plot_button)
        IPython.display.display(self._plot_container)
Exemple #7
0
    def _add_element_pane(self, element):
        header, field_values = self._unpack_element(element)

        if self.attempt_batch_prefetch:
            self._do_retrieve_batch(element, field_values)

        import html
        grid_content_boxes = []
        for field, value in field_values.items():
            field_display_name = self._to_field_display_name(element, field)
            if field_display_name and (value
                                       is not None) and not ([] == value):
                field_widget = widgets.HTML(
                    value="<b>{}</b>".format(html.escape(field_display_name)))
                field_box = widgets.Box(children=[field_widget],
                                        layout=self.field_box_layout)
                slot_widget_list = self._value_widget_list(
                    element, field, value)
                slot_box = widgets.Box(children=slot_widget_list,
                                       layout=self.slot_box_layout)
                grid_content_boxes.extend([field_box, slot_box])
        content = widgets.GridBox(layout=self.grid_container_layout,
                                  children=grid_content_boxes)

        self.accordion.children = list(self.accordion.children) + [content]
        self.accordion.set_title(len(self.element_list), header)
        self.element_id_to_index[self._to_hashable_identifier(element)] = len(
            self.element_list)
        self.element_list.append(element)
Exemple #8
0
def arrange_buttons(list_buttons, yn_button_select=True, ncol=4):
    num = len(list_buttons)
    if yn_button_select:
        feature_celeba_layout = feature_celeba_organize.feature_celeba_layout
        layout_all_buttons = ipywidgets.VBox([ipywidgets.Box([list_buttons[item] for item in row]) for row in feature_celeba_layout])
    else:
        layout_all_buttons = ipywidgets.VBox([ipywidgets.Box(list_buttons[i*ncol:(i+1)*ncol]) for i in range(num//ncol+int(num%ncol>0))])
    return layout_all_buttons
Exemple #9
0
    def setting_accord():
        data_box = widgets.Box([
            widgets.Text(value='example: data.csv',
                         description='Data Path:',
                         style={'description_width': 'initial'},
                         layout=Layout(flex='3 1 0%', width='auto')),
            widgets.Text(value='example: ~/images/',
                         description='Image Directory:',
                         style={'description_width': 'initial'},
                         layout=Layout(flex='3 1 0%', width='auto')),
            widgets.Text(value='',
                         description='Colname of Filename:',
                         style={'description_width': 'initial'}),
            widgets.Text(value='',
                         description='Colname of Label:',
                         style={'description_width': 'initial'})
        ],
                               layout=Layout(display='flex',
                                             flex_flow='column',
                                             align_items='stretch',
                                             width='80%'))

        preprocess_box = widgets.Box([
            widgets.HBox([
                widgets.Checkbox(value=False,
                                 description='Save split data',
                                 disabled=False),
                widgets.Checkbox(value=True,
                                 description='Image Augmentation',
                                 disabled=False),
                widgets.Checkbox(value=False,
                                 description='Histogram Equalization',
                                 disabled=False)
            ]),
            widgets.RadioButtons(options=[(224, 224, 3), (299, 299, 3)],
                                 description='resize:'),
            widgets.FloatRangeSlider(value=(-1.0, 1.0),
                                     min=-1.0,
                                     max=1.0,
                                     description='Range of Normalization:',
                                     style={'description_width': 'initial'}),
            widgets.FloatSlider(value=0.2,
                                min=0.1,
                                max=1.0,
                                description='Validation Set:',
                                style={'description_width': 'initial'})
        ],
                                     layout=Layout(display='flex',
                                                   flex_flow='column',
                                                   align_items='stretch',
                                                   width='80%'))

        tab_accord = widgets.Accordion(selected_index=None)
        tab_accord.children = [data_box, preprocess_box]
        tab_accord.set_title(0, 'Dataset')
        tab_accord.set_title(1, 'Preprocess')

        return tab_accord
Exemple #10
0
 def _make_layout(cls):
     box_layout = iw.Layout(width="80%",
                            height="1500px",
                            display="flex",
                            flex_flow="column nowrap",
                            justify_content="space-between",
                            align_items="stretch",
                            align_content="space-between")
     row_layout0 = iw.Layout(width="90%",
                             display="flex",
                             flex_flow="row nowrap",
                             justify_content="flex-start",
                             align_items="center",
                             align_content="flex-start")
     row_layout1 = iw.Layout(width="70%",
                             display="flex",
                             flex_flow="row nowrap",
                             justify_content="space-between",
                             align_items="flex-start",
                             align_content="flex-start")
     row_layout2 = iw.Layout(width="100%",
                             display="flex",
                             flex_flow="row nowrap",
                             justify_content="flex-start",
                             align_items="center",
                             align_content="flex-start")
     items_layout = iw.Layout(width="auto",
                              flex="0 1 auto",
                              align_self="flex-start")
     radio_buttons_layout = iw.Layout(width="auto",
                                      flex="0 1 auto",
                                      align_self="center")
     title = iw.HTML(
         '<h1>Simulation of a Drinking Water Network in an Apartment Building</h1>'
         '<p style="font-family:sans-serif; font-size:140%">'
         'The apartment building counts 8 storeys. The drinking water sub-network on each floor has been reduced'
         ' to a single "equivalent water tap". By moving the sliders the valve opening on each floor can be set. '
         'When the "run" button is clicked, the flow rates and pressure drops across the valves are calculated and '
         'are shown in the table. The diagram shows the working point of the booster pump. One can choose between a '
         'single pump, 2 identical pumps in parallel or 2 identical pumps in series. The calculated flow rates in '
         'the table can be compared with the expected flow rates at a design pressure drop of 3 bar and '
         'corresponding with the valve opening set.</p>')
     title.layout = items_layout
     row0 = iw.Box(children=[title], layout=row_layout0)
     cls.slider_panel.layout = items_layout
     cls.radio_buttons.layout = radio_buttons_layout
     cls.btn_panel.layout = items_layout
     row1 = iw.Box(
         children=[cls.slider_panel, cls.radio_buttons, cls.btn_panel],
         layout=row_layout1)
     cls.table.layout = items_layout
     row2 = iw.Box(children=[cls.table], layout=row_layout2)
     cls.fig.canvas.layout = items_layout
     row3 = iw.Box(children=[cls.fig.canvas], layout=row_layout2)
     cls.dashboard = iw.Box(children=[row0, row1, row2, row3],
                            layout=box_layout)
Exemple #11
0
    def __init__(self):
        self.trade_view = widgets.Box()
        self.quote_view = widgets.Box()
        self.root = widgets.Tab([self.trade_view, self.quote_view])

        self.root.set_title(0, 'Trades')
        self.root.set_title(1, 'Quotes')
        self._quote_task = self._client._loop.create_task(self.quote_watcher())

        self._trade_task = self._client._loop.create_task(self.trade_watcher())
Exemple #12
0
    def __init__(self, show_header=True):
        def el_ly(w):
            return dict(width='{}px'.format(w), margin='0px')

        # minimum block
        self.nomin = ipyw.Checkbox(value=True, layout=el_ly(125))
        self.min = ipyw.FloatText(value=-float('inf'), layout=el_ly(165))
        box_ly = dict(border='1px solid black',
                      display='flex',
                      margin='0px',
                      flex_flow='row',
                      width='290px')
        self.minbox = ipyw.Box([self.nomin, self.min], layout=box_ly)

        # value element
        self.value = ipyw.FloatText(value=0, layout=el_ly(170))

        # maximum block
        self.nomax = ipyw.Checkbox(value=True, layout=el_ly(125))
        self.max = ipyw.FloatText(value=float('inf'), layout=el_ly(165))
        self.maxbox = ipyw.Box([self.nomax, self.max], layout=box_ly)

        # constraints block
        self.vary = ipyw.Checkbox(value=True, layout=el_ly(125))
        self.expr = ipyw.Text(value='',
                              continuous_update=False,
                              layout=el_ly(275))

        # array elements in an horizontal block
        self.elements = [
            self.minbox, self.value, self.maxbox, self.vary, self.expr
        ]

        # Header labels
        self.header = None
        if show_header is True:
            d_lbs = (('-inf', 125), ('min', 165), ('value', 170), ('inf', 125),
                     ('max', 165), ('vary', 125), ('expression', 275))
            l_lbs = [ipyw.Label(k, layout=el_ly(v)) for (k, v) in d_lbs]
            box_ly = dict(display='flex', margin='0px', border='solid')
            self.header = ipyw.HBox(l_lbs, layout=box_ly)

        # Layout
        if self.header is None:
            box_ly = dict(display='flex',
                          margin='0px',
                          border='solid',
                          flex_flow='row')
            super(ParameterWidget, self).__init__(self.elements, layout=box_ly)
        else:
            box_ly = dict(display='flex', margin='0px', border='solid')
            b_els = ipyw.HBox(self.elements, layout=box_ly)
            box_ly.update({'flex_flow': 'column'})
            super(ParameterWidget, self).__init__([self.header, b_els],
                                                  layout=box_ly)
Exemple #13
0
    def __init__(self, mol):
        self.mol = mol

        self.toolpane = ipy.Box()
        self.viewer = self.VIEWERTYPE(mol)

        self.subtools = ipy.Box()
        self.viewer_pane = ipy.VBox([self.viewer, self.subtools])
        self.main_pane = ipy.HBox([self.viewer_pane, self.toolpane])

        super(ViewerToolBase, self).__init__([self.main_pane])
Exemple #14
0
    def __init__(self, bd: BudgetData, cats=None, **kwargs):
        self.bd = bd

        if not hasattr(self.bd, '_df'):
            self.bd.load_sql()

        if cats is None:
            cats = bd._sel.columns.tolist()

        qgrid_opts['column_definitions']['Description']['width'] = 150
        qgrid_opts['grid_options']['forceFitColumns'] = True

        kwargs['children'] = [
            widgets.HBox(children=[
                freq_dropdown(),
                widgets.Dropdown(
                    options=cats, value=cats[0], layout={'width': '300px'}),
                widgets.ToggleButton(description='Apply Notes', value=True)
            ]),
            widgets.HBox(children=[
                widgets.Box(children=[
                    qgrid.show_grid(pd.DataFrame(
                        columns=bd.df.columns), **qgrid_opts),
                ],
                            layout={
                                'display': 'flex',
                                'width': '200px',
                                'padding': '5px'
                            }),
                widgets.Box(children=[
                    qgrid.show_grid(pd.DataFrame(
                        columns=bd.df.columns), **qgrid_opts),
                ],
                            layout={
                                'display': 'flex',
                                'flex': '1 1',
                                'width': 'auto',
                                'padding': '5px'
                            }),
            ]),
            widgets.Output()
        ]

        if 'layout' not in kwargs:
            bar_layout['flex_flow'] = 'row wrap'
            kwargs['layout'] = bar_layout
        super().__init__(**kwargs)

        for child in self.children[0].children:
            child.observe(self.show_report, 'value')
        self.report.on('selection_changed', self.show_transactions)

        self.show_report()
Exemple #15
0
    def __init__(self, input_box, plot_box, output_box):

        # File layout.
        self.file_box = wg.Box()

        # Help layout.
        self.help_box = wg.Box()

        # Input area.
        narrow_input_btn = self.autosize_button('🡐')
        narrow_input_btn.on_click(self.on_narrow_input)
        widen_input_btn = self.autosize_button('🡒')
        widen_input_btn.on_click(self.on_widen_input)
        input_header = wg.HBox(
            [wg.Label(value='Input'), narrow_input_btn, widen_input_btn])
        input_layout = wg.VBox([input_header, input_box],
                               layout=wg.Layout(width='auto',
                                                grid_area='input'))

        # Plot area.
        narrow_plot = self.autosize_button('🡑')
        narrow_plot.on_click(self.on_narrow_plot)
        widen_plot = self.autosize_button('🡓')
        widen_plot.on_click(self.on_widen_plot)
        plot_header = wg.HBox(
            [wg.Label(value='Plots'), narrow_plot, widen_plot])
        plot_layout = wg.VBox([plot_header, plot_box],
                              layout=wg.Layout(width='auto', grid_area='plot'))

        # Output area.
        output_header = wg.HBox([wg.Label(value='Output')])
        output_layout = wg.VBox([output_header, output_box],
                                layout=wg.Layout(width='auto',
                                                 grid_area='output'))

        self.calc_layout = wg.GridBox(
            children=[input_layout, plot_layout, output_layout],
            layout=wg.Layout(grid_template_rows='50% auto',
                             grid_template_columns='50% auto',
                             grid_template_areas='''
                                                       "input plot"
                                                       "input output"
                                                       '''))

        # Tabbed layout for overall app.
        self.main_view = wg.Tab()
        self.main_view.children = [
            self.calc_layout, self.help_box, self.file_box
        ]
        self.main_view.set_title(0, 'App')
        self.main_view.set_title(1, 'Help')
        self.main_view.set_title(2, 'File')
def default_display_function(feature):
    """
    A default function that displays the feature and adds some padding.

    Parameters
    ----------
    feature : np.ndarray, pd.Series, pd.DataFrame
        The feature(s) you want to display
    """
    # n_samples = min(n_samples, feature.shape[0])
    IPython.display.display(widgets.Box(layout=widgets.Layout(height="2.5%")))
    IPython.display.display(feature)
    IPython.display.display(widgets.Box(layout=widgets.Layout(height="2.5%")))
Exemple #17
0
    def generate_widgets(self):
        form_item_layout = Layout(display='flex',
                                  flex_flow='row',
                                  justify_content='space-between')
        readdata_items = [
            ipywidgets.Box([self.filename], layout=form_item_layout),
            ipywidgets.Box(
                [self.em_range_display, self.ex_range_display, self.crange_cw],
                layout=form_item_layout),
            #    ipywidgets.Box([scattering_correction, scattering_interpolation],layout=form_item_layout),
            ipywidgets.Box([
                self.gaussian_smoothing, self.inner_filter_effect,
                self.scattering_correction
            ],
                           layout=form_item_layout),
            ipywidgets.Box([self.contour_mask, self.title, self.plot_abs],
                           layout=form_item_layout)
        ]
        readdata = ipywidgets.Box(readdata_items,
                                  layout=Layout(display='flex',
                                                flex_flow='column',
                                                border='solid 2px',
                                                align_items='stretch',
                                                width='100%'))
        parameters_items = [
            ipywidgets.Box([self.gaussian_sigma, self.gaussian_truncate]),
            ipywidgets.Box(
                [self.scattering_width, self.scattering_interpolation]),
            ipywidgets.Box([self.contour_otsu, self.contour_binary_threshold])
        ]
        parameters = ipywidgets.Box(parameters_items,
                                    layout=Layout(display='flex',
                                                  flex_flow='column',
                                                  border='solid 2px',
                                                  align_items='stretch',
                                                  width='100%'))
        tab2 = ipywidgets.Tab()
        tab2.children = [readdata, parameters]
        tab2.set_title(0, 'Read data')
        tab2.set_title(1, 'Parameters')

        out_parameters = ipywidgets.interactive_output(
            plot_eem_interact, self.preview_parameter_dict)

        note_step2 = ipywidgets.VBox([
            ipywidgets.Label(
                value=
                "If you see blank space in the short excitation wavelength region,\
        it's likely that the inner filter effect is too strong."),
            ipywidgets.Label(
                value="Please consider adjust the excitation wavelength range."
            )
        ])

        return tab2, note_step2, out_parameters
Exemple #18
0
 def render(self):
     """Build the widget view and return it."""
     self.layout = widgets.VBox([
         widgets.Box([self.controls[dim] for dim in self.dims],
                     layout={'flex_flow': 'row wrap'}),
         widgets.HBox([self.color_picker]),
         widgets.HBox([
             self.color_reverser, self.guideline_picker,
             self.orientation_switcher
         ],
                      layout={'flex_flow': 'row wrap'}),
         widgets.Box(self.displays, layout={'flex_flow': 'row wrap'})
     ])
     return self.layout
Exemple #19
0
    def __column_button_clicked(self, b):
        with self.where_condition_out:
            clear_output()
            columns = self.__get_column_list(self.table_text.value)
            if (b.description == '+' or b.description == 'update'):
                description = 'WHERE'
                if len(self.list_of_where_object) != 0:
                    b.description = '-'
                    description = 'AND'
                self.create_new_flag = 1
                column_name = widgets.Dropdown(
                    options=columns,
                    description=description,
                    layout=widgets.Layout(flex='1 1 auto', width='auto'),
                    style={'description_width': 'initial'})
                save_key = widgets.Text(value=str(self.count),
                                        description='Key')
                other_fields = widgets.interactive_output(
                    self.__get_other_fields, {
                        'column': column_name,
                        'key': save_key
                    })
                add_button = widgets.Button(
                    description="+",
                    icon='',
                    tooltip=str(self.count),
                    style=widgets.ButtonStyle(button_color='#E58975'))
                add_button.on_click(self.__column_button_clicked)
                column_output_box = widgets.HBox([
                    widgets.Box([column_name],
                                layout=widgets.Layout(width="45%")),
                    widgets.Box([other_fields],
                                layout=widgets.Layout(top="-6px",
                                                      width="45%")),
                    widgets.Box([add_button],
                                layout=widgets.Layout(width="10%"))
                ])
                self.list_of_where_object[str(self.count)] = column_output_box
                self.count += 1

            elif (b.description == '-'):
                del self.list_of_where_object[b.tooltip]
                list(self.list_of_where_object.values()
                     )[0].children[0].children[0].description = 'WHERE'
                del self.tmp_where_condition_dictionary[b.tooltip]

            for key in self.list_of_where_object.keys():
                display(self.list_of_where_object[key])

            self.view_query_button.click()  #################################
Exemple #20
0
    def initialize_widget(self):
        '''Setup layout of the widget'''

        #define span and size of widgets
        title_layout = Layout(
            display='flex',
            flex_flow='column',
            justify_content='flex-end',
            width='100%',
            height='70',
        )

        fullspan_layout = Layout(
            display='flex',
            flex_flow='row',
            align_items='stretch',
            justify_content='center',
            width='100%',
            height='70',
        )
        eighty_span_layout = Layout(
            display='flex',
            flex_flow='row',
            justify_content='flex-start',
            width='80%',
            height='280px',
        )
        twenty_span_layout = Layout(
            display='flex',
            flex_flow='column',
            justify_content='center',
            width='20%',
            height='280px',
        )

        #create widgets using layout
        self.set_title('')
        self.title_box = w.Box(children=self.title_items, layout=title_layout)
        self.filter_box = w.Box(children=self.filter_items,
                                layout=fullspan_layout)
        self.lightcurve = self.lightcurve_widget()
        self.scatter_box = Box(children=[self.lightcurve],
                               layout=eighty_span_layout)
        self.image_box = Box(children=[], layout=twenty_span_layout)

        #self.fold_radiobutton()
        self.plot_box = w.HBox([self.scatter_box, self.image_box])
        #position widgets using widget size
        self.widget = w.VBox([self.title_box, self.filter_box, self.plot_box],
                             layout=w.Layout(height='350px'))
Exemple #21
0
 def generate_widgets(self):
     self.button_decomposition_re_interact.on_click(
         self.decomposition_interact_re_button)
     decomposition_reconstruction_items = [
         ipywidgets.Box([
             Label(
                 value=
                 'Please first specify the number of components and decomposition method tab '
                 '"Decomposition"')
         ]),
         ipywidgets.Box(
             [self.data_to_view, self.button_decomposition_re_interact],
             layout=form_item_layout)
     ]
     return decomposition_reconstruction_items
Exemple #22
0
def modelcontrolpanel(model, *args, **kwargs):
    """Easy model control in IPython / Jupyter

    Like interact(), but with the ability to control sliders and their ranges
    live. args and kwargs are passed on to interact()
    """

    sliders = model.interact(*args, **kwargs)
    sliderboxes = []
    for sl in sliders.children:
        cb = widgets.Checkbox(value=True)
        unit_latex = sl.varkey.unitstr
        if unit_latex:
            unit_latex = "$\scriptsize"+unit_latex+"$"
        units = widgets.Latex(value=unit_latex)
        units.font_size = "1.16em"
        box = widgets.HBox(children=[cb, sl, units])
        link((box, 'visible'), (cb, 'value'))
        sliderboxes.append(box)

    widgets_css = widgets.HTML("""<style>
    [style="font-size: 1.16em;"] { padding-top: 0.25em; }
    [style="width: 3ex; font-size: 1.165em;"] { padding-top: 0.2em; }
    .widget-numeric-text { width: auto; }
    .widget-numeric-text .widget-label { width: 20ex; }
    .widget-numeric-text .form-control { background: #fbfbfb; width: 8.5ex; }
    .widget-slider .widget-label { width: 20ex; }
    .widget-checkbox .widget-label { width: 15ex; }
    .form-control { border: none; box-shadow: none; }
    </style>""")
    settings = [widgets_css]
    for sliderbox in sliderboxes:
        settings.append(create_settings(sliderbox))
    # model_latex = "$"+model.latex(show_subs=False)+"$"
    # model_eq = widgets.Latex(model_latex)
    tabs = widgets.Tab(children=[widgets.Box(children=sliderboxes,
                                             padding="1.25ex"),
                                 widgets.Box(children=settings,
                                             padding="1.25ex")])
                                # TODO: fix model equation display
                                # widgets.Box(children=[model_eq],
                                #             padding="1.25ex")])

    tabs.set_title(0, 'Variable Sliders')
    tabs.set_title(1, 'Slider Settings')
    #tabs.set_title(2, 'Model Equations')

    return tabs
Exemple #23
0
def user_prior_component(prior_name: str,
                         unit_name: Optional[str] = None,
                         _handle_change=None,
                         mu=None,
                         unc=None):
    _mu_checkbox = widgets.Checkbox(value=mu is not None, description='Value')
    _unc_checkbox = widgets.Checkbox(value=unc is not None,
                                     description='Uncertainty')
    if mu is None:
        mu = 0.5
    _mu_field = widgets.BoundedFloatText(value=mu, min=0.01, step=0.1)
    if unc is None:
        unc = 0.1
    _unc_field = widgets.BoundedFloatText(value=unc, min=0.0, step=0.05)

    def _update_state(b):
        state_dict = {prior_name: {}}
        if _mu_checkbox.value:
            state_dict[prior_name]['mu'] = _mu_field.value
        if _unc_checkbox.value:
            state_dict[prior_name]['unc'] = _unc_field.value
        _handle_change(state_dict)

    _mu_checkbox.observe(_update_state)
    _mu_field.observe(_update_state)
    _unc_checkbox.observe(_update_state)
    _unc_field.observe(_update_state)
    html_layout = widgets.Layout(display='flex',
                                 flex_flow='row',
                                 justify_content='center')
    box_layout = widgets.Layout(display='flex', flex_flow='row')
    label_text = prior_name
    if unit_name is not None and unit_name != '':
        label_text = f'{prior_name} ({unit_name})'
    items = [
        widgets.Box([widgets.HTML(value=html_element('h3', value=label_text))],
                    layout=html_layout),
        widgets.Box([_mu_checkbox, _mu_field], layout=box_layout),
        widgets.Box([_unc_checkbox, _unc_field], layout=box_layout)
    ]
    form = widgets.Box(items,
                       layout=widgets.Layout(
                           display='flex',
                           flex_flow='column',
                           align_items='stretch',
                           width='100%',
                       ))
    return form
Exemple #24
0
    def _init_widget(self):
        """构建内置的卖出策略可视化组件,构造出self.factor_box"""

        from ..WidgetBu.ABuWGPickStock import PSPriceWidget, PSRegressAngWidget
        from ..WidgetBu.ABuWGPickStock import PSShiftDistanceWidget, PSNTopWidget
        self.ps_array = []
        self.ps_array.append(PSPriceWidget(self))
        self.ps_array.append(PSRegressAngWidget(self))
        self.ps_array.append(PSShiftDistanceWidget(self))
        self.ps_array.append(PSNTopWidget(self))

        #  ps() call用widget组list
        children = [ps() for ps in self.ps_array]
        if self.scroll_factor_box:
            self.factor_box = widgets.Box(children=children,
                                          layout=self.factor_layout)
        else:
            # 一行显示两个,2个为一组,组装sub_children_group序列,
            sub_children_group = self._sub_children(children,
                                                    len(children) / 2)
            sub_children_box = [
                widgets.HBox(sub_children)
                for sub_children in sub_children_group
            ]
            self.factor_box = widgets.VBox(sub_children_box)
        # 买入因子是特殊的存在,都需要买入因子的全局数据
        self.buy_factor_manger = None
def label_widget(label, container, widget):
    """Create a non-fixed-width label for a widget

    Unlike the description= argument that can be passed to widgets, the label should expand in size
    to meet the width of the container

    label       text for a new ipywidgets.Label for the widget
    container   a pre-created ipywidgets.Box to which the label and widget will be added
                (NOTE: this function does not display this container)
                for example:
    widget      a pre-created widget

    Example:
        widgets_box = ipywidgets.Box(layout=ipywidgets.Layout(
            display='flex', flex_flow='column', align_items='stretch', width='70%'))
        propertytaxes = label_widget(
            "Yearly property taxes", widgets_box, ipywidgets.BoundedIntText(
                value=5500, min=0, max=1_000_000, step=5))
    """
    box = ipywidgets.Box()
    box.children = [ipywidgets.Label(label), widget]
    container.children += (box,)
    box.layout = ipywidgets.Layout(
        display='flex',
        flex_flow='row',
        justify_content='space-between')
    return widget
Exemple #26
0
def jobs_tab(backend):
    """Constructs a widget containing job information for an input
    backend.

    Parameters:
        backend (IBMQBackend): Input backend.

    Returns:
        HBox: An ipywidget.
    """
    title = wid.HTML('<h4>Click graph to display jobs</h4>')
    table = wid.HTML('',
                     layout=wid.Layout(
                         max_height='500px',
                         height='500px',
                         width='100%',
                         overflow='hidden scroll',
                     ))

    sun_wid = _job_summary(backend)
    sun_wid._table = table
    sun_wid._title = title

    left = wid.Box(children=[sun_wid],
                   layout=wid.Layout(width='40%', overflow='hidden hidden'))

    right = wid.VBox(children=[title, table],
                     layout=wid.Layout(width='60%', overflow='hidden hidden'))

    out = wid.HBox(children=[left, right],
                   layout=wid.Layout(max_height='500px', margin='10px'))
    return out
    def __init__(self):
        super().__init__()
        output = widgets.Output()

        self.initial_color = '#FF00DD'
        self.initial_freak = 2
        self.x = np.linspace(0, 2 * np.pi, 100)

        with output:
            self.fig, self.ax = plt.subplots(constrained_layout=True, figsize=(5, 3.5))
            self.line, = self.ax.plot(self.x, np.sin(self.x), self.initial_color)

            self.fig.canvas.toolbar_position = 'left'
            self.ax.grid(True)

            # define widgets
            self.intSlider = widgets.IntSlider( value=self.initial_freak, min=0, max=10, step=1, description='Superfreak')#, continuous_update=False)
            self.resetButton = widgets.Button( description='Reset values!')
            self.titleText = widgets.Label( value='Reset values!', layout=Layout( align_self='center') )
            self.textArea = widgets.Textarea(  placeholder='Type something',  disabled=False )#,value='Hello World',description='Resultado:',
                                               # layout=Layout( max_width='500px'))#value='Reset values!', layout=Layout( align_self='center' ))

        # layout
        controls = widgets.VBox([ self.titleText, self.intSlider, self.resetButton, self.textArea]) #, layout=Layout( width='100%')
        controls.layout = make_box_layout()
        
        out_box = widgets.Box([output],layout=Layout( width='100%'))
        output.layout = make_box_layout()
        
        # observe stuff
        self.intSlider.observe(self.update, 'value')
        self.resetButton.on_click(self.button_reset_pressed)
        
         # add to children
        self.children = [controls, output]#out_box
Exemple #28
0
    def _init_widget(self):
        """构建内置的仓位资金管理可视化组件,构造出self.factor_box"""

        from ..WidgetBu.ABuWGPosition import AtrPosWidget, KellyPosWidget, PtPosition
        self.pos_array = []
        self.pos_array.append(AtrPosWidget(self))
        self.pos_array.append(KellyPosWidget(self))
        self.pos_array.append(PtPosition(self))

        #  ps() call用widget组list
        children = [pos() for pos in self.pos_array]
        if self.scroll_factor_box:
            self.factor_box = widgets.Box(children=children,
                                          layout=self.factor_layout)
        else:
            # 一行显示两个,n个为一组,组装sub_children_group序列,
            sub_children_group = self._sub_children(
                children,
                len(children) / self._sub_children_group_cnt)
            sub_children_box = [
                widgets.HBox(sub_children)
                for sub_children in sub_children_group
            ]
            self.factor_box = widgets.VBox(sub_children_box)
        # 买入因子是特殊的存在,都需要买入因子的全局数据
        self.buy_factor_manger = None
Exemple #29
0
    def __init__(self, tool_set):
        """初始化相关分析界面"""
        super(WidgetSMTool, self).__init__(tool_set)

        corr = self.init_corr_ui()
        distances = self.init_distances_ui()
        market_corr = self.init_market_corr_ui()
        relative_corr = self.init_relative_corr_ui()
        coint_corr = self.init_coint_corr_ui()

        children = [corr, distances, market_corr, relative_corr, coint_corr]
        if self.scroll_factor_box:
            sm_box = widgets.Box(children, layout=self.scroll_widget_layout)
            # 需要再套一层VBox,不然外部的tab显示有问题
            self.widget = widgets.VBox([sm_box])
        else:
            # 一行显示两个,2个为一组,组装sub_children_group序列,
            sub_children_group = self._sub_children(
                children,
                len(children) / self._sub_children_group_cnt)
            sub_children_box = [
                widgets.HBox(sub_children)
                for sub_children in sub_children_group
            ]
            self.widget = widgets.VBox(sub_children_box)
Exemple #30
0
 def as_widget(self, width: int = 100):
     form_item_layout = widgets.Layout(display='flex',
                                       flex_flow='row',
                                       justify_content='space-between',
                                       width=f'{width}%')
     info_items = [
         widgets.Box([self.output, self.more_info_button],
                     layout=form_item_layout),
         widgets.Box([self.info_box], layout=form_item_layout)
     ]
     form = widgets.Box(info_items,
                        layout=widgets.Layout(display='flex',
                                              flex_flow='column',
                                              align_items='stretch',
                                              width='100%'))
     return form