Esempio n. 1
0
def plot_conn_comp(conn_comps, cmap=[]):
    if len(cmap) == 0:
        return shade(hv.Image(rescale(conn_comps)),
                     normalization='linear',
                     cmap=fire_cmap)
    else:
        return shade(hv.Image(rescale(conn_comps)),
                     normalization='linear',
                     cmap=cmap)
Esempio n. 2
0
    def plot_decode_image(self,
                          time=None,
                          plt_range=None,
                          x_range=None,
                          y_range=None):
        if time is None:
            time = self.posteriors.get_time_start()
        if plt_range is None:
            plt_range = self.posteriors.get_time_total()
        if x_range is None:
            x_range = (time, time + plt_range)
        if y_range is None:
            y_range = self.posteriors.get_pos_range()

        self.post_img.extents = (x_range[0], 0, x_range[1],
                                 self.enc_settings.pos_bins[-1])
        self.post_img.relabel('posteriors')
        rgb = shade(regrid(self.post_img,
                           aggregator='mean',
                           dynamic=False,
                           x_range=x_range,
                           y_range=y_range,
                           precompute=True),
                    cmap=plt.get_cmap('hot'),
                    normalization='linear',
                    dynamic=False)

        rgb.extents = (x_range[0], 0, x_range[1],
                       self.enc_settings.pos_bins[-1])
        return rgb
Esempio n. 3
0
    def __call__(self, dset, **params):

        self.p = ParamOverrides(self, params)

        if self.p.vdim is None:
            vdim = dset.vdims[0].name
        else:
            vdim = self.p.vdim

        pts = hv.util.Dynamic(dset, operation=skypoints,
                              streams=[self.p.filter_stream])

        if self.p.aggregator == 'mean':
            aggregator = ds.mean(vdim)
        elif self.p.aggregator == 'std':
            aggregator = ds.std(vdim)
        elif self.p.aggregator == 'count':
            aggregator = ds.count()


        decimate_opts = dict(plot={'tools': ['hover',
                                             'box_select']},
                             style={'alpha': 0,
                                    'size': self.p.decimate_size,
                                    'nonselection_alpha': 0})

        decimated = decimate(pts).opts(**decimate_opts)
        raster_ = rasterize(pts, aggregator=aggregator)
        color_gadget = raster_.opts(cmap=Viridis[256], colorbar=True, alpha=0)
        sky_shaded = shade(raster_, cmap=viridis)

        plot = dynspread(sky_shaded) * decimated * color_gadget

        return plot.options(bgcolor="black", responsive=True, min_height=100)
Esempio n. 4
0
 def test_shade_categorical_images_grid(self):
     xs, ys = [0.25, 0.75], [0.25, 0.75]
     data = NdOverlay(
         {
             'A':
             Image((xs, ys, [[1, 0], [0, 0]]),
                   datatype=['grid'],
                   vdims='z Count'),
             'B':
             Image((xs, ys, [[0, 0], [1, 0]]),
                   datatype=['grid'],
                   vdims='z Count'),
             'C':
             Image((xs, ys, [[0, 0], [1, 0]]),
                   datatype=['grid'],
                   vdims='z Count')
         },
         kdims=['z'])
     shaded = shade(data)
     r = [[228, 255], [66, 255]]
     g = [[26, 255], [150, 255]]
     b = [[28, 255], [129, 255]]
     a = [[40, 0], [255, 0]]
     expected = RGB((xs, ys, r, g, b, a),
                    datatype=['grid'],
                    vdims=RGB.vdims + [Dimension('A', range=(0, 1))])
     self.assertEqual(shaded, expected)
Esempio n. 5
0
def polygons(gdf, label='', geometry='geometry', col=None, agg=ds.any):
    """Return a holoviews plot.

    Multiple holoviews plots can be collected in a list and plotted with
    hv.Layout(list_of_plots).cols(3).

    Parameters
    ----------
    gdf : geopandas.GeoDataFrame
    label : str
    geometry : geometry column
    col : str
        Column on which the datashader data aggregation will be done.
        The default is `None`.
    agg : datashader aggregation function
        The default is `ds.any`.

    Returns
    -------
    shd : holoviews plot
    """
    hv.output(backend="matplotlib")

    sgdf = spd.GeoDataFrame(gdf)
    cvs = ds.Canvas()

    if col is not None:
        agg = cvs.polygons(sgdf, geometry, agg=agg(col))
    else:
        agg = cvs.polygons(sgdf, geometry, agg=agg())

    shd = hd.shade(hv.Image(agg, label=label))

    return shd
Esempio n. 6
0
 def view(self):
     points = hv.DynamicMap(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'])])
Esempio n. 7
0
 def view(self, **kwargs):
     points = hv.DynamicMap(self.points)
     agg = rasterize(points,
                     x_sampling=1,
                     y_sampling=1,
                     width=600,
                     height=400)
     stream = hv.streams.Params(self, ['cmap'])
     tiles = hv.DynamicMap(self.tiles)
     return tiles * shade(agg, streams=[stream])
Esempio n. 8
0
 def test_shade_dt_xaxis_constant_yaxis(self):
     df = pd.DataFrame({'y': np.ones(100)}, index=pd.date_range('1980-01-01', periods=100, freq='1T'))
     rgb = shade(rasterize(Curve(df), dynamic=False, width=3))
     xs = np.array(['1980-01-01T00:16:30.000000', '1980-01-01T00:49:30.000000',
                    '1980-01-01T01:22:30.000000'], dtype='datetime64[us]')
     ys = np.array([])
     bounds = (np.datetime64('1980-01-01T00:00:00.000000'), 1.0,
               np.datetime64('1980-01-01T01:39:00.000000'), 1.0)
     expected = RGB((xs, ys, np.empty((0, 3, 4))), ['index', 'y'],
                    xdensity=1, ydensity=1, bounds=bounds)
     self.assertEqual(rgb, expected)
Esempio n. 9
0
 def one_band(band, time):
     xs, ys = dataset[band].sel(time=time)[dims[0]], dataset[band].sel(
         time=time)[dims[1]]
     b = ds.utils.orient_array(dataset[band].sel(time=time))
     a = (np.where(np.logical_or(np.isnan(b), b <= nodata), 0,
                   255)).astype(np.uint8)
     return shade(regrid(
         hv.RGB((xs, ys[::-1], b, b, b, a), vdims=list('RGBA'))),
                  cmap=cmap,
                  clims=clims,
                  normalization=norm).redim(x=dims[0],
                                            y=dims[1]).opts(width=width,
                                                            height=height)
Esempio n. 10
0
 def test_shade_categorical_images_grid(self):
     xs, ys = [0.25, 0.75], [0.25, 0.75]
     data = NdOverlay({'A': Image((xs, ys, [[1, 0], [0, 0]]), datatype=['grid'], vdims='z Count'),
                       'B': Image((xs, ys, [[0, 0], [1, 0]]), datatype=['grid'], vdims='z Count'),
                       'C': Image((xs, ys, [[0, 0], [1, 0]]), datatype=['grid'], vdims='z Count')},
                      kdims=['z'])
     shaded = shade(data)
     r = [[228, 255], [66, 255]]
     g = [[26, 255], [150, 255]]
     b = [[28, 255], [129, 255]]
     a = [[40, 0], [255, 0]]
     expected = RGB((xs, ys, r, g, b, a), datatype=['grid'],
                    vdims=RGB.vdims+[Dimension('A', range=(0, 1))])
     self.assertEqual(shaded, expected)
Esempio n. 11
0
    def plot_decode_image(self,
                          time,
                          x_range=None,
                          y_range=None,
                          plt_range=10):

        sel_range = [time, time + plt_range]

        if (x_range is None):
            x_range = [time, time + plt_range]

        if (y_range is None):
            y_range = [0, self.enc_settings.pos_bins[-1]]

        x_range = list(x_range)
        #x_range[0] -= plt_range
        #x_range[1] += plt_range
        x_range[0] = max(x_range[0], self.posteriors.get_time_start())
        x_range[1] = min(x_range[1], self.posteriors.get_time_end())

        # post_time = self.posteriors.index.get_level_values('time')
        # img_sel = self.posteriors.get_distribution_view().query("(time > @x_range[0]) & (time < @x_range[1])").values.T
        # img_sel = np.flip(img_sel, axis=0)

        # img = hv.Image(img_sel, bounds=(x_range[0], self.enc_settings.pos_bins[0],
        #                                 x_range[1],
        #                                 self.enc_settings.pos_bins[-1]),
        #                kdims=['time (sec)', 'linpos (cm)'], vdims=['probability'],)

        # img = img.redim(probability={'range': (0, 0.3)})
        # img.extents = (sel_range[0], 0, sel_range[1], self.enc_settings.pos_bins[-1])
        self.post_img.extents = (sel_range[0], 0, sel_range[1],
                                 self.enc_settings.pos_bins[-1])
        self.post_img.relabel('posteriors')
        rgb = shade(regrid(self.post_img,
                           aggregator='max',
                           dynamic=False,
                           x_range=x_range,
                           y_range=y_range),
                    cmap=plt.get_cmap('magma'),
                    normalization='linear',
                    dynamic=False)
        # rgb = shade(regrid(self.post_img, aggregator='mean', dynamic=False,
        #                    x_range=x_range, y_range=y_range, y_sampling=1, x_sampling=0.001),
        #             cmap=plt.get_cmap('hot'), normalization='linear', dynamic=False)

        rgb.extents = (sel_range[0], 0, sel_range[1],
                       self.enc_settings.pos_bins[-1])
        return rgb
ddf = ddf.persist()

from bokeh.models import WMTSTileSource
url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'
wmts = gv.WMTS(WMTSTileSource(url=url))

stream = hv.streams.Stream.define('HourSelect', hour=0)()
points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])
dmap = hv.util.Dynamic(points, operation=lambda obj, hour: obj.select(hour=hour),
                       streams=[stream])

# Apply aggregation
aggregated = aggregate(dmap, link_inputs=True)

# Shade the data
shaded = shade(aggregated)

# Define PointerX stream, attach to points and declare DynamicMap for cross-section and VLine
pointer = hv.streams.PointerX(x=ddf.dropoff_x.loc[0].compute().iloc[0], source=points)
section = hv.util.Dynamic(aggregated, operation=lambda obj, x: obj.sample(dropoff_x=x),
                          streams=[pointer], link_inputs=False)
vline = hv.DynamicMap(lambda x: hv.VLine(x), streams=[pointer])

# Define options
hv.opts("RGB [width=800 height=600 xaxis=None yaxis=None] VLine (color='black' line_width=1)")
hv.opts("Curve [width=100 yaxis=None show_frame=False] (color='black') {+framewise} Layout [shared_axes=False]")

# Combine it all into a complex layout
hvobj = (wmts * shaded * vline) << section

### Pass the HoloViews object to the renderer
 def render_to_browser(self, **kwargs):
     points = hv.DynamicMap(hv.Points(self.data, kdims=['x', 'y']))
     tiles = CartoDark().apply.opts(**self.opts)
     agg = rasterize(points, width=1200, height=800)
     pn.serve(pn.Row(tiles * shade(agg, cmap=cm[self.color_map])),
              title='Datashader MapTiler')
from bokeh.models import WMTSTileSource
url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'
wmts = gv.WMTS(WMTSTileSource(url=url))

stream = hv.streams.Stream.define('HourSelect', hour=0)()
points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])
dmap = hv.util.Dynamic(points,
                       operation=lambda obj, hour: obj.select(hour=hour),
                       streams=[stream])

# Apply aggregation
aggregated = aggregate(dmap, link_inputs=True)

# Shade the data
shaded = shade(aggregated)

# Define PointerX stream, attach to points and declare DynamicMap for cross-section and VLine
pointer = hv.streams.PointerX(x=ddf.dropoff_x.loc[0].compute().iloc[0],
                              source=points)
section = hv.util.Dynamic(aggregated,
                          operation=lambda obj, x: obj.sample(dropoff_x=x),
                          streams=[pointer],
                          link_inputs=False)
vline = hv.DynamicMap(lambda x: hv.VLine(x), streams=[pointer])

# Define options
hv.opts(
    "RGB [width=800 height=600 xaxis=None yaxis=None] VLine (color='black' line_width=1)"
)
hv.opts(
Esempio n. 15
0
def plot_conn_comp(conn_comps):
    return shade(hv.Image(rescale(conn_comps)),
                 normalization='linear',
                 cmap=fire_cmap)
Esempio n. 16
0
def plot_raw_image(img):
    return shade(hv.Image(rescale(img)), normalization='linear', cmap=gray)
Esempio n. 17
0
def main(argv):

    clock_start = time.time()

    # Command line options

    parser = ArgumentParser(description='Rapid Measurement Set plotting with xarray-ms and datashader. Version {0:s}'.format(__version__))

    parser.add_argument('ms', 
                      help='Measurement set')
    parser.add_argument("-v", "--version", action='version',
                      version='{:s} version {:s}'.format(parser.prog, __version__))
    parser.add_argument('--xaxis', dest='xaxis',
                      help='[t]ime (default), [f]requency, [c]hannels, [u], [uv]distance, [r]eal, [a]mplitude', default='t')
    parser.add_argument('--yaxis', dest='yaxis',
                      help='[a]mplitude (default), [p]hase, [r]eal, [i]maginary, [v]', default='a')
    parser.add_argument('--col', dest='col',
                      help='Measurement Set column to plot (default = DATA)', default='DATA')
    parser.add_argument('--field', dest='myfields',
                      help='Field ID(s) to plot (comma separated list, default = all)', default='all')
    parser.add_argument('--spws', dest='myspws',
                      help='Spectral windows (DDIDs) to plot (comma separated list, default = all)', default='all')
    parser.add_argument('--corr', dest='corr',
                      help='Correlation index to plot (default = 0)', default=0)
    parser.add_argument('--noflags', dest='noflags',
                      help='Plot flagged data (default = False)', action='store_true', default=False)
    parser.add_argument('--noconj', dest='noconj',
                      help='Do not show conjugate points in u,v plots (default = plot conjugates)', action='store_true', default=False)
    parser.add_argument('--xmin', dest='xmin',
                      help='Minimum x-axis value (default = data min)', default='')
    parser.add_argument('--xmax', dest='xmax',
                      help='Maximum x-axis value (default = data max)', default='')
    parser.add_argument('--ymin', dest='ymin',
                      help='Minimum y-axis value (default = data min)', default='')
    parser.add_argument('--ymax', dest='ymax',
                      help='Maximum y-axis value (default = data max)', default='')
    parser.add_argument('--xcanvas', dest='xcanvas',
                      help='Canvas x-size in pixels (default = 1280)', default=1280)
    parser.add_argument('--ycanvas', dest='ycanvas',
                      help='Canvas y-size in pixels (default = 800)', default=900)
    parser.add_argument('--norm', dest='normalize',
                      help='Pixel scale normalization: eq_hist (default), cbrt, log, linear', default='eq_hist')
    parser.add_argument('--cmap', dest='mycmap',
                      help='Colorcet map to use (default = bkr)', default='bkr')
    parser.add_argument('--bgcol', dest='bgcol',
                      help='RGB hex code for background colour (default = FFFFFF)', default='FFFFFF')
    parser.add_argument('--fontsize', dest='fontsize',
                      help='Font size for all text elements (default = 20)', default=20)
    parser.add_argument('--png', dest='pngname',
                      help='PNG name (default = something verbose)', default='')
    parser.add_argument('--stamp', dest='dostamp',
                      help='Add timestamp to default PNG name', action='store_true', default=False)

    # Assign inputs

    options = parser.parse_args(argv)

    xaxis = options.xaxis.lower()
    yaxis = options.yaxis.lower()
    col = options.col.upper()
    myfields = options.myfields
    corr = int(options.corr)
    myspws = options.myspws
    noflags = options.noflags
    noconj = options.noconj
    xmin = options.xmin
    xmax = options.xmax
    ymin = options.ymin
    ymax = options.ymax
    xcanvas = int(options.xcanvas)
    ycanvas = int(options.ycanvas)
    normalize = options.normalize
    mycmap = options.mycmap
    bgcol = '#'+options.bgcol.lstrip('#')
    fontsize = options.fontsize
    pngname = options.pngname
    dostamp = options.dostamp

    # Trap no MS

    myms = options.ms.rstrip('/')

    # Check for allowed axes

    allowed = ['a', 'p', 'r', 'i', 't', 'f', 'c', 'uv', 'u', 'v']
    if xaxis not in allowed or yaxis not in allowed:
        raise ValueError('xaxis "%s" is unknown. Please check requested axes' % xaxis)

    xfullname, xunits = sms.fullname(xaxis)
    yfullname, yunits = sms.fullname(yaxis)

    log.info('Plotting %s vs %s' % (yfullname, xfullname))
    log.info('Correlation index %d' % corr)

    # Get MS metadata

    chan_freqs = sms.get_chan_freqs(myms)
    field_ids, field_names = sms.get_field_names(myms)

    # Sort out field selection(s)

    if myfields == 'all':
        fields = field_ids
        # fields = []
        # for group in msdata:
        #   fields.append(group.FIELD_ID)
        # fields = numpy.unique(fields)
    else:
        fields = list(map(int, myfields.split(',')))

    sms.blank()
    log.info('FIELD_ID   NAME')
    for i in fields:
        log.info('%-10s %-16s' % (i, field_names[i]))

    # Sort out SPW selection(s)

    if myspws == 'all':
        spws = numpy.arange(len(chan_freqs))
    else:
        spws = list(map(int, myspws.split(',')))

    sms.blank()
    log.info('SPW_ID     NCHAN ')
    for i in spws:
        nchan = len(chan_freqs.values[i])
        log.info('%-10s %-16s' % (i, nchan))

    sms.blank()

    # Construct TaQL string based on FIELD and SPW selections

    field_taq = []
    for fld in fields:
        field_taq.append('FIELD_ID=='+str(fld))

    spw_taq = []
    for spw in spws:
        spw_taq.append('DATA_DESC_ID=='+str(spw))

    mytaql = '('+' || '.join(field_taq)+') && ('+' || '.join(spw_taq)+')'

    # Read the selected data

    log.info('Reading %s' % (myms))
    log.info('%s column' % (col))

    msdata = xms.xds_from_ms(
        myms, columns=[col, 'TIME', 'FLAG', 'FIELD_ID', 'UVW'], taql_where=mytaql)

    # Replace xarray data with a,p,r,i in situ

    log.info('Rearranging the deck chairs')

    for i in range(0, len(msdata)):
        msdata[i] = msdata[i].rename({col: 'VISDATA'})

    # Initialise arrays for plot data

    ydata = numpy.array(())
    xdata = numpy.array(())
    flags = numpy.array(())

    # Get plot data into a pair of numpy arrays

    for group in msdata:
        nrows = group.VISDATA.values.shape[0]
        nchan = group.VISDATA.values.shape[1]
        fld = group.FIELD_ID
        ddid = group.DATA_DESC_ID

        if fld in fields and ddid in spws:
            chans = chan_freqs.values[ddid]
            flags = numpy.append(flags, group.FLAG.values[:, :, corr])

            if xaxis == 'uv' or xaxis == 'u' or yaxis == 'v':
                uu = group.UVW.values[:, 0]
                vv = group.UVW.values[:, 1]
                chans_wavel = sms.freq_to_wavel(chans)
                uu_wavel = numpy.ravel(
                    uu / numpy.transpose(numpy.array([chans_wavel, ]*len(uu))))
                vv_wavel = numpy.ravel(
                    vv / numpy.transpose(numpy.array([chans_wavel, ]*len(vv))))
                uvdist_wavel = ((uu_wavel**2.0)+(vv_wavel**2.0))**0.5

            if yaxis == 'a':
                ydata = numpy.append(ydata, numpy.abs(
                    group.VISDATA.values[:, :, corr]))
            elif yaxis == 'p':
                ydata = numpy.append(ydata, numpy.angle(
                    group.VISDATA.values[:, :, corr]))
            elif yaxis == 'r':
                ydata = numpy.append(ydata, numpy.real(
                    group.VISDATA.values[:, :, corr]))
            elif yaxis == 'i':
                ydata = numpy.append(ydata, numpy.imag(
                    group.VISDATA.values[:, :, corr]))
            elif yaxis == 'v':
                ydata = numpy.append(ydata, vv_wavel)

            if xaxis == 'f':
                xdata = numpy.append(xdata, numpy.tile(chans, nrows))
            elif xaxis == 'c':
                xdata = numpy.append(xdata, numpy.tile(
                    numpy.arange(nchan), nrows))
            elif xaxis == 't':
                # Add t = t - t[0] and make it relative
                xdata = numpy.append(
                    xdata, numpy.repeat(group.TIME.values, nchan))
            elif xaxis == 'uv':
                xdata = numpy.append(xdata, uvdist_wavel)
            elif xaxis == 'r':
                xdata = numpy.append(xdata, numpy.real(
                    group.VISDATA.values[:, :, corr]))
            elif xaxis == 'u':
                xdata = numpy.append(xdata, uu_wavel)
            elif xaxis == 'a':
                xdata = numpy.append(xdata, numpy.abs(
                    group.VISDATA.values[:, :, corr]))

    # Drop flagged data if required

    if not noflags:

        bool_flags = list(map(bool, flags))

        masked_ydata = numpy.ma.masked_array(data=ydata, mask=bool_flags)
        masked_xdata = numpy.ma.masked_array(data=xdata, mask=bool_flags)

        ydata = masked_ydata.compressed()
        xdata = masked_xdata.compressed()

    # Plot the conjugate points for a u,v plot if requested
    # This is done at this stage so we don't have to worry about the flags

    if not noconj and xaxis == 'u' and yaxis == 'v':
        xdata = numpy.append(xdata, xdata*-1.0)
        ydata = numpy.append(ydata, ydata*-1.0)

    # Drop data out of plot range(s)

    if xmin != '':
        xmin = float(xmin)
        masked_xdata = numpy.ma.masked_less(xdata, xmin)
        masked_ydata = numpy.ma.masked_array(
            data=ydata, mask=masked_xdata.mask)
        ydata = masked_ydata.compressed()
        xdata = masked_xdata.compressed()

    if xmax != '':
        xmax = float(xmax)
        masked_xdata = numpy.ma.masked_greater(xdata, xmax)
        masked_ydata = numpy.ma.masked_array(
            data=ydata, mask=masked_xdata.mask)
        ydata = masked_ydata.compressed()
        xdata = masked_xdata.compressed()

    if ymin != '':
        ymin = float(ymin)
        masked_ydata = numpy.ma.masked_less(ydata, ymin)
        masked_xdata = numpy.ma.masked_array(
            data=xdata, mask=masked_ydata.mask)
        ydata = masked_ydata.compressed()
        xdata = masked_xdata.compressed()

    if ymax != '':
        ymax = float(ymax)
        masked_ydata = numpy.ma.masked_greater(ydata, ymax)
        masked_xdata = numpy.ma.masked_array(
            data=xdata, mask=masked_ydata.mask)
        ydata = masked_ydata.compressed()
        xdata = masked_xdata.compressed()

    # Put plotdata into pandas data frame
    # This should be possible with xarray directly, but for freq plots we need a corner turn

    log.info('Making Pandas dataframe')

    dists = {'plotdata': pd.DataFrame(odict([(xaxis, xdata), (yaxis, ydata)]))}
    df = pd.concat(dists, ignore_index=True)

    # Run datashader on the pandas df

    log.info('Running datashader')

    canvas = ds.Canvas(xcanvas, ycanvas)
    agg = canvas.points(df, xaxis, yaxis)
    img = hd.shade(hv.Image(agg), cmap=getattr(
        colorcet, mycmap), normalization=normalize)

    # Set plot limits based on data extent or user values for axis labels

    data_xmin = numpy.min(agg.coords[xaxis].values)
    data_ymin = numpy.min(agg.coords[yaxis].values)
    data_xmax = numpy.max(agg.coords[xaxis].values)
    data_ymax = numpy.max(agg.coords[yaxis].values)

    if ymin == '':
        ymin = data_ymin
    else:
        ymin = float(ymin)
    if ymax == '':
        ymax = data_ymax
    else:
        ymax = float(ymax)
    if xmin == '':
        xmin = data_xmin
    else:
        xmin = float(xmin)
    if xmax == '':
        xmax = data_xmax
    else:
        xmax = float(xmax)


    # Setup plot labels and PNG name

    ylabel = yfullname+' '+yunits
    xlabel = xfullname+' '+xunits
    title = myms+' '+col+' (correlation '+str(corr)+')'
    if pngname == '':
        pngname = 'plot_'+myms.split('/')[-1]+'_'+col+'_'
        pngname += 'SPW-' + \
            myspws.replace(',', '-')+'_FIELD-'+myfields.replace(',', '-')+'_'
        pngname += yfullname+'_vs_'+xfullname+'_'+'corr'+str(corr)
        if dostamp:
            pngname += '_'+sms.stamp()
        pngname += '.png'

    # Render the plot

    log.info('Rendering plot')

    sms.make_plot(img.data,
              data_xmin,
              data_xmax,
              data_ymin,
              data_ymax,
              xmin,
              xmax,
              ymin,
              ymax,
              xlabel,
              ylabel,
              title,
              pngname,
              bgcol,
              fontsize,
              figx=xcanvas/60,
              figy=ycanvas/60)

    # Stop the clock

    clock_stop = time.time()
    elapsed = str(round((clock_stop-clock_start), 2))

    log.info('Done. Elapsed time: %s seconds.' % (elapsed))
Esempio n. 18
0
panel2 = gv.WMTS(WMTSTileSource(url=panel2_url))

stream = hv.streams.Stream.define('HourSelect', hour=0)()
points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])
dmap = hv.util.Dynamic(
    points,
    operation=lambda obj, hour: obj.select(dropoff_hour=hour),
    streams=[stream])

# Apply aggregation
aggregated = aggregate(dmap,
                       link_inputs=True,
                       streams=[hv.streams.RangeXY],
                       width=400,
                       height=400)
shaded = shade(aggregated, link_inputs=True)

# Define PointerX stream, attach to points and declare DynamicMap for cross-section and VLine
pointer = hv.streams.PointerX(x=ddf.dropoff_x.loc[0].compute().iloc[0],
                              source=points)
section = hv.util.Dynamic(aggregated,
                          operation=lambda obj, x: obj.sample(dropoff_x=x),
                          streams=[pointer],
                          link_inputs=False).relabel('')
vline = hv.DynamicMap(lambda x: hv.VLine(x), streams=[pointer])

# Define options
hv.opts(
    "RGB [width=600 height=600 xaxis=None yaxis=None fontsize={'title': '14pt'}] VLine (color='white' line_width=2)"
)
hv.opts(
Esempio n. 19
0

def filter_count(agg, min_count, **kwargs):
    if min_count:
        agg = deepcopy(agg)
        agg.data.Count.data[agg.data.Count.data < min_count] = 0
    return agg


def hline_fn(min_count, **kwargs):
    return hv.VLine(min_count)


def tiles_fn(alpha, **kwargs):
    return tiles.opts(style=dict(alpha=alpha))


explorer = OSMExplorer(name="OpenStreetMap GPS Explorer")

tile = hv.DynamicMap(tiles_fn, streams=[explorer])
agg = aggregate(hv.Points(df))
filtered = hv.util.Dynamic(agg, operation=filter_count, streams=[explorer])
shaded = shade(filtered, streams=[explorer])
hline = hv.DynamicMap(hline_fn, streams=[explorer])
explorer.output = (tile * shaded) << histogram(agg, log=True) * hline

doc = parambokeh.Widgets(explorer,
                         view_position='right',
                         callback=explorer.event,
                         mode='server')
Esempio n. 20
0
# Apply aggregation
aggregated = aggregate(dmap,
                       link_inputs=True,
                       streams=[hv.streams.RangeXY],
                       width=1200,
                       height=600)


# Shade the data
class ColormapPicker(hv.streams.Stream):
    colormap = param.ObjectSelector(default=cm_n["fire"],
                                    objects=cm_n.values())


cmap_picker = ColormapPicker(rename={'colormap': 'cmap'}, name='')
shaded = shade(aggregated, link_inputs=True, streams=[cmap_picker])

# Define PointerX stream, attach to points and declare DynamicMap for cross-section and VLine
pointer = hv.streams.PointerX(x=ddf.dropoff_x.loc[0].compute().iloc[0],
                              source=points)
section = hv.util.Dynamic(aggregated,
                          operation=lambda obj, x: obj.sample(dropoff_x=x),
                          streams=[pointer],
                          link_inputs=False).relabel('')
vline = hv.DynamicMap(lambda x: hv.VLine(x), streams=[pointer])

# Define options
hv.opts(
    "RGB [width=1200 height=600 xaxis=None yaxis=None fontsize={'title': '14pt'}] VLine (color='white' line_width=2)"
)
hv.opts(
child_reshaped = np.reshape(reshape_values, parent.data.shape)

plot_data = pd.DataFrame({
    "hs":
    parent.data.reshape(parent.rows * parent.cols),
    "lpmf":
    child_reshaped.reshape(parent.rows * parent.cols)
})

plot_data[plot_data == parent.no_data] = np.nan
plot_data = plot_data[~np.any(np.isnan(plot_data), axis=1)]

cvs = ds.Canvas(plot_width=400, plot_height=400)
agg = cvs.points(plot_data, "hs", "lpmf", ds.count())
hd.datashade(plot_data)
hd.shade(hv.Image(agg))
hv.RGB(np.array(tf.shade(agg).to_pil()))

tf.Image(tf.shade(agg))

import holoviews as hv
hv.extension('bokeh')
from bokeh.plotting import figure, output_file, show

output_file('test_bokeh.html')
p = figure(plot_width=400, plot_height=400)
p.vbar(x=[1, 2, 3], width=0.5, bottom=0, top=[1.2, 2.5, 3.6], color='red')
plot = plot_data.hvplot(kind='scatter', x='hs', y='lpmf', datashade=True)
show(hv.render(plot))
show(p)