Exemple #1
0
def color_dmap(butler, tracts=None, descriptions=['color_wPerp', 'color_xPerp', 'color_yPerp'], 
               styles=['psfMagHist', 'sky-stars'], scale=1.0):
    if tracts is None:
        tracts = get_tracts(butler)
    dmap = hv.DynamicMap(partial(color_tract_layout, butler=butler, tracts=tracts, scale=scale), kdims=['description', 'style'])
    dmap = dmap.redim.values(description=descriptions, style=styles)
    return dmap
def ROI_plot(reference,region_names,stretch):
    
    #Define parameters for plot presentation
    nobjects = len(region_names) #get number of objects to be drawn

    #Make reference image the base image on which to draw
    image = hv.Image((np.arange(reference.shape[1]), np.arange(reference.shape[0]), reference))
    image.opts(width=int(reference.shape[1]*stretch['width']),
               height=int(reference.shape[0]*stretch['height']),
              invert_yaxis=True,cmap='gray',
              colorbar=True,
               toolbar='above',
              title="Draw Regions: "+', '.join(region_names))

    #Create polygon element on which to draw and connect via stream to PolyDraw drawing tool
    poly = hv.Polygons([])
    poly_stream = streams.PolyDraw(source=poly, drag=True, num_objects=nobjects, show_vertices=True)
    poly.opts(fill_alpha=0.3, active_tools=['poly_draw'])

    def centers(data):
        try:
            x_ls, y_ls = data['xs'], data['ys']
        except TypeError:
            x_ls, y_ls = [], []
        xs = [np.mean(x) for x in x_ls]
        ys = [np.mean(y) for y in y_ls]
        rois = region_names[:len(xs)]
        return hv.Labels((xs, ys, rois))

    dmap = hv.DynamicMap(centers, streams=[poly_stream])
    
    return (image * poly * dmap), poly_stream
def hv_test():
    def clifford_equation(a, b, c, d, x0, y0):
        xn, yn = x0, y0
        coords = [(x0, y0)]
        for i in range(10000):
            x_n1 = np.sin(a * yn) + c * np.cos(a * xn)
            y_n1 = np.sin(b * xn) + d * np.cos(b * yn)
            xn, yn = x_n1, y_n1
            coords.append((xn, yn))
        return coords

    hv.opts.defaults(
        hv.opts.Curve(color='black'),
        hv.opts.Points(color='red', alpha=0.1, width=400, height=400))

    def clifford_attractor(a, b, c, d):
        return hv.Points(clifford_equation(a, b, c, d, x0=0, y0=0))

    clifford = hv.DynamicMap(clifford_attractor, kdims=['a', 'b', 'c', 'd'])
    clifford.redim.range(a=(-1.5, -1),
                         b=(1.5, 2),
                         c=(1, 1.2),
                         d=(0.75, 0.8),
                         x=(-2, 2),
                         y=(-2, 2))
    clifford
Exemple #4
0
    def test_scatter_selection_streaming(self):
        buffer = hv.streams.Buffer(self.data.iloc[:2], index=False)
        scatter = hv.DynamicMap(hv.Scatter, streams=[buffer])
        lnk_sel = link_selections.instance()
        linked = lnk_sel(scatter)

        # Perform selection of first and (future) third point
        boundsxy = lnk_sel._selection_expr_streams[0]._source_streams[0]
        self.assertIsInstance(boundsxy, hv.streams.BoundsXY)
        boundsxy.event(bounds=(0, 0, 4, 2))
        current_obj = linked[()]

        # Check initial base layer
        self.check_base_scatter_like(
            current_obj.Scatter.I, lnk_sel, self.data.iloc[:2]
        )

        # Check selection layer
        self.check_overlay_scatter_like(
            current_obj.Scatter.II, lnk_sel, self.data.iloc[[0]]
        )

        # Now stream third point to the DynamicMap
        buffer.send(self.data.iloc[[2]])
        current_obj = linked[()]

        # Check initial base layer
        self.check_base_scatter_like(
            current_obj.Scatter.I, lnk_sel, self.data
        )

        # Check selection layer
        self.check_overlay_scatter_like(
            current_obj.Scatter.II, lnk_sel, self.data.iloc[[0, 2]]
        )
Exemple #5
0
def network_util_graph():

    renderer = hv.renderer('bokeh')

    # Define DynamicMap callbacks returning Elements

    def network_map(data):
        plot = hv.Curve(data).options(title="Network utilization (algo1)",
                                      width=800,
                                      padding=0.1)
        return plot

    network_stream = hv.streams.Buffer(get_network_data(),
                                       length=500,
                                       index=False)

    def cb():
        network_stream.send(get_network_data())

    # Define DynamicMaps and display plot

    network_dmap = hv.DynamicMap(network_map, streams=[network_stream])

    # Render plot and attach periodic callback
    cb_attacher = PeriodicCallback(cb, 100)
    cb_attacher.start()
    return network_dmap, cb_attacher
Exemple #6
0
 def plotMap(self, show=True):
     ''' Plot the map'''
     #print(self.mapUrl)
     option = '?list_dir=no'
     vsiCurl = f'/vsicurl/{option}&url={self.mapUrl}'
     #
     da = rioxarray.open_rasterio(vsiCurl,
                                  overview_level=3,
                                  parse_coordinates=True,
                                  chunks=dict(band=1, y=512, x=512),
                                  masked=False).squeeze('band')
     img = da.hvplot.image(rasterize=True,
                           cmap='gray',
                           x='x',
                           y='y',
                           aspect='equal',
                           frame_width=400,
                           title=os.path.basename(self.mapUrl)).opts(
                               active_tools=['box_select'])
     self.box.source = img
     bounds = hv.DynamicMap(lambda bounds: hv.Bounds(bounds),
                            streams=[self.box]).opts(color='red')
     if show:
         mapview = pn.Column(img * bounds)
     else:
         mapview = None
     return mapview
    def plot_ripple_dynamic(self):
        dmap = hv.DynamicMap(self.plot_ripple_all,
                             kdims=hv.Dimension(
                                 'rip_ind',
                                 range=(0, self.riptimes.get_num_events())))

        return dmap
Exemple #8
0
def cpu_boxplot():
    renderer = hv.renderer('bokeh')

    def datafunc_down(data):
        algo1_data = data['algo-1']
        algo2_data = data['algo-2']

        return hv.BoxWhisker(algo1_data, vdims='algo-1') + hv.BoxWhisker(
            algo2_data, vdims='algo-2')

    # def datafunc_up(data):
    #    return hv.BoxWhisker(data, vdims='cpu usage algo2')
    def cb():
        down_stream.send(get_cpu_boxplot_data())

    down_stream = hv.streams.Buffer(get_cpu_boxplot_data(),
                                    length=100,
                                    index=False)
    mem_dmap = hv.DynamicMap(datafunc_down, streams=[down_stream])

    # Render plot and attach periodic callback

    cb_attacher = PeriodicCallback(cb, 100)
    cb_attacher.start()
    return mem_dmap, cb_attacher
Exemple #9
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # grey glyph for drawing label -1 (unlabeled)
        self.cmap[-1] = '#999999'

        self.path_plot = hv.DynamicMap(self.plot_path, streams=[self.pipe])
        self.freehand.source = self.path_plot

        self.path_plot.opts(opts.Path(active_tools=['freehand_draw']))
        self.pointer_pos.source = self.path_plot
        self.clicked_pos.source = self.path_plot
        self.zoom_range.source = self.path_plot
        self.plot_size.source = self.path_plot

        self.path_plot = self.path_plot * hv.DynamicMap(self.plot_pointer)
Exemple #10
0
    def view(
        self,
        ch_to_display,
        scalebar_size,
        rescale_factor,
        show_legend=True,
        legend_position="bottom_left",
    ):

        w = self.data.sizes["x"]
        h = self.data.sizes["y"]

        self.prepare_data(ch_to_display)
        self.combine_ch_colors()
        self.prepare_texts(ch_to_display)

        self.rangexy = hv.streams.RangeXY(source=self.rendered_image)
        self.scalebar_size = scalebar_size

        self.regridded_image = (
            regrid(self.rendered_image, streams=[self.rangexy])
            .options(framewise=True)
            .opts(width=int(w / rescale_factor), height=int(h / rescale_factor))
        )
        self.scalebar_image = self.regridded_image * hv.DynamicMap(
            self.scalebar, streams=[self.rangexy]
        )

        self.overlay_image = hv.Overlay([self.scalebar_image] + self.captions_legend)
        self.final_image = self.overlay_image.collate().opts(
            show_legend=show_legend, legend_position=legend_position
        )
        return self.final_image
    def test_points_selection_streaming(self):
        buffer = hv.streams.Buffer(self.data.iloc[:2], index=False)
        points = hv.DynamicMap(Points, streams=[buffer])
        lnk_sel = link_selections.instance(unselected_color='#ff0000')
        linked = lnk_sel(points)

        # Perform selection of first and (future) third point
        selectionxy = TestLinkSelections.get_value_with_key_type(
            lnk_sel._selection_expr_streams,
            hv.Points).input_streams[0].input_stream.input_streams[0]
        self.assertIsInstance(selectionxy, hv.streams.SelectionXY)
        selectionxy.event(bounds=(0, 0, 4, 2))
        current_obj = linked[()]

        # Check initial base layer
        self.check_base_points_like(current_obj.Points.I, lnk_sel,
                                    self.data.iloc[:2])

        # Check selection layer
        self.check_overlay_points_like(current_obj.Points.II, lnk_sel,
                                       self.data.iloc[[0]])

        # Now stream third point to the DynamicMap
        buffer.send(self.data.iloc[[2]])
        current_obj = linked[()]

        # Check initial base layer
        self.check_base_points_like(current_obj.Points.I, lnk_sel, self.data)

        # Check selection layer
        self.check_overlay_points_like(current_obj.Points.II, lnk_sel,
                                       self.data.iloc[[0, 2]])
Exemple #12
0
    def box_chooser(self, **kwargs):
        '''
        Visual tool for choosing rectangle shaped blocks in mask.
        :param kwargs: array, if you want to pre select pixels,
                       initialize_mask, True if you want to initialize mask.
                                        True also Overrides array.
                                        False does nothing and overrides
                                        nothing
                       initialize_value, what value you want to use in
                                        initialisation. Used if initialize_mask
                                        is True. Fallback value is 0.
        :return: hv.Object
        '''
        # cube.test_for_not_none()
        wid = len(self._obj.coords[self._obj.M.dims[1]])
        hei = len(self._obj.coords[self._obj.M.dims[0]])
        # dep = len(cube.band)

        self.__do_mask_changes(**kwargs)
        all_pixels = np.array(list(itertools.product(range(wid), range(hei))))
        mask_dims = self._obj.M.dims.copy()
        mask_dims.reverse()
        points = hv.Points(all_pixels, kdims=mask_dims)
        # print(points)
        ds_attrs = self._make_dataset_opts()
        dataset3d = hv.Dataset(**ds_attrs)
        box = hv.streams.BoundsXY(source=points, bounds=(0, 0, 0, 0))
        bounds = hv.DynamicMap(lambda bounds: hv.Bounds(bounds), streams=[box])
        third_dim_list = list(self._obj.dims)
        third_dim_list.remove(mask_dims[0])
        third_dim_list.remove(mask_dims[1])
        layout = decimate(points) * \
                 dataset3d.to(hv.Image,
                              mask_dims,
                              'Value',
                              third_dim_list) * \
                 bounds + \
                 decimate(
                     hv.DynamicMap(
                         lambda bounds: hv.Points(
                             self._record_selections(bounds, points),
                             kdims=mask_dims
                         ),
                         streams=[box]
                     )
                 )
        return layout
def plotNselect_tSNE(df_feat, features, size=10, perplexity=80, ncomp=2):
    df_i = df_feat.dropna()
    df_i = df_i.reset_index(drop=True)

    Y = TSNE(perplexity=perplexity,
             n_components=ncomp).fit_transform(df_i[features])

    options = dict(legend_position='left',
                   width=1000,
                   height=600,
                   scaling_method='width',
                   scaling_factor=2,
                   size_index=2,
                   show_grid=True,
                   tools=['hover', 'box_select', 'lasso_select'],
                   line_color='k',
                   cmap='Accent',
                   size=size,
                   nonselection_color='lightskyblue')
    quality_scatter = hv.Scatter(Y).options(**options)
    sel = streams.Selection1D(source=quality_scatter)

    image_name = df_i.loc[0, "img_name_raw"]
    img = cv2.imread(image_name, 0)
    h, w = img.shape
    w = int(0.8 * w)
    h = int(0.8 * h)
    pad = int(2.2 * w)

    def selection_callback(index):
        if not index:
            return hv.Div("")
        divtext = f'<table width={pad}  border=1 cellpadding=10 align=center valign=center>'
        for i, j in grouped(index, 2):
            value_s = '{:f}'.format(df_i[value][i])
            value_s2 = '{:f}'.format(df_i[value][j])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {i} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> {j} Value: {value_s2}</br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[i, "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[j, "img_name_raw"]} width={w} height={h}></td>'
            divtext += '</tr>'
        if len(index) % 2 == 1:
            value_s = '{:f}'.format(df_i[value][index[-1]])
            divtext += '<tr>'
            divtext += f'<td align=center valign=center><br> {index[-1]} Value: {value_s}</br></td>' + "\n"
            divtext += f'<td align=center valign=center><br> </br></td>' + "\n"
            divtext += '</tr><tr>'
            divtext += f'<td align=center valign=center><img src={df_i.loc[index[-1], "img_name_raw"]} width={w} height={h}></td>'
            divtext += f'<td align=center valign=center></td>'
            divtext += '</tr>'
        divtext += '</table>'
        return hv.Div(str(divtext))

    div = hv.DynamicMap(selection_callback, streams=[sel])
    hv.streams.PlotReset(source=quality_scatter,
                         subscribers=[lambda reset: sel.event(index=[])])
    return hv.Layout(quality_scatter + div).cols(1), sel
Exemple #14
0
def plot_column_slider(df, chart=hv.Curve, slider=False, imag_label='error'):
    '''create a Holoviews dynamic map that slice through each column

    `df`: DataFrame. if complex, take the real part as the value and imaginary part as the error bar

    `chart`: any Holoview Chart class such as Curve, Scatter

    `slider`: if True, force slider

    `imag_label`: label for the curve in the imaginary part

    hint: add ``%%opts Curve {+framewise}`` to readjust the frame on each selection
    '''
    # dispatch MultiIndex or not
    is_multi = isinstance(df.columns, pd.core.indexes.api.MultiIndex)
    is_complex = np.iscomplexobj(df)

    def plot(*args):
        # get series from a slice and its label
        if is_multi:
            _args = [
                levels[arg]
                for levels, arg in zip(df.columns.levels, args)
            ] if slider else args
            _slice = tuple(map(lambda x: slice(x, x), _args))
            series = df.loc[:, _slice]
            label = ', '.join(map(str, _args))
            del _args, _slice
        # since it is not a MultiIndex, args is of length 1
        else:
            arg = args[0]
            _arg = df.columns[arg] if slider else arg
            series = df[_arg]
            label = str(_arg)
            del arg, _arg

        x = series.index
        y = series.values
        del series

        if is_complex:
            _chart = chart(np.column_stack((x, y.real)), label=label)
            _chart *= chart(np.column_stack((x, y.imag)), label=imag_label)
        else:
            _chart = chart(np.column_stack((x, y)), label=label)

        if slider:
            _chart = _chart.opts(title=label)
        return _chart

    dmap = hv.DynamicMap(plot, kdims=df.columns.names)

    values = dict(zip(df.columns.names, df.columns.levels)) \
        if is_multi else \
        {df.columns.name: df.columns.values}
    if slider:
        values = {name: range(len(value)) for name, value in values.items()}

    return dmap.redim.values(**values)
Exemple #15
0
    def buildDynamicMap(self):
        ranges = self.getRanges()

        totalgraphopts = {"height": self.HEIGHT, "width": self.WIDTH}
        dm = hv.DynamicMap(self.buildCurvePlot,
                           kdims=self.freeDims).redim.range(**ranges)
        self.logger.info("Build into Dynamic Map")
        return self.renderer.get_widget(dm.opts(**totalgraphopts), 'widgets')
Exemple #16
0
    def view_map(self):
        map = hv.DynamicMap(
            self.adh_mod.wmts.view) * self.adh_mod.polys * self.adh_mod.points
        if not self.adh_mod.mesh.verts.empty:
            # map *= self.adh_mod.mesh.view_elements(line_color='black')
            map *= self.adh_mod.mesh.view_mesh(line_color='blue')

        return map.opts(width=self.map_width, height=self.map_height)
Exemple #17
0
def filter_layout_dmap_coadd(butler, descriptions, tracts=None, 
                            styles=['psfMagHist', 'sky-stars', 'sky-gals'], scale=0.66):
    if tracts is None:
        tracts = get_tracts(butler)

    if len(tracts) > 1:
        layout_fn = partial(filter_layout, butler=butler, visit=None, kind='coadd', scale=scale)
        values = dict(tract=tracts, description=descriptions, style=styles)
        dmap = hv.DynamicMap(layout_fn, kdims=['tract', 'description', 'style'])
    else:
        layout_fn = partial(filter_layout, butler=butler, tract=tracts[0],
                            visit=None, kind='coadd', scale=scale)
        values = dict(description=descriptions, style=styles)
        dmap = hv.DynamicMap(layout_fn, kdims=['description', 'style'])
    dmap = dmap.redim.values(**values) 

    return dmap
Exemple #18
0
 def mainview(self):
     image = hv.DynamicMap(self.get_image,
                           streams=[self.pipe, self.range_xy])
     if self.buffer:
         res = regrid(image)
     else:
         res = hd.regrid(image)
     return res
Exemple #19
0
    def spectre_chooser(self, **kwargs):
        '''
        Visual tool
        for visualizing selected spectra and narrowing down mask based
        on spectra. It is easy to make a mistake with this, so you should
        keep a backup of your mask. You shouldn't use this on very large sets.
        TODO: This algorithm seems quite unefficient, maybe adding threading
        TODO:        could help.
        :param kwargs: array, if you want to pre select pixels,
                       initialize_mask, True if you want to initialize mask.
                                        True also Overrides array.
                                        False does nothing and overrides
                                        nothing
                       initialize_value, what value you want to use in
                                        initialisation. Used if initialize_mask
                                        is True. Fallback value is 0.
        :return: hv.Object
        '''
        if not len(self._obj.shape) == 3:
            raise ValueError('The spectre_chooser only works for 3 ' +
                             'dimensional objects.')
        self.__do_mask_changes(**kwargs)
        third_dimension = self._obj.M.no_mask_dims[0]
        third_dim_list = self._obj.coords[third_dimension].data
        points = hv.Points(
            np.array([(np.min(third_dim_list), np.min(self._obj.data))]))
        box = hv.streams.BoundsXY(
            source=points,
            # bounds is defined as (x_min, y_min, x_max, y_max)
            bounds=(np.min(third_dim_list) - 0.001, np.min(self._obj.data) -
                    0.001, np.max(third_dim_list) + 0.001,
                    np.max(self._obj.data) + 0.01))

        bounds = hv.DynamicMap(lambda bounds: hv.Bounds(bounds), streams=[box])
        layout = points *\
                 hv.DynamicMap(
                     lambda bounds: hv.Overlay(
                         [hv.Curve((third_dim_list,zs),
                                   kdims=self._obj.M.no_mask_dims,
                                   vdims=['Value'])
                          for zs in self._new_choosing_spectre(bounds)]
                     ),
                     streams=[box]) * \
                 bounds
        return layout
Exemple #20
0
def graph():

    #dm = hv.DynamicMap(triGraph, kdims=[freedims]).redim.range(**ranges)
    dm = hv.DynamicMap(triGraph, kdims=["hi"]).redim.range(hi=(0, 89))
    print("DynamicMap:" + str(dm))
    cm = "Magma"
    if slCMap is not None:
        cm = slCMap.value
    return rasterize(dm).opts(cmap=cm, colorbar=True)
Exemple #21
0
def test_holoviews_widgets_from_dynamicmap(document, comm):
    range_dim = hv.Dimension('A', range=(0, 10.))
    range_step_dim = hv.Dimension('B', range=(0, 10.), step=0.2)
    range_default_dim = hv.Dimension('C', range=(0, 10.), default=3)
    value_dim = hv.Dimension('D', values=['a', 'b', 'c'])
    value_default_dim = hv.Dimension('E',
                                     values=['a', 'b', 'c', 'd'],
                                     default='b')
    value_numeric_dim = hv.Dimension('F', values=[1, 3, 10], default=3)
    kdims = [
        range_dim, range_step_dim, range_default_dim, value_dim,
        value_default_dim, value_numeric_dim
    ]
    dmap = hv.DynamicMap(lambda A, B, C, D, E, F: hv.Curve([]), kdims=kdims)
    widgets, _ = HoloViews.widgets_from_dimensions(dmap)

    assert len(widgets) == len(kdims)

    assert isinstance(widgets[0], FloatSlider)
    assert widgets[0].name == 'A'
    assert widgets[0].start == range_dim.range[0]
    assert widgets[0].end == range_dim.range[1]
    assert widgets[0].value == range_dim.range[0]
    assert widgets[0].step == 0.1

    assert isinstance(widgets[1], FloatSlider)
    assert widgets[1].name == 'B'
    assert widgets[1].start == range_step_dim.range[0]
    assert widgets[1].end == range_step_dim.range[1]
    assert widgets[1].value == range_step_dim.range[0]
    assert widgets[1].step == range_step_dim.step

    assert isinstance(widgets[2], FloatSlider)
    assert widgets[2].name == 'C'
    assert widgets[2].start == range_default_dim.range[0]
    assert widgets[2].end == range_default_dim.range[1]
    assert widgets[2].value == range_default_dim.default
    assert widgets[2].step == 0.1

    assert isinstance(widgets[3], Select)
    assert widgets[3].name == 'D'
    assert widgets[3].options == OrderedDict(
        zip(value_dim.values, value_dim.values))
    assert widgets[3].value == value_dim.values[0]

    assert isinstance(widgets[4], Select)
    assert widgets[4].name == 'E'
    assert widgets[4].options == OrderedDict(
        zip(value_default_dim.values, value_default_dim.values))
    assert widgets[4].value == value_default_dim.default

    assert isinstance(widgets[5], DiscreteSlider)
    assert widgets[5].name == 'F'
    assert widgets[5].options == OrderedDict([
        (str(v), v) for v in value_numeric_dim.values
    ])
    assert widgets[5].value == value_numeric_dim.default
Exemple #22
0
def live_plot(runner, *, plotter=None, update_interval=2, name=None):
    """Live plotting of the learner's data.

    Parameters
    ----------
    runner : Runner
    plotter : function
        A function that takes the learner as a argument and returns a
        holoviews object. By default learner.plot() will be called.
    update_interval : int
        Number of second between the updates of the plot.
    name : hasable
        Name for the `live_plot` task in `adaptive.active_plotting_tasks`.
        By default the name is `None` and if another task with the same name
        already exists that other live_plot is canceled.

    Returns
    -------
    dm : holoviews.DynamicMap
        The plot that automatically updates every update_interval.
    """
    try:
        import holoviews as hv
    except ModuleNotFoundError:
        raise RuntimeError('Plotting requires the holoviews Python package'
                           ' which is not installed.')

    def plot_generator():
        while True:
            if not plotter:
                yield runner.learner.plot()
            else:
                yield plotter(runner.learner)

    dm = hv.DynamicMap(plot_generator(),
                       streams=[hv.streams.Stream.define('Next')()])

    # Could have used dm.periodic in the following, but this would either spin
    # off a thread (and learner is not threadsafe) or block the kernel.
    async def updater():
        try:
            while not runner.task.done():
                dm.event()
                await asyncio.sleep(update_interval)
            dm.event()  # fire off one last update before we die
        finally:
            if active_plotting_tasks[name] is asyncio.Task.current_task():
                active_plotting_tasks.pop(name, None)

    global active_plotting_tasks
    if name in active_plotting_tasks:
        active_plotting_tasks[name].cancel()

    active_plotting_tasks[name] = asyncio.get_event_loop().create_task(
        updater())

    return dm
Exemple #23
0
def plot_surface(obj, **args):
    region = args.get('region', None)
    idx = obj.tag2idx(region)
    tags = args.get('tags', False)
    coord = args.get('coord', None)
    locator = args.get('locator', False)
    fill = args.get('fill', None)

    amin = np.min(obj.bbox_min[idx], axis=0)
    amax = np.max(obj.bbox_max[idx], axis=0)
    wh = amax - amin
    if np.min(wh) < 250:
        wh = wh / np.min(wh) * 250
    hvobj = hv.Path([obj.boundary[i]
                     for i in idx]).opts(style=dict(color='k'),
                                         plot=dict(yaxis=None,
                                                   xaxis=None,
                                                   aspect='equal',
                                                   width=int(ceil(wh[0])),
                                                   height=int(ceil(wh[1]))))

    if fill is not None:
        vals = np.nan * np.zeros((obj.num, ))
        for k in fill.keys():
            _idx = obj.tag2idx(k)
            for i in _idx:
                vals[i] = fill[k]

        imin = np.min(obj.bbox_min[idx], axis=0).astype(int)
        imax = np.max(obj.bbox_max[idx], axis=0).astype(int)
        im = np.nan * np.zeros(tuple((imax - imin + 1)[::-1].tolist()))
        for i in idx:
            im[obj._coords[i][:, 1] - imin[1],
               obj._coords[i][:, 0] - imin[0]] = vals[i]
        hvobj = hv.Image(np.flipud(im),
                         bounds=(imin[0], imin[1], imax[0], imax[1])).opts(
                             plot=dict(yaxis=None, xaxis=None))

    if coord is not None:
        hvobj *= hv.Curve([obj.hand2pixel((0,0)),obj.hand2pixel((coord,0))]) *\
            hv.Curve([obj.hand2pixel((0,0)),obj.hand2pixel((0,coord))])
    if tags:
        hvobj *= hv.Labels({
            'x': [obj._centers[i][0] for i in idx],
            'y': [obj._centers[i][1] for i in idx],
            'Label': [str(i) + ' ' + ''.join(obj.tags[i]) for i in idx]
        })

    # show cursor position in hand coordinates (works only in bokeh)
    if locator:
        pointer = hv.streams.PointerXY(x=0, y=0)
        dm = hv.DynamicMap(lambda x, y: hvobj * hv.Text(
            x, y + 5, '(%d,%d)' % tuple(obj.pixel2hand(np.array([x, y])))),
                           streams=[pointer])
        return dm

    return hvobj
Exemple #24
0
def description_layout_dmap_visit(butler, tract, descriptions, filt='HSC-I', styles=['psfMagHist', 'sky-stars', 'sky-gals'], scale=0.66):
    # visits = get_visits(field_name(tract), filt)
    if tract is None:
        tract = get_tracts(butler)[0]
    visits = get_visits(butler, tract, filt)
    dmap = hv.DynamicMap(partial(description_layout, descriptions=descriptions, butler=butler, tract=tract, filt=filt, kind='visit', scale=scale), 
                     kdims=['visit', 'style'])
    dmap = dmap.redim.values(visit=visits, style=styles)
    return dmap
Exemple #25
0
 def view(self):
     points = hv.Points(df, kdims=['x', 'y'])
     raster = rasterize(points,
                        x_sampling=1,
                        y_sampling=1,
                        width=900,
                        height=600)
     return hv.DynamicMap(self.tiles) * shade(
         raster, streams=[hv.streams.Params(self, ['cmap'])])
 def plot(self):
     dmap = hv.DynamicMap(self.show_images_and_centroids,
                          kdims=self.indcs_kdims)
     dmap = dmap.redim.range(y=(0.5 - self.scale_factor_h, 0.5),
                             x=(-0.5, -0.5 + self.scale_factor_w))
     dmap = dmap.redim.range(
         cent_y_scaled_flipped=(0.5 - self.scale_factor_h, 0.5),
         cent_x_scaled=(-0.5, -0.5 + self.scale_factor_w))
     dmap = dmap.redim.range(z=(0, self.max_dim))
     return dmap
Exemple #27
0
def create_dyndsmap():
    trange = np.arange(
        datetime.datetime(2011, 1, 1),
        utcnow,
        datetime.timedelta(days=1),
    )

    dyndsmap = hv.DynamicMap(plot_dsmap, kdims=["Stdnames", "TimeRange"])
    dyndsmap = dyndsmap.redim.values(Stdnames=valid_stdnames, TimeRange=trange)

    dyndsmap = hv.DynamicMap(
        pn.bind(
            plot_dsmap,
            stdname=wstdname_menu,
            timerange=wstdname_date,
        ),
    )

    return dyndsmap
Exemple #28
0
 def view(self):
     options = dict(width=self.width,
                    height=self.height,
                    xaxis=None,
                    yaxis=None,
                    projection=self.image.crs)
     dmap = hv.DynamicMap(self.extract_foreground, streams=[self])
     return (regrid(self.image).options(**options) * self.bg_paths *
             self.fg_paths + dmap.options(**options)).options(
                 merge_tools=False, clone=False)
def update_map_val(attr, old, new):
    global selection, vizual, gvplot, hvplot, heatmap, feats, points, world_map, temp_feats
    max_cur_feature = loc_feats[choice.value].max()
    min_cur_feature = loc_feats[choice.value].min()
    new_loc_feats = temp_feats.loc[(temp_feats[choice.value] <= new[1])
                                   & (temp_feats[choice.value] >= new[0])]
    feats = gv.Dataset(new_loc_feats,
                       kdims=['Longitude', 'Latitude', choice.value])
    points = feats.to(gv.Points, ['Longitude', 'Latitude'], [choice.value])
    if len(new_loc_feats) <= 20000:
        world_map = gv.Points(points).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    else:
        world_map = decimate(gv.Points(points), max_samples=20000).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    selection = hv.streams.Selection1D(source=world_map)
    heatmap = hv.DynamicMap(selected_points, streams=[selection])
    box = hv.streams.BoundsXY(source=world_map)
    zoom = hv.DynamicMap(test_bounds, streams=[box])
    hvplot = renderer.get_plot(heatmap, curdoc())
    gvplot = renderer.get_plot(world_map, curdoc())
    bvplot = renderer.get_plot(zoom, curdoc())
    vizual.children[1].children = [gvplot.state, hvplot.state, bvplot.state]
Exemple #30
0
    def main_graphs(self):
        self=self._update_self()
        print(self.ds.isel(time_slice=self.time_slice_deep_slider.value).amplitude.values.shape)
        _filter = self.selection(hv.DynamicMap(self._spectrum_graph))
        filter_graphs = _filter + hv.DynamicMap(self._update_filter)
        filter_graphs = filter_graphs.opts(plot=dict(shared_axes=False))

        shallow_slice = hv.DynamicMap(self._shallow_slice_graph)

        deep_slice = hv.DynamicMap(self._deep_slice_graph)

        graphs = pn.Column(
            filter_graphs,
            pn.pane.Markdown("##Shallow"),
            shallow_slice,
            pn.pane.Markdown("##Deep"),
            deep_slice,
        )
        return graphs