def corr_plot(portfolio_daily_retn):
    title_font = {
        'family': 'monospace',
        'color': 'blue',
        'weight': 'bold',
        'size': 15,
    }
    correlated = portfolio_daily_retn.corr()
    # Generate a mask for the upper triangle
    mask = np.zeros_like(correlated, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    # Set up the matplotlib figure
    correlated_plot, ax = plt.subplots(figsize=(12, 8))

    # Draw the heatmap with the mask and correct aspect ratio
    sns.heatmap(correlated,
                mask=mask,
                cmap="coolwarm",
                vmax=1,
                vmin=-1,
                center=0,
                square=True,
                linewidths=.5,
                annot=True)
    plt.title(f"Correlation Map of Portfolio\n", fontdict=title_font)
    #ax.set_facecolor("aliceblue")

    #correlated_plot = sns.heatmap(correlated, vmin=-1, vmax=1, annot=True,cmap="coolwarm")
    plt.close()
    return pn.Pane(correlated_plot)
def sharp_rt_plot(portfolio_daily_retn):

    title_font = {
        'family': 'monospace',
        'color': 'blue',
        'weight': 'bold',
        'size': 15,
    }
    label_font = {
        'family': 'monospace',
        'color': 'green',
        'weight': 'bold',
        'size': 12,
    }

    bar_colors = [
        "midnightblue", "royalblue", "indigo", "darkcyan", "darkgreen",
        "maroon", "purple", "darkorange", "slategray", "forestgreen",
        "darkgoldenrod", "sienna"
    ]

    sharp_ratios = portfolio_daily_retn.mean() * np.sqrt(
        252) / portfolio_daily_retn.std()

    sr_plot = plt.figure(figsize=(12, 8))
    plt.bar(x=sharp_ratios.index,
            height=sharp_ratios,
            color=random.sample(bar_colors, len(sharp_ratios.index)))
    plt.title(f"Sharpe Ratios of Portfolio\n", fontdict=title_font)
    plt.ylabel("Sharpe Ratio", fontdict=label_font)
    plt.xlabel("Assets", fontdict=label_font)
    plt.axhline(sharp_ratios.mean(), color='r')
    plt.close()
    return pn.Pane(sr_plot)
Example #3
0
def make_header_html(header_html_path=None):
    logo = "https://www.kyushu-u.ac.jp/img/common_en/logo.png"
    title = '<p style="font-size:30px">Passive Seismic Monitoring System</p>'
    #     creator = 'Created by: Fernando Lawrens Hutapea, Takeshi Tsuji, and Tatsunori Ikeda <br>'
    info = "(Ambient noise data is provided by National Research Institute for Earth Science and Disaster Prevention (NIED) Japan)"
    creator = 'Presently the monitoring result is updated weekly (Saturday) <br> Please use Firefox or Google Chrome or Microsoft Edge <br>'
    current = np.datetime64(datetime.datetime.now(), "s").astype(str)
    last_update = "Last update: {} <br>".format(current)  # today's date
    header = pn.Row(
        logo, pn.Spacer(width=30),
        pn.Column(pn.Spacer(height=0), pn.Pane(title, height=16, width=900),
                  pn.Spacer(height=18), pn.Pane(info, height=20, width=900),
                  pn.Spacer(height=8), pn.Pane(creator, height=20, width=900),
                  last_update))
    print("Finish Create Header {}".format(current))
    return (header)
def view() -> pn.Column:
    """# Bootstrap Dashboard Page.

    Creates a Bootstrap Dashboard Page with a Chart and a Table

    - inspired by the [GetBoostrap Dashboard Template]
    (https://getbootstrap.com/docs/4.4/examples/dashboard/)
    - implemented using the `awesome_panel' Python package and in particular the
    `awesome_panel.express.templates.BootstrapDashboardTemplate`

    Returns:
        pn.Column -- The Orders View
    """
    table = pn.Pane(
        _get_table_data(),
        sizing_mode="stretch_width",
    )
    pn.config.sizing_mode = "stretch_width"
    main = [
        APPLICATION.intro_section(),
        pn.Column(
            pnx.SubHeader("Dashboard"),
            pn.pane.HoloViews(_holoviews_chart()),
        ),
        pn.Column(
            pnx.SubHeader("Section Title"),
            table,
        ),
    ]
    return pn.template.FastListTemplate(title="Bootstrap Dashboard",
                                        main=main,
                                        main_max_width="800px")
def plot_conf(values=None, conf=[0, 0]):
    conifidence_plot = plt.figure(figsize=(12, 8))
    plt.hist(x=values, bins=20)
    plt.axvline(conf.iloc[0], color='r')
    plt.axvline(conf.iloc[1], color='r')
    plt.close()
    return pn.Pane(conifidence_plot)
def view() -> pn.Column:
    """# Bootstrap Dashboard Page.

    Creates a Bootstrap Dashboard Page with a Chart and a Table

    - inspired by the [GetBoostrap Dashboard Template]
    (https://getbootstrap.com/docs/4.4/examples/dashboard/)
    - implemented using the `awesome_panel' Python package and in particular the
    `awesome_panel.express.templates.BootstrapDashboardTemplate`

    Returns:
        pn.Column -- The Orders View
    """
    table = pn.Pane(
        _get_table_data(),
        sizing_mode="stretch_width",
    )
    return pn.Column(
        pn.pane.Markdown(TEXT),
        # pn.pane.PNG(str(IMAGE_PATH), max_width=600, sizing_mode="scale_both"),
        pnx.Title("Dashboard"),
        pn.layout.Divider(),
        _holoviews_chart(),
        pnx.Title("Section Title"),
        pn.layout.Divider(),
        table,
        sizing_mode="stretch_width",
        name="Dashboard",
    )
Example #7
0
 def panel(self):
     self.available_attributes()  # for the initial load
     return pn.Column(
         pn.Row(pn.Param(self.load_sim_widget, show_name=False),
                pn.Param(self.att_widget, show_name=False),
                pn.Param(self.projection, show_name=False),
                name=self.label),
         pn.Pane(self.param, parameters=['load_data'], show_name=False))
Example #8
0
def price_only(df):
    priceonly_plot = plt.figure(figsize=(10, 6))
    plt.plot(df.close, "bo-", linewidth=2, markersize=5)
    plt.title('Price over the last 45 days')
    plt.xticks(rotation="vertical")
    plt.grid(True)
    plt.legend()
    plt.close()
    return pn.Pane(priceonly_plot)
Example #9
0
def ema_plot(df):
    ema_plot = plt.figure(figsize=(10, 6))
    plt.plot(df.close, "bo-", linewidth=2, markersize=5)
    plt.plot(df.volatility_bbm, "--", linewidth=2, label='EMA BB')
    plt.title('Exponential Moving Average')
    plt.xticks(rotation="vertical")
    plt.grid(True)
    plt.legend()
    plt.close()
    return pn.Pane(ema_plot)
Example #10
0
def get_oggm_panel():
    geo_bounds  = BoundsXY(source=static_geo,  rename={'bounds':  'cenlon__cenlat'})
    elev_bounds = BoundsXY(source=static_elev, rename={'bounds':  'mean_elev__latdeg'})
    temp_bounds = BoundsX(source=static_temp, rename={'boundsx': 'avg_temp_at_mean_elev'})
    prcp_bounds = BoundsX(source=static_prcp, rename={'boundsx': 'avg_prcp'})

    selections  = [geo_bounds, elev_bounds, temp_bounds, prcp_bounds]
    dyn_data    = hv.DynamicMap(select_data, streams=selections)

    dyn_geo   = rasterize(dyn_data.apply(geo),  **geo_kw).options( **geo_opts)
    dyn_elev  = datashade(dyn_data.apply(elev), **elev_kw).options(**elev_opts)
    dyn_temp  =           dyn_data.apply(temp)
    dyn_prcp  =           dyn_data.apply(prcp)
    dyn_count =           dyn_data.apply(count)

    geomap = geo_bg * static_geo  * dyn_geo
    elevation       = static_elev * dyn_elev
    temperature     = static_temp * dyn_temp
    precipitation   = static_prcp * dyn_prcp

    def clear_selections(arg=None):
        geo_bounds.update(bounds=None)
        elev_bounds.update(bounds=None)
        temp_bounds.update(boundsx=None)
        prcp_bounds.update(boundsx=None)
        Stream.trigger(selections)

    clear_button = pn.widgets.Button(name='Clear selection')
    clear_button.param.watch(clear_selections, 'clicks');

    title       = '<div style="font-size:35px">World glaciers explorer</div>'
    instruction = 'Box-select on each plot to subselect; clear selection to reset.<br>' + \
                  'See the <a href="https://github.com/panel-demos/glaciers">Jupyter notebook</a> source code for how to build apps like this!'
    oggm_logo   = '<a href="https://oggm.org"><img src="https://raw.githubusercontent.com/OGGM/oggm/master/docs/_static/logos/oggm_s_alpha.png" width=170></a>'
    pn_logo     = '<a href="https://panel.pyviz.org"><img src="https://panel.pyviz.org/_static/logo_stacked.png" width=140></a>'

    header = pn.Row(pn.Pane(oggm_logo),  pn.layout.Spacer(width=30),
                    pn.Column(pn.Pane(title, width=400), pn.Pane(instruction, width=500)),
                    pn.layout.HSpacer(), pn.Column(pn.Pane(dyn_count), pn.layout.Spacer(height=20), clear_button),
                    pn.Pane(pn_logo, width=140))

    return pn.Column(header, pn.Row(geomap, elevation), pn.Row(temperature, precipitation), width_policy='max', height_policy='max')
    def _on_newtracks(self, *_):
        "update the values"
        old = self._col.objects[:-1]
        obj = hv.Div("No tracks selected"
                     ) if not self.selector.value else self._new_display()
        if self._cback:
            self._cback(self)
        if obj is None:
            return

        try:
            self._col.pop(-1)
            self._col.append(pn.Pane(obj))
        except KeyError:  # panel bug
            for _ in range(5):
                try:
                    self._col.clear()
                    self._col.extend(old + [pn.Pane(obj)])
                    break
                except KeyError:  # panel bug
                    pass
Example #12
0
def macd_plot(df):
    macd_plot = plt.figure(figsize=(10, 6))
    plt.plot(df.trend_macd, "--", linewidth=2, label='MACD')
    #plt.plot(df["volume"],"-", linewidth=2,label='Volume');
    plt.plot(df.trend_macd_signal, "--", linewidth=2, label='MACD Signal')
    plt.plot(df.trend_macd_diff, "--", linewidth=2, label='MACD Difference')
    plt.title('MACD, MACD Signal and MACD Difference')
    plt.xticks(rotation="vertical")
    plt.grid(True)
    plt.legend()
    plt.close()
    return pn.Pane(macd_plot)
Example #13
0
def bb_plot(df):
    bb_plot = plt.figure(figsize=(10, 6))
    plt.plot(df.close, "bo-", linewidth=2, markersize=5)
    plt.plot(df.volatility_bbh, "--", linewidth=2, label='High BB')
    plt.plot(df.volatility_bbl, "--", linewidth=2, label='Low BB')
    plt.plot(df.volatility_bbm, "--", linewidth=2, label='EMA BB')
    plt.title('Bollinger Bands')
    plt.xticks(rotation="vertical")
    plt.grid(True)
    plt.legend()
    plt.close()
    return pn.Pane(bb_plot)
Example #14
0
def bkapp(curdoc):
    #import time
    #time.sleep(5)
    """
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = data
    """
    slider = pn.widgets.FloatSlider(start=-10,
                                    end=10,
                                    value=0,
                                    step=0.01,
                                    title="Alpha")

    @pn.depends(slider.param.value)
    def create_sine_plot(alpha):
        plot = figure(y_range=(-15, 15))
        data = np.linspace(-10, 10, 500)
        y = alpha * np.sin(data)
        plot.line(x=data, y=y)
        plot.sizing_mode = "stretch_both"
        return plot

    paragraph = Paragraph(text="IOloop's id: %s" %
                          str(id(bokeh_server.io_loop.asyncio_loop)))

    row = pn.Column(slider, create_sine_plot, name="chart_1")
    row.sizing_mode = "stretch_both"
    row.server_doc(curdoc)

    other_figure = figure(title="Jajaja")
    other_figure.scatter(x=[1, 2, 3], y=[4, 5, 6])
    other_figure.sizing_mode = "stretch_both"
    pn.Pane(other_figure, name="chart_2").server_doc(curdoc)

    #curdoc.theme = Theme(filename="theme.yaml")

    # Options for Jinja template rendered by the Bokeh Server
    # (as opposed of by Starlette):
    curdoc.template = (Environment(loader=FileSystemLoader(
        searchpath="templates")).get_template("index.html"))
    curdoc.template_variables["rendered_by_bokeh_server"] = True
    def _new_display(self):
        track = self.track
        beads = list(track.beads.keys())
        if not beads:
            return pn.Pane("No beads in this track")

        sel = pnw.Select(
            name="Plot",
            value="cleancycles",
            options=["cleanbeads", "cleancycles", "cycles", "peaks"])
        lst = pnw.DiscreteSlider(name="Beads", value=beads[0], options=beads)
        pane = pn.Pane(hv.Div(""))

        def _show(_):
            dmap = getattr(track, sel.value).display.display()
            pane.object = dmap[lst.value]

        lst.param.watch(_show, "value")
        sel.param.watch(_show, "value")
        col = pn.Column(pn.Row(lst, sel), pane)
        _show(None)
        return col
 def display(
     self,
     defaultpath: Optional[str] = None,
     match: Optional[str] = None,
     callback: Optional[Callable[['_BasePathSelector'], Any]] = None
 ) -> pn.Column:
     "create the view"
     if defaultpath is not None:
         self.paths.value = defaultpath
     if match is not None:
         self.match.value = match
     if callback is not None:
         self._cback = callback
     self._col = pn.Column(pn.Row(self.paths, self.match), self.selector,
                           pn.Pane(hv.Div("")))
     self._on_update()
     return self._col
Example #17
0
def dashboard_view() -> pn.Column:
    """## Bootstrap Dashboard Template inspired by Page with orders chart and table

    Returns:
        pn.Column -- The Orders View
    """
    table = pn.Pane(services.get_table_data(), sizing_mode="stretch_width")
    return pn.Column(
        pnx.Title("Dashboard"),
        pnx.Divider(),
        holoviews_chart(),
        pnx.Title("Section Title"),
        pnx.Divider(),
        table,
        sizing_mode="stretch_width",
        name="Dashboard",
    )
Example #18
0
    def panel(self):
        # Attach a callback to geocoding & optimal route search
        self.get_best_route_action.on_click(lambda x: self.optimize_route(x))
        # Attach a callback to batch import:
        self.batch_import_str.link(self.batch_import_str,
                                   callbacks={'value': clean_space_callback})
        self.batch_import_str.value = ''
        # Attach a callback to Import Destinations button so the destinations pasted propagate into the Destinations list & sidebar
        self.get_batch_destinations.on_click(
            lambda x: self.destinations_from_import_str(x))

        # Setup the sidebar:
        widgets_sliders = pn.Column(self.param.number_dest,
                                    self.param.waypoints_per_batch)
        widgets_start_end = self.start_end_widget
        buttons_ = pn.Column(self.get_best_route_action)
        progress_bar = pn.Pane(self.progress_bar,
                               sizing_mode="stretch_width",
                               width_policy="max")

        # Set up tabs
        tab_bokeh = pn.Column(pn.Column(self.plot_bokeh),
                              self.show_urls,
                              sizing_mode="stretch_width",
                              width_policy="max")
        tab_import = pn.Row(self.batch_import_str, self.get_batch_destinations)
        self.tabs = pn.Tabs(('Optimal Route Map', tab_bokeh),
                            ('Batch Location Import', tab_import))

        result = pn.Row(
            pn.Column(
                self.title,
                widgets_sliders,
                progress_bar,
                widgets_start_end,
                buttons_,
                self.change_destinations_number,
            ),
            self.tabs,
            sizing_mode="stretch_width",
        )
        return result
def bkapp(curdoc):
    import time
    time.sleep(5)

    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = data
    plot.sizing_mode = "stretch_both"

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    paragraph = Paragraph(text="IOloop's id: %s" % str(id(bokeh_server.io_loop.asyncio_loop)))

    row = pn.Row(slider, plot, name="chart_1")
    row.sizing_mode = "stretch_both"
    row.server_doc(curdoc)

    other_figure = figure(title="Jajaja")
    other_figure.scatter(x=[1,2,3], y=[4,5,6])
    other_figure.sizing_mode = "stretch_both"
    pn.Pane(other_figure, name="chart_2").server_doc(curdoc)

    curdoc.theme = Theme(filename="theme.yaml")

    # Options for Jinja template rendered by the Bokeh Server
    # (as opposed of by Starlette):
    curdoc.template = (Environment(loader=FileSystemLoader(searchpath="templates"))
                       .get_template("index.html")
                       )
    curdoc.template_variables["rendered_by_bokeh_server"] = True
Example #20
0
import pandas as pd
import plotly.express as px

import panel as pn

pn.config.raw_css.append("""
table {
    width: 100%;
}
""")
data = {
    "Day": [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ],
    "Orders": [15539, 21345, 18483, 24003, 23489, 24092, 12034],
}
dataframe = pd.DataFrame(data)
pane = pn.Pane(dataframe, sizing_mode="stretch_width")
app = pn.Column(pane, sizing_mode="stretch_width")
app.servable()
 def panel(self):
     return pn.Pane(self.param, show_name=False)
Example #22
0
 def panel(self):
     if self.composition is None:
         return pn.Pane("no composition :(")
     print('composition: ', self.composition)
     return self.composition.panel()
instruction = (
    "<div style='font-size:15px'>Select artists on the map and album release decade to filter albums.<br>"
    "Albums view is zoomable, and axes are customizable.<br></div>")

# ### Base layout

# +
artists_points = create_artists_points(artists)
albums_points = create_albums_points(x=x_select.value,
                                     y=y_select.value,
                                     color=color_select.value,
                                     data=albums)

layout = pn.Column(pn.Row(
    pn.Column(
        pn.Pane(title, width=400),
        pn.Pane(instruction, width=400),
    ),
    pn.Pane(artists_points),
),
                   pn.Row(
                       pn.Column(
                           decade_box,
                           axes_box,
                           width=400,
                       ),
                       pn.Pane(albums_points),
                   ),
                   width_policy="max",
                   height_policy="max")
Example #24
0
 def download_link(name, n):
     if preds is None:
         return
     df = preds[0].promiscuous_binders(n=n, name=name)
     df.to_csv()
     return pn.Pane(HTML('<a>download</a>'), width=700)
Example #25
0

def clear_selections(arg=None):
    geo_bounds.update(bounds=None)
    elev_bounds.update(bounds=None)
    temp_bounds.update(boundsx=None)
    prcp_bounds.update(boundsx=None)
    Stream.trigger(selections)


import panel as pn
pn.extension()

clear_button = pn.widgets.Button(name='Clear selection')
clear_button.param.watch(clear_selections, 'clicks')

title = '<p style="font-size:35px">World glaciers explorer</p>'
instruction = 'Box-select on each plot to subselect; clear selection to reset.<br>' + 'See the <a href="https://anaconda.org/jbednar/glaciers">Jupyter notebook</a> source code for how to build apps like this!'
oggm_logo = '<a href="https://github.com/OGGM/OGGM-Dash"><img src="https://raw.githubusercontent.com/OGGM/oggm/master/docs/_static/logos/oggm_s_alpha.png" width=170></a>'
pv_logo = '<a href="https://pyviz.org"><img src="http://pyviz.org/assets/PyViz_logo_wm.png" width=80></a>'

header = pn.Row(
    pn.Pane(oggm_logo, width=170), pn.Spacer(width=50),
    pn.Column(pn.Pane(title, height=25, width=400), pn.Spacer(height=-15),
              pn.Pane(instruction, width=500)), pn.Spacer(width=180),
    pn.Column(pn.Pane(dyn_count), clear_button, pn.Spacer(height=-15)),
    pn.Pane(pv_logo, width=80))

pn.Column(header, pn.Spacer(height=-40), pn.Row(geomap, elevation),
          pn.Row(temperature, precipitation)).show()
Example #26
0
class ReactiveDashboard(param.Parameterized):
    title = pn.pane.Markdown("# Booze Cruise YYC")
    # Add a widget that picks the environment and bucket
    number_dest = param.Integer(len(DEFAULT_DEST),
                                label="Select number of destinations",
                                bounds=(0, 15))
    waypoints_per_batch = param.Integer(
        10, label="Waypoints per batch in Google Maps URL", bounds=(1, 12))

    progress_bar = pnw.misc.Progress(
        active=False,
        bar_color="light",
        value=None,
        width_policy="max",
        sizing_mode="stretch_width",
    )

    date_custom_map: Dict = {}
    get_best_route_action = pnw.Button(name="Optimize Route",
                                       button_type="primary")
    get_batch_destinations = pnw.Button(name="Import Destinations",
                                        button_type="primary")

    destinations_pane = param.Parameter(default=destinations_pane_default)
    destinations_wlist = param.List(default=destinations_wlist_default)

    destinations_latlongs = param.List(default=[(0, 0), (0, 0)],
                                       precedence=-0.5)
    gmaps_urls = param.List(default=['', ''], precedence=-0.5)

    destinations_addresses = param.List(default=[(0, 0), (0, 0)],
                                        precedence=-0.5)
    all_dates_forecast = default_altair()
    default_plot = pn.Pane(default_altair())

    start_location = param.String(label='Departure Point')
    end_location = param.String(label='Destination Point')
    batch_import_str = pnw.TextAreaInput(
        name='Batch import',
        placeholder=
        'Add locations here by e.g. copy-pasting from a spreadsheet',
        width=300,
        height=450,
        sizing_mode='scale_both')
    is_start_equal_end = param.Boolean(
        default=True, label='My final destination same as Departure Point')
    start_latlong = param.Tuple(default=(0, 0), precedence=-0.5)
    end_latlong = param.Tuple(default=(0, 0), precedence=-0.5)
    df_label = param.DataFrame(precedence=-0.5, default=pd.DataFrame())
    df_all_pts = param.DataFrame(precedence=-0.5, default=pd.DataFrame())

    # Placeholder for tabs:
    tabs = pn.Tabs(('Batch Location Import', pn.Row()))

    tmp_buffer = 'Temporary buffer'

    @param.depends("number_dest", watch=True)
    def change_destinations_number(self):
        new_destinations = create_destination_inputs(
            n=self.number_dest, prev_destinations=self.destinations_wlist)
        self.destinations_pane, self.destinations_wlist = (
            new_destinations[0],
            new_destinations[1],
        )
        self.tabs.active = 0
        return self.destinations_pane

    def geocode_dest_list_latlong(self, event, destinations_list):
        self.progress_bar.bar_color = 'info'
        self.progress_bar.active = True

        logger_bc.info(event)
        destinations_str = [_pull_value_wlist(x) for x in destinations_list]
        logger_bc.info(f"Geocoding the destinations list: {destinations_str}")
        destinations_jsons = [
            _geocode_destination_here(x) for x in destinations_str
        ]
        latlongs = [
            _pull_lat_long_here(x, n_entry=0) for x in destinations_jsons
        ]
        addresses = [
            _pull_address_here(x, n_entry=0) for x in destinations_jsons
        ]

        logger_bc.info(latlongs)
        logger_bc.info(addresses)

        # latlongs = [(random.randint(i, 20), random.randint(i, 40)) for i in range(len(destinations_list))]
        self.destinations_latlongs = latlongs
        self.destinations_addresses = addresses
        logger_bc.info(self.destinations_latlongs)
        logger_bc.info(self.destinations_addresses)

        self.progress_bar.bar_color = 'light'
        self.progress_bar.active = False

    @param.depends('destinations_latlongs')
    def show_latlongs(self):
        destinations_str = [
            _pull_value_wlist(x) for x in self.destinations_wlist
        ]

        x = f' Length = {len(self.destinations_wlist)}, vals = {destinations_str}'
        x += f' Latlongs = {len(self.destinations_latlongs)}, vals = {self.destinations_addresses}'

        res_md = pn.pane.Markdown(x)
        return res_md

    def find_best_route(self,
                        event,
                        latlong_list,
                        start_point: Tuple = (0, 0),
                        end_point: Tuple = (0, 0)):
        '''
        Find optimal route using TomTom routing service
        :param start_point:
        :param end_point:
        :param event:
        :param latlong_list:
        :return:
        '''
        self.progress_bar.bar_color = 'info'
        self.progress_bar.active = True

        latlongs = [start_point] + latlong_list + [end_point]
        latlong_concat = concat_latlongs(latlongs)

        url_locations = f'{base_url_tomtom}/{latlong_concat}/json'
        params = {
            'key': API_KEY_TOMTOM,
            'travelMode': 'car',
            'computeBestOrder': 'true',
            'traffic': 'true',
            'instructionsType': 'text',
            'computeTravelTimeFor': 'all',
        }
        response = requests.get(url_locations, params=params)
        response_json = response.json()
        latlongs_original_optimal = rearrange_waypoints(response_json)

        sorted_addresses = self.get_ordered_addresses(
            latlongs_original_optimal)
        sorted_addresses_with_terminals = [
            self.start_location
        ] + sorted_addresses + [self.end_location]
        _, urls = construct_gmaps_urls(sorted_addresses_with_terminals,
                                       waypoints_batch_size=10)
        self.gmaps_urls = urls

        # Prepare dataframes to feed Bokeh with
        self.df_label = create_label_df(start_point,
                                        end_point,
                                        latlongs_original_optimal,
                                        sorted_addresses=sorted_addresses,
                                        start_location=self.start_location,
                                        end_location=self.end_location)
        self.df_all_pts = create_legs_df(response_json)

        self.progress_bar.bar_color = 'light'
        self.progress_bar.active = False

    @param.depends('df_all_pts')
    def plot_bokeh(self):
        if self.df_all_pts.shape[0] > 0:
            print('Plotting bokeh')
            p = create_bokeh_figure(df_all_pts=self.df_all_pts,
                                    df_label=self.df_label)
        else:
            p = figure()
        return p

    def get_ordered_addresses(self, ordered_latlongs):
        """
        Sort geocoded addresses into optimal order
        """
        def closest_node(node, nodes):
            nodes = np.asarray(nodes)
            deltas = nodes - node
            dist_2 = np.einsum('ij,ij->i', deltas, deltas)
            return np.argmin(dist_2)

        sort_vector = [
            closest_node(x, self.destinations_latlongs)
            for x in ordered_latlongs
        ]
        sorted_addresses = [
            self.destinations_addresses[x]['label'] for x in sort_vector
        ]
        return sorted_addresses

    @param.depends('gmaps_urls')
    def show_urls(self):
        base_url_string = """
        ### The route links for navigation in Google Maps:
        
        URL
        """
        urls_links_md = [
            f'**[Group {i}]({u})**' for i, u in enumerate(self.gmaps_urls)
        ]
        url_string = '/n/n'.join(urls_links_md)
        base_url_string = base_url_string.replace('URL', url_string)
        res_md = pn.pane.Markdown(base_url_string)
        print(res_md)
        return res_md

    def optimize_route(self, event):
        print(f'start_loc: {self.start_location}')
        start_latlong = _pull_lat_long_here(
            _geocode_destination_here(self.start_location))
        if self.is_start_equal_end:
            end_latlong = start_latlong
            self.end_latlong = start_latlong
            self.end_location = self.start_location
        else:
            end_latlong = _pull_lat_long_here(
                _geocode_destination_here(self.end_location))
        self.start_latlong = start_latlong
        self.end_latlong = end_latlong
        self.geocode_dest_list_latlong(
            event, destinations_list=self.destinations_wlist)
        self.find_best_route(event,
                             latlong_list=self.destinations_latlongs,
                             start_point=start_latlong,
                             end_point=end_latlong)

    def destinations_from_import_str(self, event):
        self.progress_bar.bar_color = 'info'
        self.progress_bar.active = True

        destinations_new = self.batch_import_str.value.split('\n')
        self.destinations_pane, self.destinations_wlist = create_destination_inputs(
            n=len(destinations_new),
            prev_destinations=None,
            init_vals=destinations_new)
        self.number_dest = len(destinations_new)
        self.progress_bar.bar_color = 'light'
        self.progress_bar.active = False

    @param.depends('is_start_equal_end')
    def start_end_widget(self):
        if self.is_start_equal_end:
            self.end_location = self.start_location
            self.end_latlong = self.start_latlong
            return pn.Column(self.param.start_location,
                             self.param.is_start_equal_end)
        else:
            return pn.Column(self.param.start_location,
                             self.param.is_start_equal_end,
                             self.param.end_location)

    def panel(self):
        # Attach a callback to geocoding & optimal route search
        self.get_best_route_action.on_click(lambda x: self.optimize_route(x))
        # Attach a callback to batch import:
        self.batch_import_str.link(self.batch_import_str,
                                   callbacks={'value': clean_space_callback})
        self.batch_import_str.value = ''
        # Attach a callback to Import Destinations button so the destinations pasted propagate into the Destinations list & sidebar
        self.get_batch_destinations.on_click(
            lambda x: self.destinations_from_import_str(x))

        # Setup the sidebar:
        widgets_sliders = pn.Column(self.param.number_dest,
                                    self.param.waypoints_per_batch)
        widgets_start_end = self.start_end_widget
        buttons_ = pn.Column(self.get_best_route_action)
        progress_bar = pn.Pane(self.progress_bar,
                               sizing_mode="stretch_width",
                               width_policy="max")

        # Set up tabs
        tab_bokeh = pn.Column(pn.Column(self.plot_bokeh),
                              self.show_urls,
                              sizing_mode="stretch_width",
                              width_policy="max")
        tab_import = pn.Row(self.batch_import_str, self.get_batch_destinations)
        self.tabs = pn.Tabs(('Optimal Route Map', tab_bokeh),
                            ('Batch Location Import', tab_import))

        result = pn.Row(
            pn.Column(
                self.title,
                widgets_sliders,
                progress_bar,
                widgets_start_end,
                buttons_,
                self.change_destinations_number,
            ),
            self.tabs,
            sizing_mode="stretch_width",
        )
        return result
 def wxdai_range(self):
     return pn.Row(pn.Pane("Cap on wxdai staked: "), self.hatch_oracle_ratio * self.total_cstk_tokens)
Example #28
0
                      width=200)

    footer = pn.pane.Markdown(
        """The black line represents the first *principal component* of the data.
    Principal Component Analysis (PCA) is simultaneously a way of finding summerizing characteristics
    of data and giving you information to assist in predicting or reconstructing the original
    features.  The first goal (summerizing relationships between features) is performed by maximizing
    the variance along the the principal component direction.  This can be seen visually as the "spread"
    of the red lines intersecting the black line.  You can see by moving the slider bar that the original
    configuration is the one that maximizes this spread.  The black line is a characteristic of the data
    that describes the strongest differences among the original features.  <br><br>
    You might also notice that any one of the blue dots can be *reconstructed* by taking the distance
    along the black line from the origin to the intersection of the perpenticular projection from the
    blue dot to the black line (i.e. the red lines).  The red lines are indicators of *reconstruction error*
    and they are simultaneously minimized in totallity at the original configuration of the plot.  Again,
    this can be seen visually by moving the slider bar and visualing the aggregate length of the red
    lines, also you can quantitatively observe the histogram of the red line lengths on the right side
    figure.  If only the first principal component was used to reconstruct the original data, the sum of
    the squares of red lines could be used as an estimate of the reconstruction error.  Additionally, if
    this aggregate error is small enough, it may assist in *feature reduction* by allowing you to only use
    the first principal component as a predictor for the original data.
    """)

    return pn.Column(pn.Row(pn.Spacer(width=400), header), alpha,
                     pn.Row(lplt, hplt), footer)


slider = pn.Pane(create_plot)
slider.servable()
#slider.app(notebook_url=remote_jupyter_proxy_url);