Beispiel #1
0
 def _update_metric_table(self):
     if not hasattr(self.plotting_data_metrics, 'empty'):
         return None
     if not self.plotting_data_metrics.empty:
         if self.analysis_variant == 'UV':
             _fillers = list(self.plotting_data_metrics.values.ravel())
             _stat_fillers = _fillers[:26]
             _corr_fillers = _fillers[26:]
             stat_summaryPane = pn.Tabs(('Stat:X1', pn.pane.HTML(table_html_1.format(*_stat_fillers), width=300)),
                                        margin=(5, 5, 5, 5), width=300)
         elif self.analysis_variant == 'BV':
             _fillers = list(self.plotting_data_metrics.values.ravel())
             _x1stat_fillers = _fillers[:26]
             _ystat_fillers = _fillers[26:52]
             _corr_fillers = _fillers[52:]
             stat_summaryPane = pn.Tabs(('Corr:X1-Y', pn.pane.HTML(table_html_2.format(*_corr_fillers), width=300)),
                                        ('Stat:X1', pn.pane.HTML(table_html_1.format(*_x1stat_fillers), width=300)),
                                        ('Stat:Y', pn.pane.HTML(table_html_1.format(*_ystat_fillers), width=300)),
                                         margin=(5, 5, 5, 5), width=300)
         elif self.analysis_variant == 'TV' and all(k in self.plotting_data.columns for k in ['plotX1', 'plotY', 'plotX2']):
             _fillers = list(self.plotting_data_metrics.values.ravel())
             _x1stat_fillers = _fillers[:26]
             _x2stat_fillers = _fillers[26:52]
             _ystat_fillers = _fillers[52:78]
             _corryx1_fillers = _fillers[78:129]
             _corryx2_fillers = _fillers[129:]
             stat_summaryPane = pn.Tabs(('Corr:X1-Y', pn.pane.HTML(table_html_2.format(*_corryx1_fillers), width=300)),
                                        ('Corr:X2-Y', pn.pane.HTML(table_html_2.format(*_corryx2_fillers), width=300)),
                                        ('Stat:X1', pn.pane.HTML(table_html_1.format(*_x1stat_fillers), width=300)),
                                        ('Stat:X2', pn.pane.HTML(table_html_1.format(*_x2stat_fillers), width=300)),
                                        ('Stat:Y', pn.pane.HTML(table_html_1.format(*_ystat_fillers), width=300)),
                                         margin=(5, 5, 5, 5), width=300)
         return stat_summaryPane
    def view(self):

        desc = """This is a demonstration dashboard with incomplete functionality. Its purpose
        is to sit here and look pretty. We can put graphics and stuff in here to
        make it look all fancy."""

        logo = ".\images\logo_panel_stacked_s.png"

        button_desc = """The <i>Run</i> button will execute the spatial intersection and generate
        a table of identifiers found within each box and in multiple boxes.<br><br>
        Push the <i>Run</i> button after configuring all inputs and drawing boxes on the map."""

        return pn.Row(
            pn.Column("## Description", desc, logo),
            pn.Column(
                "### Configure Inputs",
                pn.Tabs(
                    ("Input 1", self.input1),
                    ("Input 2", self.input2),
                    ("Input 3", self.input3),
                    ("Input 4", self.input4),
                    ("Input 5", self.input5),
                ),
                button_desc,
                self.param.run_analysis,
            ),
            pn.Tabs(
                ("Map View", pn.Column(self.mapview.show_map())),
                ("Results Table", self.summary_pane),
            ),
        )
Beispiel #3
0
def analyze_adv(adv_data, real_data, targets, channel_labels, data_labels=None):

    dde = DashboardDataElements(name='')
    dashboard_title = '### Adversarial Data Analysis'
    dashboard_desc = 'Debuging NNs Facing Adversarial Data'

    
    if is_image:
        data = [((next(iter(in_distrbution_sample))[0]))]
        for i in samples:
            data.append(((next(iter(i))[0])))
            
        print("Generating Graph Layout...")

        tabs = []
        for i, label in zip(data, data_labels):
            i = sum(i)/len(i)
            i = i.permute(1,2,0).cpu().detach().numpy()
            tabs.append((label,pn.Column(dde.pixel_dist_img(i),
                                         dde.color_dist_img(i), )))
                                         #dde.multi_dem_color_hist(i))))
                
        dashboard = pn.Column(dashboard_title,dashboard_desc, dde.param,  pn.Tabs(*tabs))
        print("Conducting the following comparisions for image data: Color distribution, Pixel distribution, and Variance of laplacian operators")
    
    else:
        print("Conducting the following comparisions for signal data: Min/Max/Mean/StDev, Energy, and Power")
        assert(signal_frequency is not None), "Signal Frequency cannot be None"
        
        data = [((next(iter(in_distrbution_sample))[0]))]
        for i in samples:
            data.append(((next(iter(i))[0])))
            
        print("Generating Graph Layout...")

        tabs = []
        for i, label in zip(data, data_labels):
            i = sum(i)/len(i)
            i = i.cpu().detach().numpy()
            tabs.append((label,pn.Column(dde.plt_energy_spec(i,signal_frequency,channel_labels), 
                                         dde.plt_power_spec(i,signal_frequency,channel_labels), 
                                         dde.mean_plot(i,channel_labels), dde.min_plot(i,channel_labels), 
                                         dde.max_plot(i,channel_labels), dde.stdev_plot(i,channel_labels) )))
                
        dashboard = pn.Column(dashboard_title,dashboard_desc, dde.param,  pn.Tabs(*tabs))

    

    # display the dashboard, with all elements and data embedded so 
    # no 'calls' to a data source are required
    dashboard.show()
    
def get_dashboard(tickers_dict={
    "index": [],
    "crypto": []
},
                  years=2,
                  mc_trials=500,
                  mc_sim_days=252,
                  weights=None):

    data = get_assets_hist_data(tickers_dict=tickers_dict, years=years)

    mc_sim = mc.monte_carlo_sim(data[0],
                                trials=mc_trials,
                                sim_days=mc_sim_days,
                                weights=weights)
    #reset variables to clean old data remanents
    years, mc_trials, mc_sim_days, weights = 2, 500, 252, None
    if type(mc_sim) == str: print(mc_sim)

    risk_tabs = pn.Tabs(
        ("Correlation of portfolio", corr_plot(data[1])),
        ("Sharp Ratios", sharp_rt_plot(data[1])),
        #background="whitesmoke"
    )

    montecarlo_tabs = pn.Tabs(
        ("monte Carlo Simulation", plot_mont_carl(mc_sim)),
        ("Confidence Intervals",
         plot_conf(mc_sim.iloc[-1], get_conf_interval(mc_sim.iloc[-1]))),
        #background="whitesmoke"
    )

    techl_analysis_tabs = pn.Tabs(
        ("TA1", "in construction"),
        ("TA2", "in construction"),
        #background="whitesmoke"
    )

    tabs = pn.Tabs(
        ("Risk", risk_tabs),
        ("Monte Carlo Simulation", montecarlo_tabs),
        ("Tecnical Analysis", techl_analysis_tabs),
        ("Report", "in construction"),
        #background="whitesmoke",
        tabs_location="left",
        align="start")

    panel = tabs

    return panel
Beispiel #5
0
    def __init__(self, graphmgr_addr):
        self.graphmgr_addr = graphmgr_addr
        self.ctx = zmq.asyncio.Context()

        self.export = self.ctx.socket(zmq.SUB)
        self.export.setsockopt_string(zmq.SUBSCRIBE, "")
        self.export.connect(self.graphmgr_addr.comm)

        self.lock = asyncio.Lock()
        self.plot_metadata = {}
        self.plots = {}
        self.tasks = {}

        logo = 'https://www6.slac.stanford.edu/sites/www6.slac.stanford.edu/files/SLAC_LogoSD_W.png'
        self.template = pn.template.ReactTemplate(title='AMI',
                                                  header_background='#8c1515',
                                                  logo=logo)

        self.enabled_plots = pn.widgets.CheckBoxGroup(name='Plots', options=[])
        self.enabled_plots.param.watch(self.plot_checked, 'value')
        self.latency_lbls = pn.Column()
        self.tab = pn.Tabs(('Plots', self.enabled_plots),
                           ('Latency', self.latency_lbls),
                           dynamic=True)
        self.sidebar_col = pn.Column(self.tab)
        self.template.sidebar.append(self.sidebar_col)

        self.layout_widgets = {}
        self.layout = self.template.main
        for r in range(0, 12, row_step):
            for c in range(0, 12, col_step):
                col = pn.Column()
                self.layout_widgets[(r, c)] = col
                self.layout[r:r + row_step, c:c + col_step] = col
Beispiel #6
0
    def render_pane(self, config):
        general = General.from_config(config)
        log = Logfile(general.get_log_output(config))

        General_Tabs = []
        if "queue info" in config["general"]:
            queue_info = ("Queue Information", general.queue_info())
            General_Tabs.append(queue_info)
        if "run efficiency" in config["general"]:
            run_efficiency = (
                "Run Statistics",
                pn.Row(log.run_stats(), log.run_gauge()),
            )
            General_Tabs.append(run_efficiency)
        if "disk usage" in config["general"]:
            disk_usage = ("Disk Usage", general.plot_usage(config))
            General_Tabs.append(disk_usage)
        if "simulation timeline" in config["general"]:
            pass  # NotYetImplemented
        if "progress bar" in config["general"]:
            progress_bar = ("Progress Bar", general.progress_bar(config, log))
            General_Tabs.append(progress_bar)
        if "newest log" in config["general"]:
            latest_log = ("Newest Logfile",
                          general.get_logfile_by_time(config))
            General_Tabs.append(latest_log)

        return pn.Tabs(*General_Tabs)
Beispiel #7
0
    def panel(self):
        map_panel = pn.Column(
            self.view_map,
            pn.panel(self.param, parameters=['create'], show_name=False))
        # display_tab = pn.Column(
        #                         pn.panel(self.adh_mod.wmts.param, parameters=['source'], expand_button=False),
        #                         pn.pane.Markdown('Visibility', style={'font-family':'Arial'}),
        #                         pn.panel(self.adh_mod.param, parameters=['viewable_points'], show_name=False),
        #                         self.adh_mod.param.viewable_polys
        #                         )

        display_tab = pn.Column(
            pn.panel(self.adh_mod.wmts.param,
                     parameters=['source'],
                     expand_button=False,
                     show_name=False))

        # data_tab = pn.Tabs(('Polygons', self.adh_mod.poly_table), ('Points', self.adh_mod.point_table), name='View Data')

        import_tab = pn.Column(
            pn.panel(self.param,
                     parameters=['point_file', 'poly_file'],
                     show_name=False),
            pn.panel(self.import_projection, show_name=False),
            pn.panel(self.param, parameters=['load_data'], show_name=False))

        logo_box = pn.Spacer()

        tool_panel = pn.Column(
            pn.Tabs(('Conceptual Model', self._data_tab),
                    ('Display', display_tab)), logo_box)

        main = pn.Column(pn.Row(map_panel, tool_panel), self.status_bar.panel)

        return main
Beispiel #8
0
def getAppEditMode(doc):
    vizAppList = getVizAppList(doc)
    profileList = []
    layout = pn.Column()
    tabs = None

    for vizAppElement in vizAppList:
        # profileList.append(vizAppElement.trace.dataProfileApp())
        tabs = pn.Tabs((vizAppElement.title, vizAppElement.view))
        for trace in vizAppElement.traces:
            traceParam = vizAppElement.getTraceParamByTrace(trace)
            tabs.append(
                (trace.name,
                 pn.Row(pn.Column(traceParam.viewProgress, traceParam.view),
                        traceParam.panel)))
            # tabs.link(vizAppElement.traceSelector, callbacks={'value': tabSelectioncallback})

        tabs.append(('Config Viz', vizAppElement.getConfigVizPanel))

        tabs.append(('Debug Viz', vizAppElement.getDebugPanel))

        row = pn.Row(tabs)
        layout.append(row)

    for profile in profileList:
        pass

    layout.server_doc(doc)
Beispiel #9
0
 def show(self):
     s = pn.Column(self.surveyControl, pn.pane.Markdown(f"# {self.surveyTitle}"), f"{self.surveyDesc}", sizing_mode='stretch_both')
     tabs = pn.Tabs()
     for tab in self.tabs:
         tabs.append(tab.show())
     s.append(tabs)
     return s
Beispiel #10
0
 def figure(self):
     if self.nvars == 1:
         cmap = self.all_selectors[0].cmap
         return self.ds.hvplot.quadmesh('longitude',
                                        'latitude',
                                        self.query['var1'],
                                        title=self.query['var1'],
                                        geo=True,
                                        cmap=cmap,
                                        projection=ccrs.PlateCarree(),
                                        crs=ccrs.PlateCarree(),
                                        coastline=True,
                                        width=800,
                                        rasterize=True)
     figures = []
     for i in range(1, self.nvars + 1):
         v = self.v(i)
         cmap = self.all_selectors[i - 1].cmap
         f = self.ds.hvplot.quadmesh(f'longitude_{i}',
                                     f'latiitude_{i}',
                                     v,
                                     title=v,
                                     geo=True,
                                     projection=ccrs.PlateCarree(),
                                     crs=ccrs.PlateCarree(),
                                     coastline=True,
                                     cmap=cmap,
                                     width=800,
                                     rasterize=True)
         figures.append((v, f))
     return pn.Tabs(*figures)
Beispiel #11
0
 def build_tool_pane(self, logo=None):
     if logo:
         logo_box = pn.panel(logo, width=300)
     else:
         logo_box = pn.Spacer()
     # self.tool_pane = pn.Column(pn.Tabs(*self.tabs, *self.bc_ui.tabs), logo_box)
     self.tool_pane = pn.Column(pn.Tabs(*self.tabs), logo_box)
Beispiel #12
0
    def view(self):
        layout = pn.Tabs()
        plot = None
        if self.liste_des_sources:
            plot = self.liste_des_sources.plot.graphique_default()

            plot.opts(toolbar='above',
                      default_tools=['box_select', 'wheel_zoom', 'reset'],
                      active_tools=['tap', 'wheel_zoom'])

            layout.append(
                ('Graphique', pn.Row(plot, sizing_mode='stretch_width')))

            dataTable = self.liste_des_sources._dataframe
            if hvplot.util.is_geodataframe(dataTable):
                dataTable = pd.DataFrame(dataTable.drop(['geometry'], axis=1))

            table = hv.Table(dataTable,
                             sizing_mode='stretch_width').opts(height=650,
                                                               width=1500)

            layout.append(('Table', pn.Row(table)))
            if len(plot) == len(table):
                DataLink(plot, table)
            return layout
        else:
            layout = pn.Column(pn.pane.HTML(f'Aucun catalogue disponible'),
                               sizing_mode='stretch_width')
            return layout
Beispiel #13
0
def build_dashboard_google_trends_btc(
                                        price_curve_btc,
                                        cumulative_return_curve_btc, 

                                        google_predicted_positive_return_curve_btc, 
                                        google_cumulative_return_plot_btc
):

    '''
    Make panel layout for Google Trends BTC
    Returns: Panel layout
    '''
    # Content for tab_one
    tab_one = pn.Column(
        price_curve_btc,
        cumulative_return_curve_btc
    )
    

    # Content for tab_two
    tab_two = pn.Column(
        google_predicted_positive_return_curve_btc,
        google_cumulative_return_plot_btc
    )
    
    # Combined dashboard of all tabs
    dashboard_google_trends_btc = pn.Tabs(
        ('General Insights', tab_one),
        ('RNN Strategy', tab_two),
    )
    
    return dashboard_google_trends_btc
Beispiel #14
0
 def get_panel(self):
     """Return tabs with widgets to interact with the flow."""
     tabs = pn.Tabs()
     app = tabs.append
     #row = pn.Row(bkw.PreText(text=self.ddb.to_string(verbose=self.verbose.value), sizing_mode="scale_both"))
     app(("Status", pn.Row(self.status_btn, self.on_status_btn)))
     app(("History", pn.Row(self.history_btn, self.on_history_btn)))
     app(("Events", pn.Row(self.events_btn, self.on_events_btn)))
     app(("Corrections",
          pn.Row(self.corrections_btn, self.on_corrections_btn)))
     app(("Handlers", pn.Row(self.handlers_btn, self.on_handlers_btn)))
     app(("Structures",
          pn.Row(
              pn.Column(self.structures_io_checkbox, self.structures_btn),
              self.on_structures_btn)))
     ws = pn.Column(self.ebands_plotter_mode, self.ebands_ksamp_checkbox,
                    self.ebands_df_checkbox, self.ebands_plotter_btn)
     app(("Ebands", pn.Row(ws, self.on_ebands_btn)))
     app(("Abivars",
          pn.Row(pn.Column(self.vars_text, self.vars_btn),
                 self.on_vars_btn)))
     app(("Dims", pn.Row(pn.Column(self.dims_btn), self.on_dims_btn)))
     app(("Debug", pn.Row(self.debug_btn, self.on_debug_btn)))
     app(("Graphviz",
          pn.Row(pn.Column(self.engine, self.dirtree, self.graphviz_btn),
                 self.on_graphviz_btn)))
     return tabs
Beispiel #15
0
def view():
    """Returns a view of the app

    Used by the awesome-panel.org gallery"""
    style = pn.pane.HTML(STYLE, width=0, height=0, sizing_mode="fixed", margin=0)
    panel_logo = pn.pane.PNG(
        object="https://panel.holoviz.org/_static/logo_horizontal.png",
        height=35,
        sizing_mode="fixed",
        align="center",
    )
    app_bar = pn.Row(
        pn.layout.VSpacer(width=10),
        pn.pane.Markdown("### 💪 JS Actions", align="center"),
        panel_logo,
        background="black",
        css_classes=["app-bar"],
        margin=(0, 0, 25, 0),
    )
    example_tabs = pn.Tabs(copy_to_clipboard())
    info = pn.pane.Markdown(__doc__)
    return pn.Column(
        info,
        style,
        app_bar,
        example_tabs,
    )
Beispiel #16
0
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.displayer = Display(self.data)
        self.describer = Describe(self.data)
        self.fields = Fields(self.data)
        self.style = Style()
        self.coord_setter = CoordSetter(self.data)
        self.tabs = pn.Tabs(
            pn.Row(self.displayer.panel, self.describer.panel,
                   name='Variables', width_policy='max'),
            self.coord_setter.panel,
            self.fields.panel,
            self.style.panel,
            background='#f5f5f5',
            width_policy='max',
            margin=20
        )

        if has_cartopy:
            from .projection import Projection
            self.projection = Projection()
            self.tabs.append(self.projection.panel)
            self.fields.connect('x', self.check_is_projectable)
            self.fields.connect('y', self.check_is_projectable)

        self.displayer.connect("variable_selected", self.describer.setup)
        self.displayer.connect("variable_selected", self.fields.setup)
        self.displayer.connect("variable_selected", self.style.setup)

        self.panel = pn.WidgetBox(self.tabs, width_policy='max')
    def calibrate_sensor(self):
        widgets = pn.WidgetBox(
            '<b>Load a projector calibration file</b>',
            self._widget_json_filename_load_projector,
            self._widget_json_load_projector,
            '<b>Distance from edges (pixel)</b>',
            self._widget_s_top,
            self._widget_s_right,
            self._widget_s_bottom,
            self._widget_s_left,
            #self._widget_s_enable_auto_cropping,
            #self._widget_s_automatic_cropping,
            pn.layout.VSpacer(height=5),
            '<b>Distance from sensor (mm)</b>',
            self._widget_s_min,
            self._widget_s_max,
            self._widget_refresh_frame)
        box = pn.Column(
            '<b>Physical dimensions of the sandbox</b>',
            self._widget_box_width,
            self._widget_box_height,
        )
        save = pn.Column('<b>Save file</b>', self._widget_json_filename,
                         self._widget_json_save)

        rows = pn.Row(widgets, self.calib_notebook_frame)
        panel = pn.Column('## Sensor calibration', rows)
        tabs = pn.Tabs(('Calibration', panel), ("Box dimensions", box),
                       ("Save files", save))
        return tabs
Beispiel #18
0
    def show_widgets(self):
        widget = pn.Column(self._widget_activate_gradient_descend,
                           self._widget_optimum,
                           self._widget_speed_gradient_descend,
                           "<b>Frame controller</b>",
                           self._widget_activate_frame_capture,
                           self._widget_refresh_frame)

        column = pn.Column(
            "#Simulation options", self._widget_selector,
            self._widget_search_active, "<b>Controllers</b>",
            self._widget_sleep, self._widget_margins_crop,
            "<b>Visualization options</b>", self._widget_plot_points,
            self._widget_plot_contour, "<b>Modify constants</b> ",
            self._widget_variance, self._widget_number_samples,
            "<b>Adaptive options</b>", self._widget_memory_steps,
            "<b> Hamiltonian options", self._widget_leapfrog_step,
            self._widget_leapfrog_points)
        histogram = pn.WidgetBox(self._widget_histogram_refresh,
                                 self.histogram)
        row = pn.Row(column, widget)

        tabs = pn.Tabs(
            ('Controllers', row),
            ("Histogram plot", histogram),
        )

        return tabs
Beispiel #19
0
    def panel(self, debug=False):

        title = pn.pane.Markdown('# Search MAST for Moving Targets')
        row1 = pn.Row(self.obj_name, self.id_type)
        row2 = pn.Row(self.start_time, self.stop_time, self.time_step)
        button_row = pn.Row(self.param['ephem_button'],
                            self.param['tap_button'])
        output_tabs = pn.Tabs(
            ('Ephemerides', pn.Column(self.eph_col_choice, self.get_ephem)),
            ('MAST Results', pn.Column(self.mast_col_choice, self.get_mast)),
            ('MAST Plot', self.mast_figure))
        if debug:
            output_tabs.append(('Debug', self.fetch_stcs))

        gspec = pn.GridSpec(width=800, height=400)
        gspec[:1, :3] = title
        gspec[2, :3] = row1
        gspec[3, :3] = row2
        gspec[4, :3] = button_row
        gspec[5, :3] = output_tabs
        '''
        mypanel = pn.Column(title, pn.layout.Divider(),
                            row1, row2, button_row,
                            output_tabs)'''
        return gspec
Beispiel #20
0
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.displayer = Display(self.data)
        self.describer = Describe(self.data)
        self.fields = Fields(self.data)
        self.style = Style()
        self.coord_setter = CoordSetter(self.data)
        self.tabs = pn.Tabs(pn.Row(self.displayer.panel,
                                   self.describer.panel,
                                   name='Variables'),
                            self.coord_setter.panel,
                            self.fields.panel,
                            self.style.panel,
                            background=(240, 240, 240),
                            width=1160)

        if has_cartopy:
            from .projection import Projection
            self.projection = Projection()
            self.tabs.append(self.projection.panel)
            self.fields.connect('x', self.check_is_projectable)
            self.fields.connect('y', self.check_is_projectable)

        self.displayer.connect("variable_selected", self.describer.setup)
        self.displayer.connect("variable_selected", self.fields.setup)
        self.displayer.connect("variable_selected", self.style.setup)

        self.panel = pn.Column(self.tabs)
Beispiel #21
0
 def select_dataset(self):
     selectors = [
         pn.Param(selector, name=selector.name, width=450)
         for selector in self.all_selectors
     ]
     tabs = pn.Tabs(*selectors)
     return tabs
Beispiel #22
0
    def get_panel(self):
        """Build panel with widgets to interact with the structure either in a notebook or in a bokeh app"""
        tabs = pn.Tabs()
        app = tabs.append
        row = pn.Row(
            bkw.PreText(text=self.structure.to_string(verbose=self.verbose),
                        sizing_mode="scale_both"))
        app(("Summary", row))
        ws = pn.Column('# Spglib options', self.spglib_symprec,
                       self.spglib_angtol)
        app(("Spglib", pn.Row(ws, self.spglib_summary)))
        ws = pn.Column('# K-path options', self.kpath_format,
                       self.line_density)
        app(("Kpath", pn.Row(ws, self.get_kpath)))
        app(("Convert",
             pn.Row(pn.Column("# Convert structure", self.output_format),
                    self.convert)))
        app(("View",
             pn.Row(
                 pn.Column("# Visualize structure", self.viewer,
                           self.viewer_btn), self.view)))
        ws = pn.Column('# Generate GS input', self.gs_type, self.spin_mode,
                       self.kppra, self.gs_input_btn)
        app(("GS-input", pn.Row(ws, self.on_gs_input_btn)))
        app(("MP-match",
             pn.Row(pn.Column(self.mp_match_btn), self.on_mp_match_btn)))

        return tabs
Beispiel #23
0
 def panel(self):
     """
     
     """
     return pn.Tabs(("Annotate", self.labeler.panel()),
                    ("Model", self.modelpicker.panel()),
                    ("Train", self.trainmanager.panel()))
Beispiel #24
0
    def get_panel(self):
        """Return tabs with widgets to interact with the DDB file."""
        tabs = pn.Tabs()
        app = tabs.append
        row = pn.Row(
            bkw.PreText(text=self.ddb.to_string(verbose=self.verbose),
                        sizing_mode="scale_both"))
        app(("Summary", row))
        app(("Ph-bands",
             pn.Row(
                 pn.Column(
                     "# PH-bands options", *[
                         self.param[k]
                         for k in ("nqsmall", "ndivsm", "asr", "chneut",
                                   "dipdip", "lo_to_splitting", "dos_method")
                     ], self.temp_range, self.plot_phbands_btn),
                 self.plot_phbands_and_phdos)))
        app(("BECs",
             pn.Row(
                 pn.Column(
                     "# Born effective charges options", *[
                         self.param[k]
                         for k in ("asr", "chneut", "dipdip", "gamma_ev")
                     ], self.get_epsinf_btn), self.get_epsinf)))
        app(("eps0",
             pn.Row(
                 pn.Column(
                     "# epsilon_0", *[
                         self.param[k]
                         for k in ("asr", "chneut", "dipdip", "gamma_ev")
                     ], self.w_range, self.plot_eps0w_btn), self.plot_eps0w)))
        app(("Speed of sound",
             pn.Row(
                 pn.Column(
                     "# Speed of sound options",
                     *[self.param[k] for k in ("asr", "chneut", "dipdip")],
                     self.plot_vsound_btn), self.plot_vsound)))
        app(("Check ASR and DIPDIP",
             pn.Row(
                 pn.Column(
                     "# Options", *[
                         self.param[k]
                         for k in ("nqsmall", "ndivsm", "dos_method")
                     ], self.plot_check_asr_dipdip_btn),
                 self.plot_without_asr_dipdip)))

        app(("IFCs",
             pn.Row(
                 pn.Column(
                     "# Options",
                     *[self.param[k] for k in ("asr", "dipdip", "chneut")],
                     self.plot_ifc_btn), self.plot_ifc)))

        app(("Global Opts",
             pn.Column(
                 "# Global Options",
                 *[self.param[k] for k in ("units", "mpi_procs", "verbose")])))

        return tabs
Beispiel #25
0
    def report(self, show=False, **kwargs):
        '''
        Generates a PANEL object of interesting Model Stats and Data Info

        can be saved as HTML, PDF

        '''
        def get_df_info(df):
            import io
            buffer = io.StringIO()
            df.info(buf=buffer)
            s = buffer.getvalue()
            return s

        X = self.X
        app = pn.template.BootstrapTemplate(title="Model Report")
        pn.config.sizing_mode = "stretch_width"

        # Header
        app.header.header_background = 'blue'
        # app.header.append(pn.pane.Markdown("# Report"))
        # Side Bar

        #inputs = {f"{col}" : pnw.FloatSlider(name=col,start=X[col].min(), end=max(1,X[col].max()), value=X[col].median()) for col in X.columns}
        # for input in inputs:
        #    app.sidebar.append(inputs[input])

        # Main
        summary_df = self.summary().T

        preds = pd.DataFrame({
            "Actual": self.y.values.ravel(),
            "Predicted": self.predict(X=self.X).ravel()
        })
        act_vs_pred = preds.hvplot(x='Predicted',
                                   y='Actual',
                                   kind='scatter',
                                   title='Actual vs Predicted') * hv.Slope(
                                       1, 0).opts(color='red')
        summary = pn.Row(
            pn.Card(summary_df, title='Summary Statistics', height=500),
            pn.Card(act_vs_pred, title="Actual Vs Predicted", height=500))

        raw_data_page = pn.Row(
            pn.Card(pn.pane.Markdown(get_df_info(self.df)),
                    title='Data Info',
                    height=500),
            pn.Card(self.df.describe(), title='Data Stats', height=500))

        pages = pn.Tabs(('Summary', summary),
                        ('Raw Data Stats', raw_data_page),
                        ('Feature Importance', pn.panel("in work")))

        app.main.append(pages)
        if show:
            server = app.show("KJ's Model Anlaysis report", threaded=True)
            return (app, server)
        else:
            return app
Beispiel #26
0
    def render_pane(self, config):
        if config.get("use_hvplot"):
            all_timeseries = []
            for variable in config["echam"]["Global Timeseries"]:
                all_timeseries.append(plot_timeseries_with_stats(config, variable))
        else:
            all_timeseries = plot_global_timeseries(config)
        all_variable_names = list(config["echam"]["Global Timeseries"])
        names_and_ts = zip(all_variable_names, all_timeseries)

        all_climatologies = plot_global_climatology(config)
        all_variable_names = list(config["echam"]["Global Climatology"])
        names_and_clims = zip(all_variable_names, all_climatologies)
        return pn.Tabs(
            ("Timeseries", pn.Tabs(*names_and_ts)),
            ("Climatologies", pn.Tabs(*names_and_clims)),
        )
Beispiel #27
0
 def tabs_view(self):
     return pn.Tabs(
         ("Carte", self.map_view),
         ("Tableau", self.table_view),
         css_classes=[
             re.sub(r"(?<!^)(?=[A-Z])", "-", self.get_name() + "Tabs").lower()
         ],
     )
Beispiel #28
0
    def save_reports(self, reports, path, name):

        panel = pn.Tabs()
        self._dir = path
        if isinstance(reports, List):
            self._save_report_list(reports, panel)

        if isinstance(reports, Dict):
            for key in reports:
                pnl = pn.Tabs()
                self._save_report_list(reports[key], pnl)
                panel.append((key, pnl))

        panel.save(self._dir + "/" + name + self._extension,
                   resources=INLINE,
                   title="{} Report".format(name),
                   embed=True)
Beispiel #29
0
 def panel(self):
     return panel.Tabs(
         ("Database", self.db_manager.panel()),
         ("eee-cts", self.cts_loader.panel()),
         ("Parquet2sql",
          panel.Column(self.parquet.panel(), self.update_engine,
                       self.write_clicked)),
     )
Beispiel #30
0
    def build_loss_tab(self):
        # loss hists
        fig_loss_hists, ax_loss_hists = plt.subplots(1,
                                                     len(self.loss_keys),
                                                     figsize=(16 * 5, 9))
        unique_losses = self.dataset.base_data[
            ["filepath"] + self.loss_keys].drop_duplicates()
        for single_ax, key in zip(ax_loss_hists, self.loss_keys):
            single_ax.hist(unique_losses[key].values, bins=20)
            single_ax.set_title(" ".join(key.split("_")).title(), fontsize=40)
            for tick in single_ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(34)
                tick.label.set_rotation(45)
            for tick in single_ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(34)
        plt.tight_layout()
        plt.close()
        loss_hists_col = pn.pane.Matplotlib(fig_loss_hists, width=self.width)
        axis_cols = [
            'score', 'area_normalized', 'area', 'bbox_ratio', 'bbox_width',
            'bbox_height', 'num_annotations'
        ] + self.loss_keys + ['width', 'height']
        scatter_overview = scatter_plot_with_gui(
            self.dataset.base_data[self.dataset.base_data["is_prediction"] ==
                                   True],
            x_cols=axis_cols[1:] + [axis_cols[0]],
            y_cols=axis_cols,
            color_cols=["label", "num_annotations", "filename"])

        cat_2d_hist = categorical_2d_histogram_with_gui(
            self.dataset.base_data[self.dataset.base_data["is_prediction"] ==
                                   True],
            category_cols=["label", "num_annotations", "filename"],
            hist_cols=self.loss_keys + [
                'score', 'area_normalized', 'area', 'bbox_ratio', 'bbox_width',
                'bbox_height', 'num_annotations', 'width', 'height', 'label'
            ])

        try:
            gallery = ("Gallery",
                       RecordDastasetGallery(self.dataset,
                                             "base_data",
                                             "filepath",
                                             sort_cols=self.loss_keys,
                                             height=self.height).show())
        except FileNotFoundError:
            gallery = ("Gallery",
                       "Could not load images. Path might be wrong.")

        sub_tabs = pn.Tabs(("Histograms",
                            pn.Row(pn.Spacer(sizing_mode="stretch_width"),
                                   scatter_overview,
                                   pn.Spacer(sizing_mode="stretch_width"),
                                   cat_2d_hist,
                                   pn.Spacer(sizing_mode="stretch_width"),
                                   align="center")), gallery)

        return pn.Column(loss_hists_col, sub_tabs)