Beispiel #1
0
 def tap_histogram(index, x_range, y_range):
     (x0, x1), (y0, y1) = x_range, y_range
     # if nothing is selected
     if index == list():
         # select all
         index = list(self.df_extracted.index)
     return self.polys.iloc[index].opts(opts.Polygons(xlim=(x0, x1), ylim=(y0, y1)))
Beispiel #2
0
    def __post_init__(self):
        """
        :return:
        """
        data = self.spectral_cube.data

        self.ds = hv.Dataset((np.arange(data.shape[2]), np.arange(
            data.shape[1]), np.arange(data.shape[0]), data),
                             [self.spectral_axis_name, 'x', 'y'], 'Cube')
        # maybe PolyEdit as well
        # polys = hv.Polygons([hv.Box(int(self.image_width / 2), int(self.image_height / 2), int(self.image_height / 2))])
        # self.box_stream = streams.PolyEdit(source=polys)
        polys = hv.Polygons([])
        self.box_stream = streams.BoxEdit(source=polys)

        hlines = hv.HoloMap({i: hv.VLine(i)
                             for i in range(data.shape[2])}, 'wavelengths')
        dmap = hv.DynamicMap(self.roi_curves, streams=[self.box_stream])

        im = self.ds.to(hv.Image, ['x', 'y'], dynamic=True)
        self.layout = (im * polys + dmap * hlines).opts(
            opts.Image(cmap=self.color_map,
                       width=self.image_width,
                       height=self.image_height),
            opts.Curve(width=650, height=450, framewise=True),
            opts.Polygons(fill_alpha=0.2, line_color='white'),
            opts.VLine(color='black'))
Beispiel #3
0
def index():
    mystates = States.query.order_by(States.state)

    states_list = pickle.load(open(f'data/states_geo.pkl', "rb"))
    choropleth = hv.Polygons(states_list, ['lons', 'lats'],
                             ['state', 'tot', 'unemployed'])

    choropleth.opts(
        opts.Polygons(logz=True,
                      tools=['hover'],
                      xaxis=None,
                      yaxis=None,
                      show_grid=False,
                      show_frame=False,
                      width=830,
                      height=500,
                      color_index='tot',
                      cmap='Oranges',
                      colorbar=True,
                      toolbar='above',
                      line_color='white'))

    return render_template('index.html',
                           title='Health Care by the Numbers',
                           mystates=mystates)
Beispiel #4
0
def get_plot(path, poly):
    return (path * poly).opts(
        opts.Polygons(fill_alpha=0.3, active_tools=["poly_draw"]),
        opts.Path(color=LINE, height=400, line_width=5, width=400),
    )
imgs_pv = ds_sel['p_values'].hvplot.contour(**hvc_opts)
temp = xr.apply_ufunc(combine_pvalues_ufunc, ds_sel['p_values'], input_core_dims=[['ens']], \
               output_core_dims = [[]], vectorize = True, dask = 'allowed')

hvc_opts = dict(width=300, dynamic=True, \
                                         x = 'x', y = 'y',  colorbar = False, \
                                      logy = True, cmap = ['black', 'gray'], \
                                                levels=[0.01,0.05])
imgs_pv2 = temp.hvplot.contour(**hvc_opts)
# -

# ## Layout
# By combining every panel in a layout, we get clear interactive dashboard

hl = hv.HLine(0).opts(color='gray', line_dash='dotted')
dmap = dmap.opts(xticks=[(i, ens_name) for i, ens_name in enumerate(ens_ls)])
first_panel = im * imgs_pv * polys
second_panel = (dmap * hl * hlines).relabel('ROI drawer')
hv_div = hv.Div(
    f"""<h1>{invar} response to {sel_reg} for {month_names[sel_month-1]}</h1>"""
)
second_row = (
    (im2 * imgs_pv2).relabel('Model average (p-values combined using Z-score)')
    + hv_div)
layout = ((first_panel + second_panel).opts(
    opts.Curve(width=400, framewise=True),
    opts.Polygons(fill_alpha=0.2, line_color='green', fill_color='green'),
    opts.VLine(color='black')) + second_row).cols(2)

layout
Beispiel #6
0
from os.path import abspath
import webbrowser
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
from bokeh.sampledata.us_counties import data as counties
from bokeh.sampledata.unemployment import data as unemployment

counties = [dict(county, Unemployment=unemployment[cid])
            for cid, county in counties.items()
             if county["state"] == "tx"]

choropleth = hv.Polygons(counties, ['lons', 'lats'],
                         [('detailed name', 'County'), 'Unemployment'])

choropleth.opts(opts.Polygons(logz=True,
                              tools=['hover'],
                              xaxis=None, yaxis=None,
                              show_grid=False,
                              show_frame=False,
                              width=500, height=500,
                              color_index='Unemployment',
                              colorbar=True, toolbar='above',
                              line_color='white')) 

hv.save(choropleth, 'texas.html', backend='bokeh')
url = abspath('texas.html')
webbrowser.open(url)
Beispiel #7
0
    def plot(self):
        """plot pane"""
        # get the tract list
        tract_list = self.tracts_in_widget()

        # extract the filter from the original data
        self.df_filter = self.df[self.df['filter'] == self.filter_]
        # extract only the provided metric
        self.df_extracted = self.df_filter[['tract','geometry', self.metric, 'x0','x1','y0','y1']]
        # rename the metric column (necessary abstraction for plotting)
        self.df_extracted = self.df_extracted.rename(columns={self.metric: 'metric'})

        if self.df.empty:
            return pn.Spacer()
        else:
            if self.geoviews:
                self.polys = gv.Polygons(gpd.GeoDataFrame(self.df_extracted).set_geometry('geometry'), vdims=['metric', 'tract']).opts(
                    tools=['hover', 'tap'], width=self.plot_width, height=self.plot_height,
                    line_width=0, active_tools=['wheel_zoom', 'tap'],
                    colorbar=True, title=self.metric, color='metric')
            else:

                def create_dict(row):
                    """create a dictionary representation of a df row"""
                    d = {('x','y'): np.array(row.geometry.exterior.coords),
                         'tract': row['tract'],
                         'metric': row['metric']
                        }
                    return d
                # create a dictionary reprresentation of the dataframe
                data = list(self.df_extracted.apply(create_dict, axis=1))
                # declare polygons
                self.polys = hv.Polygons(data, vdims=['metric', 'tract']).opts(
                    tools=['hover', 'tap'],
                    line_width=0, active_tools=['wheel_zoom', 'tap'],
                    colorbar=True, title=self.metric, color='metric')

            # Declare Tap stream with polys as source and initial values
            self.stream.source = self.polys

            # Define a RangeXY stream linked to the image (preserving ranges from the previous image)
            self.rangexy = hv.streams.RangeXY(
                source=self.polys,
                x_range=self.rangexy.x_range,
                y_range=self.rangexy.y_range,
            )
            # set padding (degrees)
            padding = 0

            # get the limits of the selected filter/metric data
            xmin = self.df_extracted.x0.min() - padding
            xmax = self.df_extracted.x1.max() + padding
            ymin = self.df_extracted.y0.min() - padding
            ymax = self.df_extracted.y1.max() + padding

            # convert to google mercator if using geoviews
            # TODO this produces reasonable, but incorrect results
            if self.geoviews:
                xmin, ymin = ccrs.GOOGLE_MERCATOR.transform_point(xmin, ymin, ccrs.PlateCarree())
                xmax, ymax = ccrs.GOOGLE_MERCATOR.transform_point(xmax, ymax, ccrs.PlateCarree())

            # create hook for reseting to full extent
            def reset_range_hook(plot, element):
                plot.handles['x_range'].reset_start = xmin
                plot.handles['x_range'].reset_end = xmax
                plot.handles['y_range'].reset_start = ymin
                plot.handles['y_range'].reset_end = ymax

            # Define function to compute selection based on tap location
            def tap_histogram(index, x_range, y_range):
                (x0, x1), (y0, y1) = x_range, y_range
                # if nothing is selected
                if index == list():
                    # select all
                    index = list(self.df_extracted.index)
                return self.polys.iloc[index].opts(opts.Polygons(xlim=(x0, x1), ylim=(y0, y1)))
            tap_dmap = hv.DynamicMap(tap_histogram, streams=[self.stream, self.rangexy])

            # set up the plot to match the range stream
            if not self.rangexy.x_range and not self.rangexy.y_range:
                (x0, x1, y0, y1) = (None, None, None, None)
            else:
                (x0, x1), (y0, y1) = self.rangexy.x_range, self.rangexy.y_range

            return self.polys.opts(opts.Polygons(xlim=(x0, x1),
                                                 ylim=(y0, y1),
                                                 hooks=[reset_range_hook],
                                                 responsive=True,
                                                 bgcolor='black')) # TODO: responsive=True isn't changing the width
Beispiel #8
0
from holoviews.element.tiles import StamenTerrain
from mednum.loaders import *
from pygal.style import Style
from mednum import tools
from mednum.config import *

import mednum as mind


gv.extension("bokeh")

opts.defaults(
    opts.Polygons(
        width=800,
        height=600,
        toolbar="above",
        colorbar=True,
        tools=["hover", "tap"],
        aspect="equal",
    )
)


class OverallParameters(param.Parameterized):
    localisation = param.String(default="Jegun", label="")
    score = param.Range(default=(0, 250), bounds=(0, 250),)

    tout_axes = param.Boolean(False, label="")
    interfaces_num = param.ListSelector(label="")
    infos_num = param.ListSelector(label="")
    comp_admin = param.ListSelector(label="")
    comp_usage_num = param.ListSelector(label="")
Beispiel #9
0
polys = hv.Polygons([])
box_stream = streams.BoxEdit(source=polys)


def roi_curves(data):
    if not data or not any(len(d) for d in data.values()):
        return hv.NdOverlay({0: hv.Curve([], 'Time', 'Fluorescence')})

    curves = {}
    data = zip(data['x0'], data['x1'], data['y0'], data['y1'])
    for i, (x0, x1, y0, y1) in enumerate(data):
        selection = ds.select(x=(x0, x1), y=(y0, y1))
        curves[i] = hv.Curve(selection.aggregate('Time', np.mean))
    return hv.NdOverlay(curves)


hlines = hv.HoloMap({i: hv.VLine(i) for i in range(50)}, 'Time')
dmap = hv.DynamicMap(roi_curves, streams=[box_stream])

im = ds.to(hv.Image, ['x', 'y'], dynamic=True)
layout = (im * polys + dmap * hlines).opts(
    opts.Curve(width=400, framewise=True),
    opts.Polygons(fill_alpha=0.2, line_color='white'),
    opts.VLine(color='black'))

#hv.renderer('bokeh').server_doc(layout)
#pn.panel(layout).servable(title='babla')

server = pn.serve(layout, start=False, show=False)
server.start()
Beispiel #10
0
    def plot(self):

        debug("OverviewApp.plot()")
        """plot pane"""
        # get the tract list
        tract_list = self.tracts_in_widget()

        # extract the filter from the original data
        self.df_filter = self.df[self.df["filter"] == self.filter_]

        # extract only the provided metric
        self.df_extracted = self.df_filter[["tract", "geometry", self.metric, "x0", "x1", "y0", "y1"]]

        # filter down tracts
        self.df_extracted = self.df_extracted.loc[self.df_extracted.tract.isin(self.active_tracts)]

        debug("OverviewApp.plot() --> Number of Tracts to Plot {}".format(len(self.df_extracted)))

        # rename the metric column (necessary abstraction for plotting)
        self.df_extracted = self.df_extracted.rename(columns={self.metric: "metric"})

        if self.df.empty:
            return pn.Spacer()
        else:

            def create_dict(row):
                """create a dictionary representation of a df row"""
                d = {
                    ("x", "y"): np.array(row.geometry.exterior.coords),
                    "tract": row["tract"],
                    "metric": row["metric"],
                }
                return d

            # create a dictionary reprresentation of the dataframe
            data = list(self.df_extracted.apply(create_dict, axis=1))

            # declare polygons
            self.polys = hv.Polygons(data, vdims=["metric", "tract"]).opts(
                tools=["hover", "tap", "box_select"],
                line_width=0,
                active_tools=["wheel_zoom", "tap"],
                colorbar=True,
                title=self.metric,
                color="metric",
            )

            # Declare Tap stream with polys as source and initial values
            self.stream.source = self.polys

            # Define a RangeXY stream linked to the image (preserving ranges from the previous image)
            self.rangexy = hv.streams.RangeXY(
                source=self.polys, x_range=self.rangexy.x_range, y_range=self.rangexy.y_range,
            )
            # set padding (degrees)
            padding = 0

            # get the limits of the selected filter/metric data
            xmin = self.df_extracted.x0.min() - padding
            xmax = self.df_extracted.x1.max() + padding
            ymin = self.df_extracted.y0.min() - padding
            ymax = self.df_extracted.y1.max() + padding

            # create hook for reseting to full extent
            def reset_range_hook(plot, element):
                plot.handles["x_range"].reset_start = xmin
                plot.handles["x_range"].reset_end = xmax
                plot.handles["y_range"].reset_start = ymin
                plot.handles["y_range"].reset_end = ymax

            # Define function to compute selection based on tap location
            def tap_histogram(index, x_range, y_range):
                (x0, x1), (y0, y1) = x_range, y_range
                # if nothing is selected
                if index == list():
                    # select all
                    index = list(self.df_extracted.index)
                return self.polys.iloc[index].opts(opts.Polygons(xlim=(x0, x1), ylim=(y0, y1)))

            tap_dmap = hv.DynamicMap(tap_histogram, streams=[self.stream, self.rangexy])

            # set up the plot to match the range stream
            if not self.rangexy.x_range and not self.rangexy.y_range:
                (x0, x1, y0, y1) = (None, None, None, None)
            else:
                (x0, x1), (y0, y1) = self.rangexy.x_range, self.rangexy.y_range

            return self.polys.opts(
                opts.Polygons(
                    xlim=(x0, x1), ylim=(y0, y1), hooks=[reset_range_hook], responsive=True, bgcolor="black"
                )
            )  # TODO: responsive=True isn't changing the width
Beispiel #11
0
EXCLUDED = ('ak', 'hi', 'pr', 'gu', 'vi', 'mp', 'as')

counties = [
    dict(county, Density=popl_dens_dict[cid])
    for cid, county in counties.items() if county["state"] not in EXCLUDED
]

choropleth = hv.Polygons(counties, ['lons', 'lats'],
                         [('detailed name', 'County'), 'Density'])

choropleth.opts(
    opts.Polygons(
        logz=True,
        tools=['hover'],
        xaxis=None,
        yaxis=None,
        show_grid=False,
        show_frame=False,
        width=1100,
        height=700,
        colorbar=True,
        toolbar='above',
        color_index='Density',
        cmap='Greys',
        line_color=None,
        title='2010 Population Density per Square Mile of Land Area'))

hv.save(choropleth, 'choropleth.html', backend='bokeh')
url = abspath('choropleth.html')
webbrowser.open(url)