climada.hazard.centroids package#
climada.hazard.centroids.centr module#
- class climada.hazard.centroids.centr.Centroids(*, lat: ndarray | list[float], lon: ndarray | list[float], crs: Any = 'EPSG:4326', region_id: Literal['country'] | None | ndarray | list[float] = None, on_land: Literal['natural_earth'] | None | ndarray | list[bool] = None, **kwargs)[source]#
Bases:
object
Contains vector centroids as a GeoDataFrame
- lat#
Latitudinal coordinates in the specified CRS (can be any unit).
- Type:
np.array
- lon#
Longitudinal coordinates in the specified CRS (can be any unit).
- Type:
np.array
- crs#
Coordinate reference system. Default: EPSG:4326 (WGS84)
- Type:
pyproj.CRS
- region_id#
Numeric country (or region) codes. Default: None
- Type:
np.array, optional
- on_land#
Boolean array indicating on land (True) or off shore (False). Default: None
- Type:
np.array, optional
- __init__(*, lat: ndarray | list[float], lon: ndarray | list[float], crs: Any = 'EPSG:4326', region_id: Literal['country'] | None | ndarray | list[float] = None, on_land: Literal['natural_earth'] | None | ndarray | list[bool] = None, **kwargs)[source]#
Initialization
- Parameters:
lat (np.array) – Latitudinal coordinates in the specified CRS (can be any unit).
lon (np.array) – Longitudinal coordinates in the specified CRS (can be any unit).
crs (str or anything accepted by pyproj.CRS.from_user_input()) – Coordinate reference system. Default: EPSG:4326 (WGS84)
region_id (np.array or str, optional) – Array of numeric country (or region) codes. If the special value “country” is given admin-0 codes are automatically assigned. Default: None
on_land (np.array or str, optional) – Boolean array indicating on land (True) or off shore (False). If the special value “natural_earth” is given, the property is automatically determined from NaturalEarth shapes. Default: None
kwargs (dict) – Additional columns with data to store in the internal GeoDataFrame (gdf attribute).
- property lat#
Return latitudes
- property lon#
Return longitudes
- property geometry#
Return the geometry
- property on_land#
Get the on_land property
- property region_id#
Get the assigned region_id
- property crs#
Get the crs
- property size#
Get size (number of lat/lon pairs)
- property shape#
Get shape [lat, lon] assuming rastered data.
- property total_bounds#
Get total bounds (minx, miny, maxx, maxy).
- property coord#
Get [lat, lon] array.
- to_default_crs(inplace=True)[source]#
Project the current centroids to the default CRS (epsg4326)
- Parameters:
inplace (bool) – if True, modifies the centroids in place. if False, return projected centroids object. Default is True.
- Return type:
Centroids or None (if inplace is True)
- to_crs(crs, inplace=False)[source]#
Project the current centroids to the desired crs
- Parameters:
crs (str) – coordinate reference system
inplace (bool, default False) – if True, modifies the centroids in place. if False, returns a copy.
- Return type:
Centroids or None (if inplace is True)
- classmethod from_geodataframe(gdf)[source]#
Initialize centroids from a geodataframe
- Parameters:
gdf (GeoDataFrame) – Input geodataframe with centroids as points in the geometry column. All other columns are attached to the centroids geodataframe.
- Returns:
Centroids built from the geodataframe.
- Return type:
- Raises:
ValueError –
- classmethod from_exposures(exposures)[source]#
Generate centroids from the locations of exposures.
The properties “region_id” and “on_land” are also extracted from the Exposures object if available. The columns “value”, “impf_*”, “centr_*”, “cover”, and “deductible” are not used.
- Parameters:
exposures (Exposures) – Exposures from which to take the centroids locations (as well as region_id and on_land if available).
- Return type:
- Raises:
ValueError –
- classmethod from_pnt_bounds(points_bounds, res, crs='EPSG:4326')[source]#
Create Centroids object from coordinate bounds and resolution.
The result contains all points from a regular raster with the given resolution and CRS, covering the given bounds. Note that the raster bounds are larger than the points’ bounds by res/2.
- Parameters:
points_bounds (tuple) – The bounds (lon_min, lat_min, lon_max, lat_max) of the point coordinates.
res (float) – The desired resolution in same units as points_bounds.
crs (dict() or rasterio.crs.CRS, optional) – Coordinate reference system. Default: DEF_CRS
- Return type:
- append(*centr)[source]#
Append Centroids to the current centroid object for concatenation.
This method checks that all centroids use the same CRS, appends the list of centroids to the initial Centroid object and eventually concatenates them to create a single centroid object with the union of all centroids.
Note that the result might contain duplicate points if the object to append has an overlap with the current object. Remove duplicates by either using
union()
or callingremove_duplicate_points()
after appending.- Parameters:
centr (Centroids) – Centroids to append. The centroids need to have the same CRS.
- Raises:
ValueError –
See also
union
Union of Centroid objects.
remove_duplicate_points
Remove duplicate points in a Centroids object.
- union(*others)[source]#
Create the union of the current Centroids object with one or more other centroids objects by passing the list of centroids to
append()
for concatenation and then removes duplicates.All centroids must have the same CRS. Points that are contained in more than one of the Centroids objects will only be contained once (i.e. duplicates are removed).
- Parameters:
others (Centroids) – Centroids contributing to the union.
- Returns:
centroids – Centroids object containing the union of all Centroids.
- Return type:
- remove_duplicate_points()[source]#
Return a copy of centroids with duplicate points removed
- Parameters:
centr (Centroids) – Centroids with or without duplicate points
- Returns:
centroids – A new Centroids object that contains a subselection of the original centroids without duplicates. Note that a copy is returned even if there were no duplicates.
- Return type:
- select(reg_id=None, extent=None, sel_cen=None)[source]#
Return new Centroids object containing points following certain criteria
It is currently possible to filter by region (reg_id), by geographical extent (extent), or by an explicit list of indices/a mask (sel_cen). If more than one criterion is given, all of them must be satisfied for a point to be included in the selection.
- Parameters:
reg_id (int or list of int, optional) – Numeric ID (or IDs) of the region (or regions) to restrict to, according to the values in the region_id property. Default: None
extent (tuple, optional) – The geographical extent (min_lon, max_lon, min_lat, max_lat) to restrict to, including the boundary. If the value for min_lon is greater than max_lon, the extent is interpreted to cross the antimeridian ([max_lon, 180] and [-180, min_lon]). Default: None
sel_cen (np.ndarray of int or bool, optional) – Boolean mask, or list of indices to restrict to. Default: None
- Returns:
centroids – Sub-selection of this object
- Return type:
- select_mask(sel_cen=None, reg_id=None, extent=None)[source]#
Create mask of selected centroids
- Parameters:
sel_cen (np.ndarray of bool, optional) – Boolean array, with size matching the number of centroids. Default: None
reg_id (int or list of int, optional) – Numeric ID (or IDs) of the region (or regions) to restrict to, according to the values in the region_id property. Default: None
extent (tuple, optional) – The geographical extent (min_lon, max_lon, min_lat, max_lat) to restrict to, including the boundary. If the value for min_lon is greater than lon_max, the extent is interpreted to cross the antimeridian ([lon_max, 180] and [-180, lon_min]). Default: None
- Returns:
sel_cen – Boolean array (mask) with value True for centroids in selection.
- Return type:
np.ndarray of bool
- plot(*, axis=None, figsize=(9, 13), **kwargs)[source]#
Plot centroids geodataframe using geopandas and cartopy plotting functions.
- Parameters:
axis (optional) – user-defined cartopy.mpl.geoaxes.GeoAxes instance
figsize ((float, float), optional) – figure size for plt.subplots The default is (9, 13)
args (optional) – positional arguments for geopandas.GeoDataFrame.plot
kwargs (optional) – keyword arguments for geopandas.GeoDataFrame.plot
- Returns:
ax
- Return type:
cartopy.mpl.geoaxes.GeoAxes instance
- set_region_id(level='country', overwrite=False)[source]#
Set region_id as country ISO numeric code attribute for every pixel or point.
- Parameters:
level (str, optional) – The admin level on which to assign centroids. Currently only ‘country’ (admin0) is implemented. Default: ‘country’
overwrite (bool, optional) – If True, overwrite the existing region_id information. If False, region_id is set only if region_id is missing (None). Default: False
- set_on_land(source='natural_earth', overwrite=False)[source]#
Set on_land attribute for every pixel or point.
- Parameters:
source (str, optional) – The source of the on-land information. Currently, only ‘natural_earth’ (based on shapes from NaturalEarth, https://www.naturalearthdata.com/) is implemented. Default: ‘natural_earth’.
overwrite (bool, optional) – If True, overwrite the existing on_land information. If False, on_land is set only if on_land is missing (None). Default: False
- get_pixel_shapes(res=None, **kwargs)[source]#
Create a GeoSeries of the quadratic pixel shapes at the centroid locations
Note that this assumes that the centroids define a regular grid of pixels.
- Parameters:
res (float, optional) – The resolution of the regular grid the pixels are taken from. If not given, it is estimated using climada.util.coordinates.get_resolution. Default: None
kwargs (optional) – Additional keyword arguments are passed to climada.util.coordinates.get_resolution.
- Return type:
GeoSeries
- get_area_pixel(min_resol=1e-08)[source]#
Compute the area per centroid in the CEA projection
Note that this assumes that the centroids define a regular grid of pixels (area in m²).
- Parameters:
min_resol (float, optional) – When estimating the grid resolution, use this as the minimum resolution in lat and lon. It is passed to climada.util.coordinates.get_resolution. Default: 1.0e-8
- Returns:
areapixels – Area of each pixel in square meters.
- Return type:
np.array
- get_closest_point(x_lon, y_lat)[source]#
Returns closest centroid and its index to a given point.
- Parameters:
x_lon (float) – Longitudinal (x) coordinate.
y_lat (float) – Latitudinal (y) coordinate.
- Returns:
x_close (float) – x-coordinate (longitude) of closest centroid.
y_close (float) – y-coordinate (latitude) of closest centroid.
idx_close (int) – Index of centroid in internal ordering of centroids.
- get_elevation(topo_path)[source]#
Return elevation attribute for every pixel or point in meters.
- Parameters:
topo_path (str) – Path to a raster file containing gridded elevation data.
- Returns:
values – Interpolated elevation values from raster file for each given coordinate point.
- Return type:
np.array of shape (npoints,)
- get_dist_coast(signed=False, precomputed=True)[source]#
Get dist_coast attribute for every pixel or point in meters.
The distances are read from a raster file containing precomputed distances (from NASA) at 0.01 degree (approximately 1 km) resolution.
- Parameters:
signed (bool, optional) – If True, use signed distances (positive off shore and negative on land). Default: False
precomputed (bool, optional) – Whether distances should be read from a pre-computed raster (True) or computed on-the-fly (False). Default: True.
Deprecated since version 5.0: Argument is ignored, because distances are not computed on-the-fly anymore.
- Returns:
dist – (Signed) distance to coast in meters.
- Return type:
np.array
- get_meta(resolution=None)[source]#
Returns a meta raster based on the centroids bounds.
Note that this function is not perfectly inverse with from_meta since get_meta enforces a grid with equal resolution in x- and y-direction with coordinates increasing in x-direction and decreasing in y-direction.
- Parameters:
resolution (float, optional) – Resolution of the raster. If not given, the resolution is estimated from the centroids by assuming that they form a regular raster. Default: None
- Returns:
meta – meta raster representation of the centroids
- Return type:
dict
- classmethod from_raster_file(file_name, src_crs=None, window=None, geometry=None, dst_crs=None, transform=None, width=None, height=None, resampling=Resampling.nearest, return_meta=False)[source]#
Create a new Centroids object from a raster file
Select region using window or geometry. Reproject input by providing dst_crs and/or (transform, width, height).
- Parameters:
file_name (str) – path of the file
src_crs (crs, optional) – source CRS. Provide it if error without it.
window (rasterio.windows.Window, optional) – window to read
geometry (list of shapely.geometry, optional) – consider pixels only within these shapes
dst_crs (crs, optional) – reproject to given crs
transform (rasterio.Affine) – affine transformation to apply
wdith (float) – number of lons for transform
height (float) – number of lats for transform
resampling (rasterio.warp.Resampling optional) – resampling function used for reprojection to dst_crs, default: nearest
return_meta (bool, optional) – default: False
- Returns:
centr (Centroids) – Centroids according to the given raster file
meta (dict, optional if return_meta is True) – Raster meta (height, width, transform, crs).
- classmethod from_meta(meta)[source]#
initiate centroids from meta raster definition
- Parameters:
meta (dict) – meta description of raster
- Returns:
Centroids initialized for raster described by meta.
- Return type:
Centroid
- classmethod from_vector_file(file_name, dst_crs=None)[source]#
Create Centroids object from vector file (any format supported by fiona).
- Parameters:
file_name (str) – vector file with format supported by fiona and ‘geometry’ field.
dst_crs (crs, optional) – reproject to given crs If no crs is given in the file, simply sets the crs.
- Returns:
centr – Centroids with points according to the given vector file
- Return type:
- classmethod from_csv(file_path, **kwargs)[source]#
Generate centroids from a CSV file with column names in var_names.
- Parameters:
file_path (str) – path to CSV file to be read
kwargs (dict) – Additional keyword arguments to pass on to pandas.read_csv.
- Return type:
- write_csv(file_path)[source]#
Save centroids as CSV file
- Parameters:
file_path (str, Path) – absolute or relative file path and name to write to
- classmethod from_excel(file_path, sheet_name=None)[source]#
Generate a new centroids object from an excel file with column names in var_names.
- Parameters:
file_path (str) – absolute or relative file path
sheet_name (str, optional) – name of sheet in excel file containing centroid information Default: “centroids”
- Returns:
centr – Centroids with data from the given excel file
- Return type:
- write_excel(file_path)[source]#
Save centroids as excel file
- Parameters:
file_path (str, Path) – absolute or relative file path and name to write to
- write_hdf5(file_name, mode='w')[source]#
Write data frame and metadata in hdf5 format
- Parameters:
file_name (str) – (path and) file name to write to.
- classmethod from_hdf5(file_name)[source]#
Create a centroids object from a HDF5 file.
- Parameters:
file_data (str or h5) – If string, path to read data. If h5 object, the datasets will be read from there.
- Returns:
centr – Centroids with data from the given file
- Return type:
- Raises:
FileNotFoundError –
- classmethod from_mat(file_name, var_names=None)[source]#
Reading Centroids data from matlab files is not supported anymore. This method has been removed with climada 5.0
Deprecated since version Reading: Centroids data from matlab files is not supported anymore.This method has been removed with climada 5.0
- static from_base_grid(land=False, res_as=360, base_file=None)[source]#
This method has been removed with climada 5.0
Deprecated since version This: method has been removed with climada 5.0
- classmethod from_lat_lon(lat, lon, crs='EPSG:4326')[source]#
deprecated, use the constructor instead
Deprecated since version This: method will be removed in a future version. Simply use the constructor instead.
- set_area_pixel(min_resol=1e-08, scheduler=None)[source]#
deprecated, obsolete
Deprecated since version This: method is futile and will be removed in a future version. Centroids.get_area_pixel can be run without initialization.
- set_area_approx(min_resol=1e-08)[source]#
deprecated, obsolete
Deprecated since version This: method is futile and will be removed in a future version. Centroids.get_area_pixel can be run without initialization.
- set_dist_coast(signed=False, precomputed=False, scheduler=None)[source]#
deprecated, obsolete
Deprecated since version This: method is futile and will be removed in a future version. Centroids.get_dist_coast can be run without initialization.
- empty_geometry_points()[source]#
“deprecated, has no effect, which may be unexpected: no geometry points will be removed, the centroids’ GeoDataFrame is built on them!
Deprecated since version This: method has no effect and will be removed in a future version. In the current version of climada the geometry points of a Centroids object cannot be removed as they are the backbone of the Centroids’ GeoDataFrame.