Basic Filtering#
The Filter Object#
The core object in GCMFilters is the gcm_filters.Filter
object. Its full documentation below enumerates all possible options.
 gcm_filters.Filter(filter_scale: float, dx_min: float, filter_shape: gcm_filters.filter.FilterShape = FilterShape.GAUSSIAN, transition_width: float = 3.141592653589793, ndim: int = 2, n_steps: int = 0, grid_type: gcm_filters.kernels.GridType = GridType.REGULAR, grid_vars: dict = <factory>) None [source]#
A class for applying diffusionbased smoothing filters to gridded data.
 Parameters
filter_scale (float) – The filter scale, which has different meaning depending on filter shape
dx_min (float) – The smallest grid spacing. Should have same units as
filter_scale
n_steps (int, optional) – Number of total steps in the filter
n_steps == 0
means the number of steps is chosen automaticallyfilter_shape (FilterShape) –
FilterShape.GAUSSIAN
: The target filter has shape \(e^{(k filter_scale)^2/24}\)FilterShape.TAPER
: The target filter has target grid scale Lf. Smaller scales are zeroed out. Scales larger thanpi * filter_scale / 2
are left asis. In between is a smooth transition.
transition_width (float, optional) – Width of the transition region in the “Taper” filter. This is a nondimensional parameter. Theoretical minimum is 1; not recommended.
ndim (int, optional) – Laplacian is applied on a grid of dimension ndim
grid_type (GridType) – what sort of grid we are dealing with
grid_vars (dict) – dictionary of extra parameters used to initialize the grid Laplacian
 gcm_filters.filter_spec#
 Type
FilterSpec
Details related to filter_scale
, filter_shape
, transition_width
, and n_steps
can be found in the Filter Theory.
The following sections explain the options for grid_type
and grid_vars
in more detail.
Grid types#
To define a filter, we need to pick a grid and associated Laplacian that matches our data. The currently implemented grid types are:
In [1]: import gcm_filters
In [2]: list(gcm_filters.GridType)
Out[2]:
[<GridType.REGULAR: 1>,
<GridType.REGULAR_AREA_WEIGHTED: 2>,
<GridType.REGULAR_WITH_LAND: 3>,
<GridType.REGULAR_WITH_LAND_AREA_WEIGHTED: 4>,
<GridType.IRREGULAR_WITH_LAND: 5>,
<GridType.MOM5U: 6>,
<GridType.MOM5T: 7>,
<GridType.TRIPOLAR_REGULAR_WITH_LAND_AREA_WEIGHTED: 8>,
<GridType.TRIPOLAR_POP_WITH_LAND: 9>,
<GridType.VECTOR_C_GRID: 10>,
<GridType.VECTOR_B_GRID: 11>]
This list will grow as we implement more Laplacians.
The following table provides an overview of these different grid type options: what grid they are suitable for, whether they handle land (i.e., continental boundaries), what boundary condition the Laplacian operators use, and whether they come with a scalar or vector Laplacian. You can also find links to example usages.

Grid 
Handles land 
Boundary condition 
Laplacian type 
Example 


Cartesian grid 
no 
periodic 
Scalar Laplacian 


Cartesian grid 
yes 
periodic 
Scalar Laplacian 
see below 

locally orthogonal grid 
yes 
periodic 
Scalar Laplacian 
Example: Different filter types; Example: Filtering on a tripole grid 

Velocitypoint on Arakawa BGrid 
yes 
periodic 
Scalar Laplacian 


Tracerpoint on Arakawa BGrid 
yes 
periodic 
Scalar Laplacian 


locally orthogonal grid 
yes 
tripole 
Scalar Laplacian 


yes 
periodic 
Vector Laplacian 


no 
periodic 
Vector Laplacian 
Grid types with scalar Laplacians can be used for filtering scalar fields (such as temperature), and grid types with vector Laplacians can be used for filtering vector fields (such as velocity).
Grid types for simple fixed factor filtering#
The remaining grid types are for a special type of filtering: simple fixed factor filtering to achieve a fixed coarsening factor (see also the Filter Theory). If you specify one of the following grid types for your data, gcm_filters
will internally transform your original (locally orthogonal) grid to a uniform Cartesian grid with dx = dy = 1, and perform fixed factor filtering on the uniform grid. After this is done, gcm_filters
transforms the filtered field back to your original grid.
In practice, this coordinate transformation is achieved by area weighting and deweighting (see Filter Theory). This is why the following grid types have the suffix AREA_WEIGHTED
.

Grid 
Handles land 
Boundary condition 
Laplacian type 
Example 


locally orthogonal grid 
no 
periodic 
Scalar Laplacian 


locally orthogonal grid 
yes 
periodic 
Scalar Laplacian 
Example: Different filter types; Example: Filtering on a tripole grid 

locally orthogonal grid 
yes 
tripole 
Scalar Laplacian 
Grid variables#
Each grid type from the above two tables has different grid variables that must be provided as Xarray DataArrays. For example, let’s assume we are on a Cartesian grid (with uniform grid spacing equal to 1), and we want to use the grid type REGULAR_WITH_LAND
. To find out what the required grid variables for this grid type are, we can use this utility function.
In [3]: gcm_filters.required_grid_vars(gcm_filters.GridType.REGULAR_WITH_LAND)
Out[3]: ['wet_mask']
wet_mask
is a binary array representing the topography on our grid. Here the convention is that the array is 1 in the ocean (“wet points”) and 0 on land (“dry points”).
In [4]: import numpy as np
In [5]: import xarray as xr
In [6]: ny, nx = (128, 256)
In [7]: mask_data = np.ones((ny, nx))
In [8]: mask_data[(ny // 4):(3 * ny // 4), (nx // 4):(3 * nx // 4)] = 0
In [9]: wet_mask = xr.DataArray(mask_data, dims=['y', 'x'])
In [10]: wet_mask.plot()
Out[10]: <matplotlib.collections.QuadMesh at 0x7f38c504c700>
We have made a big island.
Note
Some more complicated grid types require more grid variables.
The units for these variables should be consistent, but no specific system of units is required.
For example, if grid cell edge lengths are defined using kilometers, then the filter scale and dx_min
should also be defined using kilometers, and the grid cell areas should be defined in square kilometers.
Creating the Filter Object#
We create a filter object as follows.
In [11]: filter = gcm_filters.Filter(
....: filter_scale=4,
....: dx_min=1,
....: filter_shape=gcm_filters.FilterShape.TAPER,
....: grid_type=gcm_filters.GridType.REGULAR_WITH_LAND,
....: grid_vars={'wet_mask': wet_mask}
....: )
....:
In [12]: filter
Out[12]: Filter(filter_scale=4, dx_min=1, filter_shape=<FilterShape.TAPER: 2>, transition_width=3.141592653589793, ndim=2, n_steps=16, grid_type=<GridType.REGULAR_WITH_LAND: 3>)
The string representation for the filter object in the last line includes some of the parameters it was initiliazed with, to help us keep track of what we are doing. We have created a Taper filter that will filter our data by a fixed factor of 4.
Applying the Filter#
We can now apply the filter object that we created above to some data. Let’s create a random 3D cube of data that matches our grid.
In [13]: nt = 10
In [14]: data = np.random.rand(nt, ny, nx)
In [15]: da = xr.DataArray(data, dims=['time', 'y', 'x'])
In [16]: da
Out[16]:
<xarray.DataArray (time: 10, y: 128, x: 256)>
array([[[0.83110484, 0.3491875 , 0.92918796, ..., 0.91774661,
0.96213079, 0.4693372 ],
[0.44855316, 0.3124653 , 0.9326047 , ..., 0.35255017,
0.19421032, 0.09987244],
[0.59670875, 0.88909557, 0.56432176, ..., 0.81950721,
0.16700396, 0.92967403],
...,
[0.66040374, 0.34897931, 0.74514417, ..., 0.86962144,
0.47569948, 0.89310993],
[0.23618838, 0.20863431, 0.92080494, ..., 0.23561829,
0.96295823, 0.56528705],
[0.41586461, 0.84242001, 0.10938087, ..., 0.64354422,
0.53303643, 0.83238594]],
[[0.80821291, 0.04202419, 0.57182313, ..., 0.93292355,
0.31035263, 0.00902353],
[0.46803254, 0.09797105, 0.83154626, ..., 0.69018961,
0.87599014, 0.63717797],
[0.82169322, 0.11868773, 0.3788626 , ..., 0.42883835,
0.21728258, 0.49416147],
...
[0.90316899, 0.98810019, 0.28227865, ..., 0.41505676,
0.46622144, 0.66496791],
[0.13478578, 0.8156232 , 0.93848828, ..., 0.03770053,
0.74371037, 0.51097161],
[0.33928718, 0.71307678, 0.8796349 , ..., 0.47645032,
0.97802424, 0.94947377]],
[[0.78896082, 0.18477458, 0.42288626, ..., 0.40234087,
0.08712135, 0.34193425],
[0.97128305, 0.91254977, 0.86207367, ..., 0.05630938,
0.46704055, 0.9334529 ],
[0.17407435, 0.50234789, 0.8913622 , ..., 0.73901409,
0.35120258, 0.78059694],
...,
[0.73825634, 0.9589863 , 0.22523675, ..., 0.73923122,
0.62750535, 0.93254173],
[0.20306758, 0.12057897, 0.79331885, ..., 0.89805413,
0.36640731, 0.83523521],
[0.29798349, 0.43731199, 0.85113292, ..., 0.62616299,
0.7164102 , 0.99084114]]])
Dimensions without coordinates: time, y, x
We now mask our data with the wet_mask
.
In [17]: da_masked = da.where(wet_mask)
In [18]: da_masked.isel(time=0).plot()
Out[18]: <matplotlib.collections.QuadMesh at 0x7f38c4e61550>
Now that we have some data, we can apply our filter. We need to specify which dimension names to apply the filter over. In this case, it is y
, x
.
Warning
The dimension order matters! Since some filters deal with anisotropic grids, the latitude / y dimension must appear first in order to obtain the correct result. That is not an issue for this simple (isotropic) toy example but needs to be kept in mind for applications on real GCM grids.
In [19]: %time da_filtered = filter.apply(da_masked, dims=['y', 'x'])
CPU times: user 102 ms, sys: 3.84 ms, total: 106 ms
Wall time: 106 ms
In [20]: da_filtered
Out[20]:
<xarray.DataArray (time: 10, y: 128, x: 256)>
array([[[0.56537601, 0.60367645, 0.65964055, ..., 0.51596034,
0.54357238, 0.55388856],
[0.57982163, 0.63342491, 0.69169697, ..., 0.52093019,
0.53762854, 0.55179538],
[0.58844357, 0.62773505, 0.66790333, ..., 0.52777508,
0.54991672, 0.56526884],
...,
[0.60830319, 0.56517495, 0.53013774, ..., 0.5434897 ,
0.61204656, 0.63444417],
[0.58720292, 0.55665982, 0.55115705, ..., 0.54632964,
0.61010347, 0.61995924],
[0.56638774, 0.56932038, 0.60053173, ..., 0.52758747,
0.57476203, 0.58175043]],
[[0.46837602, 0.46635255, 0.47713245, ..., 0.56632523,
0.54100427, 0.49860884],
[0.48083244, 0.45958091, 0.43465216, ..., 0.54468546,
0.52706868, 0.50372338],
[0.48780251, 0.46024597, 0.41868295, ..., 0.50769611,
0.49793811, 0.49637583],
...
[0.6476656 , 0.67462463, 0.68368148, ..., 0.53659365,
0.5666439 , 0.60795681],
[0.65964469, 0.68908383, 0.69408897, ..., 0.5443188 ,
0.57436828, 0.61634647],
[0.63658818, 0.66671892, 0.66814942, ..., 0.52431638,
0.55245057, 0.59252807]],
[[0.60348712, 0.58111226, 0.5214375 , ..., 0.52558687,
0.5662207 , 0.59459849],
[0.63170271, 0.63214075, 0.58459233, ..., 0.52010165,
0.55837254, 0.59846375],
[0.63797506, 0.65324035, 0.61582411, ..., 0.52472545,
0.55583795, 0.5951088 ],
...,
[0.60115654, 0.58521811, 0.53881972, ..., 0.47984298,
0.54714259, 0.58993279],
[0.60993791, 0.57451862, 0.51132282, ..., 0.53101155,
0.58832409, 0.61672243],
[0.59583165, 0.557596 , 0.49091102, ..., 0.53974237,
0.58504946, 0.60537552]]])
Dimensions without coordinates: time, y, x
Let’s visualize what the filter did.
In [21]: da_filtered.isel(time=0).plot()
Out[21]: <matplotlib.collections.QuadMesh at 0x7f38c4dab880>
Using Dask#
Up to now, we have filtered eagerly; when we called .apply
, the results were computed immediately and stored in memory.
GCMFilters
is also designed to work seamlessly with Dask array inputs. With dask, we can filter lazily, deferring the filter computations and possibly executing them in parallel.
We can do this with our synthetic data by converting them to dask.
In [22]: da_dask = da_masked.chunk({'time': 2})
In [23]: da_dask
Out[23]:
<xarray.DataArray (time: 10, y: 128, x: 256)>
dask.array<xarray<thisarray>, shape=(10, 128, 256), dtype=float64, chunksize=(2, 128, 256), chunktype=numpy.ndarray>
Dimensions without coordinates: time, y, x
We now filter our data lazily.
In [24]: da_filtered_lazy = filter.apply(da_dask, dims=['y', 'x'])
In [25]: da_filtered_lazy
Out[25]:
<xarray.DataArray (time: 10, y: 128, x: 256)>
dask.array<transpose, shape=(10, 128, 256), dtype=float64, chunksize=(2, 128, 256), chunktype=numpy.ndarray>
Dimensions without coordinates: time, y, x
Nothing has actually been computed yet. We can trigger computation as follows:
In [26]: %time da_filtered_computed = da_filtered_lazy.compute()
CPU times: user 311 ms, sys: 20.7 ms, total: 332 ms
Wall time: 248 ms
Here we got only a very modest speedup because our example data are too small. For bigger data, the performance benefit will be more evident.