### Zonal Grid Analysis Initialization Source: https://github.com/martibosch/pylandstats/blob/main/docs/zonal.md Initializes the zonal grid analysis by defining how the landscape data will be separated into zones. You can specify the number of columns/rows or the width/height of each zone. ```APIDOC ## __init__ Zonal Grid Analysis ### Description Initializes the zonal grid analysis. This involves defining the parameters for separating the landscape data into zones, including dimensions and offset. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **landscape_filepath** (str, file-like object, pathlib.Path object) - Required - The path to the landscape data. * **num_zone_cols** (int) - Optional - The number of zone columns. * **num_zone_rows** (int) - Optional - The number of zone rows. * **zone_width** (numeric) - Optional - The width of each zone. * **zone_height** (numeric) - Optional - The height of each zone. * **offset** (str) - Optional - Offset rule for the grid ('center' or default top-left). * **neighborhood_rule** ({'8', '4'}) - Optional - Neighborhood rule for patch adjacencies ('8' for queen's, '4' for rook's). ### Request Example ```python # Example initialization from pylandstats import ZonalGrid zonal_grid = ZonalGrid( landscape_filepath='path/to/your/landscape.tif', num_zone_cols=10, num_zone_rows=10, neighborhood_rule='8' ) ``` ### Response #### Success Response (200) Initializes the ZonalGrid object. #### Response Example ```python # No direct response, but the ZonalGrid object is created. ``` ``` -------------------------------- ### SpatioTemporalZonalGridAnalysis Class Source: https://github.com/martibosch/pylandstats/blob/main/docs/spatiotemporal-zonal.md Initializes a spatio-temporal zonal analysis around a grid. ```APIDOC ## class pylandstats.SpatioTemporalZonalGridAnalysis ### Description Spatio-temporal zonal analysis around a grid. ### Method *Constructor* ### Endpoint *N/A - Class definition* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* #### Constructor Parameters - **landscape_filepaths** (*list-like*) - Filepaths to landscape rasters. - **num_zone_cols** (*int*, optional) - Number of columns for the analysis grid. - **num_zone_rows** (*int*, optional) - Number of rows for the analysis grid. - **zone_width** (*float*, optional) - Width of each zone in the grid. - **zone_height** (*float*, optional) - Height of each zone in the grid. - **offset** (*tuple*, optional) - Offset for the grid origin (x, y). - **dates** (*list-like*, optional) - Dates corresponding to each landscape filepath. - **neighborhood_rule** (*str*, optional) - Rule for neighborhood analysis (e.g., 'rook', 'queen'). ### Request Example *N/A - Class instantiation example* ### Response #### Success Response (200) *Instance of SpatioTemporalZonalGridAnalysis* #### Response Example *N/A - Example depends on input parameters* ``` -------------------------------- ### ZonalAnalysis Initialization Source: https://github.com/martibosch/pylandstats/blob/main/docs/zonal.md Initializes the ZonalAnalysis object with landscape data and zone definitions. It allows specifying zone index, nodata values, and neighborhood rules. ```APIDOC ## ZonalAnalysis ### Description Initializes the zonal analysis with landscape data and zone definitions. ### Method `__init__` ### Parameters #### Path Parameters - **landscape_filepath** (str | file-like object | pathlib.Path object) - Required - Path to the landscape data. - **zones** (geopandas.GeoSeries | geopandas.GeoDataFrame | list-like | str | file-like object | pathlib.Path object | numpy.ndarray) - Required - Zone definitions. #### Query Parameters - **zone_index** (list-like | str) - Optional - Index to identify zones. - **zone_nodata** (numeric) - Optional - Default 0 - Value representing no data in zones. - **neighborhood_rule** ({'8', '4'}) - Optional - Neighborhood rule ('8' or '4'). ### Request Example ```python from pylandstats import ZonalAnalysis zonal_analysis = ZonalAnalysis( landscape_filepath='path/to/landscape.tif', zones='path/to/zones.shp' ) ``` ### Response #### Success Response (200) - **None** - The constructor does not return a value, it initializes the object. #### Response Example *N/A - Constructor does not return a value.* ``` -------------------------------- ### Buffer Analysis with Pylandstats (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Performs buffer analysis around specified points in a landscape file. It calculates landscape metrics within multiple buffer distances. Requires a landscape file, a shapefile of points, and the pylandstats library. ```python import pylandstats as pls buffer_points_file = 'sampling_points.shp' landscape_file = 'landscape.tif' # Create buffer analysis with custom polygons ba = pls.BufferAnalysis( landscape_file, buffer_points_file, buffer_dists=[100, 500, 1000] # multiple buffer distances ) buffer_metrics_df = ba.compute_landscape_metrics_df( metrics=['total_area', 'shannon_diversity_index'] ) print(buffer_metrics_df) ``` -------------------------------- ### Instantiate Landscape from NumPy Array using PyLandStats Source: https://context7.com/martibosch/pylandstats/llms.txt Creates a Landscape object from an in-memory NumPy array, requiring explicit specification of resolution and nodata values. This method allows for flexible landscape creation from array data. It also supports choosing different neighborhood rules (e.g., 4 or 8) for patch computation. ```python import numpy as np import pylandstats as pls # Create landscape array (categorical land cover classes) # 1 = Forest, 2 = Agriculture, 3 = Urban, 0 = NoData landscape_arr = np.array([ [1, 1, 1, 2, 2, 2, 3, 3], [1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 2, 2, 2, 2, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3], [1, 1, 1, 1, 2, 2, 2, 3], [1, 1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 1, 2] ]) # Resolution must be provided for NumPy arrays ls = pls.Landscape(landscape_arr, res=(250, 250), nodata=0) # Use 4-neighborhood (rook's case) instead of default 8-neighborhood ls_rook = pls.Landscape(landscape_arr, res=(250, 250), neighborhood_rule='4') print(f"Number of patches (8-neighbor): {ls.number_of_patches()}") print(f"Number of patches (4-neighbor): {ls_rook.number_of_patches()}") # Expected output: # Number of patches (8-neighbor): 3 # Number of patches (4-neighbor): 5 ``` -------------------------------- ### Initialize Landscape Class in PyLandStats Source: https://github.com/martibosch/pylandstats/blob/main/docs/landscape.md Demonstrates how to instantiate the core Landscape class in PyLandStats. This class is used to compute landscape metrics. It accepts various input formats for the landscape raster and allows customization of nodata values and neighborhood rules. ```python from pylandstats import Landscape # Example with a numpy array lc = Landscape(landscape_array, res=(10, 10), nodata=0, neighborhood_rule='8') # Example with a file path lc_file = Landscape('path/to/your/raster.tif') ``` -------------------------------- ### Spatiotemporal Analysis of Landscape Changes Source: https://context7.com/martibosch/pylandstats/llms.txt Analyzes landscape changes over multiple time snapshots using a list of raster files. It computes both class-level and landscape-level metrics across different dates and visualizes temporal trends. ```python import pylandstats as pls import matplotlib.pyplot as plt # Create spatiotemporal analysis from multiple raster files landscape_files = [ 'landscape_1990.tif', 'landscape_2000.tif', 'landscape_2010.tif', 'landscape_2020.tif' ] dates = ['1990', '2000', '2010', '2020'] sta = pls.SpatioTemporalAnalysis(landscape_files, dates=dates) # Compute class metrics across all time periods class_metrics_df = sta.compute_class_metrics_df( metrics=['total_area', 'number_of_patches', 'largest_patch_index'], classes=[11, 21, 31] # Forest, Agriculture, Urban ) print(class_metrics_df.head(10)) # Compute landscape-level metrics over time landscape_metrics_df = sta.compute_landscape_metrics_df( metrics=['contagion', 'shannon_diversity_index', 'effective_mesh_size'] ) print(landscape_metrics_df) # Plot metric evolution over time fig, ax = plt.subplots(figsize=(10, 6)) sta.plot_metric('total_area', class_val=11, ax=ax) ax.set_title('Forest Area Change (1990-2020)') ax.set_ylabel('Total Area (hectares)') ax.set_xlabel('Year') plt.grid(True, alpha=0.3) plt.savefig('forest_temporal.png', dpi=300) # Plot multiple classes on same axis fig, ax = plt.subplots(figsize=(12, 7)) for class_val, label, color in [(11, 'Forest', 'green'), (21, 'Agriculture', 'gold'), (31, 'Urban', 'red')]: sta.plot_metric('proportion_of_landscape', class_val=class_val, ax=ax, plot_kwargs={'label': label, 'color': color, 'linewidth': 2}) ax.legend() ax.set_title('Land Cover Proportions Over Time') ax.set_ylabel('Proportion of Landscape (%)') plt.savefig('multiclass_temporal.png', dpi=300) # Visualize all landscape snapshots in grid fig = sta.plot_landscapes( legend=True, subplots_kwargs={'figsize': (16, 4), 'ncols': 4} ) fig.suptitle('Landscape Evolution 1990-2020', fontsize=16, y=1.02) plt.savefig('landscape_snapshots.png', dpi=300, bbox_inches='tight') ``` -------------------------------- ### Instantiate Landscape from GeoTIFF using PyLandStats Source: https://context7.com/martibosch/pylandstats/llms.txt Creates a Landscape object from a GeoTIFF raster file. It automatically extracts metadata like resolution, transform, and Coordinate Reference System (CRS). The resulting object provides access to landscape properties such as cell dimensions, area, identified classes, and neighborhood rules. ```python import pylandstats as pls # Load landscape from GeoTIFF file # Automatically extracts resolution, transform, and CRS ls = pls.Landscape('land_cover_2020.tif') # Access landscape properties print(f"Cell width: {ls.cell_width} meters") print(f"Cell height: {ls.cell_height} meters") print(f"Cell area: {ls.cell_area} square meters") print(f"Classes present: {ls.classes}") print(f"Neighborhood rule: {ls.neighborhood_rule}") # Expected output: # Cell width: 30.0 meters # Cell height: 30.0 meters # Cell area: 900.0 square meters # Classes present: [11 21 31 41 42 43 52 71 81 82 90 95] # Neighborhood rule: 8 ``` -------------------------------- ### Zonal Grid Analysis with Pylandstats (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Divides a landscape into a regular grid and computes landscape and class metrics for each grid cell. It supports visualization of metrics using GeoDataFrames and exporting results to shapefiles. Requires a landscape file, matplotlib, and pylandstats. ```python import pylandstats as pls import matplotlib.pyplot as plt landscape_file = 'landscape.tif' # Create regular grid with 1000m × 1000m cells zga = pls.ZonalGridAnalysis(landscape_file, num_zone_rows=10, num_zone_cols=10) # Compute landscape metrics for each grid cell grid_metrics_df = zga.compute_landscape_metrics_df( metrics=['proportion_of_landscape', 'shannon_diversity_index', 'contagion'] ) print(grid_metrics_df.head()) # proportion_of_landscape shannon_diversity_index contagion # 0 100.00 1.456 62.34 # 1 100.00 1.678 58.92 # 2 100.00 1.234 71.23 # 3 100.00 1.823 55.67 # 4 100.00 1.567 64.45 # Compute class metrics for each grid cell grid_class_df = zga.compute_class_metrics_df( metrics=['proportion_of_landscape', 'largest_patch_index'], classes=[11, 21, 31], fillna=0 ) # Get zonal statistics as GeoDataFrame with grid geometries grid_gdf = zga.compute_zonal_statistics_gdf( metrics=['shannon_diversity_index', 'contagion'] ) # Visualize grid cells colored by metric values fig, axes = plt.subplots(1, 2, figsize=(16, 7)) grid_gdf.plot(column='shannon_diversity_index', cmap='viridis', legend=True, ax=axes[0], edgecolor='black', linewidth=0.5) axes[0].set_title('Shannon Diversity Index per Grid Cell') axes[0].set_xlabel('X Coordinate') axes[0].set_ylabel('Y Coordinate') grid_gdf.plot(column='contagion', cmap='RdYlGn', legend=True, ax=axes[1], edgecolor='black', linewidth=0.5) axes[1].set_title('Contagion per Grid Cell') axes[1].set_xlabel('X Coordinate') plt.tight_layout() plt.savefig('grid_metrics_map.png', dpi=300, bbox_inches='tight') # Export grid results to shapefile grid_gdf.to_file('grid_metrics.shp') ``` -------------------------------- ### Generate and Plot Clustergram for Optimal Cluster Number Identification Source: https://context7.com/martibosch/pylandstats/llms.txt This code snippet demonstrates how to generate a clustergram using PCA and StandardScaler to identify the optimal number of clusters for landscape data. It then plots the clustergram and saves it as an image. Finally, it performs K-means clustering with the chosen number of clusters and visualizes the results in PCA space. ```python import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.impute import SimpleImputer import pandas as pd # Assume 'ssa' and 'landscapes' are already defined and loaded # For demonstration, let's mock them: sclass ssa: metrics_df = pd.DataFrame({'metric1': [1, 2, 3, 4, 5], 'metric2': [5, 4, 3, 2, 1]}) landscapes = ['land1', 'land2', 'land3', 'land4', 'land5'] def get_cgram(k_range, decomposer, decomposer_kwargs, preprocessor, method): # Mock clustergram object class MockClustergram: def plot(self, ax): ax.text(0.5, 0.5, 'Mock Clustergram Plot') return MockClustergram() # Generate clustergram to identify optimal number of clusters cgram = ssa.get_cgram( k_range=range(2, 11), decomposer=PCA, decomposer_kwargs={'n_components': 5}, preprocessor=StandardScaler, method='ward' # hierarchical clustering method ) # Plot clustergram fig, ax = plt.subplots(figsize=(12, 8)) cgram.plot(ax=ax) ax.set_title('Clustergram: Identifying Optimal Landscape Clusters') # plt.savefig('clustergram.png', dpi=300, bbox_inches='tight') # Commented out for non-file output # Perform clustering with chosen k # Standardize and decompose metrics preprocessor = StandardScaler() pca = PCA(n_components=5) imputer = SimpleImputer(strategy='median') # Get metrics matrix metrics_matrix = ssa.metrics_df.values metrics_imputed = imputer.fit_transform(metrics_matrix) metrics_scaled = preprocessor.fit_transform(metrics_imputed) metrics_pca = pca.fit_transform(metrics_scaled) # Apply K-means clustering kmeans = KMeans(n_clusters=4, random_state=42) cluster_labels = kmeans.fit_predict(metrics_pca) # Add cluster labels to results results_df = pd.DataFrame({ 'landscape_id': range(len(landscapes)), 'cluster': cluster_labels, 'PC1': metrics_pca[:, 0], 'PC2': metrics_pca[:, 1] }) # Visualize clusters in PCA space fig, ax = plt.subplots(figsize=(10, 8)) scatter = ax.scatter(results_df['PC1'], results_df['PC2'], c=results_df['cluster'], cmap='viridis', s=100, alpha=0.7, edgecolors='black', linewidth=0.5) aa, metrics=['total_edge', 'edge_density', 'core_area', 'total_core_area'], classes=[11, 21], metrics_kwargs={ 'total_edge': {'count_boundary': False}, 'edge_density': {'count_boundary': False}, 'core_area': {'edge_depth': 2, 'count_boundary': True}, 'total_core_area': {'edge_depth': 2, 'count_boundary': True} }, fillna=0 # Replace NaN with 0 for missing classes ) print(class_df) # Custom parameters in spatiotemporal analysis sta = pls.SpatioTemporalAnalysis( ['ls_2000.tif', 'ls_2010.tif', 'ls_2020.tif'], dates=['2000', '2010', '2020'] ) temporal_class_df = sta.compute_class_metrics_df( metrics=['total_core_area', 'core_area_proportion_of_landscape'], classes=[11], metrics_kwargs={ 'total_core_area': {'edge_depth': 3, 'count_boundary': False}, 'core_area_proportion_of_landscape': {'edge_depth': 3} } ) print(temporal_class_df) ``` -------------------------------- ### Compute Zonal Landscape Metrics (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Computes landscape metrics for predefined zones within a landscape file. It calculates metrics like total area, number of patches, Shannon diversity index, and contagion for each zone. Requires a landscape file and the pylandstats library. ```python import pylandstats as pls import geopandas as gpd from shapely.geometry import box landscape_file = 'landscape.tif' # Compute class metrics for each zone zonal_class_df = za.compute_class_metrics_df( metrics=['total_area', 'proportion_of_landscape', 'patch_density'], classes=[11, 21, 31] ) print(zonal_class_df.head(10)) # total_area proportion_of_landscape patch_density # zone_name class_val # North Region 11 456.78 37.01 2.345 # 21 678.90 54.98 4.567 # 31 98.88 8.01 1.234 # South Region 11 789.12 37.61 3.456 # Create zonal analysis with custom polygons zones_gdf = gpd.GeoDataFrame({ 'zone_id': ['A', 'B', 'C'], 'geometry': [ box(0, 0, 1000, 1000), box(1000, 0, 2000, 1000), box(0, 1000, 1000, 2000) ] }, crs='EPSG:32632') za_custom = pls.ZonalAnalysis(landscape_file, zones_gdf, zone_index='zone_id') # Compute zonal statistics as GeoDataFrame (includes geometry) zonal_stats_gdf = za_custom.compute_zonal_statistics_gdf( metrics=['contagion', 'effective_mesh_size'], class_val=None # landscape level ) print(zonal_stats_gdf) # zone_id contagion effective_mesh_size geometry # 0 A 64.23 45.67 POLYGON ((0 0, 1000 0, 1000 ... # 1 B 61.45 52.34 POLYGON ((1000 0, 2000 0, 20... # 2 C 67.89 38.91 POLYGON ((0 1000, 1000 1000,... # Save zonal statistics as shapefile zonal_stats_gdf.to_file('zonal_metrics.shp') # Compute landscape metrics for each zone zonal_landscape_df = za.compute_landscape_metrics_df( metrics=['total_area', 'number_of_patches', 'shannon_diversity_index', 'contagion'] ) print(zonal_landscape_df) # total_area number_of_patches shannon_diversity_index contagion # zone_name # North Region 1234.56 145 1.834 62.45 # South Region 2098.34 234 1.923 58.67 # East Region 1543.21 189 1.756 65.23 # West Region 1876.45 198 1.812 61.89 ``` -------------------------------- ### Compute Patch-Level Metrics with PyLandStats Source: https://context7.com/martibosch/pylandstats/llms.txt Calculates various landscape metrics at the patch level, returning results as pandas DataFrames or Series. Supported metrics include area, perimeter, shape index, fractal dimension, perimeter-area ratio, core area statistics, and proximity measures. Metrics can be computed for all patches or specific classes, with options for units (e.g., hectares) and edge effect considerations. ```python import pylandstats as pls ls = pls.Landscape('landscape.tif') # Compute area for all patches (returns DataFrame with all classes) area_df = ls.area(hectares=True) print(area_df.head()) # class_val area # 0 11 45.6234 # 1 11 23.8901 # 2 21 102.3456 # 3 21 67.4532 # 4 31 89.2341 # Compute area for specific class only (returns Series) forest_areas = ls.area(class_val=11, hectares=True) print(forest_areas.head()) # 0 45.6234 # 1 23.8901 # 2 12.3456 # 3 8.7654 # 4 34.5678 # Compute perimeter (in meters) perimeter_df = ls.perimeter() # Shape complexity metrics shape_index_df = ls.shape_index() fractal_dim_df = ls.fractal_dimension() para_df = ls.perimeter_area_ratio(hectares=True) # Core area metrics (excluding edge effects) core_area_df = ls.core_area(hectares=True, edge_depth=1, count_boundary=False) n_core_areas_df = ls.number_of_core_areas(edge_depth=1) core_area_index_df = ls.core_area_index(edge_depth=1) # Proximity metrics enn_df = ls.euclidean_nearest_neighbor(class_val=11) # All metrics return pandas objects with proper indexing print(f"Shape: {area_df.shape}") print(f"Index name: {area_df.index.name}") # Shape: (145, 2) # Index name: patch_id ``` -------------------------------- ### Generate Landscape-Level Metrics DataFrame (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Creates a pandas DataFrame containing a single row with all computed landscape-level metrics. This provides a consolidated summary of the entire landscape's characteristics. Requires pylandstats and pandas libraries. ```python import pylandstats as pls import pandas as pd ls = pls.Landscape('landscape.tif') # Landscape-level: Single row × all landscape metrics landscape_df = ls.compute_landscape_metrics_df() print(landscape_df) ``` -------------------------------- ### Spatiotemporal Zonal Analysis with Pylandstats Source: https://context7.com/martibosch/pylandstats/llms.txt Performs spatiotemporal zonal analysis using multiple landscape files and a zones file. It computes class and landscape metrics for each zone and date, allowing for temporal trend analysis and comparison across regions. ```python import pylandstats as pls import matplotlib.pyplot as plt # Multiple landscape files at different dates landscape_files = [ 'landscape_2000.tif', 'landscape_2010.tif', 'landscape_2020.tif' ] dates = ['2000', '2010', '2020'] zones_file = 'regions.shp' # Create spatiotemporal zonal analysis stza = pls.SpatioTemporalZonalAnalysis( landscape_files, zones_file, dates=dates, zone_index='region_name' ) # Compute class metrics: zone × date × class × metrics stza_class_df = stza.compute_class_metrics_df( metrics=['total_area', 'number_of_patches'], classes=[11, 21, 31] ) print(stza_class_df.head(15)) # Compute landscape metrics: zone × date × metrics stza_landscape_df = stza.compute_landscape_metrics_df( metrics=['shannon_diversity_index', 'contagion', 'effective_mesh_size'] ) print(stza_landscape_df) # Plot temporal trends for specific zone region_a_data = stza_landscape_df.loc['Region A'] fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(region_a_data.index, region_a_data['shannon_diversity_index'], marker='o', linewidth=2, markersize=8, label='Shannon Diversity') ax.set_xlabel('Year') ax.set_ylabel('Shannon Diversity Index') ax.set_title('Landscape Diversity Change in Region A (2000-2020)') ax.grid(True, alpha=0.3) plt.savefig('region_a_diversity.png', dpi=300) # Compare multiple regions fig, ax = plt.subplots(figsize=(12, 7)) for region in ['Region A', 'Region B', 'Region C']: region_data = stza_landscape_df.loc[region] ax.plot(region_data.index, region_data['contagion'], marker='o', linewidth=2, label=region) ax.legend() ax.set_xlabel('Year') ax.set_ylabel('Contagion (%)') ax.set_title('Landscape Contagion Comparison Across Regions') ax.grid(True, alpha=0.3) plt.savefig('regions_comparison.png', dpi=300) ``` -------------------------------- ### Calculate Overall Landscape Metrics (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Computes aggregate landscape-level metrics without specifying a class, providing insights into the entire spatial configuration. Metrics include total area, number of patches, patch density, total edge, and edge density. Results can be in hectares. Requires a pylandstats Landscape object. ```python import pylandstats as pls ls = pls.Landscape('landscape.tif') # Overall landscape metrics (no class_val argument) total_landscape_area = ls.total_area(hectares=True) total_patches = ls.number_of_patches() overall_patch_density = ls.patch_density() total_landscape_edge = ls.total_edge() edge_dens_landscape = ls.edge_density() print(f"Landscape: {total_landscape_area:.0f} ha, {total_patches} patches") # Landscape: 3836 ha, 287 patches ``` -------------------------------- ### Spatial Signature Analysis with Pylandstats and Scikit-learn Source: https://context7.com/martibosch/pylandstats/llms.txt Performs machine learning-based pattern analysis to cluster landscapes by their metric signatures using Pylandstats for metric calculation and Scikit-learn for dimensionality reduction (PCA). It computes selected class and landscape metrics, then applies PCA for decomposition and analysis. ```python import pylandstats as pls from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer import matplotlib.pyplot as plt # Create multiple landscape objects for comparison landscape_files = [f'site_{i:03d}.tif' for i in range(1, 101)] landscapes = [pls.Landscape(f) for f in landscape_files] # Create spatial signature analysis with selected metrics ssa = pls.SpatialSignatureAnalysis( landscapes, class_metrics=['proportion_of_landscape', 'patch_density', 'largest_patch_index'], landscape_metrics=['shannon_diversity_index', 'contagion', 'effective_mesh_size'], classes=[11, 21, 31] # Forest, Agriculture, Urban ) # Decompose metrics matrix using PCA components_df, pca_model = ssa.decompose( decomposer=PCA, n_components=5, preprocessor=StandardScaler, imputer=SimpleImputer, imputer_kwargs={'strategy': 'median'} ) print(components_df.head()) # Get loading matrix to interpret components loadings_df = ssa.get_loading_df( pca_model, columns=[f'PC{i}' for i in range(1, 6)] ) print(loadings_df) ``` -------------------------------- ### Plot Cluster Landscapes Source: https://github.com/martibosch/pylandstats/blob/main/docs/spatial-signature-analysis.md Visualizes landscape samples colored by their assigned cluster. Allows customization of the number of landscapes per cluster, figure layout, and keyword arguments for various plotting elements. ```APIDOC ## plot_cluster_landscapes ### Description Scatterplot the landscape samples colored by their cluster. ### Method POST ### Endpoint /plot_cluster_landscapes ### Parameters #### Path Parameters None #### Query Parameters * **cgram** (Clustergram) - Required - Fitted clustergram object. * **n_clusters** (int) - Required - Number of clusters to use. * **n_cluster_landscapes** (int, optional, default 4) - Number of landscapes to plot for each cluster. Providing a value of None will plot all landscapes. * **n_cols** (int, optional, default 4) - Number of columns for the figure. * **sample_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. * **figure_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. * **subfigures_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. * **subplots_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. * **supylabel_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. * **plot_landscape_kwargs** (dict, optional) - Keyword arguments to be passed to pandas.DataFrame.sample, matplotlib.pyplot.figure, matplotlib.figure.Figure.subfigures, matplotlib.figure.SubFigure.subplots, matplotlib.figure.SubFigure.supylabel and pylandstats.Landscape.plot_landscape respectively. #### Request Body None ### Request Example None ### Response #### Success Response (200) * **fig** (matplotlib.figure.Figure) - The figure with its corresponding plots drawn into its axes. #### Response Example ```json { "fig": "" } ``` ``` -------------------------------- ### Compute Landscape Metrics DataFrame Source: https://github.com/martibosch/pylandstats/blob/main/docs/zonal.md Computes a DataFrame containing landscape-level metrics. This provides an overview of the entire landscape's characteristics. ```APIDOC ## compute_landscape_metrics_df Landscape Metrics DataFrame ### Description Computes the data frame of landscape-level metrics, which is indexed by the attribute value. This provides metrics for the entire landscape. ### Method `compute_landscape_metrics_df` ### Endpoint `compute_landscape_metrics_df()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **metrics** (list-like) - Optional - List of metric names to compute. If None, all landscape metrics are computed. * **metrics_kwargs** (dict) - Optional - Keyword arguments for metric computations. ### Request Example ```python # Example computation of landscape metrics landscape_metrics_df = zonal_grid.compute_landscape_metrics_df( metrics=['total_area_mosaic', 'largest_patch_index'] ) ``` ### Response #### Success Response (200) * **df** (pandas.DataFrame) - DataFrame with landscape-level metrics. #### Response Example ```python # Example DataFrame output # landscape_metrics_df.head() # Output would be a pandas DataFrame ``` ``` -------------------------------- ### Calculate Patch Shape and Connectivity Statistics by Class (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Computes distribution statistics for shape index and Euclidean Nearest Neighbor distance for patches of a specified class. These metrics help understand the complexity and spatial configuration of patches. Requires a pylandstats Landscape object. ```python import pylandstats as pls ls = pls.Landscape('landscape.tif') # Distribution statistics available for all patch-level metrics shape_mean = ls.shape_index_mn(class_val=11) shape_cv = ls.shape_index_cv(class_val=11) enn_mean = ls.euclidean_nearest_neighbor_mn(class_val=11) ``` -------------------------------- ### Generate Patch-Level Metrics DataFrame (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Creates a pandas DataFrame containing all computed patch-level metrics for every patch in the landscape. It can also be configured to compute only specific metrics or pass custom keyword arguments to metric functions. Requires pylandstats and pandas libraries. ```python import pylandstats as pls import pandas as pd ls = pls.Landscape('landscape.tif') # Patch-level: All patches × all patch metrics patch_df = ls.compute_patch_metrics_df() print(patch_df.head()) # class_val area perimeter perimeter_area_ratio shape_index ... # 0 11 45.62 2834.5 62.14 1.482 ... # 1 11 23.89 2145.2 89.81 1.752 ... # 2 21 102.35 5432.1 53.08 1.398 ... print(f"Shape: {patch_df.shape}") # Shape: (287, 9) # 287 patches × 9 patch metrics # Compute only specific metrics selected_patch_df = ls.compute_patch_metrics_df( metrics=['area', 'shape_index', 'core_area'] ) # Pass keyword arguments to metrics patch_df_custom = ls.compute_patch_metrics_df( metrics=['area', 'core_area'], metrics_kwargs={ 'area': {'hectares': False}, # area in square meters 'core_area': {'edge_depth': 2, 'count_boundary': True} } ) ``` -------------------------------- ### Calculate Number and Density of Patches by Class (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Calculates the total number of patches and the patch density for a given class. Patch density is expressed per 100 hectares. Requires a pylandstats Landscape object. ```python import pylandstats as pls ls = pls.Landscape('landscape.tif') # Number and density of patches n_patches = ls.number_of_patches(class_val=11) patch_dens = ls.patch_density(class_val=11) print(f"Forest patches: {n_patches}, Density: {patch_dens:.4f} per 100 ha") # Forest patches: 42, Density: 1.0957 per 100 ha ``` -------------------------------- ### Visualize Landscape Rasters with Matplotlib Source: https://context7.com/martibosch/pylandstats/llms.txt Plots landscape rasters using matplotlib, supporting basic plots with automatic colors and custom colormaps for specific classes. Legends can be included or excluded. ```python import pylandstats as pls import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap ls = pls.Landscape('landscape.tif') # Basic plot with automatic colors fig, ax = plt.subplots(figsize=(10, 8)) ls.plot_landscape(ax=ax, legend=True) ax.set_title('Land Cover Classification 2020') plt.tight_layout() plt.savefig('landscape_plot.png', dpi=300) # Custom colormap for specific classes # Classes: 11=Forest(green), 21=Agriculture(yellow), 31=Urban(red), 41=Water(blue) colors = ['#228B22', '#FFD700', '#FF0000', '#0000FF'] cmap = ListedColormap(colors) fig, ax = plt.subplots(figsize=(12, 10)) ls.plot_landscape(cmap=cmap, legend=True, ax=ax) ax.set_title('Custom Color Mapping') ax.set_xlabel('X Coordinate (m)') ax.set_ylabel('Y Coordinate (m)') plt.savefig('landscape_custom.png', dpi=300, bbox_inches='tight') # Plot without legend ls.plot_landscape(legend=False) ``` -------------------------------- ### Calculate Proportion of Landscape by Class (Python) Source: https://context7.com/martibosch/pylandstats/llms.txt Computes the proportion of the landscape occupied by a specified class. It takes a class value as input and returns the percentage of the landscape that class represents. Requires a pylandstats Landscape object. ```python import pylandstats as pls ls = pls.Landscape('landscape.tif') # Proportion of landscape occupied by class pland = ls.proportion_of_landscape(class_val=11) print(f"Forest covers {pland:.2f}% of landscape") # Forest covers 32.45% of landscape ``` -------------------------------- ### Compute Landscape Metrics with Python Source: https://context7.com/martibosch/pylandstats/llms.txt Calculates specified landscape metrics from a landscape raster file and returns them as a pandas DataFrame. This function allows for subsetting specific metrics for analysis. ```python import pylandstats as pls # Initialize Landscape object ls = pls.Landscape('landscape.tif') # Compute all landscape metrics landscape_df = ls.compute_landscape_metrics_df() print(f"Shape: {landscape_df.shape}") # Specify landscape metrics landscape_df_subset = ls.compute_landscape_metrics_df( metrics=['total_area', 'contagion', 'shannon_diversity_index'] ) print(landscape_df_subset) ```