### Install Salem via Pip Source: https://github.com/fmaussion/salem/blob/master/docs/installing.md Use this command to install Salem using pip. ```bash pip install salem ``` -------------------------------- ### Install Latest Salem Master via Pip Source: https://github.com/fmaussion/salem/blob/master/docs/installing.md Install the latest development version of Salem directly from its GitHub repository using pip. ```bash pip install git+https://github.com/fmaussion/salem.git ``` -------------------------------- ### Install Salem via Conda Source: https://github.com/fmaussion/salem/blob/master/docs/installing.md Use these commands to add the conda-forge channel and install Salem using conda. ```bash conda config --add channels conda-forge conda install salem ``` -------------------------------- ### Cartopy Integration for WRF Data Visualization Source: https://context7.com/fmaussion/salem/llms.txt Integrate WRF data plotting with Cartopy axes for enhanced map visualizations. Ensure Cartopy is installed. ```python import cartopy.crs as ccrs ax = plt.axes(projection=ds.salem.cartopy()) ds['T2'].isel(time=0).plot(ax=ax, transform=ds.salem.cartopy()) ax.coastlines() plt.savefig('t2_cartopy.png', dpi=150) plt.close() ``` -------------------------------- ### Open Geotiff with Rasterio Source: https://github.com/fmaussion/salem/blob/master/docs/xarray_acc.md Salem uses rasterio to open and parse geotiff files. Ensure rasterio is installed for this functionality. ```python import salem import xarray as xa data = xa.open_dataarray("your_geotiff.tif") ``` -------------------------------- ### Sync Master Branch Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Ensure your local master branch is up-to-date with the upstream repository before starting the release process. ```bash git pull upstream master ``` -------------------------------- ### Cite Salem using Zenodo DOI Source: https://github.com/fmaussion/salem/blob/master/docs/faq.md Use the provided Zenodo DOI for citing the salem library in academic publications. An example BibTeX entry is included for convenience. ```default @software{salem, author = {Fabien Maussion and Timo Roth and Johannes Landmann and Matthias Dusch and Ray Bell and tbridel}, title = {fmaussion/salem: v0.3.4}, month = mar, year = 2021, publisher = {Zenodo}, version = {v0.3.4}, doi = {10.5281/zenodo.4635291}, url = {https://doi.org/10.5281/zenodo.4635291} } ``` -------------------------------- ### Get Colormaps Source: https://context7.com/fmaussion/salem/llms.txt Retrieves standard matplotlib colormaps by name, as well as Salem-specific colormaps like 'topo', 'dem', and 'nrwc'. Requires matplotlib. ```python import salem import matplotlib.pyplot as plt import numpy as np # Standard matplotlib colormap cmap_viridis = salem.get_cmap('viridis') # Salem's topographic colormap (blue ocean → brown mountain) cmap_topo = salem.get_cmap('topo') # Salem's DEM colormap (greens/browns) cmap_dem = salem.get_cmap('dem') ``` -------------------------------- ### Build Distribution Packages Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Clean the working directory and then build the source distribution (sdist) and wheel distribution for PyPI. ```bash git clean -xdf python setup.py bdist_wheel sdist ``` -------------------------------- ### Create and Use a Custom Grid Source: https://context7.com/fmaussion/salem/llms.txt Demonstrates defining a custom Grid with a specific projection, dimensions, resolution, and origin. Shows how to retrieve geographic coordinates and transform between lon/lat and grid indices. Includes serialization and deserialization. ```python import salem import pyproj # Define a Lambert Conformal grid centered on the Alps lcc_proj = pyproj.Proj(proj='lcc', lat_1=45, lat_2=50, lat_0=47, lon_0=10, x_0=0, y_0=0, datum='WGS84') g = salem.Grid( proj=lcc_proj, nxny=(200, 150), # 200 columns, 150 rows dxdy=(5000, 5000), # 5 km resolution x0y0=(-500000, -375000), # lower-left corner in projection coords (m) ) print(g) # # proj: +datum=WGS84 +lat_0=47 +lat_1=45 +lat_2=50 +lon_0=10 +proj=lcc +x_0=0 +y_0=0 # pixel_ref: center # origin: lower-left # (nx, ny): (200, 150) # (dx, dy): (5000, 5000) # (x0, y0): (-500000.0, -375000.0) # Get lon/lat of every grid point lon, lat = g.ll_coordinates # shape (150, 200) each # Convert a lon/lat point to grid (i, j) coordinates i, j = g.transform(10.5, 47.3, crs=salem.wgs84) print(f"Grid index: i={i:.2f}, j={j:.2f}") # Regrid to 3x finer resolution g_fine = g.regrid(factor=3) # 1667 m, 600×450 grid # Serialize / restore g.to_json('/tmp/my_grid.json') g2 = salem.Grid.from_json('/tmp/my_grid.json') assert g == g2 ``` -------------------------------- ### Retrieve Salem sample data files Source: https://context7.com/fmaussion/salem/llms.txt Downloads and returns paths to Salem's sample data files. Demonstrates immediate use in workflows and reprojection of ERA5 data onto a WRF grid. ```python import salem # List of available demo files (selection) demo_files = [ 'wrfout_d01.nc', 'era_interim_t2m_tavg.nc', 'hgt.nc', 'world_borders.shp', 'namelist.wps', 'GeoTiff_1.tif', ] for f in demo_files: path = salem.get_demo_file(f) print(f"{f}: {path}") # Use immediately in workflows ds = salem.open_wrf_dataset(salem.get_demo_file('wrfout_d01.nc')) era5 = salem.open_xr_dataset(salem.get_demo_file('era_interim_t2m_tavg.nc')) # Reproject ERA5 onto WRF grid era_on_wrf = ds.salem.transform(era5['t2m'], interp='linear') ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Execute the complete test suite, including matplotlib-based tests, to ensure the stability of the release. ```bash pytest --mpl . ``` -------------------------------- ### Upload Release to PyPI Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Use Twine to upload the built distribution packages to the Python Package Index. Ensure you have ownership permissions. ```bash twine upload dist/salem-0.X.Y* ``` -------------------------------- ### Create a Map with Data and Overlays Source: https://context7.com/fmaussion/salem/llms.txt Uses the `Map` class to create a projection-aware regional map. Data is automatically reprojected, and overlays like country borders, shapefiles, and lon/lat contours can be added. Requires matplotlib. ```python import salem import matplotlib.pyplot as plt import numpy as np # Build a map from any Salem grid ds = salem.open_xr_dataset(salem.get_demo_file('wrfout_d01.nc')) smap = salem.Map(ds.salem.grid, nx=600) # Add temperature data (automatically reprojected onto map grid) t2 = ds['T2'].isel(time=0) - 273.15 smap.set_data(t2, crs=ds.salem.grid) smap.set_cmap('RdBu_r') smap.set_plot_params(vmin=-10, vmax=25, extend='both') # Overlay country borders and topography shading # smap.set_topography(salem.get_demo_file('hgt.nc')) # optional DEM shading smap.set_shapefile(countries=True, linewidth=0.8, edgecolor='black') # Add a specific shapefile (e.g., rivers) # smap.set_shapefile('rivers.shp', color='blue', linewidth=0.5) # Add lon/lat grid lines smap.set_lonlat_contours(add_ytick=True, add_xtick=True, linewidth=0.4) # Render and save fig, ax = plt.subplots(figsize=(10, 7)) smap.visualize(ax=ax, title='2m Temperature (°C)', cbar_title='°C') plt.tight_layout() plt.savefig('wrf_t2m.png', dpi=150, bbox_inches='tight') plt.close() ``` ```python import salem import matplotlib.pyplot as plt import numpy as np # Quick one-liner from the accessor ds = salem.open_xr_dataset(salem.get_demo_file('wrfout_d01.nc')) ds['T2'].isel(time=0).salem.quick_map(cmap='hot_r', vmin=260, vmax=300) plt.savefig('quick_t2m.png') plt.close() ``` -------------------------------- ### Simulate WRF domain grids from namelist.wps Source: https://context7.com/fmaussion/salem/llms.txt Parses a WPS namelist file to obtain WRF domain grids for visualization without running WRF. Plots domain extents on a world map. ```python import salem import matplotlib.pyplot as plt # Parse a WPS namelist and get the grids for all domains grids, maps = salem.geogrid_simulator( salem.get_demo_file('namelist.wps') ) print(f"Number of domains: {len(grids)}") for i, g in enumerate(grids): print(f"Domain d{i+1:02d}: {g.nx}×{g.ny} at {g.dx/1000:.1f} km resolution") # Plot the domain extents on a world map fig, ax = plt.subplots(figsize=(10, 6)) for i, (g, smap) in enumerate(zip(grids, maps)): smap.visualize(ax=ax, title=f'WRF Domains') plt.savefig('wrf_domains.png', dpi=150) plt.close() ``` -------------------------------- ### Accessing Diagnostic Variables Source: https://github.com/fmaussion/salem/blob/master/docs/wrf.md Demonstrates accessing computed diagnostic variables like temperature in Celsius (T2C) and sea-level pressure (SLP) from a WRF dataset processed by Salem. ```python T2C = dataset["T2C"] SLP = dataset["SLP"] ``` -------------------------------- ### Tag Release Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Create an annotated tag for the release with a specific version number and a corresponding message. ```bash git tag -a v0.X.Y -m 'v0.X.Y' ``` -------------------------------- ### Parse WPS Namelist for Geogrid Simulation Source: https://github.com/fmaussion/salem/blob/master/docs/wrf.md Parses the WPS namelist.wps file to generate grids and maps for WRF domain definition using salem.geogrid_simulator(). ```python sim = salem.geogrid_simulator(x=np.arange(0, 100000, 5000), y=np.arange(0, 100000, 5000)) sim.to_netcdf("geogrid_sim.nc") ``` -------------------------------- ### Open Multiple WRF Files Source: https://github.com/fmaussion/salem/blob/master/docs/wrf.md Opens multiple WRF files from different time steps using salem.open_mf_wrf_dataset(). Note that de-accumulated variables like PRCP are not available with this method. ```python ds_multi = salem.open_mf_wrf_dataset(["wrfout_d01_2020-01-01_00:00:00", "wrfout_d01_2020-01-01_03:00:00"]) ``` -------------------------------- ### Apply colormap to WRF dataset map Source: https://context7.com/fmaussion/salem/llms.txt Opens a WRF dataset, extracts a map, sets data and colormap, visualizes it, and saves the plot. ```python ds = salem.open_xr_dataset(salem.get_demo_file('wrfout_d01.nc')) smap = ds['T2'].salem.get_map() smap.set_data(ds['T2'].values) smap.set_cmap(cmap_topo) fig, ax = plt.subplots() smap.visualize(ax=ax, cbar_title='K') plt.savefig('topo_cmap.png') plt.close() ``` -------------------------------- ### Open WRF File with xarray Source: https://github.com/fmaussion/salem/blob/master/docs/wrf.md Opens a WRF model output file using xarray. WRF files require special parsing due to non-standard formats and staggered variables. ```python import salem dataset = salem.open_wrf_dataset("wrfout-2020-01-01-000000.nc") ``` -------------------------------- ### Push Changes and Tags Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Push the committed changes on the master branch and all created tags to the origin repository. ```bash git push origin master git push origin --tags ``` -------------------------------- ### Transform points onto grid coordinates Source: https://github.com/fmaussion/salem/blob/master/docs/gis.md Demonstrates transforming geographic coordinates (longitude, latitude) onto the grid's internal (i, j) coordinates. ```python lon, lat = -5, 5 i, j = grid.transform(lon, lat) ``` -------------------------------- ### open_wrf_dataset Source: https://context7.com/fmaussion/salem/llms.txt Parses a WRF NetCDF output file, handling non-CF timestamps, staggered variables, coordinate renames, and injecting diagnostic variables computed on-the-fly. ```APIDOC ## open_wrf_dataset ### Description Opens and parses a WRF NetCDF output file. This function automatically handles common WRF-specific issues such as non-CF compliant timestamps, unstaggering of variables, renaming coordinates to CF-like names, and provides on-the-fly computation of diagnostic variables like T2C, SLP, and PRCP. ### Usage ```python import salem # Open a WRF output file ds = salem.open_wrf_dataset('wrfout_d01_2020-01-01_00:00:00') # Access diagnostic variables t2c = ds['T2C'] # 2m temperature in Celsius slp = ds['SLP'] # sea-level pressure prcp = ds['PRCP'] # step-wise precipitation (de-accumulated) ``` ### Parameters - **filename** (str): Path to the WRF NetCDF output file. ### Returns - **xarray.Dataset**: The parsed WRF dataset with CF-like dimensions and on-the-fly diagnostic variables. ``` -------------------------------- ### Quick Georeferenced Plotting with quick_map Source: https://context7.com/fmaussion/salem/llms.txt Use `quick_map` for instant georeferenced plots of a DataArray. Requires matplotlib for display and saving. ```python import matplotlib.pyplot as plt smap = ds['T2'].isel(time=0).salem.quick_map(cmap='RdBu_r') plt.title('WRF 2m Temperature') plt.savefig('t2_map.png', dpi=150) plt.close() ``` -------------------------------- ### DataLevels Source: https://context7.com/fmaussion/salem/llms.txt Handles color level computation, normalization, and colorbar creation. It is the base class for `Map` and can be used standalone to synchronize colorbars across multiple panels. ```APIDOC ## DataLevels ### Description Handles color level computation, normalization, and colorbar creation. It is the base class for `Map` and can also be used standalone to synchronize colorbars across multiple panels. ### Initialization `salem.DataLevels(data=None, levels=None, vmin=None, vmax=None, nlevels=10, cmap='viridis', extend='neither', **kwargs)` - **data** (numpy.ndarray, optional) - The data to compute levels from. - **levels** (list or numpy.ndarray, optional) - Explicitly defined color levels. - **vmin** (float, optional) - Minimum data value for color scaling. - **vmax** (float, optional) - Maximum data value for color scaling. - **nlevels** (int, optional) - Number of discrete levels to create if `levels` is not provided. - **cmap** (str or matplotlib.colors.Colormap, optional) - The colormap to use. - **extend** (str, optional) - Specifies how to extend the colormap ('neither', 'both', 'min', 'max'). ### Methods - **set_data(data)**: Updates the data and recomputes levels. - **to_rgb()**: Converts the data to an RGBA array. - **visualize(**kwargs)**: Renders a colorbar. ### Example ```python import salem import numpy as np import matplotlib.pyplot as plt data = np.random.randn(50, 60) # Discrete levels with extensions dl = salem.DataLevels( data=data, levels=np.arange(-3, 3.5, 0.5), # explicit levels cmap='RdBu_r', extend='both' # triangular colorbar arrows ) print(dl.vmin, dl.vmax) print(dl.extend) # Auto-levels from vmin/vmax dl2 = salem.DataLevels(data=data, vmin=-2, vmax=2, nlevels=20, cmap='viridis') print(len(dl2.levels)) # Use in a multi-panel figure with a shared colorbar fig, axes = plt.subplots(1, 3, figsize=(12, 4)) dl_shared = salem.DataLevels(vmin=-2, vmax=2, cmap='plasma') for i, ax in enumerate(axes): d = np.random.randn(20, 20) dl_shared.set_data(d) dl_shared.visualize(ax=ax, title=f'Panel {i+1}', addcbar=(i == 2)) plt.tight_layout() plt.savefig('multi_panel.png', dpi=150) plt.close() # RGB conversion for custom imshow rgb = dl.to_rgb() print(rgb.shape) # (50, 60, 4) — RGBA ``` ``` -------------------------------- ### Define Custom Projection with Pyproj Source: https://github.com/fmaussion/salem/blob/master/docs/xarray_acc.md Salem understands any projection supported by pyproj. Provide projection information as an attribute. ```python import salem import xarray as xa from pyproj import CRS data = xa.open_dataarray("your_geotiff.tif") data.attrs["crs"] = CRS.from_epsg(3857) # or data.attrs["crs"] = "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" ``` -------------------------------- ### open_xr_dataset Source: https://context7.com/fmaussion/salem/llms.txt Opens a NetCDF file (detecting lon/lat or WRF projection automatically) or a GeoTIFF directly as an xarray Dataset. Preserves dataset attributes like projection information. ```APIDOC ## open_xr_dataset ### Description Opens a NetCDF file or a GeoTIFF directly as an xarray Dataset. It automatically detects the projection (lon/lat or WRF) and preserves dataset attributes, which can be lost in standard xarray operations. ### Usage ```python import salem # Open a NetCDF file ds = salem.open_xr_dataset('era5_temperature.nc') # Open a GeoTIFF directly ds_tif = salem.open_xr_dataset('dem.tif') ``` ### Parameters - **filename** (str): Path to the NetCDF or GeoTIFF file. ### Returns - **xarray.Dataset**: The opened dataset with preserved attributes. ``` -------------------------------- ### Revert to Development Version Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md After issuing the release, revert the master branch to the development version and push the changes. ```bash git commit -a -m 'Revert to dev version' git push origin master ``` -------------------------------- ### open_xr_dataset Source: https://context7.com/fmaussion/salem/llms.txt Opens a georeferenced dataset using xarray and propagates projection information for Salem compatibility. ```APIDOC ## open_xr_dataset — Open a georeferenced dataset with Salem metadata `open_xr_dataset` is a thin wrapper around `xarray.open_dataset` that propagates the `pyproj_srs` projection attribute to all variables, enabling the `.salem` accessor to work even after xarray drops dataset-level attributes. Also handles GeoTiff files directly. ### Method ```python salem.open_xr_dataset(filepath) ``` ### Parameters - **filepath** (str) - Path to the dataset file (e.g., NetCDF, GeoTIFF). ### Request Example ```python import salem # Assuming 'my_data.nc' is a georeferenced NetCDF file dataset = salem.open_xr_dataset('my_data.nc') # Assuming 'my_geotiff.tif' is a georeferenced GeoTIFF file dataset_tif = salem.open_xr_dataset('my_geotiff.tif') ``` ### Response - **xarray.Dataset** - An xarray Dataset object with projection information preserved. ``` -------------------------------- ### Open Georeferenced Dataset with open_xr_dataset Source: https://context7.com/fmaussion/salem/llms.txt A wrapper for xarray.open_dataset that ensures the pyproj_srs projection attribute is propagated, enabling Salem's .salem accessor. Can also open GeoTIFF files directly. ```python import salem ``` -------------------------------- ### Create a Local Mercator Grid Source: https://context7.com/fmaussion/salem/llms.txt Generates a transverse Mercator `Grid` centered on a specified longitude/latitude point with a defined spatial extent. Useful for creating localized analysis or plotting domains. Allows setting grid resolution. ```python import salem # 400 km × 300 km grid centered on Innsbruck, Austria g = salem.mercator_grid( center_ll=(11.39, 47.26), # (lon, lat) extent=(400000, 300000), # (east-west m, north-south m) ny=300, # 300 rows → dx ≈ dy ≈ 1 km ) print(g) # proj: +datum=WGS84 +k=0.9996 +lat_0=0 +lon_0=11.39 +proj=tmerc ... # (nx, ny): (400, 300) (dx, dy): (1000.0, 1000.0) # Get geographic extent [left, right, bottom, top] in WGS84 ext = g.extent_in_crs(crs=salem.wgs84) print(f"lon: {ext[0]:.2f} – {ext[1]:.2f}, lat: {ext[2]:.2f} – {ext[3]:.2f}") # lon: 7.68 – 15.11, lat: 45.90 – 48.62 # Convert lon/lat corners to grid (i,j) i0, j0 = g.transform(10.0, 46.5, crs=salem.wgs84, nearest=True) i1, j1 = g.transform(13.0, 48.0, crs=salem.wgs84, nearest=True) print(f"Subset: cols {i0}–{i1}, rows {j0}–{j1}") ``` -------------------------------- ### Update Stable Branch Source: https://github.com/fmaussion/salem/blob/master/HOWTO_RELEASE.md Checkout the stable branch, rebase it on the latest master, push the updated stable branch, and switch back to master. Force pushing to 'stable' is acceptable if needed. ```bash git checkout stable git rebase master git push origin stable git checkout master ``` -------------------------------- ### Open and Parse WRF NetCDF Output with Salem Source: https://context7.com/fmaussion/salem/llms.txt Parses WRF NetCDF output, handling non-CF timestamps, staggered variables, and injecting diagnostic variables. Standard xarray operations and salem's subsetting are supported. ```python import salem ds = salem.open_wrf_dataset('wrfout_d01_2020-01-01_00:00:00') print(list(ds.dims)) t2c = ds['T2C'] slp = ds['SLP'] prcp = ds['PRCP'] t2c_daily_mean = t2c.resample(time='1D').mean() ds_alps = ds.salem.subset(corners=((5.0, 43.0), (17.0, 49.0)), crs=salem.wgs84) import xarray as xr era5 = salem.open_xr_dataset('era5_precip.nc') era5_on_wrf = ds_alps.salem.transform(era5['tp'], interp='linear') print(era5_on_wrf.shape) ``` -------------------------------- ### Open NetCDF and GeoTIFF files with Salem Source: https://context7.com/fmaussion/salem/llms.txt Opens NetCDF files, automatically detecting coordinate systems. GeoTIFFs are opened directly as xarray Datasets. Salem preserves dataset attributes like projection information, which can be lost in standard xarray operations. ```python import salem ds = salem.open_xr_dataset('era5_temperature.nc') print(ds.attrs['pyproj_srs']) print(ds['t2m'].attrs['pyproj_srs']) t_subset = ds['t2m'].isel(time=0) print(t_subset.attrs.get('pyproj_srs')) ds_tif = salem.open_xr_dataset('dem.tif') print(ds_tif) print(ds_tif.salem.grid) ``` -------------------------------- ### Manage Color Levels and Colorbars with DataLevels Source: https://context7.com/fmaussion/salem/llms.txt Handles color level computation, normalization, and colorbar creation. Useful for standalone colorbar management or synchronizing across multiple plots. Requires matplotlib. ```python import salem import numpy as np import matplotlib.pyplot as plt data = np.random.randn(50, 60) # Discrete levels with extensions dl = salem.DataLevels( data=data, levels=np.arange(-3, 3.5, 0.5), # explicit levels cmap='RdBu_r', extend='both' # triangular colorbar arrows ) print(dl.vmin, dl.vmax) # -3.0, 3.0 print(dl.extend) # 'both' ``` ```python import salem import numpy as np import matplotlib.pyplot as plt data = np.random.randn(50, 60) # Auto-levels from vmin/vmax dl2 = salem.DataLevels(data=data, vmin=-2, vmax=2, nlevels=20, cmap='viridis') print(len(dl2.levels)) # 20 ``` ```python import salem import numpy as np import matplotlib.pyplot as plt data = np.random.randn(50, 60) # Use in a multi-panel figure with a shared colorbar fig, axes = plt.subplots(1, 3, figsize=(12, 4)) dl_shared = salem.DataLevels(vmin=-2, vmax=2, cmap='plasma') for i, ax in enumerate(axes): d = np.random.randn(20, 20) dl_shared.set_data(d) dl_shared.visualize(ax=ax, title=f'Panel {i+1}', addcbar=(i == 2)) plt.tight_layout() plt.savefig('multi_panel.png', dpi=150) plt.close() ``` ```python import salem import numpy as np import matplotlib.pyplot as plt data = np.random.randn(50, 60) # Discrete levels with extensions dl = salem.DataLevels( data=data, levels=np.arange(-3, 3.5, 0.5), # explicit levels cmap='RdBu_r', extend='both' # triangular colorbar arrows ) # RGB conversion for custom imshow rgb = dl.to_rgb() print(rgb.shape) # (50, 60, 4) — RGBA ``` -------------------------------- ### Aggregate Data with Grid.lookup_transform Source: https://context7.com/fmaussion/salem/llms.txt Performs forward aggregation by collecting finer source grid points within each coarser cell and applying a specified method (e.g., np.mean, len). Can return a lookup table for reuse with different variables. ```python import salem import numpy as np # Coarse grid (10 km) import pyproj proj = pyproj.Proj('epsg:3035') coarse = salem.Grid(proj=proj, nxny=(50, 40), dxdy=(10000, 10000), x0y0=(4000000, 2000000)) # Fine grid (1 km) — same projection fine = salem.Grid(proj=proj, nxny=(500, 400), dxdy=(1000, 1000), x0y0=(4000000, 2000000)) # Random high-resolution data (e.g., land cover classification) hr_data = np.random.randint(0, 5, size=(400, 500)) # Average value in each coarse cell (works for continuous data) mean_agg = coarse.lookup_transform(hr_data, grid=fine, method=np.mean) print(mean_agg.shape) # (40, 50) print(mean_agg.mean()) # ~2.0 # Count how many fine pixels are in each coarse cell count = coarse.lookup_transform(hr_data, grid=fine, method=len) print(count[0, 0]) # 100 (10×10 fine pixels per coarse cell) # Reuse the lookup table for multiple variables (expensive to compute once) std_agg, lut = coarse.lookup_transform(hr_data, grid=fine, method=np.std, return_lut=True) hr_data2 = np.random.rand(400, 500) mean_agg2 = coarse.lookup_transform(hr_data2, grid=fine, method=np.mean, lut=lut) ``` -------------------------------- ### open_mf_wrf_dataset Source: https://context7.com/fmaussion/salem/llms.txt Concatenates multiple WRF output files into a single xarray Dataset, applying WRF-specific fixes similar to xarray.open_mfdataset. ```APIDOC ## open_mf_wrf_dataset ### Description Opens multiple WRF output files, typically covering different time slices, and concatenates them into a single xarray Dataset. This function behaves similarly to `xarray.open_mfdataset` but includes WRF-specific corrections and handling. ### Usage ```python import salem # Open a month of WRF output files ds = salem.open_mf_wrf_dataset('wrfout_d01_2020-01-*') # Vertical interpolation z_levels = [500, 1000, 2000, 3000, 5000] # metres t_zlev = ds.salem.wrf_zlevel('T', levels=z_levels) # Pressure-level interpolation p_levels = [850, 700, 500, 300] # hPa u_plev = ds.salem.wrf_plevel('U', levels=p_levels) ``` ### Parameters - **pattern** (str): A glob pattern matching the WRF output files to open. ### Returns - **xarray.Dataset**: A single dataset containing data from all matched WRF files. ``` -------------------------------- ### Load Shapefiles into GeoDataFrame Source: https://context7.com/fmaussion/salem/llms.txt Read shapefiles into a GeoDataFrame using `read_shapefile`. Bounding columns are added for efficient spatial filtering. `read_shapefile_to_grid` additionally reprojects and caches the shapefile to a Salem `Grid`. ```python import salem # Basic read gdf = salem.read_shapefile(salem.get_demo_file('world_borders.shp')) print(gdf.columns.tolist()) # ['FIPS', 'ISO2', 'ISO3', ..., 'geometry', 'min_x', 'max_x', 'min_y', 'max_y'] # Filter to European countries using the bounding columns (fast) europe = gdf[(gdf['min_x'] > -25) & (gdf['max_x'] < 45) & (gdf['min_y'] > 34) & (gdf['max_y'] < 72)] print(len(europe)) # ~50 countries ``` -------------------------------- ### Reproject Dataset with Nearest Neighbor Source: https://github.com/fmaussion/salem/blob/master/docs/xarray_acc.md Reproject a Dataset onto another grid using the nearest neighbor interpolation method (default). ```python import salem import xarray as xa data = xa.open_xr_dataset("your_data.nc") ref_grid = xa.open_dataarray("your_reference_grid.nc") # Nearest neighbor (default) data_reprojected = data.salem.transform(ref_grid) ``` -------------------------------- ### grid_from_dataset Source: https://context7.com/fmaussion/salem/llms.txt Infer a Grid from a dataset by detecting its map projection and spatial dimensions. This function is automatically called by the `.salem` accessor. ```APIDOC ## grid_from_dataset ### Description Attempts to detect the map projection and spatial dimensions of an xarray Dataset or netCDF4 Dataset and returns the corresponding `Grid`. It is called automatically by the `.salem` accessor. ### Parameters - **ds** (xarray.Dataset or netCDF4.Dataset) - The dataset to infer the grid from. ### Returns - **Grid** or **None** - The inferred `Grid` object, or `None` if the dataset cannot be understood. ### Example ```python import salem import xarray as xr import numpy as np # Lon/lat dataset (auto-detected) ds_ll = xr.Dataset( {'precip': (['lat', 'lon'], np.random.rand(73, 144))}, coords={'lat': np.linspace(-90, 90, 73), 'lon': np.linspace(-180, 180, 144)} ) grid = salem.grid_from_dataset(ds_ll) print(grid) # A dataset with a pyproj_srs attribute (Salem convention) ds_proj = xr.Dataset( {'data': (['y', 'x'], np.random.rand(50, 60))}, coords={'x': np.arange(60) * 1000.0, 'y': np.arange(50) * 1000.0}, attrs={'pyproj_srs': '+proj=lcc +lat_1=40 +lat_2=55 +lat_0=47 +lon_0=10'} ) grid2 = salem.grid_from_dataset(ds_proj) print(grid2.proj.srs) # Returns None if the dataset cannot be understood ds_bad = xr.Dataset({'data': (['a', 'b'], np.random.rand(5, 5))}) result = salem.grid_from_dataset(ds_bad) assert result is None ``` ``` -------------------------------- ### Define a Grid with Salem Source: https://github.com/fmaussion/salem/blob/master/docs/gis.md Defines a Grid object with projection, reference point, grid spacing, and number of points. The default is to define grids according to the pixel center point. ```python from salem import Grid # Default pixel center convention grid = Grid(proj='EPSG:4326', xmin=-10, xmax=10, ymin=-10, ymax=10, nx=100, ny=100) # Using pixel_ref keyword grid_ref = Grid(proj='EPSG:4326', xmin=-10, xmax=10, ymin=-10, ymax=10, nx=100, ny=100, pixel_ref='lower_left') ``` -------------------------------- ### Open Multiple WRF Files as a Time Series Source: https://context7.com/fmaussion/salem/llms.txt Concatenates multiple WRF output files into a single xarray Dataset, applying WRF-specific fixes. Supports vertical and pressure-level interpolation. ```python import salem ds = salem.open_mf_wrf_dataset('wrfout_d01_2020-01-*') print(ds.sizes) ds_single = salem.open_wrf_dataset('wrfout_d01_2020-01-01_00:00:00') prcp_rate = ds_single['RAINNC'].salem.deacc(as_rate=True) z_levels = [500, 1000, 2000, 3000, 5000] t_zlev = ds.salem.wrf_zlevel('T', levels=z_levels) print(t_zlev.dims) p_levels = [850, 700, 500, 300] u_plev = ds.salem.wrf_plevel('U', levels=p_levels) print(u_plev['p'].attrs) ``` -------------------------------- ### Read Shapefile with Caching Source: https://context7.com/fmaussion/salem/llms.txt Reads a shapefile and caches the result for faster subsequent access. Ensure the shapefile path is correct. ```python import salem # Read and cache shapefile gdf_cached = salem.read_shapefile( salem.get_demo_file('world_borders.shp'), cached=True ) ``` -------------------------------- ### Reproject Dataset with Spline Interpolation Source: https://github.com/fmaussion/salem/blob/master/docs/xarray_acc.md Reproject a Dataset onto another grid using spline interpolation. ```python import salem import xarray as xa data = xa.open_xr_dataset("your_data.nc") ref_grid = xa.open_dataarray("your_reference_grid.nc") # Spline interpolation data_reprojected = data.salem.transform(ref_grid, method="spline") ``` -------------------------------- ### Reproject data using interpolation Source: https://github.com/fmaussion/salem/blob/master/docs/gis.md Reprojects a gridded dataset to a new grid using the `transform` method. This is recommended for similar or finer resolution output grids. Supports 'nearest', 'linear', and 'spline' interpolation. ```python new_grid = Grid(proj='EPSG:3857', xmin=0, xmax=1000000, ymin=0, ymax=1000000, nx=500, ny=500) reprojected_data = data.salem.transform(new_grid, method='linear') ``` -------------------------------- ### Vertical Interpolation of WRF Data to Altitude Levels Source: https://context7.com/fmaussion/salem/llms.txt Interpolate 3D WRF variables from native eta levels to specified altitude levels (meters above sea level) using `wrf_zlevel`. Default levels are used if none are specified. ```python import salem import numpy as np ds = salem.open_wrf_dataset(salem.get_demo_file('wrfout_d01.nc')) # Interpolate wind speed to specific altitude levels (m asl) z_levels = np.array([500, 1000, 2000, 3000, 5000, 8000]) u_z = ds.salem.wrf_zlevel('U', levels=z_levels) print(u_z.dims) # ('time', 'z', 'south_north', 'west_east') print(u_z['z'].attrs) # {'description': 'height above sea level', 'units': 'm'} # Default levels are used when not specified v_z = ds.salem.wrf_zlevel('V') # uses 16 default levels from 10 m to 10000 m ``` -------------------------------- ### Reproject Dataset with Linear Interpolation Source: https://github.com/fmaussion/salem/blob/master/docs/xarray_acc.md Reproject a Dataset onto another grid using linear interpolation. ```python import salem import xarray as xa data = xa.open_xr_dataset("your_data.nc") ref_grid = xa.open_dataarray("your_reference_grid.nc") # Linear interpolation data_reprojected = data.salem.transform(ref_grid, method="linear") ``` -------------------------------- ### read_shapefile / read_shapefile_to_grid Source: https://context7.com/fmaussion/salem/llms.txt Loads shapefiles into GeoDataFrames, with an option to reproject and cache them to a Salem Grid. ```APIDOC ## read_shapefile / read_shapefile_to_grid — Load shapefiles with optional caching `read_shapefile` reads a shapefile into a GeoDataFrame and adds `[min_x, max_x, min_y, max_y]` bounding columns for fast spatial filtering. `read_shapefile_to_grid` additionally reprojects the shapefile into a Salem `Grid`'s coordinate system and caches the result. ### Method Signature `salem.read_shapefile(shapefile_path)` `salem.read_shapefile_to_grid(shapefile_path, grid)` ### Parameters - **shapefile_path** (str) - Path to the shapefile. - **grid** (salem.Grid, optional) - The Salem Grid to reproject the shapefile to. Required for `read_shapefile_to_grid`. ### Request Example ```python import salem # Basic read gdf = salem.read_shapefile(salem.get_demo_file('world_borders.shp')) # Filter to European countries using the bounding columns (fast) europe = gdf[(gdf['min_x'] > -25) & (gdf['max_x'] < 45) & (gdf['min_y'] > 34) & (gdf['max_y'] < 72)] ``` ### Response - **read_shapefile**: A GeoPandas GeoDataFrame with added bounding box columns (`min_x`, `max_x`, `min_y`, `max_y`). - **read_shapefile_to_grid**: A GeoPandas GeoDataFrame reprojected to the specified grid's coordinate system. ``` -------------------------------- ### DatasetAccessor.wrf_zlevel / wrf_plevel Source: https://context7.com/fmaussion/salem/llms.txt Interpolates 3D WRF variables from native eta levels to specified altitude or pressure levels. ```APIDOC ## DatasetAccessor.wrf_zlevel / wrf_plevel — Vertical interpolation of WRF data `wrf_zlevel` and `wrf_plevel` interpolate 3D WRF variables from native eta levels to altitude (metres above sea level) or pressure (hPa) levels, respectively. ### Method Signature `ds.salem.wrf_zlevel(variable_name, levels=None, fill_value='extrapolate')` `ds.salem.wrf_plevel(variable_name, levels=None, fill_value='extrapolate')` ### Parameters - **variable_name** (str) - The name of the 3D WRF variable to interpolate. - **levels** (array_like, optional) - The target altitude (m asl) or pressure (hPa) levels. If None, default levels are used. - **fill_value** (str or float, optional) - Value to use for levels outside the data range. Defaults to 'extrapolate'. ### Request Example ```python import salem import numpy as np ds = salem.open_wrf_dataset(salem.get_demo_file('wrfout_d01.nc')) # Interpolate wind speed to specific altitude levels (m asl) z_levels = np.array([500, 1000, 2000, 3000, 5000, 8000]) u_z = ds.salem.wrf_zlevel('U', levels=z_levels) # Interpolate temperature to pressure levels (hPa) p_levels = np.array([1000, 925, 850, 700, 500, 300, 200]) t_p = ds.salem.wrf_plevel('T', levels=p_levels) # Use fill_value='extrapolate' for below-ground levels t_p_extrap = ds.salem.wrf_plevel('T', levels=[1013, 1000, 925], fill_value='extrapolate') ``` ### Response A new xarray DataArray with the interpolated data and a new vertical dimension ('z' for altitude, 'p' for pressure). ```