예제 #1
0
def test_ratio_gpu():

    import cupy

    # vanilla numpy version
    agg1 = create_test_arr(arr1)
    agg2 = create_test_arr(arr2)
    numpy_result = ratio(agg1, agg2)

    # cupy
    agg1_cupy = create_test_arr(arr1, backend='cupy')
    agg2_cupy = create_test_arr(arr2, backend='cupy')
    cupy_result = ratio(agg1_cupy, agg2_cupy)

    assert isinstance(cupy_result.data, cupy.ndarray)
    assert np.isclose(numpy_result, cupy_result, equal_nan=True).all()

    # dask + cupy
    agg1_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    agg2_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    dask_cupy_result = ratio(agg1_dask_cupy, agg2_dask_cupy)

    assert is_dask_cupy(dask_cupy_result)
    dask_cupy_result = dask_cupy_result.compute()
    assert np.isclose(
        numpy_result,
        dask_cupy_result.data,
        equal_nan=True,
    ).all()
예제 #2
0
def test_ndmi_dask_cupy_equals_numpy():
    # vanilla numpy version
    nir = create_test_arr(arr1)
    swir1 = create_test_arr(arr2)
    numpy_result = ndmi(nir, swir1)

    # dask + cupy
    nir_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    swir1_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    test_result = ndmi(nir_dask_cupy, swir1_dask_cupy)

    assert is_dask_cupy(test_result)
    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #3
0
def test_ebbi_dask_cupy_equals_numpy():
    # vanilla numpy version
    red = create_test_arr(arr1)
    swir = create_test_arr(arr2)
    tir = create_test_arr(arr3)
    numpy_result = ebbi(red, swir, tir)

    # dask + cupy
    red_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    swir_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    tir_dask_cupy = create_test_arr(arr3, backend='dask+cupy')
    test_result = ebbi(red_dask_cupy, swir_dask_cupy, tir_dask_cupy)

    assert is_dask_cupy(test_result)
    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #4
0
def test_sipi_dask_cupy_equals_numpy():
    # vanilla numpy version
    nir = create_test_arr(arr1)
    red = create_test_arr(arr2)
    blue = create_test_arr(arr3)
    numpy_result = sipi(nir, red, blue)

    # dask + cupy
    nir_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    red_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    blue_dask_cupy = create_test_arr(arr3, backend='dask+cupy')
    test_result = sipi(nir_dask_cupy, red_dask_cupy, blue_dask_cupy)

    assert is_dask_cupy(test_result)
    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #5
0
def test_nbr2_dask_cupy_equals_numpy():

    import cupy

    # vanilla numpy version
    swir1 = create_test_arr(arr1)
    swir2 = create_test_arr(arr2)
    numpy_result = nbr2(swir1, swir2)

    # dask + cupy
    swir1_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    swir2_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    test_result = nbr2(swir1_dask_cupy, swir2_dask_cupy)

    assert is_dask_cupy(test_result)
    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #6
0
def test_gci_dask_cupy_equals_numpy():

    import cupy

    # vanilla numpy version
    nir = create_test_arr(arr1)
    green = create_test_arr(arr2)
    numpy_result = gci(nir, green)

    # dask + cupy
    nir_dask_cupy = create_test_arr(arr1, backend='dask+cupy')
    green_dask_cupy = create_test_arr(arr2, backend='dask+cupy')
    test_result = gci(nir_dask_cupy, green_dask_cupy)

    assert is_dask_cupy(test_result)

    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #7
0
def test_ndvi_dask_cupy_equals_numpy():

    import cupy

    # vanilla numpy version
    nir = create_test_arr(arr1)
    red = create_test_arr(arr2)
    numpy_result = ndvi(nir, red)

    # dask + cupy
    nir_dask = create_test_arr(arr1, backend='dask+cupy')
    red_dask = create_test_arr(arr2, backend='dask+cupy')
    test_result = ndvi(nir_dask, red_dask)

    assert is_dask_cupy(test_result)

    test_result.data = test_result.data.compute()
    assert np.isclose(numpy_result, test_result, equal_nan=True).all()
예제 #8
0
def slope(agg: xr.DataArray,
          name: str = 'slope') -> xr.DataArray:
    """
    Returns slope of input aggregate in degrees.
    
    Parameters:
    ---------
    agg: xarray.DataArray
        2D array of elevation band data.
    name: str, optional (default = 'slope')
        name property of output xarray.DataArray

    Returns:
    ---------
    xarray.DataArray
        2D array, of the same type as the input, of calculated slope values.
        All other input attributes are preserved.

    Notes:
    ---------
    Algorithm References:
        - http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/how-slope-works.htm
        - Burrough, P. A., and McDonell, R. A., 1998.
          Principles of Geographical Information Systems
          (Oxford University Press, New York), pp 406
    Examples:
    ---------
    Imports
    >>> import numpy as np
    >>> import xarray as xr
    >>> from xrspatial import slope

    Create Data Array
    >>> agg = xr.DataArray(np.array([[0, 0, 0, 0, 0, 0, 0],
    >>>                              [0, 0, 2, 4, 0, 8, 0],
    >>>                              [0, 2, 2, 4, 6, 8, 0],
    >>>                              [0, 4, 4, 4, 6, 8, 0],
    >>>                              [0, 6, 6, 6, 6, 8, 0],
    >>>                              [0, 8, 8, 8, 8, 8, 0],
    >>>                              [0, 0, 0, 0, 0, 0, 0]]),
    >>>                     dims = ["lat", "lon"],
    >>>                     attrs = dict(res = 1))
    >>> height, width = agg.shape
    >>> _lon = np.linspace(0, width - 1, width)
    >>> _lat = np.linspace(0, height - 1, height)
    >>> agg["lon"] = _lon
    >>> agg["lat"] = _lat

    Create Slope Data Array
    >>> print(slope(agg))
    <xarray.DataArray 'slope' (lat: 7, lon: 7)>
    array([[ 0,  0,  0,  0,  0,  0,  0],
           [ 0, 46, 60, 63, 73, 70,  0],
           [ 0, 60, 54, 54, 68, 67,  0],
           [ 0, 68, 60, 54, 60, 71,  0],
           [ 0, 73, 63, 60, 54, 72,  0],
           [ 0, 74, 71, 71, 72, 75,  0],
           [ 0,  0,  0,  0,  0,  0,  0]])
    Coordinates:
      * lon      (lon) float64 0.0 1.0 2.0 3.0 4.0 5.0 6.0
      * lat      (lat) float64 0.0 1.0 2.0 3.0 4.0 5.0 6.0
    Attributes:
        res:      1
    """

    cellsize_x, cellsize_y = get_dataarray_resolution(agg)

    # numpy case
    if isinstance(agg.data, np.ndarray):
        out = _run_numpy(agg.data, cellsize_x, cellsize_y)

    # cupy case
    elif has_cuda() and isinstance(agg.data, cupy.ndarray):
        out = _run_cupy(agg.data, cellsize_x, cellsize_y)

    # dask + cupy case
    elif has_cuda() and is_dask_cupy(agg):
        out = _run_dask_cupy(agg.data, cellsize_x, cellsize_y)

    # dask + numpy case
    elif isinstance(agg.data, da.Array):
        out = _run_dask_numpy(agg.data, cellsize_x, cellsize_y)

    else:
        raise TypeError('Unsupported Array Type: {}'.format(type(agg.data)))

    return xr.DataArray(out,
                        name=name,
                        coords=agg.coords,
                        dims=agg.dims,
                        attrs=agg.attrs)
예제 #9
0
def slope(agg: xr.DataArray, name: str = 'slope') -> xr.DataArray:
    """
    Returns slope of input aggregate in degrees.

    Parameters
    ----------
    agg : xr.DataArray
        2D array of elevation data.
    name : str, default='slope'
        Name of output DataArray.

    Returns
    -------
    slope_agg : xr.DataArray of same type as `agg`
        2D array of slope values.
        All other input attributes are preserved.

    References
    ----------
        - arcgis: http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/how-slope-works.htm # noqa

    Examples
    --------
    .. plot::
       :include-source:

        import numpy as np
        import xarray as xr
        import datashader as ds
        import matplotlib.pyplot as plt
        from xrspatial import generate_terrain, slope

        # Create Canvas
        W = 500
        H = 300
        cvs = ds.Canvas(plot_width = W,
                        plot_height = H,
                        x_range = (-20e6, 20e6),
                        y_range = (-20e6, 20e6))

        # Generate Example Terrain
        terrain_agg = generate_terrain(canvas = cvs)

        # Edit Attributes
        terrain_agg = terrain_agg.assign_attrs(
            {
                'Description': 'Example Terrain',
                'units': 'km',
                'Max Elevation': '4000',
            }
        )
        
        terrain_agg = terrain_agg.rename({'x': 'lon', 'y': 'lat'})
        terrain_agg = terrain_agg.rename('Elevation')

        # Create Slope Aggregate Array
        slope_agg = slope(agg = terrain_agg, name = 'Slope')

        # Edit Attributes
        slope_agg = slope_agg.assign_attrs({'Description': 'Example Slope',
                                            'units': 'deg'})

        # Plot Terrain
        terrain_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
        plt.title("Terrain")
        plt.ylabel("latitude")
        plt.xlabel("longitude")

        # Plot Slope
        slope_agg.plot(aspect = 2, size = 4)
        plt.title("Slope")
        plt.ylabel("latitude")
        plt.xlabel("longitude")

    .. sourcecode:: python

        >>> print(terrain_agg[200:203, 200:202])
        <xarray.DataArray 'Elevation' (lat: 3, lon: 2)>
        array([[1264.02249454, 1261.94748873],
               [1285.37061171, 1282.48046696],
               [1306.02305679, 1303.40657515]])
        Coordinates:
          * lon      (lon) float64 -3.96e+06 -3.88e+06
          * lat      (lat) float64 6.733e+06 6.867e+06 7e+06
        Attributes:
            res:            1
            Description:    Example Terrain
            units:          km
            Max Elevation:  4000

        >>> print(slope_agg[200:203, 200:202])
        <xarray.DataArray 'Slope' (lat: 3, lon: 2)>
        array([[86.69626115, 86.55635267],
               [87.2235249 , 87.24527062],
               [86.69883402, 86.22918773]])
        Coordinates:
          * lon      (lon) float64 -3.96e+06 -3.88e+06
          * lat      (lat) float64 6.733e+06 6.867e+06 7e+06
        Attributes:
            res:            1
            Description:    Example Slope
            units:          deg
            Max Elevation:  4000
    """
    cellsize_x, cellsize_y = get_dataarray_resolution(agg)

    # numpy case
    if isinstance(agg.data, np.ndarray):
        out = _run_numpy(agg.data, cellsize_x, cellsize_y)

    # cupy case
    elif has_cuda() and isinstance(agg.data, cupy.ndarray):
        out = _run_cupy(agg.data, cellsize_x, cellsize_y)

    # dask + cupy case
    elif has_cuda() and is_dask_cupy(agg):
        out = _run_dask_cupy(agg.data, cellsize_x, cellsize_y)

    # dask + numpy case
    elif isinstance(agg.data, da.Array):
        out = _run_dask_numpy(agg.data, cellsize_x, cellsize_y)

    else:
        raise TypeError('Unsupported Array Type: {}'.format(type(agg.data)))

    return xr.DataArray(out,
                        name=name,
                        coords=agg.coords,
                        dims=agg.dims,
                        attrs=agg.attrs)