API reference#

This page provides a summary of GeoUtils’ API. For more details and examples, refer to the relevant chapters in the main part of the documentation.

Raster API#

GeoUtils exposes the raster API through the following interfaces:

The DataArray accessor and Raster expose the same methods and attributes. The Dataset accessor applies operations to all compatible raster variables by default, or to those selected.

Only file opening and scalable execution differ substantially between the accessors and Raster:

Opening a raster file#

Use open_raster() for an xarray.DataArray, or instantiate for a Raster.

open_raster(filename[, is_mask, downsample, ...])

Open a raster as a Xarray DataArray or Dataset.

Raster.__init__(filename_or_dataset[, ...])

Instantiate a raster from a filename or rasterio dataset.

info([stats, verbose])

Print summary information about the raster.

Create raster from an array#

Use from_array() to create a DataArray, or pass as_object_type="dataset" to create a Dataset.

from_array(data, transform, crs[, nodata, ...])

Create a georeferenced raster from a single-band or multiband array.

from_array(data, transform, crs[, nodata, ...])

Main attributes#

data

Array of the raster.

crs

Coordinate reference system of the raster.

transform

Geotransform of the raster.

nodata

Nodata value of the raster.

area_or_point

Pixel interpretation of the raster.

Derived attributes#

shape

Shape (i.e., height, width) of the raster in pixels.

height

Height of the raster in pixels.

width

Width of the raster in pixels.

count

Count of bands loaded in memory if they are, otherwise the one on disk.

bands

Band indexes loaded in memory if they are, otherwise on disk.

res

Resolution (X, Y) of the raster in georeferenced units.

bbox

Bounding box of the raster.

footprint

Footprint of the raster.

dtype

Data type of the raster.

Other attributes#

is_mask

Whether the raster array is a boolean data type (a mask).

is_loaded

Whether the raster array is loaded.

name

Name of the file on disk, if it exists.

driver

Driver used to read a file on disk.

tags

Metadata tags of the raster.

Geospatial operations#

crop(bbox[, inplace])

Crop the raster to a given extent.

icrop(bbox[, inplace])

Crop raster based on pixel indices (bbox), converting them into georeferenced coordinates.

clip(mask[, all_touched, mp_config])

Mask raster cells outside an exact clipping geometry.

reproject([ref, crs, res, grid_size, ...])

Reproject raster to a different geotransform (resolution, bounds) and/or coordinate reference system (CRS).

polygonize([target_values, connectivity, ...])

Polygonize the raster into a vector of polygon geometries delineating target values.

interp_at_points(points[, method, ...])

Interpolate raster values at a set of points.

resample_at_points(points[, method, ...])

Resample raster values at points with a named interpolation or statistic.

reduce_at_points(points[, reducer_function, ...])

Reduce raster values around point coordinates.

krige(variogram[, ref, backend, ...])

Interpolate raster values by ordinary kriging on this grid or a reference grid.

random_field(error_structure, *[, ...])

Generate one or more error fields across this raster.

Proximity#

proximity([vector, target_values, ...])

Compute proximity distances to the raster target pixels, or to a vector geometry on the raster grid.

Filters#

filter(method[, window, sigma, engine, ...])

Apply a filter to the raster array.

fill_nodata([max_search_distance, ...])

Fill nodata cells from nearby finite values.

sieve(size[, connectivity, mask])

Remove connected integer regions smaller than a number of pixels.

Plotting#

plot([bands, ref, cmap, max_pixels, vmin, ...])

Plot the raster.

Statistics#

See Statistics for estimators, grouping by intervals or categories, and variograms.

stats([statistics, by, values, bins, ...])

Calculate summary statistics or statistics grouped by categories, bins, or vector zones.

variogram(*[, band, n_pairs, sampling, ...])

Estimate a lightweight empirical variogram from raster pairs.

estimate_error_structure(other, *[, ...])

Estimate this raster's error structure from its difference with another dataset.

Sampling#

See Sampling for selecting valid observations, common locations and spatial pairs.

subsample(subsample, *[, bands, mask, ...])

Randomly sample raster cells without replacement.

cosample(other, *[, band, other_band, ...])

Sample this raster and another dataset at common finite locations.

pairsample(*[, band, n_pairs, sampling, ...])

Sample cell pairs in the raster.

Data manipulation#

copy([new_array, cast_nodata, deep])

Copy the raster in-memory.

to_nanarray([floating_dtype, return_mask])

Get NaN array from the raster.

The following methods apply only to the Raster object. Use native Xarray methods such as astype() and where() with the accessor interface.

Raster.astype(dtype[, convert_nodata, inplace])

Convert data type of the raster.

Raster.set_mask(mask)

Set a mask on the raster array.

Raster.get_mask()

Get mask of invalid values from the raster.

Loading, writing and converting#

load()

to_pointcloud([data_name, data_band, ...])

Convert raster cells to a point cloud, optionally selecting a random subsample.

from_pointcloud_regular(pointcloud[, ...])

Create a raster from a point cloud with coordinates on a regular grid.

Writing to file from accessors or Raster object:

DataArrayRasterAccessor.to_file(*args, **kwargs)

Write raster to file.

DatasetRasterAccessor.to_file(*args, **kwargs)

Write Dataset rasters to a file.

DataArrayRasterAccessor.to_geoutils()

Convert the DataArray to an in-memory GeoUtils Raster.

Raster.to_file(filename[, driver, dtype, ...])

Write the raster to file.

Raster.to_rio_dataset()

Export to a Rasterio in-memory dataset.

Raster.to_xarray([name])

Convert a xarray.DataArray raster.

Georeferencing utilities#

edit(*[, crs, transform, nodata, tags, ...])

Return a copy with selected raster metadata edited together.

set_crs(new_crs)

Set the coordinate reference system of the raster.

set_transform(new_transform)

Set the geotransform of the raster.

set_nodata(new_nodata[, update_array, ...])

Set a new nodata value for all bands.

set_area_or_point(new_area_or_point[, ...])

Set new pixel interpretation of the raster.

xy2ij(x, y[, op, precision, shift_area_or_point])

Get indexes (row,column) of coordinates (x,y).

ij2xy(i, j[, shift_area_or_point, force_offset])

Get coordinates (x,y) of indexes (row,column).

coords([grid, shift_area_or_point, ...])

Get coordinates (x,y) of all pixels in the raster.

translate(xoff, yoff[, distance_unit, inplace])

Translate a raster by a (x,y) offset.

outside_image(xi, yj[, index])

Check whether a given point falls outside the bounds of the raster.

Projection utilities#

get_metric_crs([local_crs_type, method, center])

Get a universal or custom local metric coordinate reference system for the raster.

get_bbox_projected(out_crs[, densify_points])

Get the raster bounding box projected in a specified CRS.

get_footprint_projected(out_crs[, ...])

Get raster footprint projected in a specified CRS.

intersection(other[, match_ref])

Returns the bounding box of intersection between this raster and another.

Testing utilities#

raster_equal(other[, strict_masked, ...])

Check if two rasters are equal.

georeferenced_grid_equal(other[, warn_3d_crs])

Check that raster shape, geotransform and CRS are equal.

Multiple rasters#

raster.load_multiple_rasters(raster_paths[, ...])

Function to load multiple rasters at once in a memory efficient way.

raster.stack_rasters(rasters[, reference, ...])

raster.merge_rasters(rasters[, reference, ...])

Spatially merge a list of rasters into one larger raster of their maximum extent.

Vector API#

GeoUtils exposes the vector API through two mirrored interfaces:

The GeoDataFrame accessor and Vector expose the same methods and attributes. Native GeoPandas methods are available directly on the GeoDataFrame.

Only file opening and scalable execution differ substantially between the accessor and Vector:

  • File opening: open_vector() is used for a GeoDataFrame object, while Vector objects are opened by instantiating the class,

  • Scalable execution: the vct accessor supports Dask, while the Vector supports Multiprocessing instead.

Opening a file#

open_vector(filename[, chunks, load])

Open a vector file.

Vector.__init__(filename_or_dataset[, layer])

Instantiate a vector from either a filename, a GeoPandas dataframe or series, or a Shapely geometry.

info([verbose])

Summarize information about the vector.

Main attributes#

Vector.gdf

Geodataframe of the vector.

crs

Coordinate reference system of the vector.

bbox

Total bounding box of the vector.

footprint

Footprint of the vector.

name

Name on disk, if it exists.

is_loaded

Whether the vector data are loaded in memory.

Caution

The bbox attribute of a Vector corresponds to the total_bounds attribute of a GeoDataFrame, while geopandas.GeoDataFrame.bounds returns a Series of per-feature bounds of the vector.

Writing to file#

GeoDataFrameVectorAccessor.to_file(filename)

Write the vector to a vector file or GeoParquet dataset.

Vector.to_file(filename[, driver, schema, index])

Write the Vector to a file.

Geospatial handling methods#

crop([bbox, mode, inplace, crop_geom])

Crop vector to a bounding box, without modifying geometric features.

clip(mask[, keep_geom_type, sort, mp_config])

Clip geometries exactly to a mask.

reproject([ref, crs, inplace])

Reproject vector to a specified coordinate reference system.

translate([xoff, yoff, zoff, inplace])

Shift a vector by a coordinate offset.

rasterize([ref, in_value, out_value, ...])

Rasterize vector to a raster or mask, with input geometries burned in.

Plotting#

plot([ref, cmap, vmin, vmax, alpha, ...])

Plot the vector.

Create geometry mask#

create_mask([ref, all_touched, crs, res, ...])

Create a raster or point cloud mask from the vector geometry features.

Proximity#

proximity([raster, size, distance_unit, ...])

Compute proximity distances to this vector's current geometry.

Geometry manipulation#

buffer_metric(buffer_size)

Buffer the vector features in a local metric system.

buffer_without_overlap(buffer_size[, ...])

Buffer the vector geometries without overlapping each other.

Data manipulation#

copy()

Return a copy of the vector-like object.

Projection tools#

get_metric_crs([local_crs_type, method, center])

Get a universal or custom local metric coordinate reference system for the vector.

from_bounds_projected(raster_or_vector[, ...])

Create a vector polygon from projected bounds of a raster or vector.

get_bbox_projected(out_crs[, densify_points])

Get the vector bounding box projected in a specified CRS.

get_footprint_projected(out_crs[, ...])

Get vector footprint projected in a specified CRS.

Indexing#

Vector.__getitem__(key)

Index the geodataframe.

From Shapely and GeoPandas#

Native operations remain available directly on the GeoDataFrame. The From Shapely and GeoPandas appendix lists the additional methods exposed by the Vector wrapper and explains how their outputs are converted.

Point cloud API#

GeoUtils exposes the point cloud API through the following interfaces:

The DataArray and GeoDataFrame accessors and PointCloud expose the same GeoUtils-specific methods and attributes. The Dataset accessor applies operations to all compatible point variables by default, or to those selected. Native Xarray and GeoPandas methods remain available directly on their objects.

Only file opening and scalable execution differ substantially between the accessors and PointCloud:

  • File opening: open_pointcloud() is used for Xarray or GeoPandas objects, while PointCloud objects are opened by instantiating the class,

  • Scalable execution: the accessors support Dask, while the PointCloud supports Multiprocessing instead.

Opening a file#

open_pointcloud(filename[, data_name, ...])

Open a point cloud as a Xarray DataArray, Dataset or GeoDataFrame.

PointCloud.__init__(filename_or_dataset[, ...])

Instantiate a point cloud from either a data attribute name and a vector (filename, GeoPandas dataframe or series, or a Shapely geometry), or only with a point cloud file type.

info([verbose])

Summarize information about the vector.

Main attributes#

PointCloud.gdf

Geodataframe of the point cloud.

data_name

Name of the point cloud's data.

data

Data of the point cloud.

crs

Coordinate reference system of the point cloud.

bbox

Total bounding box of the vector.

footprint

Footprint of the vector.

Other attributes#

point_count

Number of points in the point cloud.

is_loaded

Whether the point cloud data is loaded in memory.

Create and convert from data#

Use from_xyz() to create a DataArray from coordinate and value arrays. Pass as_object_type="dataset" or as_object_type="geodataframe" to choose another representation.

from_xyz(x, y, z, crs[, data_name, use_z, ...])

Create a point cloud from X, Y and value arrays.

from_xyz(x, y, z, crs[, data_name, use_z])

Create a point cloud from separate X, Y and Z arrays.

from_array(data, crs[, data_name, use_z])

Create a point cloud from a 3 x N or N x 3 array of X, Y and Z values.

from_tuples(tuples_xyz, crs[, data_name, use_z])

Create a point cloud from an iterable of X, Y and Z tuples.

to_xyz()

Convert point cloud to three 1D arrays of coordinates for X/Y/Z.

to_array()

Convert point cloud to a 3 x N array of X coordinates, Y coordinates and Z values.

to_tuples()

Convert point cloud to a list of 3-tuples.

PointCloud.to_xarray(*[, partition_lengths])

Convert coordinates and attributes to an array point cloud without changing their dtypes.

Writing to file#

Accessor methods write the native Xarray or GeoPandas representation:

DataArrayPointCloudAccessor.to_file(...)

Write points to LAS/LAZ, GeoParquet, or a geometry format.

DataArrayPointCloudAccessor.to_las(filename, *)

Write LAS/LAZ in numeric row partitions without constructing point geometries.

DataArrayPointCloudAccessor.to_parquet(...)

Write native GeoParquet points in bounded row groups or separate partition files.

DatasetPointCloudAccessor.to_file(filename, *)

Write Dataset points using the format selected by the filename suffix.

DatasetPointCloudAccessor.to_las(filename, *)

Write points in the dataset to a LAS or LAZ file.

DatasetPointCloudAccessor.to_parquet(filename, *)

Write points in the dataset to GeoParquet.

GeoDataFramePointCloudAccessor.to_file(filename)

Write point geometries to a vector file or native GeoParquet.

GeoUtils object methods:

PointCloud.to_file(filename[, driver, ...])

Write point geometries to a vector file or native GeoParquet.

PointCloud.to_las(filename[, version, ...])

Write the point cloud to LAS/LAZ/COPC file.

PointCloud.to_parquet(filename, *[, chunks, ...])

Write point coordinates and attributes to native GeoParquet row groups or partition files.

Geospatial#

crop([bbox, mode, inplace, crop_geom])

Crop vector to a bounding box, without modifying geometric features.

clip(mask[, keep_geom_type, sort, mp_config])

Remove points outside an exact clipping geometry.

reproject([ref, crs, inplace, mp_config])

Reproject point coordinates, preserving their order and value columns.

translate([xoff, yoff, zoff, inplace])

Shift a vector by a coordinate offset.

Filtering#

filter([method, radius, max_points, ...])

Filter the point cloud.

Interface with raster#

grid([ref, grid_coords, res, shape, bounds, ...])

Grid the point cloud into a raster.

krige(variogram[, ref, grid_coords, res, ...])

Interpolate point values onto a raster grid by ordinary kriging.

random_field(error_structure, *[, ...])

Generate one or more error fields at every point in this point cloud.

Plotting#

plot([column, ref, cmap, vmin, vmax, alpha, ...])

Plot the point cloud.

Data manipulation#

copy([new_array])

Copy the point cloud in-memory or as a lazy dataframe.

Statistics#

See Statistics for the same statistical workflows on point cloud values.

stats([statistics, by, values, bins, ...])

Compute statistics, global or grouped by categories, bins, or vector zones.

variogram(*[, n_pairs, sampling, estimator, ...])

Estimate a lightweight empirical variogram from point pairs.

estimate_error_structure(other, *[, ...])

Estimate error structure of this point cloud from its difference with another dataset.

Sampling#

See Sampling for sampling values and locations from point clouds.

subsample(subsample, *[, mask, ...])

Randomly sample point rows allowed by mask, without replacement.

cosample(other, *[, other_band, auxiliary, ...])

Sample this point cloud and another dataset at common finite locations.

pairsample(*[, n_pairs, sampling, ...])

Sample point pairs in the point cloud.

Testing methods#

pointcloud_equal(other, **kwargs)

Check if two point clouds are equal.

georeferenced_coords_equal(pc[, warn_3d_crs])

Check that two point cloud X/Y coordinates and CRS are equal.

Statistics#

Most statistical functions are available directly from the objects and accessors, as shown above.

Below, we list functions defining additional estimators, variogram objects, and that can help plot.

GeoUtils estimators#

stats.nmad(data[, nfact])

Calculate the normalized median absolute deviation (NMAD) of an array.

stats.linear_error(data[, interval])

Compute the linear error (LE) for a given dataset, representing the difference between the upper and lower percentiles of the data.

stats.rmse(data)

Calculate the RMSE of a data array.

stats.sum_square(data)

Calculate the sum of the square of a data array.

Variogram#

Variogram(lags, semivariance, counts[, ...])

Measured and fitted variogram values that can be saved without a fitting package object.

Plotting helpers#

stats.plot_grouped_stats(table, *[, value, ...])

Plot grouped statistics for one or two grouping variables with their sample counts shown as side histograms.

Variogram.plot([ax, show_error, ...])

Plot measured bins, pair counts, and the fitted model when present.

Numerical operators and uncertainty#

See Operators and neighborhoods for neighborhoods, weights and custom definitions, and Uncertainty for estimation and propagation workflows.

Operator interfaces and neighborhoods#

operators.Interpolator([neighborhood])

Interpolator to continuously predict values at new coordinates from nearby observations.

operators.Reducer([neighborhood])

Reducer of nearby input values into one result.

operators.LocalData(values, valid, source_ids)

This data class stores the nearby source values used to calculate one interpolator/reducer output.

operators.LinearCoefficients(weights[, offset])

This class allows to define linear operators (interpolator or reducer) that can be optionally used with weights, or with uncertainty propagation.

operators.PointNeighbours([max_points, radius])

Define a point neighborhood by a max number of points inside a radius.

operators.GridNeighbours([offsets, ...])

Define a grid neighbourhood for source cells, i.e. a window surrounding the target cells.

Interpolators#

operators.interpolator.Nearest([neighborhood])

The Nearest interpolator selects the value closest to each requested coordinate.

operators.interpolator.ScipyInterpolator([...])

The ScipyInterpolator class uses SciPy to predict values on a raster or from irregular points.

operators.interpolator.Linear([neighborhood])

The Linear interpolator predicts values by linear interpolation between nearby observations.

operators.interpolator.Cubic([neighborhood])

The Cubic interpolator uses SciPy's cubic interpolation for rasters or irregular points.

operators.interpolator.InverseDistance([...])

The InverseDistance interpolator uses nearby values with more weight on closer observations.

operators.interpolator.RasterConvolution(kernel)

Interpolate a raster with GDAL-compatible cubic or Lanczos convolution.

operators.interpolator.Kriging(model, *[, ...])

The Kriging interpolator predicts values from nearby observations and their spatial correlation.

Reducers#

operators.reducer.Mean([neighborhood])

The Mean reducer averages values, optionally weighted by sample importance or covered area/length.

operators.reducer.Sum([neighborhood])

The Sum reducer adds values, with optional sample weights and area/length weights.

operators.reducer.Quantile(q, *[, weighted, ...])

The Quantile reducer selects a value at a chosen fraction of the sorted observations.

operators.reducer.Median(*[, weighted, ...])

The Median reducer finds the middle value, optionally using sample and area/length weights.

operators.reducer.Mode(*[, weighted, ...])

The Mode reducer selects the most frequent value, optionally counting by sample/area weights.

operators.reducer.Minimum([neighborhood])

The Minimum reducer returns the smallest value in each group.

operators.reducer.Maximum([neighborhood])

The Maximum reducer returns the largest value in each group.

operators.reducer.Range([neighborhood])

The Range reducer subtracts the smallest value from the largest in each group.

operators.reducer.Count([neighborhood])

The Count reducer counts observations, or adds their sample and area/length weights when supplied.

operators.reducer.RootMeanSquare([neighborhood])

The RootMeanSquare reducer averages squared values, then takes the square root.

operators.reducer.StandardDeviation([...])

The StandardDeviation reducer measures the spread of values around their mean.

operators.reducer.AverageDistance([neighborhood])

The AverageDistance reducer averages distances from nearby observations to the output coordinate.

operators.reducer.AveragePairwiseDistance([...])

The AveragePairwiseDistance reducer averages distances between all pairs of nearby observations.

Error models and propagation#

ErrorMagnitude(kind[, value, ...])

Error magnitude, either constant or variable (i.e. heteroscedastic) with named predictors.

ErrorComponent(name, magnitude[, ...])

Error component describing both the error magnitude and its spatial autocorrelation.

ErrorStructure(components, *[, ...])

Error structure, a sum of independent error components of varying magnitude and autocorrelation.

ErrorStructure.estimate(error_proxy, *[, ...])

Estimate error structure from an error proxy variable.

PropagationSummary(*, estimate, mean, std, ...)

Propagation summary that stores propagated uncertainty descriptors, whether obtained analytically or numerically.

uncertainty.propagate(operator[, data, ...])

Use observation errors for fitting and propagate them through an operator or spatial operation.

uncertainty.random_field(error_structure[, ...])

Generate random correlated error fields.

Multiprocessing#

Pass a MultiprocConfig as mp_config to supported methods for chunked execution on GeoUtils objects. See Multiprocessing configuration for configuration and custom block examples.

Configuration and clusters#

Use ClusterGenerator to choose a BasicCluster (sequential) or MpCluster (parallel).

multiproc.MultiprocConfig(chunks[, outfile, ...])

Configuration class for handling multiprocessing parameters in raster and point cloud processing.

multiproc.ClusterGenerator(name[, nb_workers])

multiproc.BasicCluster()

multiproc.MpCluster([conf, start_method])

Block functions#

multiproc.map_overlap(func, raster_path, ...)

Apply a function to raster blocks in parallel and save the result to a file.

multiproc.map_collect(func, raster_path, ...)

Apply a function to raster blocks in parallel and collect the results into a list.

Profiling#

Measure function runtime and memory, or collect decorated workflow calls. See Profiling for examples.

profiler

Measure function runtime and memory for local inspection and controlled benchmarks.

profiler.profile_call(func, *args[, ...])

Profile one function call with the appropriate GeoUtils profiling backends.

profiler.profile(name[, interval, memprof, ...])

Geoutils profiling decorator

profiler.ProfileMetrics(runtime_s, ...[, ...])

Normalized profiling metrics for one measured call.

profiler.Profiler()

Main profiler class for Geoutils