### Install GCM-Filters from Source (GitHub) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/installation.rst Installs GCM-Filters by cloning the source repository from GitHub and running the setup script. This method allows for local development and testing. ```shell git clone https://github.com/ocean-eddy-cpt/gcm-filters.git cd gcm-filters python setup.py install ``` -------------------------------- ### Set up Environment for GCM-Filters Notebooks (Conda) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/installation.rst Creates and activates a conda environment specifically for running the example notebooks and documentation of GCM-Filters. This ensures all necessary dependencies are met. ```shell conda env create -f docs/environment.yml conda activate gcm-filters-docs-and-notebooks ``` -------------------------------- ### Setup Conda Environment Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/how_to_contribute.rst Creates and activates a conda environment for development. This environment is essential for installing project dependencies and ensuring a consistent development setup. ```bash conda env create -f ci/environment.yml conda activate gcm-filters-env ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/how_to_contribute.rst Sets up the documentation build environment, activates it, navigates to the docs directory, and builds the HTML documentation locally. The built documentation can then be viewed in a web browser. ```bash conda env create -f ci/environment_docs.yml conda activate gcm-filters-docs cd docs make html open _build/index.html ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/how_to_contribute.rst Installs pre-commit hooks for automated code linting and formatting, and then runs all configured linters on the entire project to ensure code quality and consistency. ```bash pre-commit install pre-commit run --all-files ``` -------------------------------- ### Install GCM-Filters using Pip from PyPI Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/installation.rst Installs the latest release of the GCM-Filters package from the Python Package Index (PyPI) using pip. This is a standard installation method for Python packages. ```shell pip install gcm_filters ``` -------------------------------- ### Install GCM-Filters using Pip from GitHub Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/installation.rst Installs the latest development version of GCM-Filters directly from its GitHub repository using pip. This is useful for users who want to access the newest features or contribute to the project. ```shell pip install git+https://github.com/ocean-eddy-cpt/gcm-filters.git ``` -------------------------------- ### Install GCM-Filters using Conda Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/installation.rst Installs the GCM-Filters package from the conda-forge channel. This is a recommended method for users who prefer using the conda package manager. ```shell conda install -c conda-forge gcm_filters ``` -------------------------------- ### Install Package in Editable Mode Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/how_to_contribute.rst Installs the current project package in editable mode. This allows for changes in the source code to be reflected immediately without reinstallation, facilitating development. ```bash pip install -e . ``` -------------------------------- ### Run Test Suite Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/how_to_contribute.rst Executes the project's test suite using pytest. This command is used to verify the correctness of the code and ensure that new changes have not introduced regressions. ```bash pytest ``` -------------------------------- ### Create a gcm-filters Filter Object Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/basic_filtering.rst This example shows how to instantiate a 'gcm_filters.Filter' object. It specifies parameters like filter_scale, dx_min, filter_shape, grid_type, and provides the necessary grid_vars, such as 'wet_mask', for initialization. ```python import gcm_filters import numpy as np import xarray as xr # Assuming wet_mask is defined as in the previous example ny, nx = (128, 256) mask_data = np.ones((ny, nx)) mask_data[(ny // 4):(3 * ny // 4), (nx // 4):(3 * nx // 4)] = 0 wet_mask = xr.DataArray(mask_data, dims=['y', 'x']) 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} ) print(filter) ``` -------------------------------- ### Configure gcm-filters for Regular Grid with Land Area Weighting Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Initializes the gcm-filters library by specifying the required grid variables for a REGULAR_WITH_LAND_AREA_WEIGHTED grid type. This function call sets up the library to correctly handle data on such grids, ensuring accurate filtering results. ```python # -- call gcm-filters and select desired grid type -- gcm_filters.required_grid_vars(gcm_filters.GridType.REGULAR_WITH_LAND_AREA_WEIGHTED) ``` -------------------------------- ### Define Filter Specifications - Python Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Defines the specifications for a filter, including the filter scale in meters, the filter shape (e.g., GAUSSIAN), and a minimum grid spacing. This is a common setup step before creating a filter object. ```python specs = { 'filter_scale': 200000, 'filter_shape': gcm_filters.FilterShape.GAUSSIAN, 'dx_min': dx_min_POP } ``` -------------------------------- ### Initialize gcm-filters with Gaussian and Taper Kernels Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Sets up gcm-filters objects for both Gaussian and Taper filter shapes. It specifies the filter scale, minimum grid distance, grid type, and necessary grid variables (area and wet mask). This prepares the filters for applying to the velocity data. ```python # -- choose a filtering scale -- filter_scale = 3 dx_min = 1 # -- initialze filter object for two filter types -- specs = { 'filter_scale': filter_scale, 'dx_min': dx_min, 'grid_type': gcm_filters.GridType.REGULAR_WITH_LAND_AREA_WEIGHTED, 'grid_vars': {'area': dA, 'wet_mask': wetMask} } # GAUSSIAN filter_simple_fixed_factor_G = gcm_filters.Filter(filter_shape=gcm_filters.FilterShape.GAUSSIAN, **specs) # TAPER filter_simple_fixed_factor_T = gcm_filters.Filter(filter_shape=gcm_filters.FilterShape.TAPER, **specs) ``` -------------------------------- ### Import Libraries for gcm-filters and Data Analysis Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Imports necessary Python libraries for numerical operations, data handling with xarray, plotting with matplotlib and cartopy, and the gcm_filters library for spatial filtering. These libraries are essential for the subsequent steps of data loading, processing, and visualization. ```python import numpy as np import xarray as xr import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import cartopy.crs as ccrs import gcm_filters ``` -------------------------------- ### Get Required Grid Variables for IRREGULAR_WITH_LAND (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Retrieves the list of necessary grid variables required by the gcm-filters library when using the `IRREGULAR_WITH_LAND` grid type. These variables are essential for the Laplacian calculation. ```python import gcm_filters gcm_filters.required_grid_vars(gcm_filters.GridType.IRREGULAR_WITH_LAND) ``` -------------------------------- ### Initialize Fixed Factor Filter Object Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Initializes a gcm_filters.Filter object configured for a fixed factor (10) Gaussian filter on a VECTOR_C_GRID. It utilizes pre-calculated viscosity coefficients (kappa_iso, kappa_aniso) and grid variables to define the filter's behavior. This setup is crucial for applying anisotropic viscosity filtering. ```python filter_fac10 = gcm_filters.Filter( filter_scale=filter_scale, dx_min=dx_min, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.VECTOR_C_GRID, grid_vars={'wet_mask_t': wet_mask_t, 'wet_mask_q': wet_mask_q, 'dxT': dxT, 'dyT': dyT, 'dxCu': dxCu, 'dyCu': dyCu, 'area_u': area_u, 'dxCv': dxCv, 'dyCv': dyCv, 'area_v': area_v, 'dxBu': dxBu, 'dyBu': dyBu, 'kappa_iso': kappa_iso, 'kappa_aniso': kappa_aniso } ) filter_fac10 ``` -------------------------------- ### Get Required Grid Variables for Simple Fixed Factor Filter (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Retrieves the necessary grid variables ('area', 'wet_mask') required for simple fixed factor filtering using the REGULAR_WITH_LAND_AREA_WEIGHTED grid type. These variables are essential for accurate filtering. ```python gcm_filters.required_grid_vars(gcm_filters.GridType.REGULAR_WITH_LAND_AREA_WEIGHTED) ``` -------------------------------- ### Load OSCAR Surface Velocity Data Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Loads a daily snapshot of OSCAR surface velocities (u and v components) from a NASA PODAAC OpenDAP server. It then computes the Kernel Energy (KE) as 0.5*(u^2 + v^2). Ensure the provided URL is accessible. ```python # pull from NASA PODAAC # one day of OSCAR surface velocities (1/3 degree) filename = 'https://podaac-opendap.jpl.nasa.gov/opendap/allData/oscar/preview/L4/oscar_third_deg/oscar_vel10030.nc.gz' ds = xr.open_dataset(filename) KE = 0.5*(ds['u']**2 + ds['v']**2) ``` -------------------------------- ### Comparing GCM Filter Results using Plotting Function (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb This script prepares and plots different GCM filtered datasets (unfiltered, regular, and tripolar) side-by-side using the `plot_map` function. It demonstrates the differences, particularly the 'Difference' plot, highlighting the impact of tripolar exchanges on the model grid boundaries. Requires pre-defined datasets (zeta, zeta_filtered_regular_with_land, zeta_filtered_tripolar_regular_with_land) and a figure/grid setup. ```python zeta_reg = zeta_filtered_regular_with_land.assign_coords({'geolat_c': ds2['geolat_c'], 'geolon_c': ds2['geolon_c']}) zeta_tripole = zeta_filtered_tripolar_regular_with_land.assign_coords({'geolat_c': ds2['geolat_c'], 'geolon_c': ds2['geolon_c']}) zeta = ds2['zeta'].assign_coords({'geolat_c': ds2['geolat_c'], 'geolon_c': ds2['geolon_c']}) grid1 = plt.GridSpec(1, 4, wspace=0.1, hspace=0.1) fig = plt.figure(figsize=[25,6]) max_z = 0.4e-5 subplot_kws=dict(projection=ccrs.NorthPolarStereo(central_longitude=-30.0),facecolor='grey') ax = fig.add_subplot(grid1[0, 0], projection=ccrs.NorthPolarStereo(central_longitude=-30.0),facecolor='grey') _ = plot_map(ax, zeta, vmin=-max_z, vmax=max_z, lon='geolon_c', lat='geolat_c', cmap='RdBu_r', title=r'Unfiltered Vorticity') ax = fig.add_subplot(grid1[0, 1], projection=ccrs.NorthPolarStereo(central_longitude=-30.0),facecolor='grey') _ = plot_map(ax, zeta_reg, vmin=-max_z, vmax=max_z, lon='geolon_c', lat='geolat_c', cmap='RdBu_r', title=r'REGULAR_WITH_LAND_AREA_WEIGHTED') ax = fig.add_subplot(grid1[0, 2], projection=ccrs.NorthPolarStereo(central_longitude=-30.0),facecolor='grey') _ = plot_map(ax, zeta_tripole, vmin=-max_z, vmax=max_z, lon='geolon_c', lat='geolat_c', cmap='RdBu_r', title=r'TRIPOLAR_REGULAR_WITH_LAND_AREA_WEIGHTED') ax = fig.add_subplot(grid1[0, 3], projection=ccrs.NorthPolarStereo(central_longitude=-30.0),facecolor='grey') _ = plot_map(ax, zeta_tripole - zeta_reg, vmin=-max_z*0.1, vmax=max_z*0.1, lon='geolon_c', lat='geolat_c', cmap='RdBu_r', title=r'Difference') ``` -------------------------------- ### Visualize Filter Shape and Approximation Source: https://context7.com/ocean-eddy-cpt/gcm-filters/llms.txt This example demonstrates how to visualize the transfer function of a filter, comparing the target shape (e.g., Gaussian) with its discrete approximation on a grid. It involves creating a `gcm_filters.Filter` object and then using its `plot_shape` method with Matplotlib to generate a plot. This is useful for understanding how the filter behaves across different spatial scales and validating its implementation. ```python import gcm_filters import matplotlib.pyplot as plt # Create filter filter = gcm_filters.Filter( filter_scale=100000, dx_min=5000.0, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.REGULAR ) # Plot target filter shape vs approximation fig, ax = plt.subplots(figsize=(10, 6)) filter.plot_shape(ax=ax) plt.title('Filter Transfer Function') plt.show() ``` -------------------------------- ### Define Colormap Limits for Kinetic Energy Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Sets the colormap limits for visualizing kinetic energy data. 'ke_lims' defines the minimum and maximum values for the color scale, and 'ke_cmap' specifies the colormap to be used ('magma' in this case). These parameters are used in plotting functions to ensure consistent visualization. ```python ke_lims = [0.0001, 10] # colormap limits (m^2 s^(-1)) ke_cmap = 'magma' # colormap ``` -------------------------------- ### Apply Filters and Compute Filtered Variables Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Applies the initialized Gaussian and Taper filters to the zonal (u) and meridional (v) velocities, as well as the Kernel Energy (KE). It then calculates the filtered KE and Mean Kinetic Energy (MKE) for both filter types, and finally computes the Eddy Kinetic Energy (EKE) by subtracting MKE from filtered KE. ```python # -- filter velocities, filter KE, and define EKE (for both Gaussian and Taper kernels) -- u_filtered_simple_fixed_factor = filter_simple_fixed_factor_G.apply(ds['u'], dims=['latitude', 'longitude']) v_filtered_simple_fixed_factor = filter_simple_fixed_factor_G.apply(ds['v'], dims=['latitude', 'longitude']) MKE = 0.5*(u_filtered_simple_fixed_factor**2 + v_filtered_simple_fixed_factor**2).squeeze() KE_filtered_simple_fixed_factor = filter_simple_fixed_factor_G.apply(KE, dims=['latitude', 'longitude']) u_filtered_simple_fixed_factor_T = filter_simple_fixed_factor_T.apply(ds['u'], dims=['latitude', 'longitude']) v_filtered_simple_fixed_factor_T = filter_simple_fixed_factor_T.apply(ds['v'], dims=['latitude', 'longitude']) MKE_T = 0.5*(u_filtered_simple_fixed_factor_T**2 + v_filtered_simple_fixed_factor_T**2).squeeze() KE_filtered_simple_fixed_factor_T = filter_simple_fixed_factor_T.apply(KE, dims=['latitude', 'longitude']) EKE_G = KE_filtered_simple_fixed_factor.squeeze() - MKE EKE_T = KE_filtered_simple_fixed_factor_T.squeeze() - MKE_T ``` -------------------------------- ### Create Wet Mask Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Generates a wet mask based on the Kernel Energy (KE) data. It assigns a value of 1 to grid cells that contain data (water) and 0 to cells with NaN values (land). This mask is used by gcm-filters to exclude land areas from filtering operations. ```python # -- wet mask -- # -- land = 0, water = 1 -- wetMask = xr.where(np.isnan(KE), 0, 1) ``` -------------------------------- ### Apply Tripolar Grid Filter for Global Ocean Models Source: https://context7.com/ocean-eddy-cpt/gcm-filters/llms.txt This snippet demonstrates filtering data on a tripolar grid, common in global ocean models like POP. It involves loading model output and grid data, then creating a filter with specific parameters for a tripolar grid, including land masks and varying grid spacing. The example shows filtering sea surface temperature (SST) with a Gaussian filter shape. Required grid variables like `HUS`, `HTE`, `HTN`, `HUW`, and `TAREA` are provided. ```python import gcm_filters import xarray as xr # Load POP model output with tripolar grid ds = xr.open_dataset('pop_ocean_output.nc') grid = xr.open_dataset('pop_grid.nc') # Create filter for tripolar grid with northern boundary condition filter_scale = 150000 # 150 km dx_min = float(grid.HTN.min()) # minimum grid spacing filter_tripolar = gcm_filters.Filter( filter_scale=filter_scale, dx_min=dx_min, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.TRIPOLAR_POP_WITH_LAND, grid_vars={ 'wet_mask': xr.where(grid.KMT > 0, 1, 0), 'dxe': grid.HUS, # x-spacing at eastern edge 'dye': grid.HTE, # y-spacing at eastern edge 'dxn': grid.HTN, # x-spacing at northern edge 'dyn': grid.HUW, # y-spacing at northern edge 'tarea': grid.TAREA } ) # Filter sea surface temperature области_filtered = filter_tripolar.apply(ds.SST, dims=['nlat', 'nlon']) ``` -------------------------------- ### Load MOM6 data catalog with Intake (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb This snippet demonstrates how to use the Intake library to open a catalog of MOM6 data. It then lists the available datasets within the catalog. This is a prerequisite for loading any MOM6 data for analysis. ```python from intake import open_catalog cat = open_catalog('https://raw.githubusercontent.com/ocean-eddy-cpt/cpt-data/master/catalog.yaml') list(cat) ``` -------------------------------- ### Download and Open Dataset with Pooch Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/gpu.ipynb Uses the pooch library to download a NetCDF dataset from a specified URL and known hash, then opens it using xarray. ```python import pooch fname = pooch.retrieve( url="doi:10.6084/m9.figshare.14607684.v1/POP_SST.nc", known_hash="md5:0023da8e42dcd2141805e553a023078c", ) ds = xr.open_dataset(fname) ds ``` -------------------------------- ### Load NeverWorld2 Static Grid Information with Dask Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb This Python snippet loads the static grid information for the NeverWorld2 simulation, specifically the 'neverworld_quarter_degree_static' dataset, using Dask. This dataset is crucial for understanding the spatial context and grid properties of the simulation data. ```python ds_static = cat['neverworld_quarter_degree_static'].to_dask() ds_static ``` -------------------------------- ### Get Required Grid Variables for REGULAR_WITH_LAND Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/basic_filtering.rst This function retrieves the list of grid variables required for the 'REGULAR_WITH_LAND' grid type. These variables are necessary inputs for filter operations on this specific grid. ```python import gcm_filters gcm_filters.required_grid_vars(gcm_filters.GridType.REGULAR_WITH_LAND) ``` -------------------------------- ### Load NeverWorld2 5-Day Averages Dataset with Dask Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb This Python code loads the 'neverworld_quarter_degree_averages' dataset, representing 5-day averages from the NeverWorld2 simulation, into a Dask-backed xarray Dataset. This allows for efficient handling of large datasets. ```python ds = cat['neverworld_quarter_degree_averages'].to_dask() ds ``` -------------------------------- ### Compare Simple Fixed Factor Filter Results (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Generates a plot comparing the results of the simple fixed factor filter with a more complex fixed factor filter, and visualizes the difference between them. This helps in assessing the impact of the filter's simplicity. ```python fig,axs = plt.subplots(1,3,figsize=(25,8)) KE_filtered_fixed_factor.isel(time=time, zl=layer).plot( ax=axs[0], cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) aio_axs[0].set(title='filtered with fixed factor') KE_filtered_simple_fixed_factor.isel(time=time, zl=layer).plot( ax=axs[1], cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) aio_axs[1].set(title='filtered with fixed factor (simple)', ylabel='') (KE_filtered_fixed_factor - KE_filtered_simple_fixed_factor).isel(time=time, zl=layer).plot( ax=axs[2], cbar_kwargs={'label': 'm2 s-2'} ) aio_axs[2].set(title='difference', ylabel=''); ``` -------------------------------- ### Prepare Grid Input Variables for Filtering (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Prepares essential grid variables (`wet_mask`, `area`, `dxw`, `dyw`, `dxs`, `dys`) from the static dataset for use with the gcm-filters library. It handles dimension renaming and padding removal to match the library's requirements. ```python import xarray as xr # Assuming ds_static and ds are pre-defined DataArrays/Datasets wet_mask = ds_static.wet area = ds_static.area_t dxw = xr.DataArray( data=ds_static.dxCu.isel(xq=slice(0,-1)), coords={'yh':ds.yh,'xh':ds.xh}, dims=('yh','xh') ) dyw = xr.DataArray( data=ds_static.dyCu.isel(xq=slice(0,-1)), coords={'yh':ds.yh,'xh':ds.xh}, dims=('yh','xh') ) dxs = xr.DataArray( data=ds_static.dxCv.isel(yq=slice(0,-1)), coords={'yh':ds.yh,'xh':ds.xh}, dims=('yh','xh') ) dys = xr.DataArray( data=ds_static.dyCv.isel(yq=slice(0,-1)), coords={'yh':ds.yh,'xh':ds.xh}, dims=('yh','xh') ) ``` -------------------------------- ### Compute and Visualize Grid Cell Area Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb Calculates the area of each grid cell in square meters, considering the latitude-dependent width due to the cosine of latitude. It then creates an xarray.DataArray for the area and visualizes it using a Cartopy projection. This is a required variable for gcm-filters with area weighting. ```python # -- compute cell area -- # -- for each lat/lon grid box gcm-filters needs area in same format as du,dv dy0 = 1852*60*np.abs(ds['latitude'][2].data - ds['latitude'][1].data) # ** note: dy0 is a constant over the globe ** dx0 = 1852*60*np.cos(np.deg2rad(ds['latitude'].data))*(ds['longitude'][2].data - ds['longitude'][1].data) area = dy0*np.tile(dx0, (len(ds['longitude'].data),1)) area = np.transpose(area) dA = xr.DataArray( data=area, dims=["latitude", "longitude"], coords=dict( longitude=(["longitude"], ds['longitude'].data), latitude=(["latitude"], ds['latitude'].data),), ) ­area_cmap = 'viridis' # colormap f,ax = plt.subplots(1,1,figsize=(6,4),subplot_kw={'projection':ccrs.PlateCarree()}) dA.plot(ax=ax, cmap=area_cmap) ax.set_title('Grid Cell Area [m$^2$]') ax.coastlines() gl = ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False plt.show() ``` -------------------------------- ### Initialize Simple Fixed Factor Filter Parameters (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Sets the filter scale and minimum grid spacing for the simple fixed factor filter. These parameters influence the smoothing effect and resolution of the filtered output. ```python filter_scale = 10 dx_min = 1 ``` -------------------------------- ### Visualize Viscosity Components Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Generates a 3-panel plot visualizing the isotropic viscosity (kappa_iso), anisotropic viscosity (kappa_aniso), and their sum. It uses Cartopy for geographical projection and Matplotlib for plotting, showing how viscosity varies across the domain. Requires matplotlib, cartopy, and the viscosity variables. ```python %%time fig,axs = plt.subplots(1,3,figsize=(25,5),subplot_kw={'projection':ccrs.Orthographic(central_lon, central_lat)}) kappa_iso.plot( ax=axs[0], x='geolon', y='geolat', cmap='YlOrRd', cbar_kwargs={'label': ''}, transform=ccrs.PlateCarree() ) kappa_aniso.plot( ax=axs[1], x='geolon', y='geolat', cmap='RdYlBu_r', cbar_kwargs={'label': ''}, transform=ccrs.PlateCarree() ) (kappa_iso + kappa_aniso).plot( ax=axs[2], x='geolon', y='geolat', cmap='YlOrRd', cbar_kwargs={'label': ''}, transform=ccrs.PlateCarree() ) axs[0].set(title='kappa_iso') axs[1].set(title='kappa_aniso') axs[2].set(title='kappa_iso + kappa_aniso') for ax in axs.flatten(): ax.coastlines() ax.set_extent([-90, 0, 0, 50], crs=ccrs.PlateCarree()) gl = ax.gridlines(draw_labels=True) gl.xlocator = mticker.FixedLocator([-80,-60,-40,-20]) gl.ylocator = mticker.FixedLocator([0,20,40,60]) gl.top_labels = False gl.right_labels = False ``` -------------------------------- ### Create Simple Fixed Factor Filter Instance (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Instantiates a simple fixed factor filter object with specified parameters including filter scale, grid type, and required grid variables. The Gaussian filter shape is used. ```python filter_simple_fixed_factor = gcm_filters.Filter( filter_scale=filter_scale, dx_min=dx_min, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.REGULAR_WITH_LAND_AREA_WEIGHTED, grid_vars={'area': area, 'wet_mask': wet_mask} ) ``` -------------------------------- ### Set Uniform Kappa for Spatial Filtering (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Initializes `kappa_w` and `kappa_s` arrays with ones, matching the dimensions of `dxw`. This is done to ensure a spatially uniform filter scale, as intended when the filter scale is not meant to vary across the domain. ```python import xarray as xr # Assuming dxw is a pre-defined DataArray kappa_w = xr.ones_like(dxw) kappa_s = xr.ones_like(dxw) ``` -------------------------------- ### List Grid Types in gcm_filters.GridType Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/basic_filtering.rst Demonstrates how to import the gcm_filters library and list all available GridType enumerations. This is useful for understanding the supported grid configurations. ```python import gcm_filters list(gcm_filters.GridType) ``` -------------------------------- ### Download and Inspect MOM6 Data Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Downloads a NetCDF file containing 0.1-degree MOM6 surface velocity data using the 'pooch' library and opens it as an xarray Dataset. This data is used for subsequent filtering operations. ```python import pooch fname = pooch.retrieve( url="doi:10.6084/m9.figshare.14718462.v1/MOM6_surf_vels.0.1degree.nc", known_hash="md5:99a05ca83f9560fda85ca509a66aafd7", ) ds = xr.open_dataset(fname) ds ``` -------------------------------- ### Load MOM6 dataset and display its structure (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb This code snippet loads a specific MOM6 dataset ('neverworld_quarter_degree_averages') into an xarray Dataset using Dask for potential parallel processing. It then displays the structure of the loaded dataset, including dimensions, coordinates, and data variables. This helps in understanding the data's format and symmetry. ```python ds = cat['neverworld_quarter_degree_averages'].to_dask() ds_static = cat['neverworld_quarter_degree_static'].to_dask() ds ``` -------------------------------- ### Apply Taper Filter for Scale Separation Source: https://context7.com/ocean-eddy-cpt/gcm-filters/llms.txt This example shows how to use a TAPER filter to separate large and small-scale components of a dataset, such as vorticity. It requires loading data and defining the filter scale and transition width. The function `filter.apply` is used to extract the large-scale component, and the small-scale residual is calculated by subtraction. This is useful for analyzing different spatial scales within geophysical data. ```python import gcm_filters import xarray as xr # Load data ds = xr.open_dataset('data.nc') # Create Taper filter to separate scales # Scales < 100 km removed, scales > ~157 km (π/2 * 100) preserved filter_scale = 100000 # 100 km cutoff transition_width = 2.0 # transition region width (default is π) filter_taper = gcm_filters.Filter( filter_scale=filter_scale, dx_min=5000.0, filter_shape=gcm_filters.FilterShape.TAPER, transition_width=transition_width, grid_type=gcm_filters.GridType.REGULAR_WITH_LAND, grid_vars={'wet_mask': ds.land_sea_mask} ) # Extract large-scale component large_scale = filter_taper.apply(ds.vorticity, dims=['y', 'x']) # Small-scale residual small_scale = ds.vorticity - large_scale ``` -------------------------------- ### Visualize Filtered Data (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/basic_filtering.rst Visualizes the first time step of the eagerly filtered data, allowing for a comparison with the original masked data. ```python da_filtered.isel(time=0).plot() ``` -------------------------------- ### Determine Required Grid Variables for Different Grid Types Source: https://context7.com/ocean-eddy-cpt/gcm-filters/llms.txt This code snippet shows how to programmatically determine the necessary grid variables required by the `gcm_filters.Filter` class for various `GridType` configurations. By calling `gcm_filters.required_grid_vars` with a specific `GridType`, users can obtain a list of variable names that need to be supplied in the `grid_vars` dictionary when initializing the filter. This helps ensure correct filter setup for different geophysical grids. ```python import gcm_filters # Check required grid variables for a specific grid type required_vars = gcm_filters.required_grid_vars( gcm_filters.GridType.IRREGULAR_WITH_LAND ) print(f"Required variables: {required_vars}") # Output: ['wet_mask', 'dxw', 'dyw', 'dxs', 'dys', 'area', 'kappa_w', 'kappa_s'] # For regular grid with area weighting required_vars = gcm_filters.required_grid_vars( gcm_filters.GridType.REGULAR_AREA_WEIGHTED ) print(f"Required variables: {required_vars}") # Output: ['area'] # For C-grid vector Laplacian required_vars = gcm_filters.required_grid_vars( gcm_filters.GridType.VECTOR_C_GRID ) print(f"Required variables: {required_vars}") # Output: ['wet_mask_t', 'wet_mask_q', 'dxT', 'dyT', 'dxCu', 'dyCu', # 'dxCv', 'dyCv', 'dxBu', 'dyBu', 'area_u', 'area_v', # 'kappa_iso', 'kappa_aniso'] ``` -------------------------------- ### Plotting Kinetic Energy Fields with Matplotlib and Cartopy Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_satellite_observations.ipynb This snippet initializes a Matplotlib figure with a Cartopy projection and plots various kinetic energy fields. It customizes titles, color maps, normalization, and axis labels. It also sets map extents and adds coastlines and gridlines to the plots. Dependencies include Matplotlib, Cartopy, and potentially a data source like xarray (implied by 'ds'). ```python f,ax = plt.subplots(2,3,figsize=(16,8),subplot_kw={'projection':ccrs.PlateCarree()}) KE.plot(ax=ax[0,0], cmap=ke_cmap, norm=LogNorm(vmin=ke_lims[0], vmax=ke_lims[1])) ax[0,0].set(title='Surface KE (' + str(np.round(np.abs(ds['latitude'][2].data - ds['latitude'][1].data),2)) + '$^{\circ} grid$') MKE.plot(ax=ax[0,1], cmap=ke_cmap, norm=LogNorm(vmin=ke_lims[0], vmax=ke_lims[1])) ax[0,1].set(title='MKE: Gaussian (fixed factor = ' + str(filter_scale) + ')') MKE_T.plot(ax=ax[0,2], cmap=ke_cmap, cbar_kwargs={'label': 'm2 s-2'}, norm=LogNorm(vmin=ke_lims[0], vmax=ke_lims[1])) ax[0,2].set(title='MKE: Taper (fixed factor = ' + str(filter_scale) + ')') EKE_G.plot(ax=ax[1,1], cmap='YlOrRd', vmin=0, vmax=0.175) ax[1,1].set(title='EKE: Gaussian (fixed factor = ' + str(filter_scale) + ')') EKE_T.plot(ax=ax[1,2], cmap='RdYlBu_r', cbar_kwargs={'label': 'm2 s-2'}, vmin=-0.175, vmax=0.175) ax[1,2].set(title='EKE: Taper (fixed factor = ' + str(filter_scale) + ')') gax = ax.flatten() for i in [0,1,2,4,5]: gax[i].coastlines() gax[i].set_extent([300, 330, 32.5, 52.5], crs=ccrs.PlateCarree()) gl = gax[i].gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False f.delaxes(ax[1,0]) plt.show() # f.savefig('ke_mke_eke.jpg', dpi=500) ``` -------------------------------- ### Prepare Grid Variables for Vector Laplacian Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Prepares and re-dimensions grid variables from the MOM6 dataset to be compatible with the vector Laplacian calculations. This involves swapping dimensions and calculating derived quantities like area weights. ```python # grid info centered at T-points wet_mask_t = ds.wet dxT = ds.dxT dyT = ds.dyT # grid info centered at U-points dxCu = ds.dxCu.swap_dims({"xq": "xh"}) dyCu = ds.dyCu.swap_dims({"xq": "xh"}) area_u = dxCu * dyCu # grid info centered at V-points dxCv = ds.dxCv.swap_dims({"yq": "yh"}) dyCv = ds.dyCv.swap_dims({"yq": "yh"}) area_v = dxCv * dyCv # grid info centered at vorticity points wet_mask_q = ds.wet_c.swap_dims({"xq": "xh", "yq": "yh"}) dxBu = ds.dxBu.swap_dims({"xq": "xh", "yq": "yh"}) dyBu = ds.dyBu.swap_dims({"xq": "xh", "yq": "yh"}) ``` -------------------------------- ### Prepare Velocity Vector Field for Filtering Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Prepares the input velocity data (SSU and SSV from the 'ds' dataset) for the viscosity filter. This involves creating a temporary xarray Dataset, assigning the velocity components, and swapping dimensions to match the expected input format for the filter's apply_to_vector method. ```python ds_tmp = xr.Dataset() # temporary dataset with swapped dimensions ds_tmp['u'] = ds['SSU'] ds_tmp['v'] = ds['SSV'] ds_tmp['u'] = ds_tmp['u'].swap_dims({'xq':'xh'}) ds_tmp['v'] = ds_tmp['v'].swap_dims({'yq':'yh'}) ``` -------------------------------- ### Identify Required Grid Variables for Vector C-Grid Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Lists the essential grid variables required by the gcm-filters library when using the 'VECTOR_C_GRID' type. These variables are necessary for accurate calculations on the C-grid. ```python gcm_filters.required_grid_vars(gcm_filters.GridType.VECTOR_C_GRID) ``` -------------------------------- ### Configure Filter Iteration Steps Source: https://context7.com/ocean-eddy-cpt/gcm-filters/llms.txt Demonstrates configuring the `gcm_filters.Filter` with custom iteration steps. It shows both the default auto-determination of `n_steps` and manual specification for performance tuning. ```python import gcm_filters # Let gcm-filters determine optimal n_steps (default behavior) filter_auto = gcm_filters.Filter( filter_scale=100000, dx_min=5000.0, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.REGULAR, n_steps=0 # auto-determine (default) ) print(f"Automatic n_steps: {filter_auto.n_steps}") # Manually specify n_steps for speed vs accuracy tradeoff filter_manual = gcm_filters.Filter( filter_scale=100000, dx_min=5000.0, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.REGULAR, n_steps=15 # fewer steps = faster but less accurate ) print(f"Manual n_steps: {filter_manual.n_steps}") ``` -------------------------------- ### Create and Visualize Sample Data (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/basic_filtering.rst Generates a random 3D NumPy array and converts it into an xarray DataArray with specified dimensions. It then optionally visualizes the first time step of the masked data. ```python nt = 10 data = np.random.rand(nt, ny, nx) da = xr.DataArray(data, dims=['time', 'y', 'x']) da da_masked = da.where(wet_mask) da_masked.isel(time=0).plot() ``` -------------------------------- ### Load Global MOM6 Data Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Loads the Global MOM6 simulation data from a remote URL using pooch and opens it as an xarray Dataset. This step is essential for accessing the simulation variables for further analysis. ```python fname = pooch.retrieve( url="doi:10.6084/m9.figshare.14575356.v1/Global_U_SSH.nc", known_hash="md5:f98b5f2d1f3ccef5685851519481b2da", ) ds = xr.open_dataset(fname) ds ``` -------------------------------- ### Apply Filters and Measure Performance Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Applies the created filters to the 'delta' dataset along specified dimensions and measures the execution time. This highlights the performance difference between filters with and without tripole boundary condition handling. ```python %time delta_filtered_regular_with_land = filter_regular_with_land.apply(delta, dims=['nlat', 'nlon']) %time delta_filtered_tripolar_regular_with_land = filter_tripolar_regular_with_land.apply(delta, dims=['nlat', 'nlon']) ``` -------------------------------- ### Initialize Spatial Filters Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Initializes two gcm_filters.Filter objects for applying spatial filtering. One uses the 'REGULAR_WITH_LAND_AREA_WEIGHTED' grid type, and the other uses 'TRIPOLAR_REGULAR_WITH_LAND_AREA_WEIGHTED'. Both are configured with a filter scale of 10, a minimum dx of 1, and a Gaussian filter shape, utilizing the previously prepared area and wet mask. ```python factor = 10 dx_min = 1 filter_shape = gcm_filters.FilterShape.GAUSSIAN filter_regular_with_land = gcm_filters.Filter( filter_scale=factor, dx_min=dx_min, filter_shape=filter_shape, grid_type=gcm_filters.GridType.REGULAR_WITH_LAND_AREA_WEIGHTED, grid_vars={'area': area, 'wet_mask': wet_mask} ) filter_regular_with_land filter_tripolar_regular_with_land = gcm_filters.Filter( filter_scale=factor, dx_min=1, filter_shape=filter_shape, grid_type=gcm_filters.GridType.TRIPOLAR_REGULAR_WITH_LAND_AREA_WEIGHTED, grid_vars={'area': area, 'wet_mask': wet_mask} ) filter_tripolar_regular_with_land ``` -------------------------------- ### Create Taper Filter with 8 Steps (Python) Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/theory.rst This snippet demonstrates how to create a Taper filter instance with a specified number of steps (8) and filter scale (4). It shows how to instantiate the Filter class from the gcm_filters library, setting filter_shape to TAPER and grid_type to REGULAR. The output is a Filter object representing the configured taper filter. ```python taper_filter_8steps = gcm_filters.Filter( filter_scale=4, dx_min=1, filter_shape=gcm_filters.FilterShape.TAPER, n_steps=8, grid_type=gcm_filters.GridType.REGULAR, ) taper_filter_8steps ``` -------------------------------- ### Define Filter Specifications Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Defines the specifications for a GCM filter, including scale, minimum grid spacing, and shape. This is a common configuration step before creating a filter instance. ```python specs = { 'filter_scale': 50, 'dx_min': 1, 'filter_shape': gcm_filters.FilterShape.GAUSSIAN } ``` -------------------------------- ### List available grid types in gcm-filters Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_tripole_grid.ipynb Retrieves and displays a list of all supported grid types within the gcm-filters library. This helps users identify the appropriate grid type for their specific dataset. ```python list(gcm_filters.GridType) ``` -------------------------------- ### Visualize Filtered Kinetic Energy Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Generates a plot comparing the unfiltered kinetic energy (KE), the KE filtered by the fixed factor, and the difference between them. This visualization helps to understand the impact of the fixed factor filter on the data. ```python fig,axs = plt.subplots(1,3,figsize=(25,8)) ds.KE.isel(time=time, zl=layer).plot( ax=axs[0], vmin=vmin, vmax=vmax, cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) diharapkan.set(title='unfiltered KE') KE_filtered_fixed_factor.isel(time=time, zl=layer).plot( ax=axs[1], vmin=vmin, vmax=vmax, cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) axs[1].set(title='KE filtered to 10 times local grid scale', ylabel='') (ds.KE - KE_filtered_fixed_factor).isel(time=time, zl=layer).plot( ax=axs[2], cmap='RdBu_r', cbar_kwargs={'label': 'm2 s-2'} ) axs[2].set(title='(unfiltered - filtered) KE', ylabel='') ``` -------------------------------- ### Visualize Unfiltered, Filtered, and Residual KE Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Generates a three-panel plot visualizing the kinetic energy (KE) data. It displays the original unfiltered KE, the KE after applying a 200km filter, and the difference between the two (residual). This visualization helps in understanding the effect of the spatial filter. ```python time = 0 layer = 0 vmin = 0 vmax = 1.2 fig,axs = plt.subplots(1,3,figsize=(25,8)) ds.KE.isel(time=time, zl=layer).plot( ax=axs[0], vmin=vmin, vmax=vmax, cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) axs[0].set(title='unfiltered KE') KE_filtered_to_200km.isel(time=time, zl=layer).plot( ax=axs[1], vmin=vmin, vmax=vmax, cmap='YlOrRd', cbar_kwargs={'label': 'm2 s-2'} ) axs[1].set(title='KE filtered to 200km', ylabel='') (ds.KE - KE_filtered_to_200km).isel(time=time, zl=layer).plot( ax=axs[2], cmap='RdBu_r', cbar_kwargs={'label': 'm2 s-2'} ) axs[2].set(title='(unfiltered - filtered) KE', ylabel=''); ``` -------------------------------- ### Create Viscosity-Based Gaussian Filter Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_vector_laplacian.ipynb Initializes a gcm_filters.Filter object for viscosity-based filtering. It uses a Gaussian filter shape, a vector C-grid type, and specifies various grid variables required for the filtering process, including wet masks, grid dimensions, areas, and the previously defined kappa coefficients. ```python filter_visc_100km = gcm_filters.Filter( filter_scale=filter_scale, dx_min=dx_min, filter_shape=gcm_filters.FilterShape.GAUSSIAN, grid_type=gcm_filters.GridType.VECTOR_C_GRID, grid_vars={ 'wet_mask_t': wet_mask_t, 'wet_mask_q': wet_mask_q, 'dxT': dxT, 'dyT': dyT, 'dxCu': dxCu, 'dyCu': area_u, 'dxCv': dxCv, 'dyCv': area_v, 'dxBu': dxBu, 'dyBu': dyBu, 'kappa_iso': kappa_iso, 'kappa_aniso': kappa_aniso } ) ``` -------------------------------- ### Plot Time-Averaged Deformation Radius Source: https://github.com/ocean-eddy-cpt/gcm-filters/blob/master/docs/examples/example_filter_types.ipynb Plots the time-averaged first baroclinic deformation radius for the NeverWorld2 domain. This visualization helps understand the spatial variation of the deformation radius. ```python ds['Rd1'].mean(dim='time').plot(figsize=(6,7), vmin=0, cmap='YlGn'); ```