def make_detailed(vals, n=n, cmap=viridis, label=True): """Return a Datashader image by collecting `n` trajectory points for the given attractor `fn`""" imgs = [] m = 1000000 vals[0] = 0 vals[1] = 0 cvs = ds.Canvas(plot_width = 500, plot_height = 500) agg_sum = 0 #for i in np.geomspace(200, m, 100).astype(int): for i in range(100): #print(i) lab = ("{}, "*(len(vals)-1)+" {}"+' n:'+str((1+i)*m)).format(*vals) if label else None df = trajectory(Clifford, *vals, n=m) vals[0] = df.iloc[m-1].x vals[1] = df.iloc[m-1].y agg = cvs.points(df, 'x', 'y') agg_sum = agg.values + agg_sum return xr.DataArray(agg_sum)#imgs
def test_line_autorange_axis1_x_constant(DataFrame): axis = ds.core.LinearAxis() lincoords = axis.compute_index( axis.compute_scale_and_translate((-4., 4.), 9), 9) xs = np.array([-4, 0, 4]) df = DataFrame({'y0': [0, 0], 'y1': [-4, 4], 'y2': [0, 0]}) cvs = ds.Canvas(plot_width=9, plot_height=9) agg = cvs.line(df, xs, ['y0', 'y1', 'y2'], ds.count(), axis=1) sol = np.array([[0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [2, 0, 0, 0, 0, 0, 0, 0, 2], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords, lincoords], dims=['y', 'x']) assert_eq_xr(agg, out)
def generate_heatmap_image( peak_x, # type: Deque[int] peak_y, # type: Deque[int] x_range, # type: Tuple[int, int] y_range, # type: Tuple[int, int] plot_width, # type: int plot_height, # type: int ): # type: (...) -> numpy.ndarray """Function that computes the downsampled map.""" if x_range is None or y_range is None or plot_width is None or plot_height is None: return None peak_data = pandas.DataFrame({"x": peak_x, "y": peak_y}) canvas = datashader.Canvas( x_range=x_range, y_range=y_range, plot_width=plot_width, plot_height=plot_height, ) agg_scatter = canvas.points(peak_data, x="x", y="y") return numpy.array(agg_scatter)
def pl(lbls, key, data, agg=ds.count_cat): """Returns image Takes in labels to colour in by, colour key and data from Umap Produces the image from data coloured according to the colour key Returns the image """ dataset = pd.DataFrame({ 'Column1': data[:, 0], 'Column2': data[:, 1], 'Column3': lbls }) if agg == ds.count_cat: dataset['Column3'] = dataset['Column3'].astype('category') cvs = ds.Canvas(plot_width=900, plot_height=500) aggs = cvs.points(dataset, 'Column1', 'Column2', agg('Column3')) if agg == ds.count_cat: img = ds.transfer_functions.shade(aggs, color_key=key) else: img = ds.transfer_functions.shade(aggs, cmap=plt.cm.magma_r) return img
def test_line(): axis = ds.core.LinearAxis() lincoords = axis.compute_index( axis.compute_scale_and_translate((-3., 3.), 7), 7) df = pd.DataFrame({ 'x': [4, 0, -4, -3, -2, -1.9, 0, 10, 10, 0, 4], 'y': [0, -4, 0, 1, 2, 2.1, 4, 20, 30, 4, 0] }) cvs = ds.Canvas(plot_width=7, plot_height=7, x_range=(-3, 3), y_range=(-3, 3)) agg = cvs.line(df, 'x', 'y', ds.count()) sol = np.array( [[0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1], [0, 2, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords, lincoords], dims=['y', 'x']) assert_eq_xr(agg, out)
def test_line(): df = pd.DataFrame({ 'x': [4, 0, -4, -3, -2, -1.9, 0, 10, 10, 0, 4], 'y': [0, -4, 0, 1, 2, 2.1, 4, 20, 30, 4, 0] }) ddf = dd.from_pandas(df, npartitions=3) cvs = ds.Canvas(plot_width=7, plot_height=7, x_range=(-3, 4), y_range=(-3, 4)) agg = cvs.line(ddf, 'x', 'y', ds.count()) sol = np.array( [[0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1], [0, 2, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[np.arange(-3., 4.), np.arange(-3., 4.)], dims=['y_axis', 'x_axis']) assert_eq(agg, out)
def create_aggregate(self, plot_width, plot_height, x_range, y_range, agg_field, x_field, y_field, agg_func): canvas = ds.Canvas(plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=y_range) # handle categorical field if agg_field in self.categorical_fields: agg = canvas.points(self.df, x_field, y_field, ds.count_cat(agg_field)) # handle ordinal field elif agg_field in self.ordinal_fields: func = self.aggregate_functions[agg_func] agg = canvas.points(self.df, x_field, y_field, func(agg_field)) else: agg = canvas.points(self.df, x_field, y_field) return agg
def test_raster_distributed_upsample(in_size, out_size): """ Ensure that distributed regrid is equivalent to regular regrid. """ cvs = ds.Canvas(plot_height=out_size, plot_width=out_size) vs = np.linspace(-1, 1, in_size) xs, ys = np.meshgrid(vs, vs) arr = np.sin(xs * ys) darr = da.from_array(arr, (2, 2)) coords = [('y', range(in_size)), ('x', range(in_size))] xr_darr = xr.DataArray(darr, coords=coords, name='z') xr_arr = xr.DataArray(arr, coords=coords, name='z') agg_arr = cvs.raster(xr_arr, interpolate='nearest') agg_darr = cvs.raster(xr_darr, interpolate='nearest') assert np.allclose(agg_arr.data, agg_darr.data.compute()) assert np.allclose(agg_arr.x.values, agg_darr.x.values) assert np.allclose(agg_arr.y.values, agg_darr.y.values)
def callback_InteractiveImage(self, x_range, y_range, plot_width, plot_height, name=None): cvs = ds.Canvas( plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=y_range, ) agg = cvs.line( self.result, x=['x0', 'x1'], y=['y0', 'y1'], agg=ds.count_cat('c'), axis=1, ) img = tf.shade(agg, min_alpha=255, color_key=self.color_key) return img
def create_map(data, cmap, data_agg, export_name='img'): pad = (data.x.max() - data.x.min()) / 50 x_range, y_range = ((data.x.min() - pad, data.x.max() + pad), (data.y.min() - pad, data.y.max() + pad)) ratio = (y_range[1] - y_range[0]) / (x_range[1] - x_range[0]) plot_width = int(W) plot_height = int(plot_width * ratio) if ratio > 1.5: plot_height = 550 plot_width = int(plot_height / ratio) cvs = ds.Canvas(plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=y_range) agg = cvs.points(data, 'x', 'y', data_agg) img = tf.shade(agg, cmap=cmap, how='eq_hist') return export(img, export_name)
def test_trimesh_no_double_edge(): """Assert that when two triangles share an edge that would normally get double-drawn, the edge is only drawn for the rightmost (or bottommost) triangle. """ import multiprocessing as mp # Test left/right edge shared verts = dd.from_pandas(pd.DataFrame({'x': [4, 1, 5, 5, 5, 4], 'y': [4, 5, 5, 5, 4, 4]}), npartitions=mp.cpu_count()) tris = dd.from_pandas(pd.DataFrame({'v0': [0, 3], 'v1': [1, 4], 'v2': [2, 5], 'val': [1, 2]}), npartitions=mp.cpu_count()) # Plot dims and x/y ranges need to be set such that the edge is drawn twice: cvs = ds.Canvas(plot_width=20, plot_height=20, x_range=(0, 5), y_range=(0, 5)) agg = cvs.trimesh(verts, tris) sol = np.array([ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ], dtype='i4') np.testing.assert_array_equal(np.flipud(agg.fillna(0).astype('i4').values)[:5], sol)
def create_plot(data, out, width): """Creates a figure of the ZVV transit network using ZVV's color scheme. Args: data: a csv file containing data usable for line plots out: the generated imnage is saved here Returns: None """ plot_data = pd.read_csv(data, low_memory=False) x_range = (plot_data.shape_pt_lon.min(), plot_data.shape_pt_lon.max()) y_range = (plot_data.shape_pt_lat.min(), plot_data.shape_pt_lat.max()) height = int( round(width * (y_range[1] - y_range[0]) / (x_range[1] - x_range[0]))) cvs = ds.Canvas(plot_width=width, plot_height=height, x_range=x_range, y_range=y_range) layers = [] for color, data_part in plot_data.groupby('route_color'): agg = cvs.line(data_part, 'shape_pt_lon', 'shape_pt_lat', agg=ds.sum('times_taken')) image_part = tf.shade(agg, cmap=['#000000', '#' + color], how='eq_hist') layers.append(image_part) image = tf.stack(*layers, how='add') if out.endswith('.png'): out = out[:-4] export_image(image, filename=out, background='black')
def shade_phase_diagram(refine_box, strset): dens = np.log10(refine_box['density'].ndarray_view()) temp = np.log10(refine_box['temperature'].ndarray_view()) phase = np.chararray(np.size(dens), 4) #categorize by phase phase[temp < 9.] = 'hot' phase[temp < 6.] = 'warm' phase[temp < 5.] = 'cool' phase[temp < 4.] = 'cold' phase_color_key = { 'hot': 'orange', 'warm': 'green', 'cool': 'purple', 'cold': 'salmon' } temp = ( temp - 2.5 ) / 5 # remaps the range logT = 2-8 to 0-1 (2 is min, 6 is interval) dens = ( dens + 3) / 10. # dens had been between -4 and +8, -4 is min 12 is interval df = pd.DataFrame({'temp': temp, 'dens': dens, 'phase': phase}) df.phase = df.phase.astype('category') plot_window = ((-2.8, -2), (0.2, 1.0)) def create_image(x_range, y_range, w=1080, h=1080): cvs = dshader.Canvas(plot_width=w, plot_height=h, x_range=x_range, y_range=y_range) agg = cvs.points(df, 'dens', 'temp', dshader.count_cat('phase')) img = tf.colorize(agg, phase_color_key, how='eq_hist') return img export = partial(export_image, background='white') cvs = dshader.Canvas(1080, 1080, *plot_window).points(df, 'dens', 'temp') export(create_image(*plot_window), strset + "_phase")
def datashader_stretch( values, gx, gy, x_range, y_range, plot_height=None, plot_width=None ): """ Use datashader to sample the data mesh in on a regular grid for use in image display. :param values: A numpy array of image data :param gx: The array of coordinates in projection space. :param gy: The array of coordinates in projection space. :param x_range: The range of the mesh in projection space. :param y_range: The range of the mesh in projection space. :return: An xarray of image data representing pixels. """ if plot_height is None: plot_height = values.shape[0] if plot_width is None: plot_width = values.shape[1] canvas = datashader.Canvas( plot_height=plot_height, plot_width=plot_width, x_range=x_range, y_range=y_range, ) if gx.ndim == 1: # 1D Quadmesh xarr = xarray.DataArray( values, coords=[("y", gy), ("x", gx)], name="Z" ) image = canvas.quadmesh(xarr) else: # 2D Quadmesh xarr = xarray.DataArray( values, dims=["Y", "X"], coords={"Qx": (["Y", "X"], gx), "Qy": (["Y", "X"], gy)}, name="Z", ) image = canvas.quadmesh(xarr, x="Qx", y="Qy") return np.ma.masked_array(image.values, mask=np.isnan(image.values))
def _process(self, element, key=None): agg_fn = self.p.aggregator category = agg_fn.column if isinstance(agg_fn, ds.count_cat) else None if (isinstance(element, NdOverlay) and ((isinstance(agg_fn, (ds.count, ds.sum, ds.mean)) and agg_fn.column not in element.kdims) or (isinstance(agg_fn, ds.count_cat) and agg_fn.column in element.kdims))): return self._aggregate_ndoverlay(element, agg_fn) x, y, data, glyph = self.get_agg_data(element, category) (x_range, y_range), (xs, ys), (width, height) = self._get_sampling(element, x, y) if x is None or y is None: xarray = xr.DataArray(np.full((height, width), np.NaN, dtype=np.float32), dims=['y', 'x'], coords={'x': xs, 'y': ys}) return self.p.element_type(xarray) cvs = ds.Canvas(plot_width=width, plot_height=height, x_range=x_range, y_range=y_range) column = agg_fn.column if column and isinstance(agg_fn, ds.count_cat): name = '%s Count' % agg_fn.column else: name = column vdims = [element.get_dimension(column)(name) if column else Dimension('Count')] params = dict(get_param_values(element), kdims=element.dimensions()[:2], datatype=['xarray'], vdims=vdims) agg = getattr(cvs, glyph)(data, x, y, self.p.aggregator) if agg.ndim == 2: # Replacing x and y coordinates to avoid numerical precision issues return self.p.element_type((xs, ys, agg.data), **params) else: layers = {} for c in agg.coords[column].data: cagg = agg.sel(**{column: c}) layers[c] = self.p.element_type((xs, ys, cagg.data), **params) return NdOverlay(layers, kdims=[data.get_dimension(column)])
def test_line_manual_range(df, x, y, ax): axis = ds.core.LinearAxis() lincoords = axis.compute_index( axis.compute_scale_and_translate((-3., 3.), 7), 7) ddf = dd.from_pandas(df, npartitions=2) cvs = ds.Canvas(plot_width=7, plot_height=7, x_range=(-3, 3), y_range=(-3, 3)) agg = cvs.line(ddf, x, y, ds.count(), axis=ax) sol = np.array( [[0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords, lincoords], dims=['y', 'x']) assert_eq(agg, out)
def test_bug_570(): # See https://github.com/pyviz/datashader/issues/570 df = pd.DataFrame( { 'Time': [1456353642.2053893, 1456353642.2917893], 'data': [-59.4948743433377, 506.4847376716022], }, columns=['Time', 'data']) x_range = (1456323293.9859753, 1456374687.0009754) y_range = (-228.56721300380943, 460.4042291124646) cvs = ds.Canvas(x_range=x_range, y_range=y_range, plot_height=300, plot_width=1000) agg = cvs.line(df, 'Time', 'data', agg=ds.count()) # Check location of line yi, xi = np.where(agg.values == 1) assert np.array_equal(yi, np.arange(73, 300)) assert np.array_equal(xi, np.array([590] * len(yi)))
def test_area_to_line_autorange(df, x, y, y_stack, ax): axis = ds.core.LinearAxis() lincoords_y = axis.compute_index( axis.compute_scale_and_translate((-4., 0.), 7), 7) lincoords_x = axis.compute_index( axis.compute_scale_and_translate((-4., 4.), 13), 13) cvs = ds.Canvas(plot_width=13, plot_height=7) agg = cvs.area(df, x, y, ds.count(), axis=ax, y_stack=y_stack) sol = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords_y, lincoords_x], dims=['y', 'x']) assert_eq(agg, out)
def test_area_to_zero_fixedrange(df, x, y, ax): axis = ds.core.LinearAxis() lincoords_y = axis.compute_index( axis.compute_scale_and_translate((-2.25, 2.25), 5), 5) lincoords_x = axis.compute_index( axis.compute_scale_and_translate((-3.75, 3.75), 9), 9) cvs = ds.Canvas(plot_width=9, plot_height=5, x_range=[-3.75, 3.75], y_range=[-2.25, 2.25]) agg = cvs.area(df, x, y, ds.count(), axis=ax) sol = np.array([[0, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords_y, lincoords_x], dims=['y', 'x']) assert_eq(agg, out)
def create_image(x_range=x_range, y_range=y_range, w=plot_width, h=plot_height, aggregator=ds.count(), categorical=None, black=False, cmap=None): opts = {} if categorical and cmap: opts['color_key'] = categorical_color_key( len(df[aggregator.column].unique()), cmap) cvs = ds.Canvas(plot_width=w, plot_height=h, x_range=x_range, y_range=y_range) agg = cvs.line(df, 'longitude', 'latitude', aggregator) img = tf.shade(agg, cmap=inferno, **opts) if black: img = tf.set_background(img, 'black') return img
def compute_range_created_radio_hist(ddf): """ Use Datashader to compute a 3D histogram of ddf, binned by the created, log10_range, and radio dimensions """ cvs2 = ds.Canvas( # Specify created bins plot_width=len(created_bins) - 1, x_range=[min(created_bins), max(created_bins)], # Specify log10_range bins plot_height=20, y_range=[min_log10_range, max_log10_range]) agg = cvs2.points(ddf, x='created', y='log10_range', agg=ds.count_cat('radio')) # Set created index back to datetime values agg = agg.assign_coords(created=created_bin_centers) return agg
def get(self, args): # parse args selection = args['select'].strip(',').split(',') xmin, ymin, xmax, ymax = map(float, selection) self.model.map_extent = [xmin, ymin, xmax, ymax] # create image cvs = ds.Canvas(plot_width=args['width'], plot_height=args['height'], x_range=(xmin, xmax), y_range=(ymin, ymax)) agg = cvs.points(self.model.df, self.model.active_axes[1], self.model.active_axes[2], self.model.aggregate_function(self.model.field)) pix = tf.interpolate(agg, (255, 204, 204), 'red', how=self.model.transfer_function) # serialize to image img_io = pix.to_bytesio() self.write(img_io.getvalue()) self.set_header("Content-type", "image/png")
def test_subpixel_quads_represented(): c = ds.Canvas(plot_width=8, plot_height=4, x_range=[0, 16], y_range=[0, 8]) da = xr.DataArray([[1, 2, 3, 4], [5, 6, 7, 8]], coords=[('b', [1, 2]), ('a', [1, 2, 3, 4])], name='Z') y_coords = np.linspace(1, 7, 4) x_coords = np.linspace(1, 15, 8) out = xr.DataArray(np.array([[14., 22., nan, nan, nan, nan, nan, nan], [nan, nan, nan, nan, nan, nan, nan, nan], [nan, nan, nan, nan, nan, nan, nan, nan], [nan, nan, nan, nan, nan, nan, nan, nan]], dtype='f4'), coords=[('b', y_coords), ('a', x_coords)]) res = c.quadmesh(da, x='a', y='b', agg=ds.sum('Z')) assert res.equals(out) # Check transpose gives same answer res = c.quadmesh(da.transpose('a', 'b'), x='a', y='b', agg=ds.sum('Z')) assert res.equals(out)
def test_line_manual_range(DataFrame, df_args, x, y, ax): df = DataFrame(*df_args) axis = ds.core.LinearAxis() lincoords = axis.compute_index( axis.compute_scale_and_translate((-3., 3.), 7), 7) cvs = ds.Canvas(plot_width=7, plot_height=7, x_range=(-3, 3), y_range=(-3, 3)) agg = cvs.line(df, x, y, ds.count(), axis=ax) sol = np.array( [[0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0]], dtype='i4') out = xr.DataArray(sol, coords=[lincoords, lincoords], dims=['y', 'x']) assert_eq_xr(agg, out)
def test_rect_quadmesh_manual_range(array_module): c = ds.Canvas(plot_width=8, plot_height=4, x_range=[1, 3], y_range=[-1, 3]) da = xr.DataArray(array_module.array([[1, 2, 3, 4], [5, 6, 7, 8]]), coords=[('b', [1, 2]), ('a', [1, 2, 3, 8])], name='Z') y_coords = np.linspace(-0.5, 2.5, 4) x_coords = np.linspace(1.125, 2.875, 8) out = xr.DataArray(array_module.array( [[nan, nan, nan, nan, nan, nan, nan, nan], [1., 1., 2., 2., 2., 2., 3., 3.], [5., 5., 6., 6., 6., 6., 7., 7.], [nan, nan, nan, nan, nan, nan, nan, nan]], dtype='f8'), coords=[('b', y_coords), ('a', x_coords)]) res = c.quadmesh(da, x='a', y='b', agg=ds.sum('Z')) assert_eq_xr(res, out, close=True) # Check transpose gives same answer res = c.quadmesh(da.transpose('a', 'b'), x='a', y='b', agg=ds.sum('Z')) assert_eq_xr(res, out, close=True)
def serve_image(): #dataset # parse params print('-------------- server receives request-----------') width = int(request.args.get('width')) height = int(request.args.get('height')) spread = int(request.args.get('spread')) xmin = float(request.args.get('xmin')) xmax = float(request.args.get('xmax')) ymax = float(request.args.get('ymax')) ymin = float(request.args.get('ymin')) colorw = str(request.args.get('colorw')) colorb = str(request.args.get('colorb')) colora = str(request.args.get('colora')) colorh = str(request.args.get('colorh')) coloro = str(request.args.get('coloro')) x_range = webm(latitude=ymin, longitude=xmin) y_range = webm(latitude=ymax, longitude=xmax) cvs = ds.Canvas(plot_width=width, plot_height=height, x_range=(x_range[0], y_range[0]), y_range=(x_range[1], y_range[1])) agg = cvs.points(df, 'easting', 'northing', ds.count_cat('race')) color_key = { 'w': colorw, 'b': colorb, 'a': colora, 'h': colorh, 'o': coloro } img = tf.shade(agg, color_key=color_key, how='eq_hist') img = tf.spread(img, px=spread) img_io = img.to_bytesio() return send_file(img_io, mimetype='image/png')
def dsplot(self): """Return a Datashader image by collecting `n` trajectory points for the given attractor `fn`""" cmap = palette[self._cmap][::-1] start = time.time() df = self.trajectory() end = time.time() self._timeCalc = end - start start = time.time() cvs = ds.Canvas(plot_width=self._res, plot_height=self._res) if self._aOrientation == 'XY': agg = cvs.points(df, 'x', 'y') elif self._aOrientation == 'XZ': agg = cvs.points(df, 'x', 'z') else: agg = cvs.points(df, 'y', 'z') img = tf.shade(agg, cmap=cmap) end = time.time() self._timeRender = end - start self.saveImg(img=img, tmp=True) return img
def test_curve_quadmesh_autorange(array_module): c = ds.Canvas(plot_width=4, plot_height=8) coord_array = dask.array if array_module is dask.array else np Qx = coord_array.array([[1, 2], [1, 2]]) Qy = coord_array.array([[1, 1], [4, 2]]) Z = np.arange(4, dtype='int32').reshape(2, 2) da = xr.DataArray( array_module.array(Z), coords={ 'Qx': (['Y', 'X'], Qx), 'Qy': (['Y', 'X'], Qy) }, dims=['Y', 'X'], name='Z', ) x_coords = np.linspace(0.75, 2.25, 4) y_coords = np.linspace(-0.5, 6.5, 8) out = xr.DataArray(array_module.array([[nan, nan, nan, nan], [0., 0., nan, nan], [0., 0., 1., 1.], [0., 0., 3., 3.], [2., 2., 3., nan], [2., 2., nan, nan], [2., 2., nan, nan], [2., nan, nan, nan]]), coords=OrderedDict([('Qx', x_coords), ('Qy', y_coords)]), dims=['Qy', 'Qx']) res = c.quadmesh(da, x='Qx', y='Qy', agg=ds.sum('Z')) assert_eq_xr(res, out) res = c.quadmesh(da.transpose('X', 'Y', transpose_coords=True), x='Qx', y='Qy', agg=ds.sum('Z')) assert_eq_xr(res, out)
def testDatashader(): ''' http://datashader.org/user_guide/1_Plotting_Pitfalls.html ''' num = 10000 np.random.seed(1) dists = { cat: pd.DataFrame.from_items([('x', np.random.normal(x, s, num)), ('y', np.random.normal(y, s, num)), ('val', val), ('cat', cat)]) for x, y, s, val, cat in [( 2, 2, 0.03, 10, "d1"), (2, -2, 0.10, 20, "d2"), (-2, -2, 0.50, 30, "d3"), (-2, 2, 1.00, 40, "d4"), (0, 0, 3.00, 50, "d5")] } df = pd.concat(dists, ignore_index=True) df["cat"] = df["cat"].astype("category") tf.shade(ds.Canvas().points(df, 'x', 'y')) return
def test_load_sqlite(): import sqlite3 start = time.time() db = sqlite3.connect("{}.sqlite".format(FILENAME_PREFIX)) cur = db.cursor() #for row in cur.execute("SELECT * FROM ms1_df WHERE ms1_rt > 1.0 AND ms1_rt < 1.5 AND ms1_mz < 500 AND ms1_mz > 300 AND ms1_polarity='Positive'"): # pass ms1_df = pd.read_sql( f"SELECT * FROM ms1_df WHERE ms1_rt > {RT_MIN} AND ms1_rt < {RT_MAX} AND ms1_mz < 500 AND ms1_mz > 300 AND ms1_polarity='Positive'", db) #ms1_df = pd.read_sql("SELECT * FROM ms1_df", db) width = 500 height = 500 cvs = ds.Canvas(plot_width=width, plot_height=height) agg = cvs.points(ms1_df, 'ms1_rt', 'ms1_mz', agg=ds.sum("ms1_i")) print("TIMING", time.time() - start) print(ms1_df)