Beispiel #1
0
    def _init_doc(self, doc):
        self.doc = doc
        self.doc.title = "Explore Dashboard"
        with open(os.path.join(os.path.dirname(__file__), 'templates', 'index.html')) as f:
            index_template = Template(f.read())
        doc.template = index_template
        self.doc.theme = Theme(os.path.join(os.path.dirname(__file__), 'theme.yaml'))
        self._init_plots()
        m_widgetbox = self._init_controls()

        # Create tabs
        if self.mode == "signal":
            exg_tab = Panel(child=self.exg_plot, title="ExG Signal")
            orn_tab = Panel(child=column([self.acc_plot, self.gyro_plot, self.mag_plot], sizing_mode='scale_width'),
                            title="Orientation")
            fft_tab = Panel(child=self.fft_plot, title="Spectral analysis")
            self.tabs = Tabs(tabs=[exg_tab, orn_tab, fft_tab], width=400, sizing_mode='scale_width')
            self.recorder_widget = self._init_recorder()
            self.push2lsl_widget = self._init_push2lsl()
            self.set_marker_widget = self._init_set_marker()
            self.baseline_widget = CheckboxGroup(labels=['Baseline correction'], active=[0])

        elif self.mode == "impedance":
            imp_tab = Panel(child=self.imp_plot, title="Impedance")
            self.tabs = Tabs(tabs=[imp_tab], width=500, sizing_mode='scale_width')
        banner = Div(text=""" <a href="https://www.mentalab.com"><img src=
        "https://images.squarespace-cdn.com/content/5428308ae4b0701411ea8aaf/1505653866447-R24N86G5X1HFZCD7KBWS/
        Mentalab%2C+Name+copy.png?format=1500w&content-type=image%2Fpng" alt="Mentalab"  width="225" height="39">""",
                     width=1500, height=50, css_classes=["banner"], align='center', sizing_mode="stretch_width")
        heading = Div(text=""" """, height=2, sizing_mode="stretch_width")
        if self.mode == 'signal':
            layout = column([heading,
                             banner,
                             row(m_widgetbox,
                                 Spacer(width=10, height=300),
                                 self.tabs,
                                 Spacer(width=10, height=300),
                                 column(Spacer(width=170, height=50), self.baseline_widget, self.recorder_widget,
                                        self.set_marker_widget, self.push2lsl_widget),
                                 Spacer(width=50, height=300)),
                             ],
                            sizing_mode="stretch_both")

        elif self.mode == 'impedance':
            layout = column(banner,
                            Spacer(width=600, height=20),
                            row([m_widgetbox, Spacer(width=25, height=500), self.tabs])
                            )
        self.doc.add_root(layout)
        self.doc.add_periodic_callback(self._update_fft, 2000)
        self.doc.add_periodic_callback(self._update_heart_rate, 2000)
        if self.stream_processor:
            self.stream_processor.subscribe(topic=TOPICS.filtered_ExG, callback=self.exg_callback)
            self.stream_processor.subscribe(topic=TOPICS.raw_orn, callback=self.orn_callback)
            self.stream_processor.subscribe(topic=TOPICS.device_info, callback=self.info_callback)
            self.stream_processor.subscribe(topic=TOPICS.marker, callback=self.marker_callback)
            self.stream_processor.subscribe(topic=TOPICS.env, callback=self.info_callback)
            self.stream_processor.subscribe(topic=TOPICS.imp, callback=self.impedance_callback)
Beispiel #2
0
def get_nuts_map_data(request):
    p0 = get_nuts_map(0)
    p1 = get_nuts_map(1)
    p2 = get_nuts_map(2)
    tab0 = Panel(child=p0, title="NUTS1")
    tab1 = Panel(child=p1, title="NUTS2")
    tab2 = Panel(child=p2, title="NUTS3")
    tabs = Tabs(tabs=[tab0, tab1, tab2])
    tabs.sizing_mode = 'scale_both'

    item = json_item(tabs)
    item['metadata'] = 'somemetadata'
    response = JsonResponse(item)
    return response
Beispiel #3
0
def generate_report(metrics_df, config_dict, output_dir, show_report):

    # Generate HTML
    html_file_name = os.path.join(output_dir, 'calibration_report.html')
    output_file(html_file_name, mode='inline')

    header_html = '<h1>Time-of-Flight Camera Calibration Report</h1>'
    header = Div(text=header_html, sizing_mode='stretch_width')

    plots_layout = generate_plots(metrics_df)
    plots_tab = Panel(child=plots_layout, title='Results')

    configs_layout = generate_configs_table(config_dict)
    configs_tab = Panel(child=configs_layout, title='Configuration')
    body = Tabs(tabs=[plots_tab, configs_tab])

    html_layout = layout([
        [header],
        [body],
    ])

    # Only show report if show_report is True
    if show_report:
        show(html_layout, title='Calibration Report')
    else:
        save(html_layout, title='Calibration Report')
Beispiel #4
0
def render_dt_num_cat(
    itmdt: Intermediate,
    yscale: str,
    plot_width: int,
    plot_height: int,
) -> Tabs:
    """
    Render plots from plot(df, x, y) when x is dt and y is num
    """
    tabs: List[Panel] = []
    data, grp_cnt_stats, timeunit = itmdt["data"]
    tabs.append(
        dt_multiline_viz(
            data,
            itmdt["x"],
            itmdt["y"],
            timeunit,
            yscale,
            plot_width,
            plot_height,
            grp_cnt_stats,
            z=itmdt["z"],
            agg=itmdt["agg"],
        ))
    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #5
0
    def set_layout(self):
        """Create the plot layout."""
        # What to interact with
        for control in [self.x_axis, self.y_axis]:
            control.on_change('value', lambda attr, old, new: self.update())

        # Set up sidebar
        cwd = os.path.dirname(__file__)

        def path(p):
            d = os.path.join(cwd, 'plot_config/{}.html'.format(p))
            return open(d).read()

        text_top = Div(text=path('text_top'))
        text_bottom = Div(text=path('text_bottom'))

        sidebar = [text_top, self.x_axis, self.y_axis, text_bottom]
        s = widgetbox(sidebar, width=380)

        # Set up tabs
        panels = []
        for tab in self.tabs:
            panels.append(Panel(child=tab.fig, title=tab.name))
            tab.fig.legend.click_policy = 'hide'
        tabs = Tabs(tabs=panels, width=self.width)

        # Add sidebar and tabs
        L = layout([[s, tabs]])

        # Initial load of data
        self.update()

        # Showtime
        curdoc().title = 'frbpoppy'
        curdoc().add_root(L)
Beispiel #6
0
    def build_chart(self, results: List) -> Union[Figure, List[Figure], Tabs]:
        """
        Returns the figure to include in the report for a discounted ZCB analysis
        Args:
            results: The results of the discounted ZCB analysis. It is a list of dicts containing the results
                     for each ZCB term that has been included in the analysis.

        Returns:
            The figure to include in the report for the discounted ZCB analysis.

        This returns tabs of graphs - one for each ZCB term that is included.
        """
        panels = []
        for term_result in results:
            term = term_result["term"]
            charter = MartingaleChart(title=self.title,
                                      x_axis_label="Time (y)",
                                      y_axis_label="Spot rate")
            charter.plot_from_results(
                results=term_result,
                sample_mean_name=f"Discounted ZCB ({term}y)")
            charter._figure.yaxis[0].formatter = NumeralTickFormatter(
                format="0.00%")
            panel = Panel(child=charter.figure, title=f"ZCB ({term}y)")
            panels.append(panel)

        return Tabs(tabs=panels)
Beispiel #7
0
    def build_chart(self, results: dict) -> Union[Figure, List[Figure], Tabs]:
        """
        Returns the figure to include in the report for a moments analysis
        Args:
            results: The results of the moment analysis. It should contain keys:
                'time', 'mean', 'volatility', 'skewness' and 'kurtosis'

        Returns:
            The figure to include in the report for a moments analysis.

        This returns 4 tabs of graphs - one for each moment.
        """
        if not self.title:
            raise ValueError(
                "No title for the chart for a martingale analysis.")

        moments = ['mean', 'volatility', 'skewness', 'kurtosis']
        panels = []
        for moment in moments:
            charter = MomentChart(title=self.title, x_axis_label="Time (y)")
            charter.plot_from_results(results=results, moment=moment)
            x_values = results["time"]
            y_values = results[moment]
            self.perform_additional_formatting(moment,
                                               charter,
                                               min_x_value=np.min(x_values),
                                               max_x_value=np.max(x_values),
                                               min_y_value=np.min(y_values),
                                               max_y_value=np.max(y_values))
            panel = Panel(child=charter.figure, title=moment.capitalize())
            panels.append(panel)

        return Tabs(tabs=panels)
 def create_layout(self):
   tabs = []
   main_title = Div(
     text='<b>CAVI Medical - Screening Analytics</b>', 
     width=700, 
     height=50, 
     style={
       'font-size': '40px',
       'font-family':'Helvetica',
       'color': '#04537B'
       },
     )
   main_img = Div(text="<img src='CervicalScreeningAnalysis/static/gts.png'>" , width=150, height=50)
   for name, factory in self.tabs.items():
     tabs.append(Panel(title=name, child=factory()))
   if self.debug:
     self.preprocess_data()
   full_layout = layout(
     row(
       main_img,
       main_title
       ), 
     Tabs(tabs=tabs)
     )
   return full_layout
 def create_layout(self) -> Panel:
     x_child = column(self.x_range_inputs, self.x_axis_tabs)
     x_axis_tab = Panel(title="x", child=x_child)
     y_child = column(self.y_range_inputs, self.y_axis_tabs)
     y_axis_tab = Panel(title="y", child=y_child)
     tabs = Tabs(tabs=[x_axis_tab, y_axis_tab])
     return Panel(title="Axes", child=tabs)
Beispiel #10
0
def _setup_tabs(sec_to_elements):
    """Create tabs for each section in sec_to_elements with titles.

    Args:
        sec_to_elements (dict): A nested dictionary. The first level keys will be the
        sections ("running", "succeeded", "failed", "scheduled"). The second level keys
        are the database names and the second level values a list consisting of the
        link to the dashboard and a button to activate tha dashboard.

    Returns:
        tabs (bokeh.models.Tabs): a tab for every section in sec_to_elements.

    """
    tab_list = []
    for section, name_to_row in sec_to_elements.items():
        text = f"{len(name_to_row.column_names)} optimizations {section}"
        table_rows = [
            Row(Div(text=text, width=400), name=f"{section}_how_many")
        ]
        for name, row in name_to_row.data.items():
            table_rows.append(Row(*row, name=name))
        panel = Panel(
            child=Column(*table_rows, name=f"{section}_col"),
            title=section.capitalize(),
            name=f"{section}_panel",
        )
        tab_list.append(panel)
    tabs = Tabs(tabs=tab_list, name="tabs")
    return tabs
Beispiel #11
0
def render_num(
    itmdt: Intermediate,
    yscale: str,
    plot_width: int,
    plot_height: int,
) -> Tabs:
    """
    Render plots from plot(df, x) when x is a numerical column
    """

  # pylint: disable=too-many-locals
    tabs: List[Panel] = []
    osd, qsd, dsd = itmdt["statsdata"]
    tabs.append(stats_viz_num((osd, qsd, dsd), plot_width, plot_height))
    df, miss_pct = itmdt["histdata"]
    fig = hist_viz(df, miss_pct, itmdt["col"], yscale, plot_width, plot_height,
                   True)
    tabs.append(Panel(child=fig, title="histogram"))
    df, pts_rng, pdf, _, _ = itmdt["kdedata"]
    if np.any(pdf):
        tabs.append(
            hist_kde_viz(df, pts_rng, pdf, itmdt["col"], yscale, plot_width,
                         plot_height))
    actual_qs, theory_qs, _, _ = itmdt["qqdata"]
    if np.any(theory_qs[~np.isnan(theory_qs)]):
        tabs.append(
            qqnorm_viz(actual_qs, theory_qs, itmdt["col"], plot_width,
                       plot_height))
    df, outx, outy, _ = itmdt["boxdata"]
    tabs.append(box_viz(df, outx, outy, itmdt["col"], plot_width, plot_height))

    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #12
0
def render_missing_impact(itmdt: Intermediate, plot_width: int,
                          plot_height: int) -> Tabs:
    """
    Render correlation heatmaps in to tabs
    """
    tabs: List[Panel] = []
    fig_barchart = render_bar_chart(itmdt["data_bars"], "linear", plot_width,
                                    plot_height)
    tabs.append(Panel(child=row(fig_barchart), title="Bar Chart"))

    fig_spectrum = render_missing_spectrum(itmdt["data_spectrum"],
                                           itmdt["data_total_missing"],
                                           plot_width, plot_height)
    tabs.append(Panel(child=row(fig_spectrum), title="Spectrum"))

    fig_heatmap = render_heatmaps(itmdt["data_heatmap"], plot_width,
                                  plot_height)
    tabs.append(Panel(child=row(fig_heatmap), title="Heatmap"))

    fig_dendrogram = render_dendrogram(itmdt["data_dendrogram"], plot_width,
                                       plot_height)
    tabs.append(Panel(child=row(fig_dendrogram), title="Dendrogram"))

    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #13
0
    def prediction_func():
        """Function that wraps the prediction code."""
        predict_plots = []
        for i, station in enumerate(highrisk_stations):
            try:
                date, level = predict(station.name, dataset_size=1000, lookback=200, iteration=100,
                                      display=300, use_pretrained=True, batch_size=256, epoch=20)
            except Exception:
                logger.error('NN prediction failed')
                date, level = ([], []), ([], [], [])
            predict_plot = plot_prediction(date, level)
            try:
                poly, d0 = polyfit(date[0], level[0], 4)
                predict_plot.line(date[0] + date[1],
                                  [poly(date - d0) for date in date2num(date[0] + date[1])],
                                  line_width=2,
                                  line_color='gray',
                                  legend_label='Polynomial Fit',
                                  line_dash='dashed')
            except TypeError:
                logger.error('No data for polyfit')
            predict_plot.plot_width = 400
            predict_plot.plot_height = 400
            predict_plot.sizing_mode = 'scale_width'
            predict_plots.append(Panel(child=predict_plot, title=station.name))
            predicting_text = Div(text='<p><i>Prediction is running... {:.0%}</i></p>'.format(i / 6))
            doc.add_next_tick_callback(partial(update_layout,
                                               old=predict_column,
                                               new=column(predict_text, predicting_text, width=500, height=650)))

        predict_tabs = Tabs(tabs=predict_plots)
        doc.add_next_tick_callback(partial(update_layout,
                                           old=predict_column,
                                           new=column(predict_text, predict_tabs, width=500, height=650)))
Beispiel #14
0
def standalone_doc(extra, doc):
    doc.title = "HPX performance counter dashboard"
    notifier = Notifier()

    widget = DataCollectionWidget(doc, notifier.notify)

    cmap = task_cmap
    if "cmap" in extra:
        cmap = extra["cmap"]

    task_tab = Panel(
        child=tasks_widget(doc, notifier, cmap),
        title="Tasks plot",
    )
    scheduler_tab = Panel(child=scheduler_widget(doc, notifier), title="Scheduler utilization")
    custom_counter_tab = Panel(
        child=custom_counters_widget(doc, notifier), title="Customizable plots"
    )

    doc.add_root(
        row(
            Tabs(tabs=[scheduler_tab, task_tab, custom_counter_tab]),
            widget.layout(),
            sizing_mode="scale_width",
        )
    )

    doc.template = env.get_template("normal.html")
    doc.template_variables.update(extra)
    doc.theme = BOKEH_THEME
Beispiel #15
0
def main(doc: Document,
         repo: Path,
         include_files: Iterable[str] = (),
         exclude_files: Iterable[str] = (),
         limit: int = 9,
         use_cache: bool = False) -> None:
    from bokeh.models import Panel, Tabs
    from .repo_history import main as get_stats
    df = get_stats(repo, include_files, exclude_files, use_cache)
    commits_df = df[['author', 'date', 'files']].pivot_table(values='files',
                                                             index='date',
                                                             columns='author',
                                                             aggfunc='count')
    files_df = df[['author', 'date', 'files']].pivot_table(values='files',
                                                           index='date',
                                                           columns='author',
                                                           aggfunc='sum')
    lines_df = df[['author', 'date', 'lines']].pivot_table(values='lines',
                                                           index='date',
                                                           columns='author',
                                                           aggfunc='sum')
    doc.clear()  # clear the entire document before adding plots
    doc.add_root(
        Tabs(tabs=[
            Panel(title='Commits', child=render(transform(commits_df, limit))),
            Panel(title='Files', child=render(transform(files_df, limit))),
            Panel(title='Lines', child=render(transform(lines_df, limit))),
        ]))
Beispiel #16
0
def create_page(report: ClusterReport):
    structure = []

    per_node_df = create_global_resources_df(report.monitoring)

    if not per_node_df.empty:
        structure += [
            (
                "Global utilization",
                lambda r: render_global_resource_usage(r, per_node_df),
            ),
            ("Node utilization", lambda r: render_nodes_resource_usage(r, per_node_df)),
        ]

    per_process_df = create_per_process_resources_df(report.monitoring)
    if not per_process_df.empty:
        structure += [
            (
                "Process utilization",
                lambda r: render_process_resource_usage(r, per_process_df),
            )
        ]

    structure.append(("Output", render_output))

    if report.profiling_data:
        structure.append(("Profiler", render_profiling_data))

    tabs = []
    for name, fn in structure:
        widget = fn(report)
        if widget is not None:
            tabs.append(Panel(child=widget, title=name))

    return Tabs(tabs=tabs)
Beispiel #17
0
def render_two_num_cols(
    itmdt: Intermediate,
    plot_width: int,
    plot_height: int,
    tile_size: Optional[float] = None,
) -> Tabs:
    """
    Render plots from plot(df, x, y) when x and y are numerical columns
    """
    tabs: List[Panel] = []
    tabs.append(
        scatter_viz(
            itmdt["scatdata"],
            itmdt["x"],
            itmdt["y"],
            itmdt["spl_sz"],
            plot_width,
            plot_height,
        ))
    df, outx, outy, _ = itmdt["boxdata"]
    tabs.append(
        box_viz(df, outx, outy, itmdt["x"], plot_width, plot_height,
                itmdt["y"]))
    tabs.append(
        hexbin_viz(
            itmdt["hexbindata"],
            itmdt["x"],
            itmdt["y"],
            plot_width,
            plot_height,
            tile_size,
        ))
    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #18
0
def render_basic_x_num(
    itmdt: Intermediate,
    yscale: str,
    plot_width: int,
    plot_height: int,
) -> Tabs:
    """
    Render plots from plot(df, x) when x is a numerical column
    """
    tabs: List[Panel] = []
    df, miss_pct = itmdt["histdata"]
    fig = hist_viz(df, miss_pct, itmdt["col"], yscale, plot_width, plot_height,
                   True)
    tabs.append(Panel(child=fig, title="histogram"))
    df, pts_rng, pdf = itmdt["kdedata"]
    tabs.append(
        hist_kde_viz(df, pts_rng, pdf, itmdt["col"], yscale, plot_width,
                     plot_height))
    actual_qs, theory_qs = itmdt["qqdata"]
    tabs.append(
        qqnorm_viz(actual_qs, theory_qs, itmdt["col"], plot_width,
                   plot_height))
    df, outx, outy, _ = itmdt["boxdata"]
    tabs.append(box_viz(df, outx, outy, itmdt["col"], plot_width, plot_height))
    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #19
0
    def add_thumb_tab(self, spectra, plots, widgets, nspec):
        self.ncols_grid = 5  # TODO un-hardcode
        self.miniplot_width = (plots.plot_width +
                               (plots.plot_height // 2)) // self.ncols_grid

        self.full_viewer = Tabs()
        titles = None  # TODO define
        self.thumb_grid = grid_thumbs(spectra,
                                      self.miniplot_width,
                                      x_range=(plots.xmin, plots.xmax),
                                      ncols_grid=self.ncols_grid,
                                      titles=titles)
        tab1 = Panel(child=self.main_bokehlayout, title='Main viewer')
        tab2 = Panel(child=self.thumb_grid, title='Gallery')
        self.full_viewer.tabs = [tab1, tab2]

        # Dirty trick : callback functions on thumbs need to be defined AFTER the full_viewer is implemented
        # Otherwise, at least one issue = no toolbar anymore for main fig. (apparently due to ifiberslider in callback args)
        for i_spec in range(nspec):
            self.thumb_callback = CustomJS(args=dict(
                full_viewer=self.full_viewer,
                i_spec=i_spec,
                ifiberslider=widgets.ifiberslider),
                                           code="""
            full_viewer.active = 0
             ifiberslider.value = i_spec
            """)
            (self.thumb_grid.children[i_spec][0]).js_on_event(
                bokeh.events.DoubleTap, self.thumb_callback)
Beispiel #20
0
def render_missing_impact_1v1(itmdt: Intermediate, plot_width: int,
                              plot_height: int) -> Union[Tabs, Figure]:
    """
    Render the plot from `plot_missing(df, "x", "y")`
    """
    x, y = itmdt["x"], itmdt["y"]
    meta = itmdt["meta"]

    if is_numerical(meta["dtype"]):
        panels = []

        fig = render_hist(itmdt["hist"], y, meta, plot_width, plot_height)
        panels.append(Panel(child=fig, title="Histogram"))

        fig = render_dist(itmdt["dist"], y, "pdf", plot_width, plot_height)
        panels.append(Panel(child=fig, title="PDF"))

        fig = render_dist(itmdt["dist"], y, "cdf", plot_width, plot_height)
        panels.append(Panel(child=fig, title="CDF"))

        fig = render_boxwhisker(itmdt["box"], plot_width, plot_height)
        panels.append(Panel(child=fig, title="Box"))

        tabs = Tabs(tabs=panels)
        return tabs
    else:
        fig = render_hist(itmdt["hist"], y, meta, plot_width, plot_height)

        shown, total = meta["partial"]
        if shown != total:
            fig.title = Title(
                text=f"Missing impact of {x} by ({shown} out of {total}) {y}")
        else:
            fig.title = Title(text=f"Missing impact of {x} by {y}")
        return fig
Beispiel #21
0
    def layout(self):
        panels = [None, None]

        # Main panel: data
        panels[0] = Panel(
            child=row(
                column(
                    self.data.layout(),
                    Spacer(height=10),
                    self.specials.layout(),
                    width=160,
                ),
                Spacer(width=10),
                column(
                    self.xaxis.layout([self.yaxis.widget]),
                    Spacer(height=10),
                    self.size.layout([self.color.widget]),
                ),
            ),
            title="data",
        )

        # Secondary panel: appearance
        panels[1] = Panel(child=Div(), title="appearance",)

        tabs = Tabs(tabs=panels)

        header = Div(
            text=f"""<img src="{LOGO_URL}"></img>""",
            css_classes=["header-image"],
            width=320,
            height=100,
        )

        return row(column(header, tabs), Spacer(width=10), self.plot)
Beispiel #22
0
def covid_app(doc, plot_data, description):
    """Create the page with the master dashboard.

    Args:
        doc (bokeh.Document):
            document where the overview over the optimizations will be displayed
            by their current stage.
        plot_data (dict)
        description (pd.DataFrame)

    """
    tab_names = ["Overview", "Timeline"]
    tab_list = []
    for i, sec_title in enumerate(tab_names):
        subtopic = description["subtopic"].unique()[i]
        title = Div(text=subtopic.capitalize(), style={"font-size": "200%"})
        p = create_standard_figure(title="")
        source = ColumnDataSource(plot_data)
        p.line(source=source, x="x", y="y")
        col = Column(*[title, p])
        panel = Panel(
            child=col,
            title=sec_title,
            name=f"{sec_title}_panel",
        )
        tab_list.append(panel)

    tabs = Tabs(tabs=tab_list, name="tabs")
    doc.add_root(tabs)
Beispiel #23
0
def render_missing_impact_1vn(itmdt: Intermediate, plot_width: int,
                              plot_height: int) -> Tabs:
    """
    Render the plot from `plot_missing(df, "x")`
    """

    dfs = itmdt["data"]
    x = itmdt["x"]
    meta = itmdt["meta"]

    panels = []
    for col, df in dfs.items():
        fig = render_hist(df, col, meta[col], plot_width, plot_height)
        shown, total = meta[col]["partial"]

        if shown != total:
            fig.title = Title(
                text=f"Missing impact of {x} by ({shown} out of {total}) {col}"
            )
        else:
            fig.title = Title(text=f"Missing impact of {x} by {col}")
        panels.append(Panel(child=fig, title=col))

    tabs = Tabs(tabs=panels)
    return tabs
Beispiel #24
0
def examine_daily_distributions(returns, name, n_tr_days):
    '''
    Function to use in a notebook to organise all the output
    :param returns: Daily returns to model
    :param name: Name of the strategy
    :param n_tr_days: Number of trading days of the strategy
    :return:
    '''
    drv = DailyReturnVisualisations(name,
                                    returns,
                                    n_trading_days=n_tr_days,
                                    n_drawdown_simulations=10000)
    display(HTML('<h3>{} Daily Returns</h3>'.format(name)))
    display(
        HTML('{} days, best fitting distribution is {}'.format(
            len(returns), drv.chosen_rv.dist.name)))
    tabs = [
        Panel(child=drv.generate_daily_returns_plot(), title='Daily returns'),
        Panel(child=drv.generate_simulated_drawdown_plot(), title='Drawdown'),
        Panel(child=drv.generate_autocorrelation_plot(),
              title='Autocorrelation')
    ]
    _ = show(
        column(drv.generate_summary_table(), Tabs(tabs=tabs),
               drv.generate_simulated_drawdown_table(),
               drv.generate_stationarity_table()))
Beispiel #25
0
def render_cat_and_num_cols(
    itmdt: Intermediate, yscale: str, plot_width: int, plot_height: int,
) -> Tabs:
    """
    Render plots from plot(df, x, y) when x is a categorical column
    and y is a numerical column
    """
    tabs: List[Panel] = []
    df, outx, outy, grp_cnt_stats = itmdt["boxdata"]
    tabs.append(
        box_viz(
            df,
            outx,
            outy,
            itmdt["x"],
            plot_width,
            plot_height,
            itmdt["y"],
            grp_cnt_stats,
        )
    )
    histdict, grp_cnt_stats = itmdt["histdata"]
    tabs.append(
        line_viz(
            histdict,
            itmdt["x"],
            itmdt["y"],
            yscale,
            plot_width,
            plot_height,
            grp_cnt_stats,
        )
    )
    tabs = Tabs(tabs=tabs)
    return tabs
Beispiel #26
0
 def output_viz(self, width, height):
     p2d = self._gen_2d_chart(width, height)
     tab2 = Panel(child=p2d, title="2D")
     p1d = self._gen_1d_chart(width, height)
     tab1 = Panel(child=p1d, title="1D")
     tabs = Tabs(tabs=[tab2, tab1])
     return tabs
Beispiel #27
0
def modify_doc(doc, mytabs):

	start, end = 1, 20
	samples_count = 5
	slider = Slider(start=start, end=end, value=start, step=1, title="Counts")
	select = Select(title="Count", value="aux", options=["box", "pack", "image", "user"])

	renderer = hv.renderer('bokeh')##.instance(mode='server')
	hv.extension('bokeh')
	hv.output(size=200)
	links = pd.DataFrame(data['links'])
	print(links.head(3))
	nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
	chord = hv.Chord((links, nodes)).select(value=(samples_count, None))
	chord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), labels='name', node_color=dim('index').str()))    	
	# Create HoloViews plot and attach the document
	hvplot = renderer.get_plot(chord, doc)
	
	def slider_update(attrname, old, new):
		# Notify the HoloViews stream of the slider update 
		print ("update received")
		samples_count = new
		
		links = pd.DataFrame(data['links'])
		print(links.head(3))
		nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
		chord = hv.Chord((links, nodes)).select(value=(samples_count, None))
		chord.opts(opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), labels='name', node_color=dim('index').str()))    	
		# Create HoloViews plot and attach the document
		hvplot = renderer.get_plot(chord, doc)
		tab3 = Panel(child=row(slider, hvplot.state), title="Chord Plot")

		mytabs.append(tab3)
		views = Tabs(tabs = mytabs)
		layout=row(views)
		doc.add_root(layout)
	
		return doc

	slider.on_change('value', slider_update)

	
	def select_update(attrname, old, new):
		# Notify the HoloViews stream of the slider update 
		print ("update received. Old: {} New: {}".format(old, new))
		

	select.on_change('value', select_update)		

	# Combine the holoviews plot and widgets in a layout

	tab3 = Panel(child=row(slider, hvplot.state), title="Chord Plot")

	mytabs.append(tab3)
	views = Tabs(tabs = mytabs)
	layout=row(views)
	doc.add_root(layout)
	
	return doc
def tabbed_am(df):
    output_file("ambulance_tabs.html")
    tab1 = Panel(child=ambulance_response(df, 15), title="Quarter Hour")
    tab2 = Panel(child=ambulance_response(df), title="Half Hour")
    tab3 = Panel(child=ambulance_response(df, 60), title="Hour")

    tabs = Tabs(tabs=[tab1, tab2, tab3])
    show(tabs)
def tabbed_call(df):
    output_file("response_tabs.html")
    tab1 = Panel(child=response_to_call(df, 15), title="Quarter Hour")
    tab2 = Panel(child=response_to_call(df), title="Half Hour")
    tab3 = Panel(child=response_to_call(df, 60), title="Hour")

    tabs = Tabs(tabs=[tab1, tab2, tab3])
    show(tabs)
def create_figure():
    """
    get data from generate_bokeh_data and create the data source. Define widgets and create the two figures.
    Position the widgets and figures according to rows and columns
    :return: send layout of widgets and plots back to Bokeh
    """
    global active_attributes_list, width, depth, level_width, acc, periods, groups, data_source,\
        attr_info, attribute_checkbox, apply_changes_button, decision_button, arrow_button, root_select, method_select,\
        tree_select, dataset_select, dataset_slider, p, arrow_data_source, circles, rectangles, best_circles,\
        best_rectangles, best_root_plot, best_root_plot_data_source, tree_tab, best_arrow_data_source, text_props, Instance

    active_attributes_list = [
        attr for attr in Instance.attr_list if attr != Instance.attr_list[-1]
    ]
    source, width, depth, level_width, acc = get_bokeh_data(
        Instance, "gini", active_attributes_list + [Instance.attr_list[-1]],
        selected_root)
    # X and y range calculated
    periods = [str(i) for i in range(0, width + 1)]
    groups = [str(x) for x in range(0, depth + 2)]

    elements = pd.DataFrame.from_dict(source)
    df = elements.copy()
    get_new_data_source(df)
    data_source = ColumnDataSource(data=df)
    text_props = {
        "source": data_source,
        "text_align": "center",
        "text_baseline": "middle"
    }
    p, arrow_data_source, circles, rectangles = create_plot("customized")

    best_root_plot_data = data_source.data.copy()
    best_root_plot_data_source = ColumnDataSource(data=best_root_plot_data)
    best_root_plot, best_arrow_data_source, best_circles, best_rectangles = create_plot(
        "optimal")
    p.select(name="decision_text").visible = False
    best_root_plot.select(name="decision_text").visible = False
    p.select(name="arrowLabels").visible = False
    best_root_plot.select(name="arrowLabels").visible = False

    tab1 = Panel(child=p, title="Yeni ağacınız")
    tab2 = Panel(child=best_root_plot, title="İdeal ağaç")
    tree_tab = Tabs(tabs=[tab1, tab2], width=p.plot_width)
    widgets = widgetbox(root_select,
                        attr_info,
                        attribute_checkbox,
                        dataset_slider,
                        apply_changes_button,
                        decision_button,
                        arrow_button,
                        dataset_select,
                        tree_select,
                        file_button,
                        sizing_mode="stretch_both")

    main_frame = layout([[widgets, tree_tab]])
    return main_frame