pyresample.geometry module
Classes for geometry operations.
- class pyresample.geometry.AreaDefinition(area_id, description, proj_id, projection, width, height, area_extent, nprocs=1, lons=None, lats=None, dtype=<class 'numpy.float64'>)
Bases:
_ProjectionDefinitionHolds definition of an area.
- Parameters:
area_id (str) – Identifier for the area
description (str) – Human-readable description of the area
proj_id (str) – ID of projection
projection (dict or str or pyproj.crs.CRS) – Dictionary of PROJ parameters or string of PROJ or WKT parameters. Can also be a
pyproj.crs.CRSobject.width (int) – x dimension in number of pixels, aka number of grid columns
height (int) – y dimension in number of pixels, aka number of grid rows
area_extent (list) – Area extent as a list (lower_left_x, lower_left_y, upper_right_x, upper_right_y)
nprocs (int, optional) – Number of processor cores to be used for certain calculations
- area_id
Identifier for the area
- Type:
str
- description
Human-readable description of the area
- Type:
str
- proj_id
ID of projection
- Type:
str
- projection
Dictionary or string with Proj.4 parameters
- Type:
dict or str
- width
x dimension in number of pixels, aka number of grid columns
- Type:
int
- height
y dimension in number of pixels, aka number of grid rows
- Type:
int
- size
Number of points in grid
- Type:
int
- area_extent_ll
Area extent in lons lats as a tuple (lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat)
- Type:
tuple
- pixel_size_x
Pixel width in projection units
- Type:
float
- pixel_size_y
Pixel height in projection units
- Type:
float
- upper_left_extent
Coordinates (x, y) of upper left corner of upper left pixel in projection units
- Type:
tuple
- pixel_upper_left
Coordinates (x, y) of center of upper left pixel in projection units
- Type:
tuple
- pixel_offset_x
x offset between projection center and upper left corner of upper left pixel in units of pixels.
- Type:
float
- pixel_offset_y
y offset between projection center and upper left corner of upper left pixel in units of pixels..
- Type:
float
- crs
Coordinate reference system object similar to the PROJ parameters in proj_dict and proj_str. This is the preferred attribute to use when working with the pyproj library. Note, however, that this object is not thread-safe and should not be passed between threads.
- Type:
pyproj.crs.CRS
- crs_wkt
WellKnownText version of the CRS object. This is the preferred way of describing CRS information as a string.
- Type:
str
- cartesian_coords
Grid cartesian coordinates
- Type:
object
Initialize AreaDefinition.
- __init__(area_id, description, proj_id, projection, width, height, area_extent, nprocs=1, lons=None, lats=None, dtype=<class 'numpy.float64'>)
Initialize AreaDefinition.
- aggregate(**dims)
Return an aggregated version of the area.
- property area_extent
Tuple of this area’s extent (xmin, ymin, xmax, ymax).
- colrow2lonlat(cols, rows)
Return lons and lats for the given image columns and rows.
Both scalars and arrays are supported. To be used with scarse data points instead of slices (see get_lonlats).
- copy(**override_kwargs)
Make a copy of the current area.
This replaces the current values with anything in override_kwargs.
- create_areas_def()
Generate YAML formatted representation of this area.
Deprecated. Use
dump()instead.
- create_areas_def_legacy()
Create area definition in legacy format.
- crop_around(other_area)
Crop this area around other_area.
- dump(filename=None)
Generate YAML formatted representation of this area.
For the opposite (i.e. to get an AreaDefinition from a YAML-formatted representation), see
load_area_from_string().- Parameters:
filename (str or pathlib.Path or file-like object) – Yaml file location to dump the area to.
- Returns:
If file is None returns yaml str
- classmethod from_area_of_interest(area_id, projection, shape, center, resolution, units=None, **kwargs)
Create an AreaDefinition from center, resolution, and shape.
- Parameters:
area_id (str) – ID of area
projection (dict or str) – Projection parameters as a proj4_dict or proj4_string
shape (list) – Number of pixels in the y and x direction (height, width)
center (list) – Center of projection (x, y)
resolution (list or float) – Size of pixels: (dx, dy). Can be specified with one value if dx == dy
units (str, optional) –
Units that provided arguments should be interpreted as. This can be one of ‘deg’, ‘degrees’, ‘meters’, ‘metres’, and any parameter supported by the cs2cs -lu command. Units are determined in the following priority:
units expressed with each variable through a DataArray’s attrs attribute.
units passed to
unitsunits used in
projectionmeters
description (str, optional) – Description/name of area. Defaults to area_id
proj_id (str, optional) – ID of projection
nprocs (int, optional) – Number of processor cores to be used
lons (numpy array, optional) – Grid lons
lats (numpy array, optional) – Grid lats
- Returns:
AreaDefinition
- Return type:
- classmethod from_cf(cf_file, variable=None, y=None, x=None)
Create an AreaDefinition object from a netCDF/CF file.
- Parameters:
nc_file (string or object) – path to a netCDF/CF file, or opened xarray.Dataset object
variable (string, optional) – name of the variable to load the AreaDefinition from If variable is None the file will be searched for valid CF area definitions
y (string, optional) – name of the variable to use as ‘y’ axis of the CF area definition If y is None an appropriate ‘y’ axis will be deduced from the CF file
x (string, optional) – name of the variable to use as ‘x’ axis of the CF area definition If x is None an appropriate ‘x’ axis will be deduced from the CF file
- Returns:
AreaDefinition
- Return type:
- classmethod from_circle(area_id, projection, center, radius, shape=None, resolution=None, units=None, **kwargs)
Create an AreaDefinition from center, radius, and shape or from center, radius, and resolution.
- Parameters:
area_id (str) – ID of area
projection (dict or str) – Projection parameters as a proj4_dict or proj4_string
center (list) – Center of projection (x, y)
radius (list or float) – Length from the center to the edges of the projection (dx, dy)
shape (list, optional) – Number of pixels in the y and x direction (height, width)
resolution (list or float, optional) – Size of pixels: (dx, dy)
units (str, optional) –
Units that provided arguments should be interpreted as. This can be one of ‘deg’, ‘degrees’, ‘meters’, ‘metres’, and any parameter supported by the cs2cs -lu command. Units are determined in the following priority:
units expressed with each variable through a DataArray’s attrs attribute.
units passed to
unitsunits used in
projectionmeters
description (str, optional) – Description/name of area. Defaults to area_id
proj_id (str, optional) – ID of projection
nprocs (int, optional) – Number of processor cores to be used
lons (numpy array, optional) – Grid lons
lats (numpy array, optional) – Grid lats
optimize_projection – Whether the projection parameters have to be optimized for a DynamicAreaDefinition.
- Returns:
AreaDefinition or DynamicAreaDefinition – If shape or resolution are provided, an AreaDefinition object is returned. Else a DynamicAreaDefinition object is returned
- Return type:
Notes
resolutionandradiuscan be specified with one value if dx == dy
- classmethod from_epsg(code, resolution)
Create an AreaDefinition object from an epsg code (string or int) and a resolution.
- classmethod from_extent(area_id, projection, shape, area_extent, units=None, **kwargs)
Create an AreaDefinition object from area_extent and shape.
- Parameters:
area_id (str) – ID of area
projection (dict or str) – Projection parameters as a proj4_dict or proj4_string
shape (list) – Number of pixels in the y and x direction (height, width)
area_extent (list) – Area extent as a list (lower_left_x, lower_left_y, upper_right_x, upper_right_y)
units (str, optional) –
Units that provided arguments should be interpreted as. This can be one of ‘deg’, ‘degrees’, ‘meters’, ‘metres’, and any parameter supported by the cs2cs -lu command. Units are determined in the following priority:
units expressed with each variable through a DataArray’s attrs attribute.
units passed to
unitsunits used in
projectionmeters
description (str, optional) – Description/name of area. Defaults to area_id
proj_id (str, optional) – ID of projection
nprocs (int, optional) – Number of processor cores to be used
lons (numpy array, optional) – Grid lons
lats (numpy array, optional) – Grid lats
- Returns:
AreaDefinition
- Return type:
- classmethod from_ul_corner(area_id, projection, shape, upper_left_extent, resolution, units=None, **kwargs)
Create an AreaDefinition object from upper_left_extent, resolution, and shape.
- Parameters:
area_id (str) – ID of area
projection (dict or str) – Projection parameters as a proj4_dict or proj4_string
shape (list) – Number of pixels in the y and x direction (height, width)
upper_left_extent (list) – Upper left corner of upper left pixel (x, y)
resolution (list or float) – Size of pixels in meters: (dx, dy). Can be specified with one value if dx == dy
units (str, optional) –
Units that provided arguments should be interpreted as. This can be one of ‘deg’, ‘degrees’, ‘meters’, ‘metres’, and any parameter supported by the cs2cs -lu command. Units are determined in the following priority:
units expressed with each variable through a DataArray’s attrs attribute.
units passed to
unitsunits used in
projectionmeters
description (str, optional) – Description/name of area. Defaults to area_id
proj_id (str, optional) – ID of projection
nprocs (int, optional) – Number of processor cores to be used
lons (numpy array, optional) – Grid lons
lats (numpy array, optional) – Grid lats
- Returns:
AreaDefinition
- Return type:
- geocentric_resolution(ellps='WGS84', radius=None)
Find best estimate for overall geocentric resolution.
This method is extremely important to the results of KDTree-based resamplers like the nearest neighbor resampling. This is used to determine how far the KDTree should be queried for valid pixels before giving up (radius_of_influence). This method attempts to make a best guess at what geocentric resolution (the units used by the KDTree) represents the majority of an area.
To do this this method will:
Create a vertical mid-line and a horizontal mid-line.
Convert these coordinates to geocentric coordinates.
Compute the distance between points along these lines.
Take the histogram of each set of distances and find the bin with the most points.
Take the average of the edges of that bin.
Return the maximum of the vertical and horizontal bin edge averages.
- get_area_slices(area_to_cover, shape_divisible_by=None)
Compute the slice to read based on an area_to_cover.
- get_array_coordinates_from_lonlat(lon, lat)
Retrieve the array coordinates (float) for a given lon/lat.
If lon,lat is a tuple of sequences of longitudes and latitudes, a tuple of arrays is returned.
- Parameters:
lon (array_like) – point or sequence of longitudes
lat (array_like) – point or sequence of latitudes
- Returns:
the array coordinates (cols/rows)
- Return type:
floats or arrays of floats
- get_array_coordinates_from_projection_coordinates(xm, ym)
Find the floating-point grid cell index for a specified projection coordinate.
If xm, ym is a tuple of sequences of projection coordinates, a tuple of arrays are returned.
- Parameters:
xm (array_like) – point or sequence of x-coordinates in meters (map projection)
ym (array_like) – point or sequence of y-coordinates in meters (map projection)
- Returns:
the array coordinates (cols/rows)
- Return type:
floats or arrays of floats
- get_array_indices_from_lonlat(lon, lat)
Find the closest integer grid cell index for a given lon/lat.
If lon,lat is a point, a ValueError is raised if it is outside the area domain. If lon,lat is a tuple of sequences of longitudes and latitudes, a tuple of masked arrays are returned. The masked values are the actual row and col indexing the grid cell if the area had been big enough, or the numpy default (999999) if invalid.
- Parameters:
lon (array_like) – point or sequence of longitudes
lat (array_like) – point or sequence of latitudes
- Returns:
the array indices (cols/rows)
- Return type:
ints or masked arrays of ints
- Raises:
ValueError – if the return point is outside the area domain
- get_array_indices_from_projection_coordinates(xm, ym)
Find the closest integer grid cell index for a specified projection coordinate.
If xm, ym is a point, a ValueError is raised if it is outside the area domain. If xm, ym is a tuple of sequences of projection coordinates, a tuple of masked arrays are returned.
- Parameters:
xm (array_like) – point or sequence of x-coordinates in meters (map projection)
ym (array_like) – point or sequence of y-coordinates in meters (map projection)
- Returns:
the array indices (cols/rows)
- Return type:
ints or masked arrays of ints
- Raises:
ValueError – if the return point is outside the area domain
- get_edge_bbox_in_projection_coordinates(vertices_per_side=None, frequency=None)
Return the bounding box in projection coordinates.
- get_lonlat(row, col)
Retrieve lon and lat values of single point in area grid.
- Parameters:
row (int)
col (int)
- Returns:
(lon, lat)
- Return type:
tuple of floats
- get_lonlat_from_array_coordinates(cols, rows)
Get the longitude and latitude from (floating) column and row indices.
If cols, rows is a tuple of sequences of array coordinates, a tuple of arrays is returned.
- Parameters:
cols (array_like) – the column coordinates
rows (array_like) – the row coordinates
- Returns:
the longitude, latitude in degrees
- Return type:
floats or arrays of floats
- get_lonlat_from_projection_coordinates(xm, ym)
Get the lonlat from projection coordinates.
If xm, ym is a tuple of sequences of projection coordinates, a tuple of arrays is returned.
- Parameters:
xm (array_like) – the x projection coordinates in meters
ym (array_like) – the y projection coordinates in meters
- Returns:
the longitude, latitude in degrees
- Return type:
floats or arrays of floats
- get_lonlats(nprocs=None, data_slice=None, cache=False, dtype=None, chunks=None)
Return lon and lat arrays of area.
Note that this historically this method always returns longitude/latitudes on the geodetic (unprojected) model of the Earth used by the Coordinate Reference System (CRS) for this area. However, this is not true for shifted datums. For example, a projection including a PROJ.4 parameter like
+pm=180to shift longitudes/latitudes 180 degrees, will return degrees on the+pm=0equivalent of the geodetic CRS.- Parameters:
nprocs (int, optional) – Number of processor cores to be used. Defaults to the nprocs set when instantiating object
data_slice (slice object, optional) – Calculate only coordinates for specified slice
cache (bool, optional) – Store the result internally for later reuse. Requires data_slice to be None.
dtype (numpy.dtype, optional) – Data type of the returned arrays
chunks (int or tuple, optional) – Create dask arrays and use this chunk size
- Returns:
(lons, lats) – Grids of area lons and and lats
- Return type:
tuple of numpy arrays
- get_lonlats_dask(chunks=None, dtype=None)
Get longitudes and latitudes.
- get_proj_coords(data_slice=None, dtype=None, chunks=None)
Get projection coordinates of grid.
- Parameters:
data_slice (slice object, optional) – Calculate only coordinates for specified slice
dtype (numpy.dtype, optional) – Data type of the returned arrays
chunks (int or tuple, optional) – Create dask arrays and use this chunk size
- Returns:
(target_x, target_y) (tuple of numpy arrays) – Grids of area x- and y-coordinates in projection units
.. versionchanged:: 1.11.0 – Removed ‘cache’ keyword argument and add ‘chunks’ for creating dask arrays.
- get_proj_coords_dask(chunks=None, dtype=None)
Get projection coordinates.
- get_proj_vectors(dtype=None, chunks=None)
Calculate 1D projection coordinates for the X and Y dimension.
- Parameters:
dtype (numpy.dtype) – Numpy data type for the returned arrays
chunks (int or tuple) – Return dask arrays with the chunk size specified. If this is a tuple then the first element is the Y array’s chunk size and the second is the X array’s chunk size.
- Returns:
tuple ((X, Y) where X and Y are 1-dimensional numpy arrays)
The data type of the returned arrays can be controlled with the
dtype keyword argument. If chunks is provided then dask arrays
are returned instead.
- get_proj_vectors_dask(chunks=None, dtype=None)
Get projection vectors.
- get_projection_coordinates_from_array_coordinates(cols, rows)
Get the projection coordinate from the array coordinates.
If cols, rows is a tuple of sequences of array coordinates, a tuple of arrays is returned.
- Parameters:
cols (array_like) – the column coordinates
rows (array_like) – the row coordinates
- Returns:
the projection coordinates x, y in meters
- Return type:
floats or arrays of floats
- get_projection_coordinates_from_lonlat(lon, lat)
Get the projection coordinate from longitudes and latitudes.
If lon,lat is a tuple of sequences of longitudes and latitudes, a tuple of arrays is returned.
- Parameters:
lon (array_like) – point or sequence of longitudes
lat (array_like) – point or sequence of latitudes
- Returns:
the projection coordinates x, y in meters
- Return type:
floats or arrays of floats
- get_xy_from_lonlat(lon, lat)
Retrieve closest x and y coordinates.
Retrieve the closest x and y coordinates (column, row indices) for the specified geolocation (lon,lat) if inside area. If lon,lat is a point a ValueError is raised if the return point is outside the area domain. If lon,lat is a tuple of sequences of longitudes and latitudes, a tuple of masked arrays are returned.
- Parameters:
lon – point or sequence (list or array) of longitudes
lat – point or sequence (list or array) of latitudes
- Returns:
tuple of points/arrays
- Return type:
(x, y)
- get_xy_from_proj_coords(xm, ym)
Find closest grid cell index for a specified projection coordinate.
If xm, ym is a tuple of sequences of projection coordinates, a tuple of masked arrays are returned.
- Parameters:
xm (list or array) – point or sequence of x-coordinates in meters (map projection)
ym (list or array) – point or sequence of y-coordinates in meters (map projection)
- Returns:
column and row grid cell indexes as 2 scalars or arrays
- Return type:
x, y
- Raises:
ValueError – if the return point is outside the area domain
- property is_geostationary
Whether this area is in a geostationary satellite projection or not.
- lonlat2colrow(lons, lats)
Return image columns and rows for the given lons and lats.
Both scalars and arrays are supported. Same as get_xy_from_lonlat, renamed for convenience.
- property name
Return area name.
- property outer_boundary_corners
Return the lon,lat of the outer edges of the corner points.
- property proj4_string
Return projection definition as Proj.4 string.
- property proj_str
Return PROJ projection string.
This is no longer the preferred way of describing CRS information. Switch to the crs or crs_wkt properties for the most flexibility.
- property projection_x_coords
Return projection X coordinates.
- property projection_y_coords
Return projection Y coordinates.
- property resolution
Return area resolution in X and Y direction.
- to_cartopy_crs()
Convert projection to cartopy CRS object.
- to_odc_geobox()
Convert AreaDefinition to ODC GeoBox.
- update_hash(existing_hash=None)
Update a hash, or return a new one if needed.
- class pyresample.geometry.BaseDefinition(lons=None, lats=None, nprocs=1)
Bases:
objectBase class for geometry definitions.
Changed in version 1.8.0: BaseDefinition no longer checks the validity of the provided longitude and latitude coordinates to improve performance. Longitude arrays are expected to be between -180 and 180 degrees, latitude -90 to 90 degrees. Use
check_and_wrap()to preprocess your arrays.Initialize BaseDefinition.
- __init__(lons=None, lats=None, nprocs=1)
Initialize BaseDefinition.
- boundary(vertices_per_side=None, force_clockwise=False, frequency=None)
Retrieve the AreaBoundary object.
- Parameters:
vertices_per_side – (formerly frequency) The number of points to provide for each side. By default (None) the full width and height will be provided.
force_clockwise – Perform minimal checks and reordering of coordinates to ensure that the returned coordinates follow a clockwise direction. This is important for compatibility with
pyresample.spherical.SphPolygonwhere operations depend on knowing the inside versus the outside of a polygon. These operations assume that coordinates are clockwise. Default is False.
- property corners
Return the corners centroids of the current area.
- get_area()
Get the area of the convex area defined by the corners of the curren area.
- get_area_extent_for_subset(row_LR, col_LR, row_UL, col_UL)
Calculate extent for a subdomain of this area.
Rows are counted from upper left to lower left and columns are counted from upper left to upper right.
- Parameters:
row_LR (int) – row of the lower right pixel
col_LR (int) – col of the lower right pixel
row_UL (int) – row of the upper left pixel
col_UL (int) – col of the upper left pixel
- Returns:
Area extent (LL_x, LL_y, UR_x, UR_y) of the subset
- Return type:
area_extent (tuple)
- Author:
Ulrich Hamann
- get_area_slices(area_to_cover)
Compute the slice to read based on an area_to_cover.
- get_bbox_lonlats(vertices_per_side=None, force_clockwise=True, frequency=None)
Return the bounding box lons and lats sides.
- Parameters:
vertices_per_side (
Optional[int]) – The number of points to provide for each side. By default (None) the full width and height will be provided.frequency (
Optional[int]) – Deprecated, use vertices_per_sideforce_clockwise (
bool) – Perform minimal checks and reordering of coordinates to ensure that the returned coordinates follow a clockwise direction. This is important for compatibility withpyresample.spherical.SphPolygonwhere operations depend on knowing the inside versus the outside of a polygon. These operations assume that coordinates are clockwise. Default is True.
- Return type:
tuple- Returns:
Two lists of four elements each. The first list is longitude coordinates, the second latitude. Each element is a numpy array representing a specific side of the geometry. The order of the arrays is first row (index 0), last column, last row, and first column. The arrays are sliced (ordered) in a way to ensure that the coordinates follow a clockwise path. In the usual case this results in the coordinates starting in the north-west corner. In the case where the data is oriented with the first pixel (row 0, column 0) in the south-east corner, the coordinates will start in that corner. Other orientations that are detected to follow a counter-clockwise path will be reordered to provide a clockwise path in order to be compatible with other parts of pyresample (ex.
pyresample.spherical.SphPolygon).
- get_boundary_lonlats()
Return Boundary objects.
- get_cartesian_coords(nprocs=None, data_slice=None, cache=False)
Retrieve cartesian coordinates of geometry definition.
- Parameters:
nprocs (int, optional) – Number of processor cores to be used. Defaults to the nprocs set when instantiating object
data_slice (slice object, optional) – Calculate only cartesian coordnates for the defined slice
cache (bool, optional) – Store result the result. Requires data_slice to be None
- Returns:
cartesian_coords
- Return type:
numpy array
- get_edge_lonlats(vertices_per_side=None, frequency=None)
Get the concatenated boundary of the current swath.
- get_lonlat(row, col)
Retrieve lon and lat of single pixel.
- Parameters:
row (int)
col (int)
- Returns:
(lon, lat)
- Return type:
tuple of floats
- get_lonlats(data_slice=None, chunks=None, **kwargs)
Get longitude and latitude arrays representing this geometry.
- Returns:
(lon, lat) – If chunks is provided then the arrays will be dask arrays with the provided chunk size. If chunks is not provided then the returned arrays are the same as the internal data types of this geometry object (numpy or dask).
- Return type:
tuple of numpy arrays
- get_lonlats_dask(chunks=None)
Get the lon lats as a single dask array.
- intersection(other)
Return the corners of the intersection polygon of the current area with other.
- Parameters:
other (object) – Instance of subclass of BaseDefinition
- Returns:
(corner1, corner2, corner3, corner4)
- Return type:
tuple of points
- property is_geostationary
Whether this geometry is in a geostationary satellite projection or not.
- overlap_rate(other)
Get how much the current area overlaps an other area.
- Parameters:
other (object) – Instance of subclass of BaseDefinition
- Returns:
overlap_rate
- Return type:
float
- overlaps(other)
Test if the current area overlaps the other area.
This is based solely on the corners of areas, assuming the boundaries to be great circles.
- Parameters:
other (object) – Instance of subclass of BaseDefinition
- Returns:
overlaps
- Return type:
bool
- update_hash(existing_hash=None)
Update the hash.
- class pyresample.geometry.CoordinateDefinition(lons, lats, nprocs=1)
Bases:
BaseDefinitionBase class for geometry definitions defined by lons and lats only.
Initialize CoordinateDefinition.
- __init__(lons, lats, nprocs=1)
Initialize CoordinateDefinition.
- append(other)
Append another coordinate definition to existing one.
- concatenate(other)
Concatenate coordinate definitions.
- geocentric_resolution(ellps='WGS84', radius=None, nadir_factor=2)
Calculate maximum geocentric pixel resolution.
If lons is a
xarray.DataArrayobject with a resolution attribute, this will be used instead of loading the longitude and latitude data. In this case the resolution attribute is assumed to mean the nadir resolution of a swath and will be multiplied by the nadir_factor to adjust for increases in the spatial resolution towards the limb of the swath.- Parameters:
ellps (str) – PROJ Ellipsoid for the Cartographic projection used as the target geocentric coordinate reference system. Default: ‘WGS84’. Ignored if radius is provided.
radius (float) – Spherical radius of the Earth to use instead of the definitions in ellps.
nadir_factor (int) – Number to multiply the nadir resolution attribute by to reflect pixel size on the limb of the swath.
- Returns: Estimated maximum pixel size in meters on a geocentric
coordinate system (X, Y, Z) representing the Earth.
- Raises: RuntimeError if a simple search for valid longitude/latitude
data points found no valid data points.
- exception pyresample.geometry.DimensionError
Bases:
ValueErrorWrap ValueError.
- class pyresample.geometry.DynamicAreaDefinition(area_id=None, description=None, projection=None, width=None, height=None, area_extent=None, resolution=None, optimize_projection=False)
Bases:
objectAn AreaDefintion containing just a subset of the needed parameters.
The purpose of this class is to be able to adapt the area extent and shape of the area to a given set of longitudes and latitudes, such that e.g. polar satellite granules can be resampled optimally to a given projection.
Note that if the provided projection is geographic (lon/lat degrees) and the provided longitude and latitude data crosses the anti-meridian (-180/180), the resulting area will be the smallest possible in order to contain that data and avoid a large area spanning from -180 to 180 longitude. This means the resulting AreaDefinition will have a right-most X extent greater than 180 degrees. This does not apply to data crossing the north or south pole as there is no “smallest” area in this case.
- area_id
The name of the area.
- description
The description of the area.
- projection
The dictionary or string or CRS object of projection parameters. Doesn’t have to be complete. If not complete,
proj_infomust be provided tofreezeto “fill in” any missing parameters.
- width
x dimension in number of pixels, aka number of grid columns
- height
y dimension in number of pixels, aka number of grid rows
- shape
Corresponding array shape as (height, width)
- area_extent
The area extent of the area.
- resolution
Resolution of the resulting area as (pixel_size_x, pixel_size_y) or a scalar if pixel_size_x == pixel_size_y.
- optimize_projection
Whether the projection parameters have to be optimized.
Initialize the DynamicAreaDefinition.
- __init__(area_id=None, description=None, projection=None, width=None, height=None, area_extent=None, resolution=None, optimize_projection=False)
Initialize the DynamicAreaDefinition.
- compute_domain(corners, resolution=None, shape=None, projection=None)
Compute shape and area_extent from corners and [shape or resolution] info.
- Parameters:
corners (
Sequence) – 4-element sequence representing the outer corners of the region. Note that corners represents the center of pixels, while area_extent represents the edge of pixels. The four values are (xmin_corner, ymin_corner, xmax_corner, ymax_corner). If the x corners areNonethen the full extent (area of use) of the projection will be used. When needed, area of use is taken from the PROJ library or in the case of a geographic lon/lat projection -180/180 is used. A RuntimeError is raised if the area of use is needed (when x corners areNone) and area of use can’t be determined.resolution (
Union[float,tuple[float,float],None]) – Spatial resolution in projection units (typically meters or degrees). If not specified then shape must be provided. If a scalar then it is treated as the x and y resolution. If a tuple then x resolution is the first element, y is the second.shape (
Optional[tuple[int,int]]) – Number of pixels in the area as a 2-element tuple. The first is number of rows, the second number of columns.projection (
Union[CRS,dict,str,int,None]) – PROJ.4 definition string, dictionary, integer EPSG code, or pyproj CRS object.
Note that
shapeis (rows, columns) andresolutionis (x_size, y_size); the dimensions are flipped.
- freeze(lonslats=None, resolution=None, shape=None, proj_info=None, antimeridian_mode=None)
Create an AreaDefinition from this area with help of some extra info.
- Parameters:
lonlats (SwathDefinition or tuple) – The geographical coordinates to contain in the resulting area. A tuple should be
(lons, lats). If a SwathDefinition is provided, and it has a “bounding_box” attribute, it will be used instead of the full longitude and latitude to avoid potentially slow computations.resolution – the resolution of the resulting area.
shape – the shape of the resulting area.
proj_info – complementing parameters to the projection info.
antimeridian_mode –
How to handle lon/lat data crossing the anti-meridian of the projection. This currently only affects lon/lat geographic projections and data cases not covering the north or south pole. The possible options are:
- ”modify_extents”: Set the X bounds to the edges of the data, but
add 360 to the right-most bound. This has the effect of making the area coordinates continuous from the left side to the right side. However, this means that some coordinates will be outside the coordinate space of the projection. Although most PROJ and pyresample functionality can handle this there may be some edge cases.
- ”modify_crs”: Change the prime meridian of the projection
from 0 degrees longitude to 180 degrees longitude. This has the effect of putting the data on a continuous coordinate system. However, this means that comparing data resampled to this resulting area and an area not over the anti-meridian would be more difficult.
- ”global_extents”: Ignore the bounds of the data and use -180/180
degrees as the west and east bounds of the data. This will generate a large output area, but with the benefit of keeping the data on the original projection. Note that some resampling methods may produce artifacts when resampling on the edge of the area (the anti-meridian).
created (Shape parameters are ignored if the instance is)
True. (with the optimize_projection flag set to)
- property pixel_size_x
Pixel width in projection units.
- property pixel_size_y
Pixel height in projection units.
- class pyresample.geometry.GridDefinition(lons, lats, nprocs=1)
Bases:
CoordinateDefinitionGrid defined by lons and lats.
- Parameters:
lons (numpy array)
lats (numpy array)
nprocs (int, optional) – Number of processor cores to be used for calculations.
- shape
Grid shape as (rows, cols)
- Type:
tuple
- size
Number of elements in grid
- Type:
int
- lons
Grid lons
- Type:
object
- lats
Grid lats
- Type:
object
- cartesian_coords
Grid cartesian coordinates
- Type:
object
Initialize GridDefinition.
- __init__(lons, lats, nprocs=1)
Initialize GridDefinition.
- exception pyresample.geometry.IncompatibleAreas
Bases:
ValueErrorError when the areas to combine are not compatible.
- exception pyresample.geometry.InvalidArea
Bases:
ValueErrorError to be raised when an area is invalid for a given purpose.
- class pyresample.geometry.StackedAreaDefinition(*definitions, **kwargs)
Bases:
_ProjectionDefinitionDefinition based on muliple vertically stacked AreaDefinitions.
Initialize StackedAreaDefinition based on definitions.
kwargs used here are nprocs and dtype (see AreaDefinition).
- __init__(*definitions, **kwargs)
Initialize StackedAreaDefinition based on definitions.
kwargs used here are nprocs and dtype (see AreaDefinition).
- append(definition)
Append another definition to the area.
- get_lonlats(nprocs=None, data_slice=None, cache=False, dtype=None, chunks=None)
Return lon and lat arrays of the area.
- get_lonlats_dask(chunks=None, dtype=None)
Return lon and lat dask arrays of the area.
- property height
Return height of the area definition.
- property proj4_string
Return projection definition as Proj.4 string.
- property proj_str
Return projection definition as Proj.4 string.
- squeeze()
Generate a single AreaDefinition if possible.
- update_hash(the_hash=None)
Update the hash.
- property width
Return width of the area definition.
- class pyresample.geometry.SwathDefinition(lons, lats, nprocs=1, crs=None)
Bases:
CoordinateDefinitionSwath defined by lons and lats.
- Parameters:
lons (numpy array)
lats (numpy array)
nprocs (int, optional) – Number of processor cores to be used for calculations.
crs (pyproj.CRS,) – The CRS to use. longlat on WGS84 by default.
- shape
Swath shape
- Type:
tuple
- size
Number of elements in swath
- Type:
int
- ndims
Swath dimensions
- Type:
int
- lons
Swath lons
- Type:
object
- lats
Swath lats
- Type:
object
- cartesian_coords
Swath cartesian coordinates
- Type:
object
Initialize SwathDefinition.
- __init__(lons, lats, nprocs=1, crs=None)
Initialize SwathDefinition.
- aggregate(**dims)
Aggregate the current swath definition by averaging.
For example, averaging over 2x2 windows: sd.aggregate(x=2, y=2)
- compute_bb_proj_params(proj_dict)
Compute BB projection parameters.
- compute_optimal_bb_area(proj_dict=None, resolution=None)
Compute the “best” bounding box area for this swath with proj_dict.
By default, the projection is Oblique Mercator (omerc in proj.4), in which case the right projection angle alpha is computed from the swath centerline. For other projections, only the appropriate center of projection and area extents are computed.
The height and width are computed so that the resolution is approximately the same across dimensions.
- copy()
Copy the current swath.
- pyresample.geometry.combine_area_extents_vertical(area1, area2)
Combine the area extents of areas 1 and 2.
- pyresample.geometry.concatenate_area_defs(area1, area2, axis=0)
Append area2 to area1 and return the results.
- pyresample.geometry.daskify_2in_2out(func)
Daskify the coordinate conversion functions.
- pyresample.geometry.enclose_areas(*areas, area_id='joint-area')
Return the smallest areadefinition enclosing one or more others.
From one or more AreaDefinition objects (most usefully at least two), which shall differ only in extent, calculate the smallest AreaDefinition that encloses all. Touches only the
area_extent; projection and units must be identical in all input areas and will be unchanged in the resulting area. When the input areas \(i=1..n\) have extent \((a_i, b_i, c_i, d_i)\), the resulting area will have extent \((\\min_i{a_i}, \\min_i{b_i}, \\max_i{c_i}, \\max_i{d_i})\).- Parameters:
*areas (AreaDefinition) – AreaDefinition objects to enclose.
area_id (Optional[str]) – Name of joint area, defaults to “joint-area”.
- pyresample.geometry.get_array_hashable(arr)
Compute a hashable form of the array arr.
Works with numpy arrays, dask.array.Array, and xarray.DataArray.
- pyresample.geometry.get_full_geostationary_bounding_box_in_proj_coords(geos_area, nb_points=50)
Get the valid boundary geos projection coordinates of the full disk.
- Parameters:
geos_area – Geostationary area definition to get the bounding box for.
nb_points – Number of points on the polygon
- pyresample.geometry.get_geostationary_angle_extent(geos_area)
Get the max earth (vs space) viewing angles in x and y.
- pyresample.geometry.get_geostationary_bounding_box(geos_area, nb_points=50)
Get the bbox in lon/lats of the valid pixels inside geos_area.
- Parameters:
geos_area – Geostationary area definition to get the bounding box for.
nb_points – Number of points on the polygon
- pyresample.geometry.get_geostationary_bounding_box_in_lonlats(geos_area, nb_points=50)
Get the bbox in lon/lats of the valid pixels inside geos_area.
- Parameters:
geos_area – Geostationary area definition to get the bounding box for.
nb_points – Number of points on the polygon
- pyresample.geometry.get_geostationary_bounding_box_in_proj_coords(geos_area, nb_points=50)
Get the bbox in geos projection coordinates of the valid pixels inside geos_area.
- Parameters:
geos_area – Geostationary area definition to get the bounding box for.
nb_points – Number of points on the polygon.
- pyresample.geometry.masked_ints(func)
Return masked integer arrays when returning array indices.
- pyresample.geometry.ordered_dump(data, stream=None, Dumper=<class 'yaml.dumper.Dumper'>, **kwds)
Dump the data to YAML in ordered fashion.
- pyresample.geometry.preserve_scalars(func)
Preserve scalars through the coordinate conversion functions.