xrspatial.focal.apply

xrspatial.focal.apply(raster, kernel, func=CPUDispatcher(<function _calc_mean>))[source]

Returns custom function applied array using a user-created window.

Parameters
  • raster (xarray.DataArray) – 2D array of input values to be filtered.

  • kernel (numpy.array) – 2D array where values of 1 indicate the kernel.

  • func (callable, default=xrspatial.focal._calc_mean) – Function which takes an input array and returns an array.

Returns

agg – 2D aggregate array of filtered values.

Return type

xarray.DataArray of same type as raster

Examples

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

from xrspatial import generate_terrain, aspect
from xrspatial.focal import apply
from xrspatial.convolution import circle_kernel

# Generate Example Terrain
W = 500
H = 300

template_terrain = xr.DataArray(np.zeros((H, W)))
x_range=(-20e6, 20e6)
y_range=(-20e6, 20e6)

terrain_agg = generate_terrain(
    template_terrain, x_range=x_range, y_range=y_range
)

# 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'})

# Edit Attributes
terrain_agg = terrain_agg.rename('Elevation')

# Create Kernel
kernel = circle_kernel(10, 10, 100)

# Apply Kernel
agg = apply(raster = terrain_agg,
            kernel = kernel)

# Edit Attributes
agg = agg.assign_attrs({'Description': 'Example Filtered Terrain'})

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

# Plot Filtered Terrain
agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Filtered Terrain")
plt.ylabel("latitude")
plt.xlabel("longitude")
../../_images/xrspatial-focal-apply-1_00.png

(png, hires.png, pdf)

../../_images/xrspatial-focal-apply-1_01.png

(png, hires.png, pdf)

>>> print(terrain_agg[200:203, 200:202])
<xarray.DataArray 'Elevation' (lat: 3, lon: 2)>
array([[1264.02296597, 1261.947921  ],
       [1285.37105519, 1282.48079719],
       [1306.02339636, 1303.4069579 ]])
Coordinates:
* lon      (lon) float64 -3.96e+06 -3.88e+06
* lat      (lat) float64 6.733e+06 6.867e+06 7e+06
Attributes:
    res:            (80000.0, 133333.3333333333)
    Description:    Example Terrain
    units:          km
    Max Elevation:  4000

>>> print(agg[200:203, 200:202])
<xarray.DataArray (lat: 3, lon: 2)>
array([[1307.19395948, 1302.69168271],
       [1323.55815161, 1318.75959349],
       [1342.33133041, 1336.93821534]])
Coordinates:
* lon      (lon) float64 -3.96e+06 -3.88e+06
* lat      (lat) float64 6.733e+06 6.867e+06 7e+06
Attributes:
    res:            (80000.0, 133333.3333333333)
    Description:    Example Filtered Terrain
    units:          km
    Max Elevation:  4000