Example #1
0
 def _build_tabs(self,
                 resources: dict,
                 options_box: Box,
                 instance_creation: Optional[Box] = None) -> Tab:
     """
     Build tabs of widgets to display in Jupyter notebook
     :param resources: Dictionary description: html link from which the values are put into HTML and presented as
     description and link
     :param options_box: Box with method parameters/options (displayed under 'Method parameters' tab)
     :param instance_creation: Box with instance creation widget (displayed under 'Explained instance' tab)
     if provided. If None, no 'Explained instance' tab will be created.
     :return: Tabs to be displayed
     """
     tabs = Tab()
     if instance_creation is not None:
         tabs.children = [
             instance_creation, options_box,
             self._build_resources_widgets(resources)
         ]
         tabs.set_title(0, 'Explained instance')
         tabs.set_title(1, 'Method parameters')
         tabs.set_title(2, 'Resources')
     else:
         tabs.children = [
             options_box,
             self._build_resources_widgets(resources)
         ]
         tabs.set_title(0, 'Method parameters')
         tabs.set_title(1, 'Resources')
     return tabs
Example #2
0
 def get_final_plots(self, quad_funcs=[np.abs, np.angle]):
     from ipywidgets import Tab
     tab = Tab()
     plots = []
     for i, p in enumerate(self.plotters):
         tab.set_title(i, p.filter_name)
         plots.append(p.get_final_plot(quad_funcs=quad_funcs))
     tab.children = plots
     return tab
Example #3
0
 def compose_panel(self, widgets_dict):
     # compose navigation_bar
     navigation_bar = self.navigation_bar.panel
     track_config = compose_track_config_panel(widgets_dict['track_config'])
     panel = Tab()
     panel.children = [navigation_bar, track_config]
     panel.set_title(0, "Navigation")
     panel.set_title(1, "Tracks")
     return panel
Example #4
0
def data_column_dropdown_multiple_tabs(data, t=['x', 'y', 'y2', 'z']):
    """
	 
	Helper function for putting together multiple data column dropdowns in tab format
	"""
    from ipywidgets import Tab

    if t is None:
        t = ['x', 'y', 'y2', 'z']
    tab_contents = t
    children = [data_column_dropdown(data) for name in tab_contents]
    tab = Tab()
    tab.children = children
    tab_dict = {}
    for i, var in enumerate(tab_contents):
        tab.set_title(i, var)
        tab_dict[var] = tab.children[i]

    return tab_dict, tab
Example #5
0
    
buildBtn.on_click(buildBtn_clicked)
            
#modelDd.observe(model_change)

buildTab = VBox(build_items)


################################# image tab end ###################################



################################ Finally ##########################################################
        
tab_nest = Tab()
tab_nest.children = [swanInputBox, runBox, outputBox, buildTab]
tab_nest.set_title(0, 'Input')
tab_nest.set_title(1, 'Run')
tab_nest.set_title(2, 'Output')
tab_nest.set_title(3, 'Build')

setvar("""PATH=$HOME/agave-model/bin:$PATH""")
cmd("auth-tokens-refresh")
clear_output()

def on_change(change):
    global cur_model
    if change['type'] == 'change' and change['name'] == 'value':
        with logOp:
            setvar("MODEL_TITLE="+modelTitle.value)
    
Example #6
0
    def _widget(self):
        """Create IPython widget for display within a notebook"""
        try:
            return self._cached_widget
        except AttributeError:
            pass

        try:
            from ipywidgets import (
                HTML,
                Accordion,
                Button,
                HBox,
                IntText,
                Layout,
                Tab,
                VBox,
            )
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        status = HTML(self._repr_html_())

        if self._supports_scaling:
            request = IntText(0, description="Workers", layout=layout)
            scale = Button(description="Scale", layout=layout)

            minimum = IntText(0, description="Minimum", layout=layout)
            maximum = IntText(0, description="Maximum", layout=layout)
            adapt = Button(description="Adapt", layout=layout)

            accordion = Accordion(
                [HBox([request, scale]),
                 HBox([minimum, maximum, adapt])],
                layout=Layout(min_width="500px"),
            )
            accordion.selected_index = None
            accordion.set_title(0, "Manual Scaling")
            accordion.set_title(1, "Adaptive Scaling")

            def adapt_cb(b):
                self.adapt(minimum=minimum.value, maximum=maximum.value)
                update()

            adapt.on_click(adapt_cb)

            def scale_cb(b):
                with log_errors():
                    n = request.value
                    with suppress(AttributeError):
                        self._adaptive.stop()
                    self.scale(n)
                    update()

            scale.on_click(scale_cb)
        else:
            accordion = HTML("")

        scale_status = HTML(self._scaling_status())

        tab = Tab()
        tab.children = [status, VBox([scale_status, accordion])]
        tab.set_title(0, "Status")
        tab.set_title(1, "Scaling")

        self._cached_widget = tab

        def update():
            status.value = self._repr_html_()
            scale_status.value = self._scaling_status()

        cluster_repr_interval = parse_timedelta(
            dask.config.get("distributed.deploy.cluster-repr-interval",
                            default="ms"))
        pc = PeriodicCallback(update, cluster_repr_interval * 1000)
        self.periodic_callbacks["cluster-repr"] = pc
        pc.start()

        return tab
Example #7
0
        print("Successfully convert images to " + videoNameText.value + '.mp4')

    except Exception as ex_results:
        print('Error: ', ex_results)


cvtBtn.on_click(convert_btn_clicked)

tab1_items = [
    Box([
        Label(value="Images Folder:", layout=Layout(width='200px')),
        imgsDicText
    ]),
    Box([
        Label(value="Video Name:", layout=Layout(width='200px')), videoNameText
    ]),
    Box([
        Label(value="Frames Per Second:", layout=Layout(width='200px')),
        fpsSlider
    ]),
    Box([cvtBtn])
]
tab1Box = VBox(tab1_items)

tab_nest = Tab()
tab_nest.children = [tab0Box, tab1Box]
tab_nest.set_title(0, 'Download')
tab_nest.set_title(1, 'ImgsToVideo')

display(tab_nest)
Example #8
0
def interface(f):
    
    try:
        with open(f.selected, "r") as file:
            data = json.loads(file.read(), cls=MontyDecoder)
    except FileNotFoundError:
        return "Please select an existing file."
    
    print("NKPTS = " + str(data["n_kpoints"]) + "\tNBANDS = " + str(data["nbands"]))
    timing_list = data["timing_list"]
    
    try:
        assert isinstance(timing_list, list)
    except AssertionError:
        return "timing_list is not a List. Please check your input file."

    nodes_list = list(set([t["nodes"] for t in timing_list]))
    nodes_list.sort()

    kpar_list = list(set([t["kpar"] for t in timing_list]))
    kpar_list.sort()

    ncore_list = list(set([t["ncore"] for t in timing_list]))
    ncore_list.sort()
    
    select_layout = Layout(width='70px')

    versus = Select(options=["NODES", "KPAR"], index=0,
                    layout=select_layout)
    nodes = Select(options=nodes_list, index=0,
                   layout=select_layout)
    x_axis_select = Select(options=["NCORE", "NPAR"], index=0, 
                           layout=select_layout)
    nodes_select = SelectMultiple(options=nodes_list,
                                  value=nodes_list[:3],
                                  rows=len(nodes_list),
                                  layout=select_layout)
    kpar_select = SelectMultiple(options=kpar_list,
                                 value=kpar_list[:3],
                                 rows=len(kpar_list),
                                 layout=select_layout)
    ncore_select = SelectMultiple(options=ncore_list,
                                  value=ncore_list[:3],
                                  rows=len(ncore_list),
                                  layout=select_layout)
    is_hybrid = Checkbox(value=False,
                      description="Hybrid?")

    widget_mappings = {
        "Timestep": {
            "descriptions": ["X-axis", ],
            "input": (versus, ),
            "output": interactive_output(
                time_plot, {"timing_list": fixed(timing_list),
                            "versus": versus}
            )
        },
        "Chessboard": {
            "descriptions": ["Nodes", "X-axis", "Hybrid"],
            "input": (nodes, x_axis_select, is_hybrid),
            "output": interactive_output(
                chessboard_plot, {"data": fixed(data),
                                  "nodes": nodes, 
                                  "x_axis": x_axis_select,
                                  "is_hybrid": is_hybrid}
            )
        },
        "Tetris": {
            "descriptions": ["Nodes", "KPAR", "NCORE", "Hybrid"],
            "input": [nodes_select, kpar_select, ncore_select, is_hybrid],
            "output": interactive_output(
                tetris_plot, {"data": fixed(data),
                              "nodes_choices": nodes_select,
                              "kpar_choices": kpar_select,
                              "ncore_choices": ncore_select,
                              "is_hybrid": is_hybrid}
            )
        },
        "Optimal": {
            "descriptions": [],
            "input": (),
            "output": interactive_output(
                optimal_settings, {"timing_list": fixed(timing_list)}
            )
        },
#         "NPAR line plot": {
#             "descriptions": ["Nodes", ],
#             "input": (nodes, ),
#             "output": interactive_output(
#                 npar_line_plot, {"timing_list": fixed(timing_list),
#                                 "nodes": nodes}
#             )
#         },
#         "NCORE line plot": {
#             "descriptions": ["Nodes", ],
#             "input": (nodes, ),
#             "output": interactive_output(
#                 ncore_line_plot, {"timing_list": fixed(timing_list),
#                                   "nodes": nodes}
#             )
#         }
    }

    tab = Tab()
    tab.children = [VBox((HBox([VBox((Button(description=desc, layout=select_layout), inp)) 
                                if desc != "Hybrid" else inp for (desc, inp) in zip(w["descriptions"], w["input"])]), w["output"])) 
                    for w in widget_mappings.values()]

    for i, title in enumerate(widget_mappings.keys()):
        tab.set_title(i, title)
    
    return tab
Example #9
0
    def display(self,
                states,
                shapes,
                mapping,
                tree,
                height=600,
                tree_width=250,
                cad_width=800,
                quality=0.5,
                axes=True,
                axes0=True,
                grid=True,
                ortho=True,
                transparent=False,
                position=None,
                rotation=None,
                zoom=None,
                mac_scrollbar=True):

        if platform.system() != "Darwin":
            mac_scrollbar = False

        # Output widget
        output_height = height * 0.4 - 20 + 2
        self.info = Info(tree_width, output_height - 6)

        self.info.html.add_class("scroll-area")
        if mac_scrollbar:
            self.info.html.add_class("mac-scrollbar")

        self.output = Box([self.info.html])
        self.output.layout = Layout(height="%dpx" % output_height,
                                    width="%dpx" % tree_width,
                                    overflow_y="scroll",
                                    overflow_x="scroll")

        self.output.add_class("view_output")

        ## Threejs rendering of Cadquery objects
        self.cq_view = CadqueryView(width=cad_width,
                                    height=height,
                                    quality=quality,
                                    default_mesh_color=self.default_mesh_color,
                                    default_edge_color=self.default_edge_color,
                                    info=self.info)

        for shape in shapes:
            self.cq_view.add_shape(shape["name"], shape["shape"],
                                   shape["color"])
        renderer = self.cq_view.render(position, rotation, zoom)
        renderer.add_class("view_renderer")

        bb = self.cq_view.bb
        clipping = Clipping(self.image_path, self.output, self.cq_view,
                            tree_width)
        for normal in ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)):
            clipping.add_slider(bb.max * 1.2, -bb.max * 1.3, bb.max * 1.2,
                                0.01, normal)

        # Tree widget to change visibility
#       tree_height = height - output_height - 35
        tree_view = TreeView(image_paths=self.image_paths,
                             tree=tree,
                             state=states,
                             layout=Layout(height="%dpx" % (height * 0.6 - 25),
                                           width="%dpx" % (tree_width - 20)))
        tree_view.add_class("view_tree")
        tree_view.add_class("scroll-area")
        if mac_scrollbar:
            tree_view.add_class("mac-scrollbar")

        tree_view.observe(self.cq_view.change_visibility(mapping), "state")

        tab_contents = ['Tree', 'Clipping']
        tree_clipping = Tab(layout=Layout(height="%dpx" % (height * 0.6 + 20),
                                          width="%dpx" % tree_width))
        tree_clipping.children = [tree_view, clipping.create()]
        for i in range(len(tab_contents)):
            tree_clipping.set_title(i, tab_contents[i])
        tree_clipping.add_class("tab-content-no-padding")

        # Check controls to swith orto, grid and axis
        self.check_controls = [
            self.create_checkbox("axes", "Axes", axes,
                                 self.cq_view.toggle_axes),
            self.create_checkbox("grid", "Grid", grid,
                                 self.cq_view.toggle_grid),
            self.create_checkbox("zero", "@ 0", axes0,
                                 self.cq_view.toggle_center),
            self.create_checkbox("ortho", "Ortho", ortho,
                                 self.cq_view.toggle_ortho),
            self.create_checkbox("transparent", "Transparency", transparent,
                                 self.cq_view.toggle_transparent),
            self.create_checkbox("black_edges", "Black Edges", False,
                                 self.cq_view.toggle_black_edges),
        ]
        self.check_controls[-2].add_class("indent")

        # Set initial state
        self.cq_view.toggle_ortho(ortho)
        self.cq_view.toggle_axes(axes)
        self.cq_view.toggle_center(axes0)
        self.cq_view.toggle_grid(grid)
        self.cq_view.toggle_transparent(transparent)

        for obj, vals in states.items():
            for i, val in enumerate(vals):
                self.cq_view.set_visibility(mapping[obj], i, val)

        # Buttons to switch camera position
        self.view_controls = []
        for typ in CadqueryDisplay.types:
            if typ == "refit":
                tooltip = "Fit view"
            elif typ == "reset":
                tooltip = "Reset view"
            else:
                tooltip = "Change view to %s" % typ
            button = self.create_button(
                typ, self.cq_view.change_view(typ, CadqueryDisplay.directions),
                tooltip)
            self.view_controls.append(button)

        return HBox([
            VBox([HBox(self.check_controls[:-2]), tree_clipping, self.output]),
            VBox([
                HBox(self.view_controls + self.check_controls[-2:]), renderer
            ])
        ])
Example #10
0
    def init_dashboard(self):
        from bqplot import DateScale, LinearScale, DateScale, Axis, Lines, Figure, Tooltip
        from bqplot.colorschemes import CATEGORY10, CATEGORY20
        from bqplot.toolbar import Toolbar
        from ipywidgets import VBox, Tab
        from IPython.display import display
        from tornado import gen

        cpu_sx = LinearScale()
        cpu_sy = LinearScale()
        cpu_x = Axis(label='Time (s)', scale=cpu_sx)
        cpu_y = Axis(label='CPU Usage (%)',
                     scale=cpu_sy,
                     orientation='vertical')
        mem_sx = LinearScale()
        mem_sy = LinearScale()
        mem_x = Axis(label='Time (s)', scale=mem_sx)
        mem_y = Axis(label='Memory Usage (MB)',
                     scale=mem_sy,
                     orientation='vertical')
        thru_sx = LinearScale()
        thru_sy = LinearScale()
        thru_x = Axis(label='Time (s)', scale=thru_sx)
        thru_y = Axis(label='Data Processed (MB)',
                      scale=thru_sy,
                      orientation='vertical')

        colors = CATEGORY20
        tt = Tooltip(fields=['name'], labels=['Filter Name'])
        self.cpu_lines = {
            str(n): Lines(labels=[str(n)],
                          x=[0.0],
                          y=[0.0],
                          colors=[colors[i]],
                          tooltip=tt,
                          scales={
                              'x': cpu_sx,
                              'y': cpu_sy
                          })
            for i, n in enumerate(self.other_nodes)
        }
        self.mem_lines = {
            str(n): Lines(labels=[str(n)],
                          x=[0.0],
                          y=[0.0],
                          colors=[colors[i]],
                          tooltip=tt,
                          scales={
                              'x': mem_sx,
                              'y': mem_sy
                          })
            for i, n in enumerate(self.other_nodes)
        }
        self.thru_lines = {
            str(n): Lines(labels=[str(n)],
                          x=[0.0],
                          y=[0.0],
                          colors=[colors[i]],
                          tooltip=tt,
                          scales={
                              'x': thru_sx,
                              'y': thru_sy
                          })
            for i, n in enumerate(self.other_nodes)
        }

        self.cpu_fig = Figure(marks=list(self.cpu_lines.values()),
                              axes=[cpu_x, cpu_y],
                              title='CPU Usage',
                              animation_duration=50)
        self.mem_fig = Figure(marks=list(self.mem_lines.values()),
                              axes=[mem_x, mem_y],
                              title='Memory Usage',
                              animation_duration=50)
        self.thru_fig = Figure(marks=list(self.thru_lines.values()),
                               axes=[thru_x, thru_y],
                               title='Data Processed',
                               animation_duration=50)

        tab = Tab()
        tab.children = [self.cpu_fig, self.mem_fig, self.thru_fig]
        tab.set_title(0, 'CPU')
        tab.set_title(1, 'Memory')
        tab.set_title(2, 'Throughput')
        display(tab)

        perf_queue = Queue()
        self.exit_perf = Event()

        def wait_for_perf_updates(q, exit, cpu_lines, mem_lines, thru_lines):
            while not exit.is_set():
                messages = []

                while not exit.is_set():
                    try:
                        messages.append(q.get(False))
                    except queue.Empty as e:
                        time.sleep(0.05)
                        break

                for message in messages:
                    filter_name, time_val, cpu, mem_info, processed = message
                    mem = mem_info[0] / 2.**20
                    vmem = mem_info[1] / 2.**20
                    proc = processed / 2.**20
                    cpu_lines[filter_name].x = np.append(
                        cpu_lines[filter_name].x, [time_val.total_seconds()])
                    cpu_lines[filter_name].y = np.append(
                        cpu_lines[filter_name].y, [cpu])
                    mem_lines[filter_name].x = np.append(
                        mem_lines[filter_name].x, [time_val.total_seconds()])
                    mem_lines[filter_name].y = np.append(
                        mem_lines[filter_name].y, [mem])
                    thru_lines[filter_name].x = np.append(
                        thru_lines[filter_name].x, [time_val.total_seconds()])
                    thru_lines[filter_name].y = np.append(
                        thru_lines[filter_name].y, [proc])

        for n in self.other_nodes:
            n.perf_queue = perf_queue

        self.perf_thread = Thread(target=wait_for_perf_updates,
                                  args=(perf_queue, self.exit_perf,
                                        self.cpu_lines, self.mem_lines,
                                        self.thru_lines))
        self.perf_thread.start()
Example #11
0
def resetSpGCheckBoxes(b):
    for k in spgSelector:
        if type(k) == int:
            spgSelector[k].value = False
    spgSelector[1].value = True


spgSelector['reset'].on_click(resetSpGCheckBoxes)

spgSelectorLayout = HBox([
    VBox([spgSelector[i] for i in range(1, 6)]),
    VBox([spgSelector[i] for i in range(6, 11)]),
    VBox([spgSelector[i] for i in [11, 21, 31, 'which', 'reset']])
])

bottLine = HBox([AOGenus, ATspecies, spgSelectorLayout])

startEnd = IntRangeSlider(value=[1, 10],
                          min=1,
                          max=10,
                          step=1,
                          description='Ranks')

aggWidg = VBox([topRowGroup, midLine, bottLine, startEnd])

kind = Tab()
kind.children = [aggWidg, unaggWidg]
for i, name in enumerate(['Aggregated', 'Unaggregated']):
    kind.set_title(i, name)
                          'left': 80,
                          'right': 20
                      })
run_viewmodel({'new': 0.})
UI_model = VBox([
    HBox(UI_viewcontrol, layout=Layout(width='1000px')),
    HBox([fig_bar]),
    HBox([fig_line])
])  # specifies the length of the lhs of the interface
#UI_model = HBox([loading_html])

# END OF ************************************************************************************************************** Build bar charts (use of bqp)  ***********************

tab = Tab()
#tab.children = [UI_model, UI_sec_input]
tab.children = [UI_model]
tab.set_title(0, 'Portfolio Optimizer')
#tab.set_title(1, 'Settings')
#tab.set_title(2, 'Reference Data')


def updatedseclist(obj=None):
    if obj['old'] == 1:
        save_settings()
        solve_intial_opt_weight()
        run_viewmodel({'new': 0.})


# START OF ************************************************************************************************************** (use of bqcde)  ***********************

#import bqcde #Requires Bloomberg's Database and is henceforth unaccessible to us. AND BELOW...interal portfolio thing
Example #13
0
    def __init__(self, *args, **kwargs):

        self.progress_callback = self.set_progress

        super().__init__(progress_callback=self.progress_callback,
                         *args,
                         **kwargs)

        fc = FileChooser()
        fc.show_only_dirs = True
        fc.default_path = tempfile.gettempdir()

        self.ms_storage_path = fc

        self.ms_upload = FileUpload()

        self.peaklist_files_button = FileUpload(description='Peaklists',
                                                accept='csv,xlsx',
                                                multiple=False)

        self.peaklist_files_button.observe(self.load_peaklist, names='value')

        self.load_ms_button = Button(description='Load MS-files')

        self.load_ms_button.on_click(self.search_files)

        self.detect_peaks_button = Button(description="Detect Peaks")
        self.detect_peaks_button.on_click(self.detect_peaks)

        self.message_box = Textarea(
            value='',
            placeholder='Please select some files and click on Run.',
            description='',
            disabled=True,
            layout={
                'width': '90%',
                'height': '500px',
                'font_family': 'monospace'
            })

        self.run_button = Button(description="Run")
        self.run_button.on_click(self.run)
        self.run_button.style.button_color = 'lightgray'

        self.optimize_rt_button = Button(description="Find closest peaks")
        self.optimize_rt_button.on_click(self.action_optimize_rt)

        self.download_button = Button(description="Export")
        self.download_button.on_click(self.export_action)
        self.download_button.style.button_color = 'lightgray'

        self.progress_bar = Progress(min=0,
                                     max=100,
                                     layout=Layout(width='90%'),
                                     description='Progress:',
                                     bar_style='info')

        self.output = widgets.Output()

        tabs = Tab()
        tabs.children = [
            HBox([self.ms_storage_path, self.ms_upload, self.load_ms_button]),
            HBox([
                self.peaklist_files_button, self.detect_peaks_button,
                self.optimize_rt_button
            ]),
        ]

        tabs.set_title(0, 'MS-Files')
        tabs.set_title(1, 'Peaklists')

        self.layout = VBox([
            tabs, self.message_box,
            HBox([self.run_button, self.download_button]), self.progress_bar
        ])