def test_shade(agg, attr, span):
    x = getattr(agg, attr)
    cmap = ['pink', 'red']

    img = tf.shade(x, cmap=cmap, how='log', span=span)
    sol = solutions['log']
    assert_eq_xr(img, sol)
    # Check dims/coordinates order
    assert list(img.coords) == ['x_axis', 'y_axis']
    assert list(img.dims) == ['y_axis', 'x_axis']

    img = tf.shade(x, cmap=cmap, how='cbrt', span=span)
    sol = solutions['cbrt']
    assert_eq_xr(img, sol)

    img = tf.shade(x, cmap=cmap, how='linear', span=span)
    sol = solutions['linear']
    assert_eq_xr(img, sol)

    # span option not supported with how='eq_hist'
    img = tf.shade(x, cmap=cmap, how='eq_hist')
    sol = tf.Image(eq_hist_sol[attr], coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    img = tf.shade(x,
                   cmap=cmap,
                   how=lambda x, mask: np.where(mask, np.nan, x**2))
    sol = np.array([[0, 4291543295, 4291148543], [4290030335, 0, 4285557503],
                    [4282268415, 4278190335, 0]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
示例#2
0
def test_colorize():
    coords = [np.array([0, 1]), np.array([2, 5])]
    cat_agg = xr.DataArray(np.array([[(0, 12, 0), (3, 0, 3)],
                                     [(12, 12, 12), (24, 0, 0)]]),
                           coords=(coords + [['a', 'b', 'c']]),
                           dims=(dims + ['cats']))

    colors = [(255, 0, 0), '#0000FF', 'orange']

    img = tf.colorize(cat_agg, colors, how='log')
    sol = np.array([[3137273856, 2449494783], [4266997674, 3841982719]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    colors = dict(zip('abc', colors))
    img = tf.colorize(cat_agg, colors, how='cbrt')
    sol = np.array([[3070164992, 2499826431], [4283774890, 3774873855]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg, colors, how='linear')
    sol = np.array([[1660878848, 989876991], [4283774890, 2952790271]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg, colors, how=lambda x: x**2)
    sol = np.array([[788463616, 436228863], [4283774890, 2080375039]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
def test_colorize():
    coords = [np.array([0, 1]), np.array([2, 5])]
    cat_agg = xr.DataArray(np.array([[(0, 12, 0), (3, 0, 3)],
                                     [(12, 12, 12), (24, 0, 0)]]),
                           coords=(coords + [['a', 'b', 'c']]),
                           dims=(dims + ['cats']))

    colors = [(255, 0, 0), '#0000FF', 'orange']

    img = tf.colorize(cat_agg, colors, how='log')
    sol = np.array([[2583625728, 335565567], [4283774890, 3707764991]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    colors = dict(zip('abc', colors))
    img = tf.colorize(cat_agg, colors, how='cbrt')
    sol = np.array([[2650734592, 335565567], [4283774890, 3657433343]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg, colors, how='linear')
    sol = np.array([[1140785152, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg,
                      colors,
                      how=lambda x, m: np.where(m, np.nan, x)**2)
    sol = np.array([[503250944, 335565567], [4283774890, 1744830719]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
def test_shade_bool():
    data = ~np.eye(3, dtype='bool')
    x = tf.Image(data, coords=coords, dims=dims)
    sol = tf.Image(np.where(data, 4278190335, 0).astype('uint32'),
                       coords=coords, dims=dims)
    img = tf.shade(x, cmap=['pink', 'red'], how='log')
    assert_eq_xr(img, sol)
    img = tf.shade(x, cmap=['pink', 'red'], how='cbrt')
    assert_eq_xr(img, sol)
    img = tf.shade(x, cmap=['pink', 'red'], how='linear')
    assert_eq_xr(img, sol)
    img = tf.shade(x, cmap=['pink', 'red'], how='eq_hist')
    assert_eq_xr(img, sol)
def test_shade_zeros(array):
    coords = [np.array([0, 1]), np.array([2, 5])]
    cat_agg = tf.Image(array([[(0, 0, 0), (0, 0, 0)], [(0, 0, 0), (0, 0, 0)]],
                             dtype='u4'),
                       coords=(coords + [['a', 'b', 'c']]),
                       dims=(dims + ['cats']))

    colors = [(255, 0, 0), '#0000FF', 'orange']

    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=0)
    sol = np.array([[5584810, 5584810], [5584810, 5584810]], dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
示例#6
0
文件: Graph.py 项目: sammatuba/omf
def newPlotlyGeneration(relayoutData):
    f = go.Figure(data=[{'x': [relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']], 
                           'y': [relayoutData['yaxis.range[0]'], relayoutData['yaxis.range[1]']], 
                           'mode': 'markers',
                           'marker': {'opacity': 0}}], # invisible trace to init axes and to support autoresize
                    layout={'width': 800, 
                            'height': 600}
                   )
    newImg = newGraphplot(fd, connect_edges(fd,edges), x_range=[relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']], y_range=[relayoutData['yaxis.range[0]'], relayoutData['yaxis.range[1]']])
    newPil = tf.Image(newImg).to_pil()
    #in_mem_file = io.BytesIO()
    #newPil.save(in_mem_file, format = "PNG")
    # reset file pointer to start
    #in_mem_file.seek(0)
    #img_bytes = in_mem_file.read()
    #base64_encoded_result_bytes = base64.b64encode(img_bytes)
    #base64_encoded_result_str = base64_encoded_result_bytes.decode('ascii')

    f.layout.images = [go.layout.Image(
        source = newPil,  # plotly now performs auto conversion of PIL image to png data URI
        xref = "x",
        yref = "y",
        x = relayoutData['xaxis.range[0]'],
        y = relayoutData['yaxis.range[1]'],
        sizex = relayoutData['xaxis.range[1]'] - relayoutData['xaxis.range[0]'],
        sizey = relayoutData['yaxis.range[1]'] - relayoutData['yaxis.range[0]'],
        #sizing = "stretch",
        layer = "below")]
    return f
def test_shade_cmap_non_categorical_alpha(agg, cmap):
    img = tf.shade(agg.a, how='log', cmap=cmap)
    sol = np.array([[         0,  671088640, 1946157056],
                    [2701131776,          0, 3640655872],
                    [3976200192, 4278190080,          0]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
示例#8
0
def zoomButton():

    jsonResp = request.get_json()
    cvsopts['plot_height'] = int(jsonResp["height"])
    cvsopts['plot_width'] = int(jsonResp["width"])
    current_x_range = tuple(
        (float(jsonResp["current_x_low"]), float(jsonResp["current_x_high"])))
    current_y_range = tuple(
        (float(jsonResp["current_y_low"]), float(jsonResp["current_y_high"])))
    current_y_low, current_y_high = current_y_range[0], current_y_range[1]
    current_x_low, current_x_high = current_x_range[0], current_x_range[1]

    dsPlot = newGraphplot(randomloc,
                          connect_edges(randomloc, edges),
                          x_range=current_x_range,
                          y_range=current_y_range)
    #convert datashder image to png
    back_img = tf.Image(dsPlot).to_pil()
    in_mem_file = io.BytesIO()
    back_img.save(in_mem_file, format="PNG")
    # reset file pointer to start
    in_mem_file.seek(0)
    img_bytes = in_mem_file.read()
    base64_encoded_result_bytes = base64.b64encode(img_bytes)
    base64_encoded_result_str = 'data:image/png;base64,' + base64_encoded_result_bytes.decode(
        'ascii')
    return jsonify(newImage=base64_encoded_result_str,
                   x_low=current_x_range[0],
                   y_low=current_y_range[0],
                   x_high=current_x_range[1],
                   y_high=current_y_range[1])
def test_shade_mpl_cmap(agg):
    cm = pytest.importorskip('matplotlib.cm')
    img = tf.shade(agg.a, how='log', cmap=cm.viridis)
    sol = np.array([[0, 4283695428, 4287524142], [4287143710, 0, 4282832267],
                    [4280213706, 4280608765, 0]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
示例#10
0
 def _apply_spreading(self, array):
     img = tf.Image(array)
     return tf.dynspread(img,
                         max_px=self.p.max_px,
                         threshold=self.p.threshold,
                         how=self.p.how,
                         shape=self.p.shape).data
def test_shade_cmap(agg):
    cmap = ['red', (0, 255, 0), '#0000FF']
    img = tf.shade(agg.a, how='log', cmap=cmap)
    sol = np.array([[0, 4278190335, 4278236489], [4280344064, 0, 4289091584],
                    [4292225024, 4294901760, 0]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
示例#12
0
    def _process(self, overlay, key=None):
        if not isinstance(overlay, CompositeOverlay):
            return overlay
        elif len(overlay) == 1:
            return overlay.last if isinstance(overlay, NdOverlay) else overlay.get(0)

        imgs = []
        for rgb in overlay:
            if not isinstance(rgb, RGB):
                raise TypeError('stack operation expect RGB type elements, '
                                'not %s name.' % type(rgb).__name__)
            rgb = rgb.rgb
            dims = [kd.name for kd in rgb.kdims][::-1]
            coords = {kd.name: rgb.dimension_values(kd, False)
                      for kd in rgb.kdims}
            imgs.append(tf.Image(self.uint8_to_uint32(rgb), coords=coords, dims=dims))

        try:
            imgs = xr.align(*imgs, join='exact')
        except ValueError:
            raise ValueError('RGB inputs to stack operation could not be aligned, '
                             'ensure they share the same grid sampling.')

        stacked = tf.stack(*imgs, how=self.p.compositor)
        arr = shade.uint32_to_uint8(stacked.data)[::-1]
        data = (coords[dims[1]], coords[dims[0]], arr[:, :, 0],
                arr[:, :, 1], arr[:, :, 2])
        if arr.shape[-1] == 4:
            data = data + (arr[:, :, 3],)
        return rgb.clone(data, datatype=[rgb.interface.datatype]+rgb.datatype)
def test_shade_should_handle_zeros_array():
    data = np.array([[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='uint32')
    arr = tf.Image(data, dims=['x', 'y'])
    img = tf.shade(arr, cmap=['white', 'black'], how='linear')
    assert img is not None
示例#14
0
def plot_ts_histograms(
    axes: Axes,
    data: pd.DataFrame,
    sample_col: Text,
    N_obs: Optional[int] = None,
    **canvas_kwargs,
) -> Axes:  # pragma: no cover
    """Plot time series histograms on `datashader`'s canvas

    Parameters
    ==========
    axes: Axes
        The Matplotlib axes to use for plotting.
    data: DataFrame
        The sample data to be plotted. This should be in "long" format: i.e.
        the index should be "time" and the columns should contain "draw" and
        `sample_col`.
    sample_col: str
        Sample column to be plotted.
    N_obs: int
        Number of observations to plot. If unspecified, plotting all oberservations
        in `data`.
    canvas_kwargs
        Keywords passed to ``plot_split_timeseries``.

    """
    if "draw" not in data.columns:
        raise ValueError("`data` does not have 'draw' number in its columns")
    n_draws = np.max(data["draw"]) + 1
    total_obs = data.shape[0] // n_draws
    if N_obs is None:
        N_obs = total_obs
    elif N_obs > total_obs:
        raise ValueError(
            f"`N_obs` ({N_obs}) must be <= `total_obs` ({total_obs})")

    if "plot_width" not in canvas_kwargs:
        canvas_kwargs["plot_width"] = N_obs

    # initialize canvas
    canvas = ds.Canvas(**canvas_kwargs)

    # get data to plot
    data = data.head(N_obs * n_draws).copy()
    dts = data.index.unique()[:N_obs]
    data["dt"] = np.repeat(dts.view(np.int64), n_draws)

    agg = canvas.points(data, "dt", sample_col)
    agg.coords.update({"dt": dts})

    shade_res = tf.shade(agg, cmap="black", how="eq_hist")
    shade_res.values = shade_res.values / np.max(shade_res.values) * np.max(
        agg.values)
    res_img = tf.Image(shade_res)

    # start painting
    _ = res_img.plot(cmap="Blues", ax=axes, label="posterior predictives")

    return axes
示例#15
0
def render_map(source: MapSource,  # noqa: C901
               xmin: float = None, ymin: float = None,
               xmax: float = None, ymax: float = None,
               x: float = None, y: float = None,
               z: float = None,
               height: int = None, width: int = None, ):

    if x is not None and y is not None and z is not None:
        xmin, ymin, xmax, ymax = tile_def.get_tile_meters(x, y, z)

    sxmin, symin, sxmax, symax = source.full_extent

    # handle null extent
    if xmin is None:
        xmin = sxmin

    if ymin is None:
        ymin = symin

    if xmax is None:
        xmax = sxmax

    if ymax is None:
        ymax = symax

    # handle null h/w
    if height is None and width is None:
        width = 1000

    if height is None:
        x_range, y_range = ((xmin, xmax), (ymin, ymax))
        height = height_implied_by_aspect_ratio(width, x_range, y_range)

    if width is None:
        x_range, y_range = ((xmin, xmax), (ymin, ymax))
        width = height_implied_by_aspect_ratio(height, y_range, x_range)

    # handle out of bounds
    if xmin < sxmin and ymin < symin and xmax > symax and ymax > symax:
        agg = tf.Image(np.zeros(shape=(height, width), dtype=np.uint32),
                       coords={'x': np.linspace(xmin, xmax, width),
                               'y': np.linspace(ymin, ymax, height)},
                       dims=['x', 'y'])
        img = shade_agg(source, agg, xmin, ymin, xmax, ymax)
        return img

    agg = create_agg(source, xmin, ymin, xmax, ymax, x, y, z, height, width)

    if source.span and isinstance(source.span, (list, tuple)):
        agg = agg.where((agg >= source.span[0]) & (agg <= source.span[1]))

    source, agg = apply_additional_transforms(source, agg)
    img = shade_agg(source, agg, xmin, ymin, xmax, ymax)

    # apply dynamic spreading ----------
    if source.dynspread and source.dynspread > 0:
        img = tf.dynspread(img, threshold=1, max_px=int(source.dynspread))

    return img
示例#16
0
def color_values(agg, color_key, alpha=255):
    def _convert_color(c):
        r, g, b = rgb(c)
        return np.array([r, g, b, alpha]).astype(np.uint8).view(np.uint32)[0]

    _converted_colors = {k: _convert_color(v) for k, v in color_key.items()}
    f = np.vectorize(lambda v: _converted_colors.get(v, 0))
    return tf.Image(f(agg.data))
def test_set_background():
    out = tf.set_background(img1)
    assert out.equals(img1)
    sol = tf.Image(np.array([[0xff00ffff, 0xff0000ff],
                             [0xff0000ff, 0xff00ff7d]], dtype='uint32'),
                   coords=coords2, dims=dims)
    out = tf.set_background(img1, 'red')
    assert out.equals(sol)
def test_rgb_dynspread():
    b = 0xffff0000
    coords = [np.arange(5), np.arange(5)]
    data = np.array([[b, b, 0, 0, 0], [b, b, 0, 0, 0], [0, 0, 0, 0, 0],
                     [0, 0, 0, b, 0], [0, 0, 0, 0, 0]],
                    dtype='uint32')
    img = tf.Image(data, coords=coords, dims=dims)
    assert tf.dynspread(img).equals(img)
    data = np.array([[b, 0, 0, 0, 0], [0, 0, 0, 0, 0], [b, 0, 0, 0, b],
                     [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
                    dtype='uint32')
    img = tf.Image(data, coords=coords, dims=dims)
    assert tf.dynspread(img, threshold=0.4).equals(tf.spread(img, 0))
    assert tf.dynspread(img, threshold=0.7).equals(tf.spread(img, 1))
    assert tf.dynspread(img, threshold=1.0).equals(tf.spread(img, 3))
    assert tf.dynspread(img, max_px=0).equals(img)

    pytest.raises(ValueError, lambda: tf.dynspread(img, threshold=1.1))
    pytest.raises(ValueError, lambda: tf.dynspread(img, max_px=-1))
def test_span_cmap_single(agg, cmap):
    # Get input
    x = agg.a

    # Build expected solution DataArray
    sol = np.array([[0, 671088640, 1946157056], [2701131776, 0, 3640655872],
                    [3976200192, 4278190080, 0]])
    sol = tf.Image(sol, coords=coords, dims=dims)

    # Check span
    check_span(x, cmap, 'log', sol)
def test_shade_category(array):
    coords = [np.array([0, 1]), np.array([2, 5])]
    cat_agg = xr.DataArray(array([[(0, 12, 0), (3, 0, 3)],
                                  [(12, 12, 12), (24, 0, 0)]]),
                           coords=(coords + [['a', 'b', 'c']]),
                           dims=(dims + ['cats']))

    colors = [(255, 0, 0), '#0000FF', 'orange']

    img = tf.shade(cat_agg, color_key=colors, how='log', min_alpha=20)
    sol = np.array([[2583625728, 335565567], [4283774890, 3707764991]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # Check dims/coordinates order
    assert list(img.coords) == ['x_axis', 'y_axis']
    assert list(img.dims) == ['y_axis', 'x_axis']

    colors = dict(zip('abc', colors))

    img = tf.shade(cat_agg, color_key=colors, how='cbrt', min_alpha=20)
    sol = np.array([[2650734592, 335565567], [4283774890, 3657433343]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=20)
    sol = np.array([[1140785152, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    img = tf.shade(cat_agg,
                   color_key=colors,
                   how=lambda x, m: np.where(m, np.nan, x)**2,
                   min_alpha=20)
    sol = np.array([[503250944, 335565567], [4283774890, 1744830719]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
def test_span_cmap_mpl(agg):
    # Get inputs
    x = agg.a

    # Get MPL colormap
    cm = pytest.importorskip('matplotlib.cm')
    cmap = cm.viridis

    # Build expected solution Data Array
    sol = np.array([[0, 4283695428, 4287524142], [4287143710, 0, 4282832267],
                    [4280213706, 4280608765, 0]])
    sol = tf.Image(sol, coords=coords, dims=dims)

    # Check span
    check_span(x, cmap, 'log', sol)
示例#22
0
def shade_discrete(agg, color_key, name='shaded', alpha=255, nodata=0):

    if not agg.ndim == 2:
        raise ValueError("agg must be 2D")

    data = ds.utils.orient_array(agg)

    # check for dask array
    if isinstance(data, da.Array):
        data = data.compute()
    else:
        data = data.copy()

    # support grouped color_key
    first_cat = tuple(color_key.keys())[0]
    if isinstance(first_cat, (list, tuple)):
        cats = []
        colors = []
        for categories, val in color_key.items():
            cor = rgb(val)
            for c in categories:
                cats.append(c)
                colors.append(cor)
    else:
        cats = color_key.keys()
        colors = [rgb(color_key[c]) for c in cats]

    rs, gs, bs = map(np.array, zip(*colors))
    h, w = agg.shape

    r = np.zeros((h, w), dtype=np.uint8)
    g = np.zeros((h, w), dtype=np.uint8)
    b = np.zeros((h, w), dtype=np.uint8)

    for i, c in enumerate(cats):
        value_mask = data == c
        r[value_mask] = rs[i]
        g[value_mask] = gs[i]
        b[value_mask] = bs[i]

    a = np.where(np.logical_or(np.isnan(r), r <= nodata), 0, alpha)
    img = np.dstack((r, g, b, a)).astype('uint8').view(dtype=np.uint32).reshape(a.shape)
    return tf.Image(img, coords=agg.coords, dims=agg.dims, name=name)
示例#23
0
def render_map(source: MapSource,
               xmin: float = None,
               ymin: float = None,
               xmax: float = None,
               ymax: float = None,
               x: float = None,
               y: float = None,
               z: float = None,
               height: int = 256,
               width: int = 256):

    if x is not None and y is not None and z is not None:
        xmin, ymin, xmax, ymax = tile_def.get_tile_meters(x, y, z)

    sxmin, symin, sxmax, symax = source.full_extent

    # handle out of bounds
    if xmin < sxmin and ymin < symin and xmax > symax and ymax > symax:
        agg = tf.Image(np.zeros(shape=(height, width), dtype=np.uint32),
                       coords={
                           'x': np.linspace(xmin, xmax, width),
                           'y': np.linspace(ymin, ymax, height)
                       },
                       dims=['x', 'y'])
        img = shade_agg(source, agg, xmin, ymin, xmax, ymax)
        return img

    agg = create_agg(source, xmin, ymin, xmax, ymax, x, y, z, height, width)

    if source.span and isinstance(source.span, (list, tuple)):
        agg = agg.where((agg >= source.span[0]) & (agg <= source.span[1]))

    source, agg = apply_additional_transforms(source, agg)
    img = shade_agg(source, agg, xmin, ymin, xmax, ymax)

    # apply dynamic spreading ----------
    if source.dynspread and source.dynspread > 0:
        img = tf.dynspread(img, threshold=1, max_px=int(source.dynspread))

    return img
示例#24
0
def to_raster(source: MapSource,
              xmin: float = None, ymin: float = None,
              xmax: float = None, ymax: float = None,
              height: int = None, width: int = None):

    if height is None and width is None:
        width = 1000

    sxmin, symin, sxmax, symax = source.full_extent

    if xmin is None:
        xmin = sxmin

    if ymin is None:
        ymin = symin

    if xmax is None:
        xmax = sxmax

    if ymax is None:
        ymax = symax

    # handle null h/w
    if height is None:
        x_range, y_range = ((xmin, xmax), (ymin, ymax))
        height = height_implied_by_aspect_ratio(width, x_range, y_range)

    if width is None:
        x_range, y_range = ((xmin, xmax), (ymin, ymax))
        width = height_implied_by_aspect_ratio(height, y_range, x_range)

    # handle out of bounds
    if xmin < sxmin and ymin < symin and xmax > symax and ymax > symax:
        agg = tf.Image(np.zeros(shape=(height, width), dtype=np.uint32),
                       coords={'x': np.linspace(xmin, xmax, width),
                               'y': np.linspace(ymin, ymax, height)},
                       dims=['x', 'y'])
        return agg

    return create_agg(source, xmin, ymin, xmax, ymax, None, None, None, height, width)
示例#25
0
 def _apply_spreading(self, array):
     img = tf.Image(array)
     return tf.spread(img, px=self.p.px,
                      how=self.p.how, shape=self.p.shape).data
def test_spread():
    p = 0x7d00007d
    g = 0x7d00FF00
    b = 0x7dFF0000
    data = np.array([[p, p, 0, 0, 0], [p, g, 0, 0, 0], [0, 0, 0, 0, 0],
                     [0, 0, 0, b, 0], [0, 0, 0, 0, 0]],
                    dtype='uint32')
    coords = [np.arange(5), np.arange(5)]
    img = tf.Image(data, coords=coords, dims=dims)

    s = tf.spread(img)
    o = np.array([[0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xbc00a82a, 0xbc00a82a, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000,
                   0x7dff0000]])
    np.testing.assert_equal(s.data, o)
    assert (s.x_axis == img.x_axis).all()
    assert (s.y_axis == img.y_axis).all()
    assert s.dims == img.dims

    s = tf.spread(img, px=2)
    o = np.array([[0xed00863b, 0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xf581411c, 0xdc904812, 0x7dff0000],
                  [0xed00863b, 0xf581411c, 0xed864419, 0xbca85600, 0x7dff0000],
                  [0xbc00a82a, 0xdc904812, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000,
                   0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, shape='square')
    o = np.array([[0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xbc00a82a, 0xbc00a82a, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000,
                   0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, how='add')
    o = np.array([[0xff007db7, 0xff007db7, 0xfa007f3e, 0x00000000, 0x00000000],
                  [0xff007db7, 0xff007db7, 0xfa007f3e, 0x00000000, 0x00000000],
                  [0xfa007f3e, 0xfa007f3e, 0xfa7f7f00, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000,
                   0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    mask = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
    s = tf.spread(img, mask=mask)
    o = np.array([[0xbc00a82a, 0xbc00007d, 0x7d00ff00, 0x00000000, 0x00000000],
                  [0xbc00007d, 0xbc00a82a, 0x7d00007d, 0x00000000, 0x00000000],
                  [0x7d00ff00, 0x7d00007d, 0xbca85600, 0x00000000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x00000000, 0x7dff0000, 0x00000000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x00000000,
                   0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, px=0)
    np.testing.assert_equal(s.data, img.data)

    pytest.raises(ValueError, lambda: tf.spread(img, px=-1))
    pytest.raises(ValueError, lambda: tf.spread(img, mask=np.ones(2)))
    pytest.raises(ValueError, lambda: tf.spread(img, mask=np.ones((2, 2))))
    sol = np.array([[1140785152, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg,
                      colors,
                      how=lambda x, m: np.where(m, np.nan, x)**2)
    sol = np.array([[503250944, 335565567], [4283774890, 1744830719]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)


coords2 = [np.array([0, 2]), np.array([3, 5])]
img1 = tf.Image(np.array([[0xff00ffff, 0x00000000], [0x00000000, 0xff00ff7d]],
                         dtype='uint32'),
                coords=coords2,
                dims=dims)
img2 = tf.Image(np.array([[0x00000000, 0x00000000], [0x000000ff, 0x7d7d7dff]],
                         dtype='uint32'),
                coords=coords2,
                dims=dims)


def test_set_background():
    out = tf.set_background(img1)
    assert out.equals(img1)
    sol = tf.Image(np.array(
        [[0xff00ffff, 0xff0000ff], [0xff0000ff, 0xff00ff7d]], dtype='uint32'),
                   coords=coords2,
                   dims=dims)
    out = tf.set_background(img1, 'red')
def test_shade_category(array):
    coords = [np.array([0, 1]), np.array([2, 5])]
    cat_agg = tf.Image(array([[(0, 12, 0),
                               (3, 0, 3)], [(12, 12, 12), (24, 0, 0)]],
                             dtype='u4'),
                       coords=(coords + [['a', 'b', 'c']]),
                       dims=(dims + ['cats']))

    colors = [(255, 0, 0), '#0000FF', 'orange']

    img = tf.shade(cat_agg, color_key=colors, how='log', min_alpha=20)
    sol = np.array([[2583625728, 335565567], [4283774890, 3707764991]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # Check dims/coordinates order
    assert list(img.coords) == ['x_axis', 'y_axis']
    assert list(img.dims) == ['y_axis', 'x_axis']

    colors = dict(zip('abc', colors))

    img = tf.shade(cat_agg, color_key=colors, how='cbrt', min_alpha=20)
    sol = np.array([[2650734592, 335565567], [4283774890, 3657433343]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=20)
    sol = np.array([[1140785152, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    img = tf.shade(cat_agg,
                   color_key=colors,
                   how=lambda x, m: np.where(m, np.nan, x)**2,
                   min_alpha=20)
    sol = np.array([[503250944, 335565567], [4283774890, 1744830719]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    # all pixels should be at min_alpha
    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=0,
                   span=(50, 100))
    sol = np.array([[16711680, 21247], [5584810, 255]], dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # redundant verification that alpha channel is all 0x00
    assert ((img.data[0, 0] >> 24) & 0xFF) == 0
    assert ((img.data[0, 1] >> 24) & 0xFF) == 0
    assert ((img.data[1, 0] >> 24) & 0xFF) == 0
    assert ((img.data[1, 1] >> 24) & 0xFF) == 0

    # all pixels should be at max_alpha
    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=0,
                   span=(0, 2))
    sol = np.array([[4294901760, 4278211327], [4283774890, 4278190335]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # redundant verification that alpha channel is all 0xFF
    assert ((img.data[0, 0] >> 24) & 0xFF) == 255
    assert ((img.data[0, 1] >> 24) & 0xFF) == 255
    assert ((img.data[1, 0] >> 24) & 0xFF) == 255
    assert ((img.data[1, 1] >> 24) & 0xFF) == 255

    # One pixel should be min-alpha, the other max-alpha
    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=0,
                   span=(6, 36))
    sol = np.array([[872349696, 21247], [4283774890, 2566914303]], dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # redundant verification that alpha channel is correct
    assert ((img.data[0, 0] >> 24) & 0xFF) == 51  # (6 / 30) * 255
    assert ((img.data[0, 1] >> 24) & 0xFF) == 0
    assert ((img.data[1, 0] >> 24) & 0xFF) == 255
    assert ((img.data[1, 1] >> 24) & 0xFF) == 153  # ( 18 /30) * 255

    # One pixel should be min-alpha, the other max-alpha
    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=0,
                   span=(0, 72))
    sol = np.array([[721354752, 352342783], [2136291242, 1426063615]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    # redundant verification that alpha channel is correct
    assert ((img.data[0, 0] >> 24) & 0xFF) == 42  # (12 / 72) * 255
    assert ((img.data[0, 1] >> 24) & 0xFF) == 21  # (6 / 72) * 255
    assert ((img.data[1, 0] >> 24) & 0xFF) == 127  # ( 36 / 72) * 255
    assert ((img.data[1, 1] >> 24) & 0xFF) == 85  # ( 24 /72 ) * 255

    # test that empty coordinates are always fully transparent, even when
    # min_alpha is non-zero
    cat_agg = tf.Image(array([[(0, 0, 0), (3, 0, 3)], [(12, 12, 12),
                                                       (24, 0, 0)]],
                             dtype='u4'),
                       coords=(coords + [['a', 'b', 'c']]),
                       dims=(dims + ['cats']))

    # First test auto-span
    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=20)
    sol = np.array([[5584810, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    # redundant verification that alpha channel is correct
    assert ((img.data[0, 0] >> 24) & 0xFF) == 0  # fully transparent
    assert ((img.data[0, 1] >> 24) & 0xFF) != 0  # not fully transparent
    assert ((img.data[1, 0] >> 24) & 0xFF) != 0  # not fully transparent
    assert ((img.data[1, 1] >> 24) & 0xFF) != 0  # not fully transparent

    # Next test manual-span
    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=20,
                   span=(6, 36))
    sol = np.array([[5584810, 335565567], [4283774890, 2701132031]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)

    # redundant verification that alpha channel is correct
    assert ((img.data[0, 0] >> 24) & 0xFF) == 0  # fully transparent
    assert ((img.data[0, 1] >> 24) & 0xFF) != 0  # not fully transparent
    assert ((img.data[1, 0] >> 24) & 0xFF) != 0  # not fully transparent
    assert ((img.data[1, 1] >> 24) & 0xFF) != 0  # not fully transparent

    # Categorical aggregations with some reductions (such as sum) can result in negative
    # values in the data here we test positive and negative values
    cat_agg = tf.Image(array([[(0, -30, 0),
                               (18, 0, -18)], [(-2, 2, -2), (-18, 9, 12)]],
                             dtype='i4'),
                       coords=(coords + [['a', 'b', 'c']]),
                       dims=(dims + ['cats']))

    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=20)
    sol = np.array([[335565567, 3914667690], [3680253090, 4285155988]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    assert ((img.data[0, 0] >> 24) & 0xFF) == 20
    assert ((img.data[0, 1] >> 24) & 0xFF) == 233
    assert ((img.data[1, 0] >> 24) & 0xFF) == 219
    assert ((img.data[1, 1] >> 24) & 0xFF) == 255

    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=20,
                   span=(0, 3))
    sol = np.array([[335565567, 341120682], [341587106, 4285155988]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    assert ((img.data[0, 0] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[0, 1] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[1, 0] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[1, 1] >> 24) & 0xFF) == 255

    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=20,
                   color_baseline=9)
    sol = np.array([[341129130, 3909091583], [3679795114, 4278232575]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    assert ((img.data[0, 0] >> 24) & 0xFF) == 20
    assert ((img.data[0, 1] >> 24) & 0xFF) == 233
    assert ((img.data[1, 0] >> 24) & 0xFF) == 219
    assert ((img.data[1, 1] >> 24) & 0xFF) == 255

    # Categorical aggregations with some reductions (such as sum) can result in negative
    # values in the data, here we test all negative values
    cat_agg = tf.Image(array([[(0, -30, 0),
                               (-18, 0, -18)], [(-2, -2, -2), (-18, 0, 0)]],
                             dtype='i4'),
                       coords=(coords + [['a', 'b', 'c']]),
                       dims=(dims + ['cats']))

    img = tf.shade(cat_agg, color_key=colors, how='linear', min_alpha=20)
    sol = np.array([[1124094719, 344794225], [4283774890, 2708096148]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    assert ((img.data[0, 0] >> 24) & 0xFF) == 67
    assert ((img.data[0, 1] >> 24) & 0xFF) == 20
    assert ((img.data[1, 0] >> 24) & 0xFF) == 255
    assert ((img.data[1, 1] >> 24) & 0xFF) == 161

    img = tf.shade(cat_agg,
                   color_key=colors,
                   how='linear',
                   min_alpha=20,
                   span=(6, 36))
    sol = np.array([[335565567, 344794225], [341129130, 342508692]],
                   dtype='u4')
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert_eq_xr(img, sol)
    assert ((img.data[0, 0] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[0, 1] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[1, 0] >> 24) & 0xFF) == 20  # min alpha
    assert ((img.data[1, 1] >> 24) & 0xFF) == 20  # min alpha
示例#29
0
文件: Graph.py 项目: sammatuba/omf
    if canvas is None:
        xr = nodes.x.min(), nodes.x.max()
        yr = nodes.y.min(), nodes.y.max()
        canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts)
        
    np = nodesplot(nodes, name + " nodes", canvas, cat)
    #print(np)
    ep = edgesplot(edges, name + " edges", canvas)
    #print(ep)
    return tf.stack(ep, np, how="over", name=name)

fd = forcedirected
fd_d = graphplot(fd, connect_edges(fd,edges)) 

#convert datashder image to png
back_img = tf.Image(fd_d).to_pil()


x_range=fd.x.min(), fd.x.max()
y_range=fd.y.min(), fd.y.max()

#xr = nodes.x.min(), nodes.x.max()
#yr = nodes.y.min(), nodes.y.max()
plot_height=600
plot_width=800


#Create initial plotly graph with datashader image as background
import plotly.graph_objs as go
f = go.Figure(data=[{'x': x_range, 
                           'y': y_range, 
示例#30
0
    assert img.equals(sol)
    img = tf.colorize(cat_agg, colors, how='linear')
    sol = np.array([[1660878848, 989876991], [4283774890, 2952790271]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)
    img = tf.colorize(cat_agg, colors, how=lambda x: x**2)
    sol = np.array([[788463616, 436228863], [4283774890, 2080375039]])
    sol = tf.Image(sol, coords=coords, dims=dims)
    assert img.equals(sol)


coords2 = [np.array([0, 2]), np.array([3, 5])]
img1 = tf.Image(np.dstack([
    np.array([[255, 0], [0, 125]], 'uint8'),
    np.array([[255, 0], [0, 255]], 'uint8'),
    np.array([[0, 0], [0, 0]], 'uint8'),
    np.array([[255, 0], [0, 255]], 'uint8')
]).view(np.uint32).reshape((2, 2)),
                coords=coords2,
                dims=dims)

img2 = tf.Image(np.dstack([
    np.array([[0, 0], [0, 255]], 'uint8'),
    np.array([[0, 0], [0, 125]], 'uint8'),
    np.array([[0, 0], [0, 125]], 'uint8'),
    np.array([[0, 0], [255, 125]], 'uint8')
]).view(np.uint32).reshape((2, 2)),
                coords=coords2,
                dims=dims)


def test_stack():