Processing¶
TifProcessor reads, clips, and samples a GeoTIFF. The functions below work on tables and geometries. The processing guide shows both.
from gigaspatial import TifProcessor, convert_to_geodataframe, aggregate_points_to_zones
from gigaspatial.processing import get_centroids, annotate_with_admin_regions
from gigaspatial.processing.elevation import LOSAnalyzer
Handler for TIF data processing and analysis.
Supports advanced operations like merging multiple rasters, reprojection, clipping to geometries, and converting raster data to formats like DataFrames or Graphs.
Attributes:
| Name | Type | Description |
|---|---|---|
dataset_path | Union[Path, str, List[Union[Path, str]]] | Path(s) to the TIF file(s). |
data_store | Optional[DataStore] | DataStore instance for file access. |
mode | Literal['single', 'rgb', 'rgba', 'multi'] | Processing mode ('single', 'rgb', 'rgba', 'multi'). |
merge_method | Literal['first', 'last', 'min', 'max', 'mean'] | Method for merging multiple rasters. |
target_crs | Optional[str] | Optional CRS to reproject to. |
resampling_method | Resampling | Resampling algorithm to use. |
reprojection_resolution | Optional[Tuple[float, float]] | Target pixel size for reprojection. |
to_dataframe(drop_nodata=True, check_memory=True, min_value=None, max_value=None, **kwargs) ¶
Convert the raster data into a pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_nodata | If True, pixels with the nodata value are excluded. | True | |
check_memory | If True, checks system memory availability before loading. | True | |
min_value | Optional[float] | Optional minimum threshold to filter pixels. | None |
max_value | Optional[float] | Optional maximum threshold to filter pixels. | None |
**kwargs | Additional arguments like | {} |
Returns:
| Type | Description |
|---|---|
DataFrame | A DataFrame with 'lon', 'lat', and band values. |
Raises:
| Type | Description |
|---|---|
ValueError | If processing fails due to mode mismatch or invalid data. |
to_geodataframe(check_memory=True, min_value=None, max_value=None, **kwargs) ¶
Convert the raster data into a GeoDataFrame.
Each row represents a pixel, with a Point or Box geometry representing its spatial extent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
check_memory | If True, checks system memory availability. | True | |
min_value | Optional[float] | Optional minimum threshold for pixel values. | None |
max_value | Optional[float] | Optional maximum threshold for pixel values. | None |
**kwargs | Additional arguments passed to | {} |
Returns:
| Type | Description |
|---|---|
GeoDataFrame | A GeoDataFrame containing pixel centroids or boxes and their values. |
clip_to_geometry(geometry, crop=True, all_touched=True, invert=False, nodata=None, pad=False, pad_width=0.5, return_clipped_processor=True) ¶
Clip the raster to the boundaries of specific geometries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry | Union[Polygon, MultiPolygon, GeoDataFrame, GeoSeries, List[dict], dict] | The geometry to clip to (Polygon, GDF, GeoSeries, etc.). | required |
crop | bool | If True, the raster's extent is reduced to the geometry's bounding box. | True |
all_touched | bool | If True, includes all pixels touched by the geometry. | True |
invert | bool | If True, masks pixels inside the geometry. | False |
nodata | Optional[Union[int, float]] | Override for the nodata value in the output. | None |
pad | bool | Whether to pad the geometry before clipping. | False |
pad_width | float | Width of the padding in pixels. | 0.5 |
return_clipped_processor | bool | If True, returns a new TifProcessor instance. | True |
Returns:
| Type | Description |
|---|---|
Union[TifProcessor, tuple] | A new TifProcessor instance (if return_clipped_processor is True) or |
Union[TifProcessor, tuple] | a tuple of (clipped_array, transform, metadata). |
Raises:
| Type | Description |
|---|---|
ValueError | If the geometry does not overlap with the raster or CRS is incompatible. |
clip_to_bounds(bounds, bounds_crs=None, return_clipped_processor=True) ¶
Clip the raster to a rectangular bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds | tuple | Bounding box as (minx, miny, maxx, maxy). | required |
bounds_crs | Optional[str] | The CRS of the input bounds. Defaults to raster CRS. | None |
return_clipped_processor | bool | If True, returns a new TifProcessor instance. | True |
Returns:
| Type | Description |
|---|---|
Union[TifProcessor, tuple] | The clipped TifProcessor or tuple of data/metadata. |
sample_by_coordinates(coordinate_list, **kwargs) ¶
Extract raster values at specific point coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinate_list | List[Tuple[float, float]] | List of (longitude, latitude) tuples. | required |
**kwargs | Additional arguments passed to rasterio.sample. | {} |
Returns:
| Type | Description |
|---|---|
Union[ndarray, dict] | Numpy array of values (single-band) or dict of band values (RGB/RGBA). |
sample_by_polygons(polygon_list, stat='mean') ¶
Sample raster values within polygons and compute aggregate statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
polygon_list | List of Shapely Polygon or MultiPolygon objects. | required | |
stat | Union[str, Callable, List[Union[str, Callable]]] | Statistic(s) to compute. Can be a string (e.g., 'mean'), a callable, or a list of both. | 'mean' |
Returns:
| Type | Description |
|---|---|
| Numpy array of results (if single stat) or a list of dictionaries (if multi-stat). |
reproject_to(target_crs, output_path=None, resampling_method=None, resolution=None) ¶
Reproject the current raster to a new CRS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_crs | str | The destination CRS (e.g., "EPSG:4326"). | required |
output_path | Optional[Union[str, Path]] | Optional path to save the result. If None, saves to temp. | None |
resampling_method | Optional[Resampling] | Optional override for resampling. | None |
resolution | Optional[Tuple[float, float]] | Optional target pixel resolution (x, y). | None |
Returns:
| Type | Description |
|---|---|
| Path to the reprojected file. |
get_raster_info(include_statistics=False, approx_ok=False) ¶
Get comprehensive metadata and statistics for the raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_statistics | bool | Whether to compute pixel statistics (mean, std, etc.). | False |
approx_ok | bool | Whether to allow approximate statistics for speed. | False |
Returns:
| Type | Description |
|---|---|
Dict[str, Any] | Dictionary containing metadata like dimensions, CRS, bounds, and optionally statistics. |
Convert a pandas DataFrame to a GeoDataFrame.
Supports conversion from latitude/longitude columns or WKT/geometry columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | DataFrame | Input DataFrame. | required |
lat_col | str | Name of the latitude column. | None |
lon_col | str | Name of the longitude column. | None |
crs | Coordinate Reference System. Defaults to 'EPSG:4326'. | 'EPSG:4326' |
Returns:
| Type | Description |
|---|---|
GeoDataFrame | A GeoDataFrame containing the input data with a geometry column. |
Raises:
| Type | Description |
|---|---|
TypeError | If input is not a pandas DataFrame. |
ValueError | If required columns are missing or invalid. |
Buffer a GeoDataFrame with a distance in meters.
Automatically handles UTM transformation for accurate buffering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf | GeoDataFrame | The GeoDataFrame to be buffered. | required |
buffer_distance_meters | Union[float, array, Series] | The buffer distance. | required |
cap_style | Literal['round', 'square', 'flat'] | Style of caps ('round', 'square', 'flat'). | 'round' |
copy | Whether to create a copy of the input. | True |
Returns:
| Type | Description |
|---|---|
GeoDataFrame | The buffered GeoDataFrame in the original CRS. |
Aggregate point data to zones with flexible aggregation methods.
For zones with no overlapping points: - "count" aggregation fills missing values with 0. - All other aggregations fill missing values with np.nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points | Union[DataFrame, GeoDataFrame] | Point data to aggregate. | required |
zones | GeoDataFrame | Zones to aggregate points to. | required |
value_columns | Optional[Union[str, List[str]]] | Column(s) containing values to aggregate. | None |
aggregation | Union[str, Dict[str, str]] | Aggregation method(s) to use. | 'count' |
point_zone_predicate | str | Spatial predicate (e.g., 'within', 'intersects'). | 'within' |
zone_id_column | str | Column in zones containing zone identifiers. | 'zone_id' |
output_suffix | str | Suffix to add to output column names. | '' |
drop_geometry | bool | Whether to drop the geometry column from output. | False |
Returns:
| Type | Description |
|---|---|
GeoDataFrame | Zones with aggregated point values. |
Raises:
| Type | Description |
|---|---|
TypeError | If zones is not a GeoDataFrame or aggregation is invalid. |
ValueError | If columns are missing or metadata is inconsistent. |
Aggregates polygon data to zones based on a spatial relationship.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
polygons | Union[DataFrame, GeoDataFrame] | Polygon data to aggregate. | required |
zones | GeoDataFrame | Target zones. | required |
value_columns | Union[str, List[str]] | Column(s) in polygons with numeric values. | required |
aggregation | Union[str, Dict[str, str]] | Aggregation method(s) to use (str or dict). | 'sum' |
predicate | Literal['intersects', 'within', 'fractional'] | Spatial relationship ('intersects', 'within', 'fractional'). | 'intersects' |
zone_id_column | str | Unique identifier column in zones. | 'zone_id' |
output_suffix | str | Suffix for output columns. | '' |
drop_geometry | bool | Whether to drop the geometry column. | False |
Returns:
| Type | Description |
|---|---|
GeoDataFrame | The zones GeoDataFrame with aggregated values. |
Raises:
| Type | Description |
|---|---|
TypeError | If polygons/zones are not GeoDataFrames. |
ValueError | If columns or predicates are invalid. |
Calculate the Haversine distance between two points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat1 | Latitude of point 1. | required | |
lon1 | Longitude of point 1. | required | |
lat2 | Latitude of point 2. | required | |
lon2 | Longitude of point 2. | required | |
R | Earth radius in meters. | 6371000.0 |
Returns:
| Type | Description |
|---|---|
| Distance in meters. |
Map whether each point is within any polygon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_points_gdf | GeoDataFrame containing points. | required | |
polygon_gdf | GeoDataFrame containing polygons. | required |
Returns:
| Type | Description |
|---|---|
| The |
Raises:
| Type | Description |
|---|---|
ValueError | If geometries are invalid or match is impossible (CRS mismatch). |