コード例 #1
0
    def __init__(self):
        tm_box = self.init_time_mode_ui()
        # 修改为默认使用开始结束日期
        self.time_mode.value = 1
        # 修改开始结束日期时间字符串
        self.start.value = '2011-08-08'
        self.end.value = '2017-08-08'

        self.market = widgets.Dropdown(
            options=OrderedDict({
                u'美股':
                EMarketTargetType.E_MARKET_TARGET_US.value,
                u'A股':
                EMarketTargetType.E_MARKET_TARGET_CN.value,
                u'港股':
                EMarketTargetType.E_MARKET_TARGET_HK.value,
                u'国内期货':
                EMarketTargetType.E_MARKET_TARGET_FUTURES_CN.value,
                u'国际期货':
                EMarketTargetType.E_MARKET_TARGET_FUTURES_GLOBAL.value,
                u'数字货币':
                EMarketTargetType.E_MARKET_TARGET_TC.value
            }),
            value=ABuEnv.g_market_target.value,
            description=u'下载更新市场:',
        )
        self.market.observe(self.on_market_change, names='value')
        """数据源进行切换"""
        self.data_source_accordion = widgets.Accordion()
        date_source_dict_us = OrderedDict({
            u'腾讯数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_tx.value,
            u'百度数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_bd.value,
            u'新浪美股(美股)':
            EMarketSourceType.E_MARKET_SOURCE_sn_us.value,
            u'网易数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_nt.value,
        })

        date_source_dict_cn = OrderedDict({
            u'百度数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_bd.value,
            u'腾讯数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_tx.value,
            u'网易数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_nt.value
        })

        date_source_dict_hk = OrderedDict({
            u'网易数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_nt.value,
            u'腾讯数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_tx.value,
            u'百度数据源(美股,A股,港股)':
            EMarketSourceType.E_MARKET_SOURCE_bd.value
        })

        date_source_dict_futures_cn = {
            u'新浪国内期货(国内期货)': EMarketSourceType.E_MARKET_SOURCE_sn_futures.value
        }
        date_source_dict_futures_gb = {
            u'新浪国际期货(国际期货)':
            EMarketSourceType.E_MARKET_SOURCE_sn_futures_gb.value
        }
        date_source_dict_futures_tc = {
            u'火币网:比特币,莱特币': EMarketSourceType.E_MARKET_SOURCE_hb_tc.value
        }

        self.date_source_market_map = {
            EMarketTargetType.E_MARKET_TARGET_US.value: date_source_dict_us,
            EMarketTargetType.E_MARKET_TARGET_CN.value: date_source_dict_cn,
            EMarketTargetType.E_MARKET_TARGET_HK.value: date_source_dict_hk,
            EMarketTargetType.E_MARKET_TARGET_FUTURES_CN.value:
            date_source_dict_futures_cn,
            EMarketTargetType.E_MARKET_TARGET_FUTURES_GLOBAL.value:
            date_source_dict_futures_gb,
            EMarketTargetType.E_MARKET_TARGET_TC.value:
            date_source_dict_futures_tc
        }

        self.current_date_source_dict = self.date_source_market_map[
            self.market.value]
        self.date_source = widgets.RadioButtons(
            options=list(self.current_date_source_dict.keys()),
            value=list(self.current_date_source_dict.keys())[0],
            description=u'数据源:',
            disabled=False)
        self.date_source.observe(self.on_date_source_change, names='value')

        self.yun_down_bt = widgets.Button(description=u'美股|A股|港股|币类|期货6年日k',
                                          layout=widgets.Layout(width='50%'),
                                          button_style='info')
        self.yun_down_bt.on_click(self.run_yun_down)

        self.run_kl_update_bt = widgets.Button(
            description=u'从数据源下载更新',
            layout=widgets.Layout(width='50%'),
            button_style='danger')
        self.run_kl_update_bt.on_click(self.run_kl_update)
        description = widgets.Textarea(
            value=u'非沙盒数据,特别是回测交易多的情况下,比如全市场测试,回测前需要先将数据进行更新。\n'
            u'建议直接从云盘下载入库完毕的数据库,不需要从各个数据源再一个一个的下载数据进行入库。\n'
            u'abupy内置数据源都只是为用户学习使用,并不能保证数据一直通畅,而且如果用户很在乎数据质量,'
            u'比如有些数据源会有前复权数据错误问题,有些数据源成交量不准确等问题,那么就需要接入用户自己的数据源。\n'
            u'接入用户的数据源请阅读教程第19节中相关内容',
            disabled=False,
            layout=widgets.Layout(height='200px'))
        self.widget = widgets.VBox([
            description, self.market, tm_box, self.date_source,
            self.yun_down_bt, self.run_kl_update_bt
        ])
コード例 #2
0
def initProcess_Left(grid):
    leftab_title = ['Code', 'DataPath', 'Cache']

    # Code界面是一个out,里面是一个grid
    leftCode_out = widgets.Output()
    leftCode_grid = widgets.GridspecLayout(20,
                                           10,
                                           width='auto',
                                           height='9.6cm')
    leftCode_grid[0:19, 0:10] = widgets.Textarea(
        layout=widgets.Layout(width='auto', height='8.6cm'))
    leftCode_grid[19, 2] = widgets.Button(description='清空',
                                          layout=widgets.Layout(width='2cm'))
    leftCode_grid[19, 7] = widgets.Button(description='运行',
                                          layout=widgets.Layout(width='2cm'))
    with leftCode_out:
        display(leftCode_grid)

    # DataPath界面是一个Out, 里面是一个自定义Datapath类的组件
    leftDataPath_out = widgets.Output(layout={
        'width': '17.3cm',
        'height': '11cm'
    })
    datapath_grid = widgets.GridspecLayout(10, 4, width='auto', height='11cm')
    with leftDataPath_out:
        display(datapath_grid)
    datapath_widget = pfunction.Datapath()
    datapath_grid[:9, :] = datapath_widget
    datapath_grid[9, 1] = widgets.Play(interval=1000,
                                       value=0,
                                       min=0,
                                       max=0,
                                       step=1,
                                       disabled=True)
    datapath_grid[9, 2] = widgets.SelectionSlider(
        options=['0.25px', '0.5px', '1px', '2px', '4px'],
        value='1px',
        continuous_update=True,
        disabled=True,
        layout=widgets.Layout(width='auto'))

    widgets.link((datapath_grid[9, 1], 'value'), (datapath_widget, 'step'))
    widgets.link((datapath_grid[9, 1], 'max'), (datapath_widget, 'max_step'))

    def slider_play(change):
        if change['new'] == '0.25px':
            datapath_grid[9, 1].interval = 4000
        elif change['new'] == '0.5px':
            datapath_grid[9, 1].interval = 2000
        elif change['new'] == '1px':
            datapath_grid[9, 1].interval = 1000
        elif change['new'] == '2px':
            datapath_grid[9, 1].interval = 500
        elif change['new'] == '4px':
            datapath_grid[9, 1].interval = 250

    datapath_grid[9, 2].observe(slider_play, names='value')

    # Cache里面是一个Grid
    leftCache_accordion = widgets.Accordion([
        widgets.GridspecLayout(10, 4, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 4, width='auto', height='9.5cm')
    ])
    leftCache_accordion.set_title(0, '数据访问')
    leftCache_accordion.set_title(1, '替换算法')
    leftCache_accordion.selected_index = None

    # 过程演示界面中左半部分组件
    leftab = widgets.Tab(layout=widgets.Layout(width='auto', height='auto'),
                         selected_index=0)
    leftab.children = [leftCode_out, leftDataPath_out, leftCache_accordion]
    for i in range(len(leftab.children)):
        leftab.set_title(i, leftab_title[i])
    grid[1:19, 0:20] = leftab

    left = {
        'code': leftCode_grid,
        'datapath': datapath_grid,
        'cache': leftCache_accordion
    }

    return [leftab, left]
コード例 #3
0
defaultloc = 'chr5:142,903,034-142,906,867'
defaultgeneid = 'Actb'
defaultrefseqid = 'NM_007393'
defaultstrand = "-"

#### Accordian Change File Locations ####
w_default_folder = widgets.Text(
    description='RnaSeq Folder',
    value=default_track_folder,
)
w_default_folder.width="80%"
w_default_folder_valid = widgets.Valid(value=True)
hboxdefaultfolder = widgets.HBox([w_default_folder,w_default_folder_valid])
page1 = widgets.VBox(children=[hboxdefaultfolder])

accord = widgets.Accordion(children=[page1], width="80%")
display(accord)

accord.set_title(1, 'Defaults')


#### Define Widgets ###
lookuptype_widget = widgets.RadioButtons(
    options={'By location':'location','By geneid (3\'UTR only)':"geneid"},
    value='location',
    description='Lookup:',
    disabled=False
)

location_widget = widgets.Text(
    value=defaultloc,
コード例 #4
0
ファイル: image_canvas.py プロジェクト: yt-project/widgyts
    def setup_controls(self):
        down = ipywidgets.Button(icon="arrow-down",
                                 layout=ipywidgets.Layout(width="auto",
                                                          grid_area="down"))
        up = ipywidgets.Button(icon="arrow-up",
                               layout=ipywidgets.Layout(width="auto",
                                                        grid_area="up"))
        right = ipywidgets.Button(
            icon="arrow-right",
            layout=ipywidgets.Layout(width="auto", grid_area="right"),
        )
        left = ipywidgets.Button(icon="arrow-left",
                                 layout=ipywidgets.Layout(width="auto",
                                                          grid_area="left"))
        zoom_start = 1.0 / (self.frb_model.view_width[0])
        # By setting the dynamic range to be the ratio between coarsest and
        # finest, we ensure that at the fullest zoom, our smallest point will
        # be the size of our biggest point at the outermost zoom.
        dynamic_range = max(self.variable_mesh_model._pdx.max(),
                            self.variable_mesh_model._pdy.max()) / min(
                                self.variable_mesh_model._pdx.min(),
                                self.variable_mesh_model._pdy.min())

        zoom = ipywidgets.FloatSlider(
            min=0.5,
            max=dynamic_range,
            step=0.1,
            value=zoom_start,
            description="Zoom",
            layout=ipywidgets.Layout(width="auto", grid_area="zoom"),
        )
        is_log = ipywidgets.Checkbox(value=False, description="Log colorscale")
        colormaps = ipywidgets.Dropdown(
            options=list(self.colormaps.colormap_values.keys()),
            description="colormap",
            value="viridis",
        )
        vals = [
            _ for _ in self.variable_mesh_model.field_values
            if _.field_name == self.current_field
        ][0]._array
        mi = vals.min()
        ma = vals.max()
        min_val = ipywidgets.BoundedFloatText(
            description="lower colorbar bound:", value=mi, min=mi, max=ma)
        max_val = ipywidgets.BoundedFloatText(
            description="upper colorbar bound:", value=ma, min=mi, max=ma)

        down.on_click(self.on_ydownclick)
        up.on_click(self.on_yupclick)
        right.on_click(self.on_xrightclick)
        left.on_click(self.on_xleftclick)
        zoom.observe(self.on_zoom, names="value")
        # These can be jslinked, so we will do so.
        ipywidgets.jslink((is_log, "value"), (self, "is_log"))
        ipywidgets.jslink((min_val, "value"), (self, "min_val"))
        ipywidgets.link((min_val, "value"), (self, "min_val"))
        ipywidgets.jslink((max_val, "value"), (self, "max_val"))
        ipywidgets.link((max_val, "value"), (self, "max_val"))
        # This one seemingly cannot be.
        ipywidgets.link((colormaps, "value"), (self, "colormap_name"))

        nav_buttons = ipywidgets.GridBox(
            children=[up, left, right, down],
            layout=ipywidgets.Layout(
                width="100%",
                grid_template_columns="33% 34% 33%",
                grid_template_rows="auto auto auto",
                grid_template_areas="""
                                    " . up . "
                                    " left . right "
                                    " . down . "
                                    """,
                grid_area="nav_buttons",
            ),
        )

        all_navigation = ipywidgets.GridBox(
            children=[nav_buttons, zoom],
            layout=ipywidgets.Layout(
                width="300px",
                grid_template_columns="25% 50% 25%",
                grid_template_rows="auto auto",
                grid_template_areas="""
                    ". nav_buttons ."
                    "zoom zoom zoom"
                    """,
            ),
        )

        all_normalizers = ipywidgets.GridBox(
            children=[is_log, colormaps, min_val, max_val],
            layout=ipywidgets.Layout(width="auto"),
        )

        accordion = ipywidgets.Accordion(
            children=[all_navigation, all_normalizers])

        accordion.set_title(0, "navigation")
        accordion.set_title(1, "colormap controls")

        return accordion
コード例 #5
0
 def clearTerms(cls):
     cls.profilePresent = widgets.Accordion(children=[])
     cls.profileAbsent = widgets.Accordion(children=[])
     cls.profile.children = tuple([cls.profilePresent, cls.profileAbsent])
     cls.profile.set_title(0, "Sign Present")
     cls.profile.set_title(1, "Sign Absent")
コード例 #6
0
    description='Max autotune time ',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='d'
)



setup_seg = widgets.VBox([setup_target, setup_seg1, setup_seg2, setup_rejected])
setup_imp = widgets.VBox([basic_imp_vars, basic_imp_cont, basic_imp_nom])
setup_rate = widgets.VBox([tgt_event_rate, min_observations])
setup_tune = widgets.VBox([autotune_opt, max_time_autotune])

setup_accordion = widgets.Accordion(children=[setup_seg, setup_imp, setup_rate, setup_tune])
setup_accordion.set_title(0, 'Segments and Target')
setup_accordion.set_title(1, 'Imputation')
setup_accordion.set_title(2, 'Segment settings')
setup_accordion.set_title(3, 'Autotune settings')
setup_box = widgets.VBox([setup_caslib, setup_table, setup_project, setup_accordion])

# decision tree params

dtree_enabled = widgets.ToggleButtons(
    options=['Yes', 'No'],
    description='Use',
    disabled=False,
    button_style='',  # 'success', 'info', 'warning', 'danger' or ''
    tooltips=['Use this model', 'Don\'t use this model'],
    #     icons=['check'] * 3
コード例 #7
0
def init():
    global courseCurr
    tab = widgets.Tab(titles=['title:' + str(i) for i in range(len(titles))])
    tab.children = [widgets.Output() for title in titles]
    [tab.set_title(i, title) for i, title in enumerate(titles)]

    with tab.children[0]:
        courseCurr['outputDesc'] = widgets.Output()
        topicsL1 = widgets.Select(options=courses.keys(),
                                  value=list(courses.keys())[0],
                                  description='',
                                  disabled=False)  # rows=10,
        topicsL1.observe(on_topicL1_change, names='value')
        topicsL2 = widgets.Select(
            options=courses[list(courses.keys())[0]].keys(),
            value=list(courses[list(courses.keys())[0]].keys())[0],
            description='',
            disabled=False)  # rows=10,
        topicsL3 = widgets.Select(options=['Foo', 'Bar', 'Blah'],
                                  value='Foo',
                                  description='',
                                  disabled=False)  # rows=10,
        with courseCurr['outputDesc']:
            display(HTML("<h2>간단소개</h2>"))
            display(courseCurr['description'])
        display(
            HBox([
                VBox([Label(value='대분류'), topicsL1]),
                VBox([Label(value='중분류'), topicsL2]),
                VBox([Label(value='소분류'), topicsL3])
            ]))
        display(courseCurr['outputDesc'])
    with tab.children[1]:
        #labelCourse = Label(value='과정명: '+courseCurr['title'])
        display(HTML(f'<h2>과정명: {courseCurr["title"]}</h2>'))

        outputVideos = [widgets.Output() for video in courseCurr['videos']]
        for idx, outputVideo in enumerate(outputVideos):
            with outputVideo:
                display(YouTubeVideo(courseCurr['videos'][idx]['vid']))
        #[videos[idx].display(YouTubeVideo(vid)) for idx, vid in enumerate(vids)]
        accordion = widgets.Accordion(children=outputVideos)
        [
            accordion.set_title(idx, video['subject'])
            for idx, video in enumerate(courseCurr['videos'])
        ]
        display(accordion)
        #print('아코디언 형태로 비디오 목록 보여주면 좋을듯...')
        #display(YouTubeVideo('Nxz6FxGH_6U'))

    with tab.children[2]:
        display(HTML(f'<h2>과정명: {courseCurr["title"]}</h2>'))
        #labelCourse = Label(value='과정명: '+courseCurr['title'])
        outputContent = widgets.Output()
        with outputContent:
            display("[다음]버튼을 눌러서 시작해주세요.")
        btnPrev = widgets.Button(description='이전')
        btnPrev.action = 'prev'
        btnPrev.output = outputContent  #tab.children[2]
        btnPrev.on_click(on_summary_clicked)
        btnNext = widgets.Button(description='다음')
        btnNext.action = 'next'
        btnNext.output = outputContent  #tab.children[2]
        btnNext.on_click(on_summary_clicked)
        display(VBox([outputContent, HBox([btnPrev, btnNext])]))

    with tab.children[3]:
        #labelCourse = Label(value='과정명: '+courseCurr['title'])
        display(HTML(f'<h2>과정명: {courseCurr["title"]}</h2>'))
        outputContent = widgets.Output()
        with outputContent:
            display("[다음]버튼을 눌러서 시작해주세요.")
        btnPrev = widgets.Button(description='이전')
        btnPrev.action = 'prev'
        btnPrev.output = outputContent  #tab.children[2]
        btnPrev.on_click(on_test_clicked)
        btnNext = widgets.Button(description='다음')
        btnNext.action = 'next'
        btnNext.output = outputContent  #tab.children[2]
        btnNext.on_click(on_test_clicked)
        display(VBox([outputContent, HBox([btnPrev, btnNext])]))
        #display(outputContent)
    with tab.children[4]:
        display(HTML(f'<h2>과정명: {courseCurr["title"]}</h2>'))
        with open('rc/ref.html') as f:
            strRef = f.read()
            display(HTML(value=strRef))

    display(tab)
コード例 #8
0
def mainPage(out, grid, filename):
    grid = close_FrontPage(out, grid)

    filepath = './' + filename

    data = xlrd.open_workbook(filepath, encoding_override='utf-8')
    table = data.sheets()[0]  #选定表
    nrows = table.nrows  #获取行号
    ncols = table.ncols  #获取列号

    # ------------------------------------ #
    grid[0, 0:29].description = '质量检测分析'
    grid[19, 9:11] = widgets.Dropdown(options=[('目       录', 0)],
                                      layout=widgets.Layout(width='5cm'),
                                      description='跳转到: ')
    grid[19, 17:18] = widgets.Button(description='进入',
                                     style={'button_color': '#004080'},
                                     button_style='info',
                                     layout=widgets.Layout(width='2.5cm'))

    #跳转页面
    def jumpToPage(b):
        value = grid[19, 9:11].value
        if value == 0:
            firstPage(out, grid)

    grid[19, 17:18].on_click(jumpToPage)

    #-------------------------------------#
    class_accordion = widgets.Accordion([
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm')
    ])
    class_accordion.set_title(0, '参与率')
    class_accordion.set_title(1, '名次变化')
    class_accordion.set_title(2, '尖优生名单')
    class_accordion.set_title(3, '学困生名单')
    class_accordion.set_title(4, '尖优生学科均衡度')
    class_accordion.set_title(5, '各科对班级的贡献度')

    subject_accordion = widgets.Accordion([
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm'),
        widgets.GridspecLayout(10, 5, width='auto', height='9.5cm')
    ])
    subject_accordion.set_title(0, '学科名次变化')
    subject_accordion.set_title(1, '学科尖优生变化')
    subject_accordion.set_title(2, '学科学困生变化')

    tab = widgets.Tab(children=[class_accordion, subject_accordion])
    tab.set_title(0, '班级评价')
    tab.set_title(1, '学科评价')

    grid[1:19, 0:30] = tab

    #-------------班级评价--------------#
    shikao_count = cankaolv.cankaolv(out, grid, table, nrows, ncols)
    class_mingci_change.mingci_change(grid, table, nrows, ncols, shikao_count)
    up_down_student.stuUpDown(grid, table, nrows, ncols)
    junhengdu.jianyousheng(grid, table, nrows)
    gongxiandu.gongxianToClass(grid, table, nrows)

    return
コード例 #9
0
ファイル: file_browser.py プロジェクト: weichea/msticpy
    def __init__(self, path: str = ".", select_cb: Callable[[str], Any] = None):
        """
        Initialize the class for path and with optional callback.

        Parameters
        ----------
        path : str, optional
            Path to open at, by default "."
        select_cb : Callable[[str], Any], optional
            Callback function, by default None. This is executed
            when the user hits the "Select File" button. The function
            is passed the path of the selected file.

        """
        self.current_folder = Path(path).resolve()
        self.file: Optional[str] = None
        self.action = select_cb

        file_layout = widgets.Layout(height="200px", width="45%")
        self.select_file = widgets.Select(description="Files", layout=file_layout)
        folder_layout = widgets.Layout(height="150px", width="99%")
        self.select_folder = widgets.Select(description="Folders", layout=folder_layout)

        self.btn_open = widgets.Button(description="Select File")
        self.btn_f_nav = widgets.Button(description="Open folder")
        self.txt_path = widgets.Text(
            description="Path",
            value=str(self.current_folder),
            layout=widgets.Layout(width="75%"),
        )

        style_indent = {"description_width": "150px"}
        self.select_search = widgets.Select(
            description="Results",
            layout=self.no_border_layout("75%"),
            style=style_indent,
        )
        self.select_search.observe(self._select_search_file, names="value")
        self.lbl_search = widgets.Label(value="Search for file in current path")

        self.txt_search = widgets.Text(
            description="Search pattern",
            layout=widgets.Layout(width="50%"),
            style=style_indent,
            continuous_update=False,
        )
        self.txt_search.observe(self._search, "value")
        self.btn_search = widgets.Button(description="Search")
        self.btn_search.on_click(self._search)
        hb_search = widgets.HBox([self.txt_search, self.btn_search])
        vb_search = widgets.VBox([self.lbl_search, hb_search, self.select_search])
        self.accd_search = widgets.Accordion(children=[vb_search])
        self.accd_search.set_title(0, "Search")
        self.accd_search.selected_index = None

        self.txt_path.continuous_update = False
        self.txt_path.observe(self._enter_folder, "value")
        self.btn_open.on_click(self._return_file)
        self.btn_f_nav.on_click(self._open_folder)
        self.select_file.observe(self._select_file, names="value")

        self._open_folder(tgt_folder=self.current_folder)

        vb_folder_nav = widgets.VBox(
            [self.select_folder, self.btn_f_nav], layout=widgets.Layout(width="30%")
        )
        hb_files_folders = widgets.HBox(
            [vb_folder_nav, self.select_file], layout=self.border_layout("98%")
        )

        hb_search = widgets.HBox([self.txt_search, self.btn_search])
        vb_search = widgets.VBox([self.lbl_search, hb_search, self.select_search])

        self.layout = widgets.VBox(
            [self.txt_path, hb_files_folders, self.accd_search, self.btn_open],
            layout=self.border_layout("98%"),
        )
コード例 #10
0
ファイル: Core.py プロジェクト: slel/Pynac
    def build_a_beam(self):
        beta_x = widgets.FloatSlider(
            value=7.5,
            min=0.01,
            max=20.0,
            step=0.01,
            description='beta_x:',
            disabled=False,
            continuous_update=False,
        )
        alpha_x = widgets.FloatSlider(
            value=0.0,
            min=-5.0,
            max=5.0,
            step=0.01,
            description='alpha_x:',
            disabled=False,
            continuous_update=False,
        )
        emit_x = widgets.FloatSlider(
            value=0.5,
            min=0.01,
            max=10.0,
            step=0.01,
            description='emit_x:',
            disabled=False,
            continuous_update=False,
        )
        beta_y = widgets.FloatSlider(
            value=7.5,
            min=0.01,
            max=20.0,
            step=0.01,
            description='beta_y:',
            disabled=False,
            continuous_update=False,
        )
        alpha_y = widgets.FloatSlider(
            value=0.0,
            min=-5.0,
            max=5.0,
            step=0.01,
            description='alpha_y:',
            disabled=False,
            continuous_update=False,
        )
        emit_y = widgets.FloatSlider(
            value=0.5,
            min=0.01,
            max=10.0,
            step=0.01,
            description='emit_y:',
            disabled=False,
            continuous_update=False,
        )
        beta_z = widgets.FloatSlider(
            value=7.5,
            min=0.01,
            max=20.0,
            step=0.01,
            description='beta_z:',
            disabled=False,
            continuous_update=False,
        )
        alpha_z = widgets.FloatSlider(
            value=0.0,
            min=-5.0,
            max=5.0,
            step=0.01,
            description='alpha_z:',
            disabled=False,
            continuous_update=False,
        )
        emit_z = widgets.FloatSlider(
            value=500,
            min=1.0,
            max=1000.0,
            step=1.0,
            description='emit_z:',
            disabled=False,
            continuous_update=False,
        )

        label_layout = widgets.Layout(width='100%')
        twiss_x_label = widgets.Label(value="Horizontal Twiss", layout=label_layout)
        twiss_y_label = widgets.Label(value="Vertical Twiss", layout=label_layout)
        twiss_z_label = widgets.Label(value="Longitudinal Twiss", layout=label_layout)

        energy_offset = widgets.FloatText(value=0.0, display='flex', width='20%')
        x_offset = widgets.FloatText(value=0.0, display='flex', width='20%')
        xp_offset = widgets.FloatText(value=0.0, display='flex', width='20%')
        y_offset = widgets.FloatText(value=0.0, display='flex', width='20%')
        yp_offset = widgets.FloatText(value=0.0, display='flex', width='20%')
        phase_offset = widgets.FloatText(value=0.0, display='flex', width='20%')

        energy_offset_label = widgets.Label(value="Energy Offset (MeV):", layout=label_layout)
        x_offset_label = widgets.Label(value="x Offset (cm):", layout=label_layout)
        xp_offset_label = widgets.Label(value="xp Offset (mrad):", layout=label_layout)
        y_offset_label = widgets.Label(value="y Offset (cm):", layout=label_layout)
        yp_offset_label = widgets.Label(value="yp Offset (mrad):", layout=label_layout)
        phase_offset_label = widgets.Label(value="Phase Offset (s):", layout=label_layout)

        beam_freq = widgets.IntText(value=352.21e6, display='flex', flex_basis='20%')
        bunch_population = widgets.IntText(value=1000, display='flex', flex_basis='20%')
        self.bunchPopulation = bunch_population

        beam_freq_label = widgets.Label(value="Beam Freq (Hz):", layout=label_layout)
        bunch_population_label = widgets.Label(value="Bunch pop.:", layout=label_layout)

        rest_mass = widgets.FloatText(value=938.27231, display='flex', flex_basis='20%')
        atomic_num = widgets.FloatText(value=1, display='flex', flex_basis='20%')
        charge = widgets.FloatText(value=1, display='flex', flex_basis='20%')

        rest_mass_label = widgets.Label(value="Rest mass (MeV/c^2):", layout=label_layout)
        atomic_num_label = widgets.Label(value="Atomic Number:", layout=label_layout)
        charge_label = widgets.Label(value="Particle Charge:", layout=label_layout)

        def get_pynac_input():
            beam = ['GEBEAM', [
                [4, 1],
                [beam_freq.value, bunch_population.value],
                [energy_offset.value, x_offset.value,
                    xp_offset.value, y_offset.value,
                    yp_offset.value, phase_offset.value,
                 ],
                [alpha_x.value, beta_x.value, emit_x.value],
                [alpha_y.value, beta_y.value, emit_y.value],
                [alpha_z.value, beta_z.value, emit_z.value],
            ]]
            return beam

        def get_dynac_input():
            beam = 'GEBEAM\r\n'
            beam += '4 1\r\n'
            beam += '%e %d\r\n' % (beam_freq.value, bunch_population.value)
            beam += '%f %f %f %f %f %f\r\n' % (energy_offset.value, x_offset.value, xp_offset.value,
                                               y_offset.value, yp_offset.value, phase_offset.value)
            beam += '%f %f %f\r\n' % (alpha_x.value, beta_x.value, emit_x.value)
            beam += '%f %f %f\r\n' % (alpha_y.value, beta_y.value, emit_y.value)
            beam += '%f %f %f' % (alpha_z.value, beta_z.value, emit_z.value)
            return beam

        css_height_str = '170px'
        view_btn = widgets.Button(description="View Pynac Input")
        pynac_view_area = widgets.Textarea()
        pynac_view_area.layout.height = css_height_str
        dynac_view_area = widgets.Textarea()
        dynac_view_area.layout.height = css_height_str

        pynac_view_area.value = get_pynac_input().__str__()
        dynac_view_area.value = get_dynac_input()

        self.inputBeamLattice = []
        self.inputBeamLattice.append(get_pynac_input())
        self.inputBeamLattice.append(['INPUT', [[938.27231, 1.0, 1.0], [3.6223537, 0.0]]])
        self.inputBeamLattice.append(['REFCOG', [[0]]])
        self.inputBeamLattice.append(['EMITGR', [
            ['Generated Beam'],
            [0, 9],
            [0.5, 80.0, 0.5, 80.0, 0.5, 0.5, 50.0, 1.0]
        ]])
        self.inputBeamLattice.append(['STOP', []])

        test = Pynac.from_lattice("Zero-length lattice for beam generation", self.inputBeamLattice)
        test.run()

        with open('emit.plot') as f:
            for i in range(204):
                f.readline()
            num_parts = int(f.readline())
            x, xp = [], []
            for i in range(num_parts):
                dat = f.readline().split()
                x.append(float(dat[0]))
                xp.append(float(dat[1]))
            f.readline()
            for i in range(202):
                f.readline()
            y, yp = [], []
            for i in range(num_parts):
                dat = f.readline().split()
                y.append(float(dat[0]))
                yp.append(float(dat[1]))
            f.readline()
            for i in range(203):
                f.readline()
            z, zp = [], []
            for i in range(num_parts):
                dat = f.readline().split()
                z.append(float(dat[0]))
                zp.append(float(dat[1]))

        data_source = ColumnDataSource(data=dict(x=x, xp=xp, y=y, yp=yp, z=z, zp=zp))

        p0 = figure(plot_height=250, plot_width=296, y_range=(-5, 5), x_range=(-1, 1))
        p0.xaxis.axis_label = 'Horizontal position'
        p0.yaxis.axis_label = 'Horizontal angle'
        p0.circle('x', 'xp', color="#2222aa", alpha=0.5, line_width=2, source=data_source)

        p1 = figure(plot_height=250, plot_width=296, y_range=(-5, 5), x_range=(-1, 1))
        p1.xaxis.axis_label = 'Vertical position'
        p1.yaxis.axis_label = 'Vertical angle'
        p1.circle('y', 'yp', color="#2222aa", alpha=0.5, line_width=2, source=data_source, name="foo")

        p2 = figure(plot_height=250, plot_width=296, y_range=(-0.1, 0.1), x_range=(-150, 150))
        p2.xaxis.axis_label = 'Longitudinal phase'
        p2.yaxis.axis_label = 'Longitudinal energy'
        p2.circle('z', 'zp', color="#2222aa", alpha=0.5, line_width=2, source=data_source, name="foo")

        grid = gridplot([[p0, p1, p2]])
        self.beamBuilderPlotHandle = show(grid, notebook_handle=True)
        self.beamBuilderPlotDoc = curdoc()
        push_notebook(document=self.beamBuilderPlotDoc, handle=self.beamBuilderPlotHandle)

        def on_button_clicked(_):
            pynac_view_area.value = get_pynac_input().__str__()
            dynac_view_area.value = get_dynac_input()
            self.inputBeamLattice[0] = get_pynac_input()
            self.inputBeamLattice[0][1][1][1] = 1000
            zero_length_lattice = Pynac.from_lattice("Zero-length lattice for beam generation", self.inputBeamLattice)
            zero_length_lattice.run()
            with open('emit.plot') as f:
                for i in range(204):
                    f.readline()
                num_parts = int(f.readline())
                x, xp = [], []
                for i in range(num_parts):
                    dat = f.readline().split()
                    x.append(float(dat[0]))
                    xp.append(float(dat[1]))
                f.readline()
                for i in range(202):
                    f.readline()
                y, yp = [], []
                for i in range(num_parts):
                    dat = f.readline().split()
                    y.append(float(dat[0]))
                    yp.append(float(dat[1]))
                f.readline()
                for i in range(203):
                    f.readline()
                z, zp = [], []
                for i in range(num_parts):
                    dat = f.readline().split()
                    z.append(float(dat[0]))
                    zp.append(float(dat[1]))
            data_source.data['x'] = x
            data_source.data['xp'] = xp
            data_source.data['y'] = y
            data_source.data['yp'] = yp
            data_source.data['z'] = z
            data_source.data['zp'] = zp
            push_notebook(document=self.beamBuilderPlotDoc, handle=self.beamBuilderPlotHandle)

        active_widget_list = [beta_x, alpha_x, emit_x, beta_y, alpha_y, emit_y, beta_z, alpha_z, emit_z,
                              energy_offset, x_offset, xp_offset, y_offset, yp_offset, phase_offset,
                              beam_freq, bunch_population, rest_mass, atomic_num, charge
                              ]
        for slider in active_widget_list:
            slider.observe(on_button_clicked)

        pynac_box_label = widgets.Label(value="Pynac Input", layout=label_layout)
        dynac_box_label = widgets.Label(value="Dynac Input", layout=label_layout)

        twiss_controls = HBox([
                VBox([twiss_x_label, beta_x, alpha_x, emit_x]),
                VBox([twiss_y_label, beta_y, alpha_y, emit_y]),
                VBox([twiss_z_label, beta_z, alpha_z, emit_z]),
            ])
        col_layout = Layout(display='flex', flex_flow='column', align_items='stretch')
        other_controls = Box([
                Box([rest_mass_label, atomic_num_label, charge_label, beam_freq_label, bunch_population_label],
                    layout=col_layout),
                Box([rest_mass, atomic_num, charge, beam_freq, bunch_population], layout=col_layout),
                Box([energy_offset_label, x_offset_label, xp_offset_label,
                     y_offset_label, yp_offset_label, phase_offset_label], layout=col_layout),
                Box([energy_offset, x_offset, xp_offset, y_offset, yp_offset, phase_offset], layout=col_layout),
            ], layout=Layout(
                    display='flex',
                    flex_flow='row',
                    align_items='stretch',
                    width='100%'
        ))

        input_text = HBox([
                VBox([pynac_box_label, pynac_view_area]),
                VBox([dynac_box_label, dynac_view_area])
            ])

        accordion = widgets.Accordion(children=[twiss_controls, other_controls, input_text])
        accordion.set_title(0, 'Twiss (to alter the phase-space plots)')
        accordion.set_title(1, 'Beam details (will not alter the phase-space plots)')
        accordion.set_title(2, "Pynac/Dynac input (to copy'n'paste into your own files)")
        display(accordion)
コード例 #11
0
def wrap_schedule(interestrate, value, principal, saleprice, years,
                  overpayment, appreciation, monthlycosts, rent):
    """Show a loan's mortgage schedule in a Jupyter notebook"""

    term = years * mmath.MONTHS_IN_YEAR
    overpayments = [overpayment for _ in range(term)]

    # Calculate the monthly payments for the mortgage schedule detail,
    # yearly payments for the mortgage schedule summary
    # and monthly payments with no overpayments for comparative analysis in prefacetempl
    months = [
        month for month in schedule.schedule(interestrate,
                                             value,
                                             principal,
                                             saleprice,
                                             term,
                                             overpayments=overpayments,
                                             appreciation=appreciation,
                                             monthlycosts=monthlycosts,
                                             monthlyrent=rent)
    ]
    months_no_over = [
        month for month in schedule.schedule(interestrate,
                                             value,
                                             principal,
                                             saleprice,
                                             term,
                                             overpayments=None,
                                             appreciation=appreciation,
                                             monthlyrent=rent)
    ]
    years = [year for year in schedule.monthly2yearly_schedule(months)]

    # Display a preface / summary first
    display(
        HTML(
            Templ.SchedulePreface.render(
                interestrate=interestrate,
                principal=principal,
                term=term,
                overpayment=overpayment,
                appreciation=appreciation,
                monthlypayments=months,
                monthlypayments_no_over=months_no_over)))

    # Create new Output objects, and call display(HTML(...)) in them
    # We do this because IPython.display.HTML() has nicer talbles
    # than ipywidgets.HTML(), but only ipywidgets-type widgets can be put
    # into an Accordion.
    summaryout = ipywidgets.Output()
    detailout = ipywidgets.Output()
    with summaryout:
        display(
            HTML(
                Templ.Schedule.render(principal=principal,
                                      value=value,
                                      loanpayments=years,
                                      paymentinterval_name="Year")))
    with detailout:
        display(
            HTML(
                Templ.Schedule.render(principal=principal,
                                      value=value,
                                      loanpayments=months,
                                      paymentinterval_name="Month")))

    parentwidg = ipywidgets.Accordion()
    parentwidg.children = [summaryout, detailout]
    parentwidg.set_title(0, 'Yearly summary')
    parentwidg.set_title(1, 'Monthly detail')
    display(parentwidg)

    return months
コード例 #12
0
def get_ipy_navigation_sliders(obj,
                               in_accordion=False,
                               random_position_button=False,
                               **kwargs):
    continuous_update = ipywidgets.Checkbox(True,
                                            description="Continous update")
    wdict = {}
    wdict["continuous_update"] = continuous_update
    widgets = []
    for i, axis in enumerate(obj):
        axis_dict = {}
        wdict["axis{}".format(i)] = axis_dict
        iwidget = ipywidgets.IntSlider(min=0,
                                       max=axis.size - 1,
                                       readout=True,
                                       description="index")
        link((continuous_update, "value"), (iwidget, "continuous_update"))
        link((axis, "index"), (iwidget, "value"))
        vwidget = ipywidgets.BoundedFloatText(min=axis.low_value,
                                              max=axis.high_value,
                                              step=axis.scale,
                                              description="value"
                                              # readout_format=".lf"
                                              )
        link((continuous_update, "value"), (vwidget, "continuous_update"))
        link((axis, "value"), (vwidget, "value"))
        link((axis, "high_value"), (vwidget, "max"))
        link((axis, "low_value"), (vwidget, "min"))
        link((axis, "scale"), (vwidget, "step"))
        name = ipywidgets.Label(str(axis),
                                layout=ipywidgets.Layout(width="15%"))
        units = ipywidgets.Label(layout=ipywidgets.Layout(width="5%"))
        link((axis, "name"), (name, "value"))
        link((axis, "units"), (units, "value"))
        bothw = ipywidgets.HBox([name, iwidget, vwidget, units])
        # labeled_widget = labelme(str(axis), bothw)
        widgets.append(bothw)
        axis_dict["value"] = vwidget
        axis_dict["index"] = iwidget
        axis_dict["units"] = units

    if random_position_button:
        random_nav_position = ipywidgets.Button(
            description="Set random navigation position.",
            tooltip="Set random navigation position, useful to check the "
            "method paramters.",
            layout=ipywidgets.Layout(width="auto"))

        def _random_navigation_position_fired(b):
            am = obj[0].axes_manager
            index = np.random.randint(0, am._max_index)
            am.indices = np.unravel_index(
                index, tuple(am._navigation_shape_in_array))[::-1]

        random_nav_position.on_click(_random_navigation_position_fired)

        wdict["random_nav_position_button"] = random_nav_position
        widgets.append(random_nav_position)

    widgets.append(continuous_update)
    box = ipywidgets.VBox(widgets)
    if in_accordion:
        box = ipywidgets.Accordion((box, ))
        box.set_title(0, "Navigation sliders")
    return {"widget": box, "wdict": wdict}
コード例 #13
0
    def __init__(self,
                 pathDF,
                 dataType='pickle',
                 dataIndex='multi',
                 colname='text',
                 maxValues=2500,
                 pathMeta=False,
                 pathType=False):

        super(CorpusGUI, self).__init__(pathDF, dataType, dataIndex, colname,
                                        maxValues, pathMeta, pathType)
        self.initSearch = SearchWordGUI(self.searchFields, self.column)
        self.accordion = widgets.Accordion(children=[self.initSearch])
        self.accordion.set_title(0, 'Enter search term')

        self.extendSearch = widgets.ToggleButtons(options=['more', 'less'])
        self.extendSearch.on_msg(self._addSearchField)

        self.searchButton = widgets.Button(description='Search',
                                           button_style='danger')

        self.searchButton.on_msg(self._searchLogic)

        self.displayResult = pd.DataFrame()

        self.direction = widgets.IntSlider(
            value=0,
            min=0,
            max=self.displayResult.shape[0],
            step=1,
        )

        self.direction.observe(self._setSentence, names='value')

        self._chooseResult()

        self.outInfo = widgets.Output()

        self.dfOut = widgets.Output()

        self.checkDataframe = widgets.Checkbox(value=False,
                                               description='Return Dataframe',
                                               disabled=False)

        self.outSentence = widgets.Textarea(value='',
                                            layout=widgets.Layout(
                                                flex='0 1 auto',
                                                height='200px',
                                                min_height='40px',
                                                width='70%'),
                                            placeholder='Sentence')

        self.outMeta = widgets.Textarea(placeholder='Result',
                                        layout=widgets.Layout(
                                            flex='0 1 auto',
                                            height='200px',
                                            min_height='40px',
                                            width='30%'),
                                        value='')

        self.sentenceFields = widgets.HBox([self.outMeta, self.outSentence])
コード例 #14
0
    def _initialise_frontend(self):
        """A hidden method for initialising the transmitter frontend.
        
        This method creates the frontend user interface by creating
        selected widgets. These widgets have a dict_id that links
        them to the configuration dictionary. When the widget is interacted
        with, the dict_id is used to update the configuration dictionary
        appropriately.
        """
        """The centre frequency float text widget."""
        self._widgets.update({
            'centre_frequency':
            FloatText(
                callback=self._update_config,
                value=self._config['centre_frequency'],
                min_value=0,
                max_value=self.controller._block.BlockStatus['SamplingFreq'] *
                1e3,
                step=1,
                dict_id='centre_frequency',
                description='Transmitter Frequency (MHz):',
                description_width='200px')
        })
        """The amplitude float text widget."""
        self._widgets.update({
            'amplitude':
            FloatText(callback=self._update_config,
                      value=self._config['amplitude'],
                      min_value=0,
                      max_value=1.0,
                      step=0.1,
                      dict_id='amplitude',
                      description='Amplitude (V):',
                      description_width='200px')
        })
        """The transmit enable button widget."""
        self._widgets.update({
            'transmit_enable':
            Button(callback=self._update_config,
                   description_on='On',
                   description_off='Off',
                   state=False,
                   dict_id='transmit_enable')
        })
        """The transmit system accordion"""
        self._accordions.update({
            'system':
            ipw.Accordion(children=[
                ipw.HBox([
                    ipw.VBox([ipw.Label(value='Transmitter: ')]),
                    ipw.VBox([self._widgets['transmit_enable'].get_widget()])
                ],
                         layout=ipw.Layout(justify_content='space-around'))
            ],
                          layout=ipw.Layout(justify_content='flex-start',
                                            width='initial'))
        })

        self._accordions['system'].set_title(0, 'System')
        """The transmit properties accordion."""
        self._accordions.update({
            'properties':
            ipw.Accordion(children=[
                ipw.VBox([
                    self._widgets['centre_frequency'].get_widget(),
                    self._widgets['amplitude'].get_widget()
                ])
            ],
                          layout=ipw.Layout(justify_content='flex-start',
                                            width='initial'))
        })

        self._accordions['properties'].set_title(0, 'Transmitter Control')

        self._update_config(self._config)
コード例 #15
0
    def __init__(self,
                 description="Select code:",
                 path_to_root="../",
                 **kwargs):
        """Dropdown for Codes for one input plugin.

        description (str): Description to display before the dropdown.
        """
        self.output = ipw.HTML()

        self.code_select_dropdown = ipw.Dropdown(description=description,
                                                 disabled=True,
                                                 value=None)
        traitlets.link((self, "codes"), (self.code_select_dropdown, "options"))
        traitlets.link((self.code_select_dropdown, "value"), (self, "value"))

        self.observe(self.refresh,
                     names=["allow_disabled_computers", "allow_hidden_codes"])

        self.btn_setup_new_code = ipw.ToggleButton(
            description="Setup new code")
        self.btn_setup_new_code.observe(self._setup_new_code, "value")

        self._setup_new_code_output = ipw.Output(layout={"width": "500px"})

        children = [
            ipw.HBox([self.code_select_dropdown, self.btn_setup_new_code]),
            self._setup_new_code_output,
            self.output,
        ]
        super().__init__(children=children, **kwargs)

        # Setting up codes and computers.
        self.comp_resources_database = ComputationalResourcesDatabaseWidget(
            input_plugin=self.input_plugin)

        self.ssh_computer_setup = SshComputerSetup()
        ipw.dlink(
            (self.comp_resources_database, "ssh_config"),
            (self.ssh_computer_setup, "ssh_config"),
        )

        self.aiida_computer_setup = AiidaComputerSetup()
        ipw.dlink(
            (self.comp_resources_database, "computer_setup"),
            (self.aiida_computer_setup, "computer_setup"),
        )

        self.aiida_code_setup = AiidaCodeSetup()
        ipw.dlink(
            (self.comp_resources_database, "code_setup"),
            (self.aiida_code_setup, "code_setup"),
        )

        quick_setup_button = ipw.Button(description="Quick Setup")
        quick_setup_button.on_click(self.quick_setup)
        quick_setup = ipw.VBox(children=[
            self.ssh_computer_setup.username,
            quick_setup_button,
            self.ssh_computer_setup.setup_ssh_out,
            self.aiida_computer_setup.setup_compupter_out,
            self.aiida_code_setup.setup_code_out,
        ])

        detailed_setup = ipw.Accordion(children=[
            self.ssh_computer_setup,
            self.aiida_computer_setup,
            self.aiida_code_setup,
        ])
        detailed_setup.set_title(0, "Set up password-less SSH connection")
        detailed_setup.set_title(1, "Set up a computer in AiiDA")
        detailed_setup.set_title(2, "Set up a code in AiiDA")

        self.output_tab = ipw.Tab(children=[quick_setup, detailed_setup])
        self.output_tab.set_title(0, "Quick Setup")
        self.output_tab.set_title(1, "Detailed Setup")

        self.refresh()
コード例 #16
0
    def dashboard(self):
        def dashboard_callback(value, button_id=0):
            if button_id == 0:
                self.transmitter.controller.enable_transmitter = int(value)
            elif button_id == 1:
                self.receiver.controller.coarse_passthrough = int(not value)
            elif button_id == 2:
                self.receiver.controller.reset_time_sync = int(not value)
            elif button_id == 3:
                self.receiver.controller.reset_phase_sync = int(not value)
            elif button_id == 4:
                self.receiver.controller.reset_frame_sync = int(not value)
            else:
                pass

        def adc_callback(change):
            self.adc_block.MixerSettings["Freq"] = change['new']
            self.adc_block.UpdateEvent(xrfdc.EVENT_MIXER)
            freq_label.value = 'Reported Frequency Offset: ' + \
                                str(self.receiver.controller.freq_offset)

        def dac_callback(change):
            self.dac_block.MixerSettings["Freq"] = change['new']
            self.dac_block.UpdateEvent(xrfdc.EVENT_MIXER)
            freq_label.value = 'Reported Frequency Offset: ' + \
                                str(self.receiver.controller.freq_offset)

        # Create button descriptions
        desc_b = [
            'Transmit Enable', 'Coarse Sync', 'Time Sync', 'Carrier Sync',
            'Frame Sync'
        ]

        buttons = [None] * 5
        widgets = [None] * 5

        # Create buttons
        for i in range(5):
            buttons[i] = Button(description=desc_b[i],
                                state=True,
                                callback=dashboard_callback,
                                button_id=i)

        # Create float text objects for entering the ADC & DAC mixer frequencies
        adc_fc = ipw.FloatText(value=64,
                               description='ADC Frequency (MHz):',
                               style={'description_width': 'initial'},
                               disabled=False)
        dac_fc = ipw.FloatText(value=64,
                               description='DAC Frequency (MHz):',
                               style={'description_width': 'initial'},
                               disabled=False)
        adc_fc.observe(adc_callback, names='value')
        dac_fc.observe(dac_callback, names='value')

        layout = ipw.Layout(display='inline-flex',
                            justify_content='flex-start',
                            align_items='flex-start',
                            align_content='flex-start')

        freq_label =  ipw.Label('Reported Frequency Offset: ' + \
                                str(self.receiver.controller.freq_offset) + \
                                    ' Hz')

        button_container = ipw.VBox([
            ipw.HBox([buttons[1].get_widget(), buttons[2].get_widget()]),
            ipw.HBox([buttons[3].get_widget(), buttons[4].get_widget()])
        ])

        dashboard = ipw.VBox(children=[
            ipw.HBox(children=[dac_fc, buttons[0].get_widget()],
                     layout=layout),
            ipw.HBox(children=[adc_fc, button_container], layout=layout),
            freq_label
        ],
                             layout=layout)

        dashboard_accordion = ipw.Accordion(children=[dashboard])
        dashboard_accordion.set_title(0, 'System Control')

        return dashboard_accordion
コード例 #17
0
    def init_env_set_ui(self):
        """构建基础env widget ui return widgets.VBox"""
        """沙盒数据与开放数据模式切换"""
        self.date_mode = widgets.RadioButtons(
            options=[u'沙盒数据模式', u'开放数据模式'],
            value=u'沙盒数据模式'
            if ABuEnv._g_enable_example_env_ipython else u'开放数据模式',
            description=u'数据模式:',
            disabled=False)
        #沙盒模糊,设置如下两个值。
        ABuEnv.enable_example_env_ipython(show_log=False)
        # """csv模式与hdf5模式模式切换"""
        self.store_mode_dict = {
            EDataCacheType.E_DATA_CACHE_CSV.value: u'csv模式(推荐)',
            EDataCacheType.E_DATA_CACHE_HDF5.value: u'hdf5模式'
        }
        self.store_mode = widgets.RadioButtons(
            options=[u'csv模式(推荐)', u'hdf5模式'],
            value=self.store_mode_dict[ABuEnv.g_data_cache_type.value],
            description=u'缓存模式:',
            disabled=False)
        # self.store_mode.disabled = True
        # self.fetch_mode.disabled = True

        # self.date_mode.observe(self.on_data_mode_change, names='value') #改变触发的方法。

        # set_mode_label_tip = widgets.Label(u'缓存模式|联网模式|数据源只在开放数据模式下生效:',
        #                                    layout=widgets.Layout(width='300px', align_items='stretch'))

        # """csv模式与hdf5模式模式切换"""
        # self.store_mode_dict = {EDataCacheType.E_DATA_CACHE_CSV.value: u'csv模式(推荐)',
        #                         EDataCacheType.E_DATA_CACHE_HDF5.value: u'hdf5模式'}
        # self.store_mode = widgets.RadioButtons(
        #     options=[u'csv模式(推荐)', u'hdf5模式'],
        #     value=self.store_mode_dict[ABuEnv.g_data_cache_type.value],
        #     description=u'缓存模式:',
        #     disabled=False
        # )
        # self.store_mode.observe(self.on_data_store_change, names='value')
        # 确定csv模式
        ABuEnv.g_data_cache_type = EDataCacheType.E_DATA_CACHE_CSV.value  #设置数据缓存模式
        """数据获取模式模式切换"""
        self.fetch_mode_dict = {
            EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL.value: u'本地数据模式(推荐)',
            EMarketDataFetchMode.E_DATA_FETCH_NORMAL.value: u'本地网络结合模式',
            EMarketDataFetchMode.E_DATA_FETCH_FORCE_NET.value: u'强制全部使用网络'
        }
        self.fetch_mode = widgets.RadioButtons(
            options=[u'本地数据模式(推荐)', u'本地网络结合模式', u'强制全部使用网络'],
            value=self.fetch_mode_dict[ABuEnv.g_data_fetch_mode.value],
            description=u'联网模式:',
            disabled=False)

        self.fetch_mode.value = self.fetch_mode_dict[
            ABuEnv.g_data_fetch_mode.value]  #myfunction尽量从本地获取

        # self.fetch_mode.observe(self.on_fetch_mode_change, names='value')
        """数据源进行切换"""
        self.data_source_accordion = widgets.Accordion()
        self.date_source_dict = {
            EMarketSourceType.E_MARKET_SOURCE_bd.value: u'百度数据源(美股,A股,港股)',
            EMarketSourceType.E_MARKET_SOURCE_tx.value: u'腾讯数据源(美股,A股,港股)',
            EMarketSourceType.E_MARKET_SOURCE_nt.value: u'网易数据源(美股,A股,港股)',
            EMarketSourceType.E_MARKET_SOURCE_sn_us.value: u'新浪美股(美股)',
            EMarketSourceType.E_MARKET_SOURCE_sn_futures.value:
            u'新浪国内期货(国内期货)',
            EMarketSourceType.E_MARKET_SOURCE_sn_futures_gb.value:
            u'新浪国际期货(国际期货)',
            EMarketSourceType.E_MARKET_SOURCE_hb_tc.value: u'比特币,莱特币'
        }
        self.date_source = widgets.RadioButtons(
            options=[
                u'百度数据源(美股,A股,港股)', u'腾讯数据源(美股,A股,港股)', u'网易数据源(美股,A股,港股)',
                u'新浪美股(美股)', u'新浪国内期货(国内期货)', u'新浪国际期货(国际期货)', u'比特币,莱特币'
            ],
            value=self.date_source_dict[ABuEnv.g_market_source.value],
            description=u'数据源:',
            disabled=False)
        self.date_source.observe(self.on_date_source_change, names='value')
        source_label_tip1 = widgets.Label(u'内置的数据源仅供学习使用',
                                          layout=widgets.Layout(
                                              width='300px',
                                              align_items='stretch'))
        source_label_tip2 = widgets.Label(u'abupy提供了接入外部数据源的接口和规范',
                                          layout=widgets.Layout(
                                              width='300px',
                                              align_items='stretch'))
        source_label_tip3 = widgets.Label(u'详阅读github上教程第19节的示例',
                                          layout=widgets.Layout(
                                              width='300px',
                                              align_items='stretch'))

        other_data_set_box = widgets.VBox([
            self.fetch_mode, source_label_tip1, self.date_source,
            source_label_tip2, source_label_tip3, self.store_mode
        ])

        self.data_source_accordion.children = [other_data_set_box]
        self.data_source_accordion.set_title(0, u'缓存模式|联网模式|数据源')
        accordion_shut(self.data_source_accordion)
コード例 #18
0
    def __init__(self, file):

        self.filename = file
        self.noMaterials = 0
        self.noObjects = 0

        self.matAll = []
        self.objAll = []
        self.widgetList = []
        self.objectList = []
        self.wfList = []
        self.wfAll = []
        self.srcAll = []
        self.rcAll = []
        self.goList = []
        self.goAll = []
        self.rem = []

        self.accNames = [
            'Space', 'Materials', 'Objects', 'Source/Receiver',
            'Geometry Output'
        ]
        self.add_mat = wd.Button(value=False,
                                 description='Add material',
                                 disabled=False)
        self.widgetList = [
            self.add_mat,
            wd.Label('free_space : Built-in identifier for air',
                     layout=wd.Layout(width='30%',
                                      margin='-35px 0px 0px 200px')),
            wd.Label(
                'pec : Built-in identifier for a perfect electric conductor',
                layout=wd.Layout(width='50%', margin='-10px 0px 10px 200px'))
        ]

        self.add_obj = wd.Button(value=False,
                                 description='Add object',
                                 disabled=False)

        self.rem_obj = wd.Button(value=False,
                                 description='Remove last object',
                                 disabled=False)

        self.objectList = [
            wd.HBox([self.add_obj, self.rem_obj],
                    layout=wd.Layout(margin='10px 0px 20px 0px'))
        ]

        self.wrFile = wd.Button(value=False,
                                description='Write input file',
                                disabled=False,
                                layout=wd.Layout(height='30px',
                                                 width='40%',
                                                 margin='10px 0px 20px 20px'))

        self.dd = [
            wd.Dropdown(options=[
                ' ', 'Edge', 'Plate', 'Triangle', 'Box', 'Sphere', 'Cylinder'
            ],
                        description='Object {}:'.format(i + 1),
                        disabled=False,
                        layout=wd.Layout(margin='20px 0px 10px -20px'))
            for i in range(20)
        ]

        self.ddwf = wd.Dropdown(options=[
            ' ', 'gaussian', 'gaussiandot', 'gaussiandotnorm',
            'gaussiandotdot', 'gaussiandotdotnorm', 'ricker', 'gaussianprime',
            'gaussiandoubleprime', 'sine', 'contsine'
        ],
                                description='Waveform: ',
                                disabled=False,
                                layout=wd.Layout(width='23%',
                                                 margin='2px 5px 10px 0px'))

        self.ddsrc = wd.Dropdown(options=[
            ' ', 'hertzian_dipole', 'voltage_source', 'magnetic_dipole'
        ],
                                 description='Source: ',
                                 disabled=False,
                                 layout=wd.Layout(width='23%',
                                                  margin='2px 5px 10px 0px'))

        self.dom = [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)]
        self.sp = [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)]
        self.time_window = wd.Text(layout=wd.Layout(width='15%'))
        self.title = wd.Text(layout=wd.Layout(width='50%'))
        self.msg = wd.Text(layout=wd.Layout(width='15%'))
        self.intRes = wd.Text(
            layout=wd.Layout(width='11%', margin='10px 0px 0px 0px'))
        self.wfAll.append(
            [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)])
        self.srcAll.append(
            [wd.Text(layout=wd.Layout(width='13%')) for i in range(4)])
        self.rcAll.append(
            [wd.Text(layout=wd.Layout(width='13%')) for i in range(3)])
        self.steps = [wd.Text(layout=wd.Layout(width='15%')) for i in range(6)]
        self.goAll.append(
            [wd.Text(layout=wd.Layout(width='13%')) for i in range(9)])
        self.goAll[0].append(wd.Text(layout=wd.Layout(width='25%')))

        self.spaceList = [
            wd.HBox([
                wd.Label('Title: ', layout=wd.Layout(width='20%')), self.title
            ]),
            wd.HBox([
                wd.Label('', layout=wd.Layout(width='25%')),
                wd.Label('X', layout=wd.Layout(width='15%')),
                wd.Label('Y', layout=wd.Layout(width='15%')),
                wd.Label('Z', layout=wd.Layout(width='15%'))
            ]),
            wd.HBox([
                wd.Label('Domain: ', layout=wd.Layout(width='20%')),
                self.dom[0], self.dom[1], self.dom[2]
            ]),
            wd.HBox([
                wd.Label('', layout=wd.Layout(width='25%')),
                wd.Label('dx', layout=wd.Layout(width='15%')),
                wd.Label('dy', layout=wd.Layout(width='15%')),
                wd.Label('dz', layout=wd.Layout(width='15%'))
            ]),
            wd.HBox([
                wd.Label('Spacing: ', layout=wd.Layout(width='20%')),
                self.sp[0], self.sp[1], self.sp[2]
            ]),
            wd.HBox([
                wd.Label('Time Window: ', layout=wd.Layout(width='20%')),
                self.time_window
            ]),
            wd.HBox([
                wd.Label('Messages(y/n): ', layout=wd.Layout(width='20%')),
                self.msg
            ])
        ]

        self.propLabels = wd.HBox([
            wd.Label('', layout=wd.Layout(width='10%')),
            wd.Label('Relative Permittivity', layout=wd.Layout(width='15%')),
            wd.Label('\t\t\tConductivity', layout=wd.Layout(width='15%')),
            wd.Label('Relative Permeability', layout=wd.Layout(width='15%')),
            wd.Label('Magnetic Loss', layout=wd.Layout(width='15%')),
            wd.Label('Name', layout=wd.Layout(width='25%'))
        ])
        self.srList = [
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='12%')),
                wd.Label('Type', layout=wd.Layout(width='11.5%')),
                wd.Label('Scaling of max amplitude',
                         layout=wd.Layout(width='17%')),
                wd.Label('Center frequency', layout=wd.Layout(width='17%')),
                wd.Label('Name', layout=wd.Layout(width='5%'))
            ],
                    layout=wd.Layout(margin='10px 0px 10px 0px')),
            wd.HBox([
                self.ddwf, self.wfAll[0][0], self.wfAll[0][1], self.wfAll[0][2]
            ]),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='12%')),
                wd.Label('Type', layout=wd.Layout(width='11%')),
                wd.Label('Polarization (x,y or z)',
                         layout=wd.Layout(width='19%')),
                wd.Label('X', layout=wd.Layout(width='12%')),
                wd.Label('Y', layout=wd.Layout(width='13%')),
                wd.Label('Z', layout=wd.Layout(width='15%')),
            ],
                    layout=wd.Layout(margin='10px 0px 10px 0px')),
            wd.HBox([
                self.ddsrc, self.srcAll[0][0], self.srcAll[0][1],
                self.srcAll[0][2], self.srcAll[0][3]
            ]),
            wd.HBox([
                wd.Label(
                    'If voltage source specify internal resistance (Ohm):',
                    layout=wd.Layout(width='30%', margin='10px 0px 0px 87px')),
                self.intRes
            ]),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='14%')),
                wd.Label('X', layout=wd.Layout(width='13%')),
                wd.Label('Y', layout=wd.Layout(width='12%')),
                wd.Label('Z', layout=wd.Layout(width='9%'))
            ],
                    layout=wd.Layout(margin='10px 0px 0px 0px')),
            wd.HBox([
                wd.Label('Receiver: ',
                         layout=wd.Layout(width='6.2%',
                                          margin='0px 0px 20px 25px')),
                self.rcAll[0][0], self.rcAll[0][1], self.rcAll[0][2]
            ]),
            wd.HBox([
                wd.Label(
                    'For B-scan specify increments to move sources and receivers:',
                    layout=wd.Layout(width='40%', margin='10px 0px 0px 5px'))
            ]),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='17%')),
                wd.Label('x', layout=wd.Layout(width='15%')),
                wd.Label('y', layout=wd.Layout(width='15%')),
                wd.Label('z', layout=wd.Layout(width='15%'))
            ]),
            wd.HBox([
                wd.Label('Source steps: ', layout=wd.Layout(width='10%')),
                self.steps[0], self.steps[1], self.steps[2]
            ]),
            wd.HBox([
                wd.Label('Receiver steps: ', layout=wd.Layout(width='10%')),
                self.steps[3], self.steps[4], self.steps[5]
            ],
                    layout=wd.Layout(margin='0px 0px 20px 0px'))
        ]

        self.goList = [
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='5%')),
                wd.Label('X start', layout=wd.Layout(width='13%')),
                wd.Label('Y start', layout=wd.Layout(width='13%')),
                wd.Label('Z start', layout=wd.Layout(width='13%')),
                wd.Label('X end', layout=wd.Layout(width='13%')),
                wd.Label('Y end', layout=wd.Layout(width='13%')),
                wd.Label('Z end', layout=wd.Layout(width='9%'))
            ],
                    layout=wd.Layout(margin='10px 0px 0px 0px')),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][0],
                self.goAll[0][1], self.goAll[0][2], self.goAll[0][3],
                self.goAll[0][4], self.goAll[0][5]
            ]),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='6%')),
                wd.Label('dx', layout=wd.Layout(width='13%')),
                wd.Label('dy', layout=wd.Layout(width='13%')),
                wd.Label('dz', layout=wd.Layout(width='9%'))
            ],
                    layout=wd.Layout(margin='10px 0px 0px 0px')),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][6],
                self.goAll[0][7], self.goAll[0][8]
            ]),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='3%')),
                wd.Label('Geometry filename (no extension)',
                         layout=wd.Layout(width='22%'))
            ],
                    layout=wd.Layout(margin='10px 0px 0px 0px')),
            wd.HBox([
                wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][9]
            ],
                    layout=wd.Layout(margin='0px 0px 20px 0px')), self.wrFile
        ]

        self.add_mat.on_click(self.on_button_clicked)
        self.add_obj.on_click(self.on_button_clicked2)
        self.rem_obj.on_click(self.on_button_clicked3)
        self.wrFile.on_click(self.write_file)

        [self.dd[i].observe(self.on_change, 'value') for i in range(20)]
        self.gb = wd.GridBox(
            children=self.spaceList,
            layout=wd.Layout(grid_template_columns="repeat(1, 500px)"))
        self.gb2 = wd.GridBox(
            children=self.widgetList,
            layout=wd.Layout(grid_template_columns="repeat(1, 900px)"))
        self.gb3 = wd.GridBox(
            children=self.objectList,
            layout=wd.Layout(grid_template_columns="repeat(1, 1100px)"))
        self.gb4 = wd.GridBox(
            children=self.srList,
            layout=wd.Layout(grid_template_columns="repeat(1, 1000px)"))
        self.gb5 = wd.GridBox(
            children=self.goList,
            layout=wd.Layout(grid_template_columns="repeat(1, 900px)"))

        self.acc = wd.Accordion(
            children=[self.gb, self.gb2, self.gb3, self.gb4, self.gb5])
        for i in range(5):
            self.acc.set_title(i, self.accNames[i])

        display(self.acc)
コード例 #19
0
highlight2 = widgets.Box([hl2, c2])
highlight3 = widgets.Box([hl3, c3])
highlight4 = widgets.Box([hl4, c4])
highlight5 = widgets.Box([hl5, c5])
highlight6 = widgets.Box([hl6, c6])
highlight7 = widgets.Box([hl7, c7])
highlight8 = widgets.Box([hl8, c8])
highlight9 = widgets.Box([hl9, c9])
highlight10 = widgets.Box([hl10, c10])

highlight = widgets.VBox([
    highlight1, highlight2, highlight3, highlight4, highlight5, highlight6,
    highlight7, highlight8, highlight9, highlight10
])

accordion = widgets.Accordion(children=[bands, properties1, bboptions])
accordion.set_title(0, 'Photometric Bands')
accordion.set_title(1, 'Plot Properties')
accordion.set_title(2, 'Blackbody properties (optional)')

accordion1 = widgets.Accordion(children=[bands, properties, bboptions])
accordion1.set_title(0, 'Photometric Bands')
accordion1.set_title(1, 'Plot Properties')
accordion1.set_title(2, 'Blackbody properties (optional)')

accordion2 = widgets.Accordion(
    children=[bands, properties, bboptions, highlight])
accordion2.set_title(0, 'Photometric Bands')
accordion2.set_title(1, 'Plot Properties')
accordion2.set_title(2, 'Blackbody properties (optional)')
accordion2.set_title(3, 'Highlighted Planets (max 10)')
コード例 #20
0
# In[8]:

#Fancy boxes

# In[9]:

name1 = widgets.Text(description='Location:')
zip1 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page1 = widgets.Box(children=[name1, zip1])

name2 = widgets.Text(description='Location:')
zip2 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page2 = widgets.Box(children=[name2, zip2])

accord = widgets.Accordion(children=[page1, page2], width=400)
display(accord)

accord.set_title(0, 'From')
accord.set_title(1, 'To')

# In[10]:

name = widgets.Text(description='Name:', padding=4)
color = widgets.Dropdown(
    description='Color:',
    padding=4,
    options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
page1 = widgets.Box(children=[name, color], padding=4)

age = widgets.IntSlider(description='Age:',
コード例 #21
0
ファイル: clusterDB_w.py プロジェクト: nysol/miningpy
 def widget(self):
     exe_w = widgets.Button(description='clear', disabled=False)
     exe_w.on_click(self.clear_h)
     self.cList_w = widgets.Accordion(children=[])
     box = widgets.VBox([exe_w, self.cList_w])
     return box
コード例 #22
0
def figure_of_merit():
    figure_type = widgets.Dropdown(options=[('Palpha', 'Palpha'),
                                            ('Ralpha', 'Ralpha'),
                                            ('Spectral', 'spectral')],
                                   value='Palpha',
                                   description='Figure:',
                                   layout=widgets.Layout(width='180px'),
                                   style=style_default)

    figure_alpha = widgets.Text(value='2',
                                description='Value of \\(\\alpha\\):',
                                layout=widgets.Layout(width='130px'),
                                style=style_default)

    coord_unif = widgets.Checkbox(value=True,
                                  description='Coordinate-Uniform evaluation',
                                  style=style_default)

    norm_type = widgets.Text(value='2',
                             description='Norm type q > 0 or q = "inf":',
                             layout=widgets.Layout(width='220px'),
                             style=style_default,
                             disabled=True)

    figure_of_merit_expl = widgets.HTMLMath(
        value=
        '<p> Please note (and see the documentation for more details) that: </p> \
                        <ul>\
                            <li> The list of available figures of merit depend on the point set type and the interlacing factor. </li>\
                            <li> The \\(P_\\alpha \\) method requires \\( \\alpha \\in \\{ 2, 4, 6 \\} \\), \\(R_\\alpha \\) requires \\( \\alpha > 0 \\) and \\(B_{d, \\alpha, (1)} \\) requires \\( \\alpha > 0 \\). </li> \
                            <li> The Coordinate-Uniform (CU) evaluation method is generally faster, but requires a specific norm type.<br>Depending on the point set type and the figure, this option is mandatory, optional or impossible.</li> \
                            <li> The possibility to choose the norm type depends on the point set type, the figure, and the CU option.</li>\
                            <li> For the t-value figure, weights, norm type and CU evaluation do not make sense.</li>\
                        </ul>')

    is_normalization = widgets.Checkbox(description='Normalization',
                                        value=False,
                                        style=style_default)
    minimum_level = widgets.Text(placeholder='1',
                                 description='Min Level (optional):',
                                 layout=widgets.Layout(
                                     width='180px',
                                     margin='0px 10px 0px 0px',
                                     display='none'),
                                 style=style_default)
    maximum_level = widgets.Text(placeholder='10',
                                 description='Max Level (optional):',
                                 layout=widgets.Layout(width='180px',
                                                       display='none'),
                                 style=style_default)

    combiner_level = widgets.BoundedIntText(description='Level:',
                                            min=1,
                                            layout=widgets.Layout(
                                                display='none', width='130px'))
    combiner_dropdown = widgets.Dropdown(options=[
        ('weighted sum', 'sum'), ('maximum weighted value', 'max'),
        ('weighted value of the highest level', 'level:max'),
        ('weighted value of a specific level', 'level:')
    ],
                                         value='sum',
                                         description='Combiner:',
                                         style=style_default)
    combiner_options = widgets.HBox([combiner_dropdown, combiner_level],
                                    layout=widgets.Layout(display='none'))

    low_pass_filter = widgets.Checkbox(description='Low-Pass Filter',
                                       value=False,
                                       style=style_default)
    low_pass_filter_options = widgets.Text(value='1',
                                           description='Low-Pass Threshold',
                                           layout=widgets.Layout(
                                               display='none', width='200px'),
                                           style=style_default)

    figure_of_merit_wrapper = widgets.Accordion([
        widgets.VBox([
            figure_of_merit_expl,
            widgets.HBox(
                [figure_type, figure_alpha, coord_unif, norm_type],
                layout=widgets.Layout(justify_content='space-between')),
            combiner_options,
            widgets.HBox([is_normalization, minimum_level, maximum_level]),
            widgets.HBox([low_pass_filter, low_pass_filter_options])
        ])
    ])

    figure_of_merit_wrapper.set_title(0, 'Figure of Merit')

    return BaseGUIElement(figure_type=figure_type,
                          figure_alpha=figure_alpha,
                          coord_unif=coord_unif,
                          norm_type=norm_type,
                          is_normalization=is_normalization,
                          low_pass_filter=low_pass_filter,
                          minimum_level=minimum_level,
                          maximum_level=maximum_level,
                          combiner_level=combiner_level,
                          combiner_dropdown=combiner_dropdown,
                          combiner_options=combiner_options,
                          low_pass_filter_options=low_pass_filter_options,
                          main=figure_of_merit_wrapper,
                          _callbacks={
                              'figure_type': change_figure_type,
                              'coord_unif': change_coord_unif,
                              'low_pass_filter': change_low_pass_filter,
                              'combiner_dropdown': change_combiner_options,
                              'is_normalization': change_normalization
                          })
コード例 #23
0
 def createProfile(cls):
     cls.profile = widgets.Accordion(children=[])
     return cls.profile
コード例 #24
0
def remove_background_ipy(obj, **kwargs):
    wdict = {}
    left = ipywidgets.FloatText(disabled=True, description="Left")
    right = ipywidgets.FloatText(disabled=True, description="Right")
    link((obj, "ss_left_value"), (left, "value"))
    link((obj, "ss_right_value"), (right, "value"))
    fast = ipywidgets.Checkbox(description="Fast")
    help = ipywidgets.HTML(
        "Click on the signal figure and drag to the right to select a"
        "range. Press `Apply` to remove the background in the whole dataset. "
        "If fast is checked, the background parameters are estimated using a "
        "fast (analytical) method that can compromise accuray. When unchecked "
        "non linear least squares is employed instead.", )
    wdict["help"] = help
    help = ipywidgets.Accordion(children=[help])
    help.set_title(0, "Help")
    close = ipywidgets.Button(
        description="Close",
        tooltip="Close widget and remove span selector from the signal figure."
    )
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Remove the background in the whole dataset.")

    polynomial_order = ipywidgets.IntText(description="Polynomial order")
    background_type = enum2dropdown(obj.traits()["background_type"])
    background_type.description = "Background type"

    def enable_poly_order(change):
        if change.new == "Polynomial":
            polynomial_order.layout.display = ""
        else:
            polynomial_order.layout.display = "none"

    background_type.observe(enable_poly_order, "value")
    link((obj, "background_type"), (background_type, "value"))

    # Trigger the function that controls the visibility of poly order as
    # setting the default value doesn't trigger it.

    class Dummy:
        new = background_type.value

    enable_poly_order(change=Dummy())
    link((obj, "polynomial_order"), (polynomial_order, "value"))
    link((obj, "fast"), (fast, "value"))
    wdict["left"] = left
    wdict["right"] = right
    wdict["fast"] = fast
    wdict["polynomial_order"] = polynomial_order
    wdict["background_type"] = background_type
    wdict["apply_button"] = apply
    box = ipywidgets.VBox([
        left,
        right,
        background_type,
        polynomial_order,
        fast,
        help,
        ipywidgets.HBox((apply, close)),
    ])

    def on_apply_clicked(b):
        obj.apply()
        box.close()

    apply.on_click(on_apply_clicked)

    def on_close_clicked(b):
        obj.span_selector_switch(False)
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
コード例 #25
0
def knowledgePage(out, grid):

    grid = close_FrontPage(out, grid)
    grid[0, 0:29].description = '知识梳理'
    grid[19, 9:11] = widgets.Dropdown(options=[('目       录', 0), ('过程演示', 1),
                                               ('巩固测试', 2)],
                                      layout=widgets.Layout(width='5cm'),
                                      description='跳转到: ')
    grid[19, 17:18] = widgets.Button(description='进入',
                                     style={'button_color': '#004080'},
                                     button_style='info',
                                     layout=widgets.Layout(width='2.5cm'))

    #跳转页面
    def jumpToPage(b):
        value = grid[19, 9:11].value
        if value == 0:
            contentsPage(out, grid)
        elif value == 1:
            processPage(out, grid)
        elif value == 2:
            testPage(out, grid)

    grid[19, 17:18].on_click(jumpToPage)

    #-------------------------------------#

    #显示图片
    with open('./image/teacher.jpg', 'rb') as f:
        teacher_image = f.read()
        grid[6:12, 1:6] = widgets.Image(value=teacher_image)
    f.close()

    #--------------------------------------#

    #显示知识点内容
    with open('./doc/datapath.txt', 'r') as f1:
        datapath_txt = f1.read()
    f1.close()
    datapath_grid = widgets.GridspecLayout(10, 5, width='auto', height='9.5cm')
    datapath_grid[:9, :] = widgets.Textarea(value=datapath_txt,
                                            disabled=True,
                                            layout=widgets.Layout(
                                                height='8cm', width='auto'))
    datapath_grid[9, 1] = widgets.Button(description='更改',
                                         style={'button_color': '#004080'},
                                         button_style='info',
                                         layout=widgets.Layout(width='2.5cm'))
    datapath_grid[9, 3] = widgets.Button(description='保存',
                                         style={'button_color': '#004080'},
                                         button_style='info',
                                         layout=widgets.Layout(width='2.5cm'))
    datapath_accordion = widgets.Accordion(children=[datapath_grid])
    datapath_accordion.set_title(0, '知识概要')
    datapath_accordion.selected_index = None

    with open('./doc/cache.txt', 'r') as f2:
        cache_txt = f2.read()
    f2.close()

    cache_grid = widgets.GridspecLayout(10, 5, width='auto', height='9.5cm')
    cache_grid[:9, :] = widgets.Textarea(value=cache_txt,
                                         disabled=True,
                                         layout=widgets.Layout(height='8cm',
                                                               width='auto'))
    cache_grid[9, 1] = widgets.Button(description='更改',
                                      style={'button_color': '#004080'},
                                      button_style='info',
                                      layout=widgets.Layout(width='2.5cm'))
    cache_grid[9, 3] = widgets.Button(description='保存',
                                      style={'button_color': '#004080'},
                                      button_style='info',
                                      layout=widgets.Layout(width='2.5cm'))
    cache_accordion = widgets.Accordion(children=[
        cache_grid,
        widgets.GridspecLayout(10, 4, width='auto', height='9.5cm')
    ])
    cache_accordion.set_title(0, '知识概要')
    cache_accordion.set_title(1, '基础操作')
    #cache_accordion.set_title(2, '数据访问')
    cache_accordion.selected_index = None

    #--------------------------------------#

    #实现“基础操作”内容
    cache.knowledge_base(cache_accordion.children[1])
    #实现“数据访问”内容
    #cache.knowledge_mapway(cache_accordion.children[2])

    #--------------------------------------#

    tab_title = ['数据通路', 'Cache']
    tab = widgets.Tab(layout=widgets.Layout(width='18cm', height='11cm'))
    tab.children = [datapath_accordion, cache_accordion]
    for i in range(2):
        tab.set_title(i, tab_title[i])
    grid[1:18, 8:17] = tab

    #更改、保存按钮实现
    def datapath_update(b):
        datapath_grid[:9, :].disabled = False

    datapath_grid[9, 1].on_click(datapath_update)

    def cache_update(b):
        cache_grid[:9, :].disabled = False

    cache_grid[9, 1].on_click(cache_update)

    def datapath_save(b):
        text = datapath_grid[:9, :].value
        with open('./doc/datapath.txt', 'w') as fd:
            fd.write(text)
        fd.close()
        datapath_grid[:9, :].disabled = True

    datapath_grid[9, 3].on_click(datapath_save)

    def cache_save(b):
        text = cache_grid[:9, :].value
        with open('./doc/cache.txt', 'w') as fd:
            fd.write(text)
        fd.close()
        cache_grid[:9, :].disabled = True

    cache_grid[9, 3].on_click(cache_save)

    return
コード例 #26
0
def spikes_removal_ipy(obj, **kwargs):
    wdict = {}
    threshold = ipywidgets.FloatText()
    add_noise = ipywidgets.Checkbox()
    default_spike_width = ipywidgets.IntText()
    interpolator_kind = enum2dropdown(obj.traits()["interpolator_kind"])
    spline_order = ipywidgets.IntSlider(min=1, max=10)
    progress_bar = ipywidgets.IntProgress(max=len(obj.coordinates) - 1)
    help = ipywidgets.HTML(
        value=SPIKES_REMOVAL_INSTRUCTIONS.replace('\n', '<br/>'))
    help = ipywidgets.Accordion(children=[help])
    help.set_title(0, "Help")

    show_diff = ipywidgets.Button(
        description="Show derivative histogram",
        tooltip="This figure is useful to estimate the threshold.",
        layout=ipywidgets.Layout(width="auto"))
    close = ipywidgets.Button(
        description="Close",
        tooltip="Close widget and remove span selector from the signal figure."
    )
    next = ipywidgets.Button(description="Find next",
                             tooltip="Find next spike")
    previous = ipywidgets.Button(description="Find previous",
                                 tooltip="Find previous spike")
    remove = ipywidgets.Button(description="Remove spike",
                               tooltip="Remove spike and find next one.")
    wdict["threshold"] = threshold
    wdict["add_noise"] = add_noise
    wdict["default_spike_width"] = default_spike_width
    wdict["interpolator_kind"] = interpolator_kind
    wdict["spline_order"] = spline_order
    wdict["progress_bar"] = progress_bar
    wdict["show_diff_button"] = show_diff
    wdict["close_button"] = close
    wdict["next_button"] = next
    wdict["previous_button"] = previous
    wdict["remove_button"] = remove

    def on_show_diff_clicked(b):
        obj._show_derivative_histogram_fired()

    show_diff.on_click(on_show_diff_clicked)

    def on_next_clicked(b):
        obj.find()

    next.on_click(on_next_clicked)

    def on_previous_clicked(b):
        obj.find(back=True)

    previous.on_click(on_previous_clicked)

    def on_remove_clicked(b):
        obj.apply()

    remove.on_click(on_remove_clicked)
    labeled_spline_order = labelme("Spline order", spline_order)

    def enable_interpolator_kind(change):
        if change.new == "Spline":
            for child in labeled_spline_order.children:
                child.layout.display = ""
        else:
            for child in labeled_spline_order.children:
                child.layout.display = "none"

    interpolator_kind.observe(enable_interpolator_kind, "value")
    link((obj, "interpolator_kind"), (interpolator_kind, "value"))
    link((obj, "threshold"), (threshold, "value"))
    link((obj, "add_noise"), (add_noise, "value"))
    link((obj, "default_spike_width"), (default_spike_width, "value"))
    link((obj, "spline_order"), (spline_order, "value"))
    link((obj, "index"), (progress_bar, "value"))

    # Trigger the function that controls the visibility  as
    # setting the default value doesn't trigger it.

    class Dummy:
        new = interpolator_kind.value

    enable_interpolator_kind(change=Dummy())
    advanced = ipywidgets.Accordion((ipywidgets.VBox([
        labelme("Add noise", add_noise),
        labelme("Interpolator kind", interpolator_kind),
        labelme("Default spike width", default_spike_width),
        labelme("Spline order", spline_order),
    ]), ))

    advanced.set_title(0, "Advanced settings")
    box = ipywidgets.VBox([
        ipywidgets.VBox([
            show_diff,
            labelme("Threshold", threshold),
            labelme("Progress", progress_bar),
        ]), advanced, help,
        ipywidgets.HBox([previous, next, remove, close])
    ])

    def on_close_clicked(b):
        obj.span_selector_switch(False)
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
コード例 #27
0
def initProcess_Right(grid):

    code_rightab = widgets.Tab(
        layout=widgets.Layout(width='auto', height='auto'))
    datapath_rightab = widgets.Tab(
        layout=widgets.Layout(width='auto', height='auto'))
    cache_rightab = widgets.Tab(
        layout=widgets.Layout(width='auto', height='auto'))

    #---------1) Code 右半部分---------#
    with open('./doc/instructions.txt', 'r') as f:
        instructions = f.read()
    f.close()
    code_rchildren = widgets.Accordion(children=[
        widgets.Textarea(value=instructions,
                         disabled=True,
                         layout=widgets.Layout(width='auto', height='6cm')),
        widgets.Textarea(disabled=True,
                         layout=widgets.Layout(width='auto', height='6cm'))
    ],
                                       selected_index=None)
    code_rchildren.set_title(0, 'Instructions')
    code_rchildren.set_title(1, 'Event Log')
    code_rightab.children = [code_rchildren]
    code_rightab.set_title(0, 'Information')

    #-------2) Datapth 右半部分--------#
    datapath_rchildren = widgets.GridspecLayout(34,
                                                4,
                                                width='auto',
                                                height='auto')
    datapath_rchildren[0, 0] = widgets.Button(
        description='Name',
        style={'button_color': '#004080'},
        button_style='info',
        layout=widgets.Layout(width='auto', height='auto'))
    datapath_rchildren[0, 1] = widgets.Button(
        description='Alias',
        style={'button_color': '#004080'},
        button_style='info',
        layout=widgets.Layout(width='auto', height='auto'))
    datapath_rchildren[0, 2:4] = widgets.Button(
        description='Value',
        style={'button_color': '#004080'},
        button_style='info',
        layout=widgets.Layout(width='auto', height='auto'))
    alias = [
        'zero', 'ra', 'sp', 'gp', 'tp', 't0', 't1', 't2', 'fp', 's0', 'a0',
        'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 's1', 's2', 's3', 's4', 's5',
        's6', 's7', 's8', 's9', 's10', 't3', 't4', 't5', 't6'
    ]
    for i in range(1, 33):
        for j in range(3):
            if j == 0:
                datapath_rchildren[i, j] = widgets.Button(
                    description='x' + str(i - 1),
                    disabled=True,
                    layout=widgets.Layout(width='auto', height='auto'))
            elif j == 1:
                datapath_rchildren[i, j] = widgets.Button(
                    description=alias[i - 1],
                    disabled=True,
                    layout=widgets.Layout(width='auto', height='auto'))
            elif j == 2:
                datapath_rchildren[i, 2:4] = widgets.Button(
                    description="0x00000000",
                    disabled=True,
                    layout=widgets.Layout(width='auto', height='auto'))
    datapath_rchildren[33, :2] = widgets.Button(
        description='播放次数',
        disabled=False,
        style={'button_color': '#004080'},
        button_style='info',
        layout=widgets.Layout(width='auto', height='auto'))
    datapath_rchildren[33, 2:] = widgets.Button(description='',
                                                disabled=False,
                                                layout=widgets.Layout(
                                                    width='auto',
                                                    height='auto'))

    datapath_rightab.children = [datapath_rchildren]
    datapath_rightab.set_title('0', 'Register')

    #---------3) Cache 右半部分--------#
    cache_rightab.children = [
        widgets.GridspecLayout(18, 4, width='auto', height='auto')
    ]
    cache_rightab.set_title('0', 'Parameter')

    grid[1:19, 20:30] = code_rightab

    right = {
        'code': code_rightab,
        'datapath': datapath_rightab,
        'cache': cache_rightab
    }

    return right
コード例 #28
0
def calibrate_ipy(obj, **kwargs):
    # Define widgets
    wdict = {}
    axis = obj.axis
    left = ipywidgets.FloatText(disabled=True, description="Left")
    right = ipywidgets.FloatText(disabled=True, description="Right")
    offset = ipywidgets.FloatText(disabled=True, description="Offset")
    scale = ipywidgets.FloatText(disabled=True, description="Scale")
    new_left = ipywidgets.FloatText(disabled=False, description="New left")
    new_right = ipywidgets.FloatText(disabled=False, description="New right")
    units = ipywidgets.Text(description="Units", )
    unitsl = ipywidgets.Label(layout=ipywidgets.Layout(width="10%"))
    help = ipywidgets.HTML(
        "Click on the signal figure and drag to the right to select a signal "
        "range. Set the new left and right values and press `Apply` to update "
        "the calibration of the axis with the new values or press "
        " `Close` to cancel.", )
    wdict["help"] = help
    help = ipywidgets.Accordion(children=[help])
    help.set_title(0, "Help")
    close = ipywidgets.Button(
        description="Close",
        tooltip="Close widget and remove span selector from the signal figure."
    )
    apply = ipywidgets.Button(
        description="Apply",
        tooltip="Set the axis calibration with the `offset` and `scale` values "
        "above.")

    # Connect
    link((obj, "ss_left_value"), (left, "value"))
    link((obj, "ss_right_value"), (right, "value"))
    link((obj, "left_value"), (new_left, "value"))
    link((obj, "right_value"), (new_right, "value"))
    link((obj, "units"), (units, "value"))
    link((obj, "units"), (unitsl, "value"))
    link((obj, "offset"), (offset, "value"))
    link((obj, "scale"), (scale, "value"))

    def on_apply_clicked(b):
        if (new_left.value, new_right.value) != (0, 0):
            # traitlets does not support undefined, therefore we need to makes
            # sure that the values are updated in the obj if they make sense
            if new_left.value == 0 and obj.left_value is t.Undefined:
                obj.left_value = 0
            elif new_right.value == 0 and obj.right_value is t.Undefined:
                obj.right_value = 0
            # This is the default value, we need to update
        obj.apply()

    apply.on_click(on_apply_clicked)

    box = ipywidgets.VBox([
        ipywidgets.HBox([new_left, unitsl]),
        ipywidgets.HBox([new_right, unitsl]),
        ipywidgets.HBox([left, unitsl]),
        ipywidgets.HBox([right, unitsl]),
        ipywidgets.HBox([offset, unitsl]), scale, units, help,
        ipywidgets.HBox((apply, close))
    ])

    def on_close_clicked(b):
        obj.span_selector_switch(False)
        box.close()

    close.on_click(on_close_clicked)

    wdict["left"] = left
    wdict["right"] = right
    wdict["offset"] = offset
    wdict["scale"] = scale
    wdict["new_left"] = new_left
    wdict["new_right"] = new_right
    wdict["units"] = units
    wdict["close_button"] = close
    wdict["apply_button"] = apply

    return {
        "widget": box,
        "wdict": wdict,
    }
コード例 #29
0
    def init_metrics_ui(self):
        """构建基础env widget ui return widgets.VBox"""
        # 回测时间模式
        self.metrics_mode = widgets.RadioButtons(options={
            u'考虑初始资金+标尺大盘对比': 0,
            u'不考虑初始资金+不对比标尺': 1
        },
                                                 value=0,
                                                 description=u'度量模式:',
                                                 disabled=False)

        self.metrics_out_put = widgets.RadioButtons(options={
            u'只输出交易单:orders_pd': 0,
            u'只输出行为单:action_pd': 1,
            u'只输出资金单:capital_pd': 2,
            u'输出交易单,行为单,资金单': 3
        },
                                                    value=0,
                                                    description=u'输出对象:',
                                                    disabled=False)

        out_put_display_max_label1 = widgets.Label(u'输出显示最大行列数,最大100行,100列',
                                                   layout=widgets.Layout(
                                                       width='300px',
                                                       align_items='stretch'))
        out_put_display_max_label2 = widgets.Label(u'如需查看更多输出表单,请选择保存输出至文件',
                                                   layout=widgets.Layout(
                                                       width='300px',
                                                       align_items='stretch'))
        self.out_put_display_max_rows = widgets.IntSlider(
            value=50,
            min=1,
            max=100,
            step=1,
            description=u'行数',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='d')

        self.out_put_display_max_columns = widgets.IntSlider(
            value=50,
            min=1,
            max=100,
            step=1,
            description=u'列数',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='d')
        out_put_display = widgets.VBox([
            out_put_display_max_label1, out_put_display_max_label2,
            self.out_put_display_max_rows, self.out_put_display_max_columns
        ])

        save_out_put_lable = widgets.Label(u'是否保存交易单,行为单,资金单到文件',
                                           layout=widgets.Layout(
                                               width='300px',
                                               align_items='stretch'))
        save_out_put_lable2 = widgets.Label(
            u'路径:{}'.format(os.path.join(ABuEnv.g_project_data_dir,
                                         'out_put')),
            layout=widgets.Layout(width='300px', align_items='stretch'))
        self.save_out_put = widgets.Checkbox(
            value=False,
            description=u'保存输出',
            disabled=False,
        )
        save_out_put = widgets.VBox(
            [save_out_put_lable, save_out_put_lable2, self.save_out_put])

        accordion = widgets.Accordion()
        accordion.children = [
            widgets.VBox([
                self.metrics_mode, self.metrics_out_put, out_put_display,
                save_out_put
            ])
        ]
        accordion.set_title(0, u'回测度量结果设置')
        accordion_shut(accordion)

        return accordion
コード例 #30
0
def analysis(m, geo):
    #Data Preprocessing
    field_select = widgets.Select(options=list(
        zip(geo.attributes, range(2,
                                  len(geo.attributes) + 2))),
                                  description="fields")
    lr_button = widgets.Button(description='Apply')
    lr_tool = widgets.HBox([field_select, lr_button])
    lr_area = widgets.VBox(
        [widgets.Label(value='Standardized Normalization'), lr_tool])

    def lr_click(change):
        if field_select.value is not None:
            import mygeopackage.pproc
            mygeopackage.pproc.standardNormalization(geo, field_select.value)
            print(geo.data[:, field_select.value])

    lr_button.on_click(lr_click)

    #Unsupervised Machine Learning
    style = {'description_width': 'initial'}
    n_text = widgets.IntText(value=2,
                             description='Desired Clusters',
                             style=style)
    field_multiple = widgets.SelectMultiple(options=list(
        zip(['X', 'Y', *geo.attributes], range(0,
                                               len(geo.attributes) + 2))),
                                            description="Fields")
    index_field = widgets.Select(options=list(
        zip(geo.attributes, range(2,
                                  len(geo.attributes) + 2))),
                                 description="Identifier")
    k_means_button = widgets.Button(description='Apply')
    k_means_tool = widgets.HBox([n_text, field_multiple, index_field])
    k_means_area = widgets.VBox(
        [widgets.Label(description='K_Means'), k_means_tool, k_means_button])

    def k_means_click(change):

        import mygeopackage.unsupervised
        if field_multiple.value is not None:
            clusters = mygeopackage.unsupervised.Cluster(geo.data)
            mygeopackage.unsupervised.k_means(n_text.value,
                                              field_multiple.value, clusters,
                                              index_field.value)
            clusters.show(map=m)

    k_means_button.on_click(k_means_click)

    eps_text = widgets.Text(value='0.5', description="EPS")
    min_samples = widgets.IntText(value=5, description="Min_Samples")
    dbscan_button = widgets.Button(description="Apply")
    dbscan_tool = widgets.HBox(
        [eps_text, min_samples, field_multiple, index_field])
    dbscan_area = widgets.VBox(
        [widgets.Label(description="DBSCAN"), dbscan_tool, dbscan_button])

    def dbscan_click(change):
        import mygeopackage.unsupervised
        if field_multiple.value is not None:
            clusters = mygeopackage.unsupervised.Cluster(geo.data)
            mygeopackage.unsupervised.dbscan(float(eps_text.value),
                                             min_samples.value,
                                             field_multiple.value, clusters,
                                             index_field.value)
            clusters.show(map=m)

    dbscan_button.on_click(dbscan_click)
    accordion = widgets.Accordion(children=[k_means_area, dbscan_area])
    accordion.set_title(0, 'K Means')
    accordion.set_title(1, 'DBSCAN')
    #Regression
    dependent_field = widgets.Select(options=list(
        zip(['X', 'Y', *geo.attributes], range(0,
                                               len(geo.attributes) + 2))),
                                     description="Dependent Variable",
                                     style=style)
    independent_fields = widgets.SelectMultiple(
        options=list(
            zip(['X', 'Y', *geo.attributes], range(0,
                                                   len(geo.attributes) + 2))),
        description="Independent Variable",
        style=style)
    regression_button = widgets.Button(description="Apply")
    regression_tool = widgets.HBox(
        [dependent_field, independent_fields, index_field])
    regression_area = widgets.VBox([
        widgets.Label(description="Ordinary Least Square"), regression_tool,
        regression_button
    ])

    def regression_click(change):
        import mygeopackage.regression
        if dependent_field.value is not None:
            reg_results = mygeopackage.regression.Regression()
            reg_results = mygeopackage.regression.ols(geo,
                                                      dependent_field.value,
                                                      independent_fields.value,
                                                      index_field.value)
            reg_results.show(map=m)
            print('R2 Score: ' + str(reg_results.score))

    regression_button.on_click(regression_click)

    tab = widgets.Tab()
    tab_contents = ['Data Preprocessing', 'Unsupervised', 'Regression']
    tab.set_title(0, 'Data Preprocessing')
    tab.set_title(1, 'Unsupervised')
    tab.set_title(2, 'Regression')
    tab.children = [lr_area, accordion, regression_area]
    display(tab)