focalpy#
Toolkit for focal site multi-scale studies in Python.

(C) OpenStreetMap contributors, tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France
Overview#
Compute multi-scale spatial predictors:
import geopandas as gpd
from sklearn import ensemble
import focalpy
species_richness_filepath = "data/bird-richness.gpkg"
buildings_gdf_filepath = "data/buildings.gpkg"
tree_canopy_filepath = "data/tree-canopy.tif"
buffer_dists = [100, 250, 500]
species_gdf = gpd.read_file(species_richness_filepath)
y_col = "n.species" # species richness
fa = focalpy.FocalAnalysis(
[buildings_gdf_filepath, tree_canopy_filepath],
species_gdf,
buffer_dists,
[
"compute_vector_features",
"compute_raster_features",
],
feature_col_prefixes=["building", "tree"],
feature_methods_args={
"compute_vector_features": [{"area": "sum"}],
},
feature_methods_kwargs={
"compute_raster_features": {"stats": "sum"},
},
)
fa.features_df.head()
| building_area_sum_100 | building_area_sum_250 | building_area_sum_500 | tree_sum_100 | tree_sum_250 | tree_sum_500 | |
|---|---|---|---|---|---|---|
| 0 | 13069.227511 | 60218.251616 | 207368.012055 | 2016.0 | 14875.0 | 61452.0 |
| 1 | 7439.635337 | 41645.546860 | 131432.855040 | 1331.0 | 15760.0 | 84520.0 |
| 2 | 8962.495280 | 54251.129360 | 146157.281494 | 2385.0 | 16725.0 | 79704.0 |
| 3 | 8001.653873 | 29735.393494 | 102803.559740 | 2512.0 | 22892.0 | 95945.0 |
| 4 | 10447.531020 | 39405.263870 | 110922.947475 | 3886.0 | 19860.0 | 99111.0 |
# target area (for region-wide prediction/extrapolation)
study_area_filepath = "data/study-area.gpkg"
grid_res = 500
# train a model and spatially extrapolate it
model = ensemble.GradientBoostingRegressor().fit(fa.features_df, species_gdf[y_col])
pred_da = fa.predict_raster(model, study_area_filepath, grid_res, pred_label=y_col)
# plot the field data and predicted raster
focalpy.plot_raster_and_gdf(
pred_da, species_gdf, species_gdf[y_col], cmap="BuGn", attribution=False
)

(C) OpenStreetMap contributors, tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France
See the user guide and the API documentation for more details on the features of focalpy.
Installation#
Like many other geospatial Python packages, focalpy requires many base C libraries that cannot be installed with pip. Accordingly, the best way to install focalpy is to use conda/mamba, i.e., in a given conda environment, run:
# or mamba install -c conda-forge geopandas
conda install -c conda-forge geopandas
Within the same conda environment, you can then install focalpy using pip:
pip install https://github.com/martibosch/focalpy/archive/main.zip
Acknowledgements#
This package was created with the martibosch/cookiecutter-geopy-package project template.
References#
Huais, P. Y. (2024). Multilandr: An r package for multi-scale landscape analysis. Landscape Ecology, 39(8), 140.