Skip to content

GridFIA API

The GridFIA class is the primary interface for all GridFIA functionality. It provides methods for downloading species data, creating Zarr stores, calculating forest metrics, and generating visualizations.

Overview

GridFIA follows an API-first design pattern, providing a single clean interface that:

  • Downloads species biomass rasters from the FIA BIGMAP service
  • Converts GeoTIFF files to cloud-optimized Zarr arrays
  • Calculates diversity metrics (Shannon, Simpson, richness)
  • Generates publication-ready maps and visualizations

Quick Start

from gridfia import GridFIA

# Initialize the API
api = GridFIA()

# Download species data for a state
files = api.download_species(
    state="Montana",
    species_codes=["0202", "0122"],  # Douglas-fir, Ponderosa pine
    output_dir="downloads/montana"
)

# Create a Zarr store from downloaded data
zarr_path = api.create_zarr(
    input_dir="downloads/montana",
    output_path="data/montana.zarr"
)

# Calculate forest metrics
results = api.calculate_metrics(
    zarr_path,
    calculations=["species_richness", "shannon_diversity"]
)

# Create visualization maps
maps = api.create_maps(
    zarr_path,
    map_type="diversity",
    state="MT"
)

Class Reference

gridfia.api.GridFIA

GridFIA(config: Optional[Union[str, Path, GridFIASettings]] = None)

Main API interface for GridFIA spatial forest analysis.

GridFIA provides spatial raster analysis of USDA Forest Service BIGMAP data, including species biomass mapping, diversity metrics, and visualization.

Part of the FIA Python Ecosystem - use with PyFIA for survey data, PyFVS for growth simulation, and AskFIA for AI-powered queries.

Examples

from gridfia import GridFIA api = GridFIA()

Download species data for North Carolina

api.download_species(state="NC", species_codes=["0131", "0068"])

Create zarr store from downloaded data

api.create_zarr("downloads/", "data/nc_forest.zarr")

Calculate forest metrics

results = api.calculate_metrics( ... "data/nc_forest.zarr", ... calculations=["species_richness", "shannon_diversity"] ... )

Create visualization

api.create_maps("data/nc_forest.zarr", map_type="diversity")

Initialize GridFIA API.

Parameters

config : str, Path, or GridFIASettings, optional Configuration file path or settings object. If None, uses default settings.

rest_client property

rest_client: BigMapRestClient

Lazy-load REST client for FIA BIGMAP service (thread-safe).

processor property

processor: ForestMetricsProcessor

Lazy-load forest metrics processor (thread-safe).

list_species

list_species() -> List[SpeciesInfo]

List all available tree species from FIA BIGMAP service.

Returns

List[SpeciesInfo] List of available species with codes and names.

Examples

api = GridFIA() species = api.list_species() print(f"Found {len(species)} species") for s in species[:5]: ... print(f"{s.species_code}: {s.common_name}")

download_species

download_species(output_dir: Union[str, Path] = 'downloads', species_codes: Optional[List[str]] = None, state: Optional[str] = None, county: Optional[str] = None, bbox: Optional[Tuple[float, float, float, float]] = None, location_config: Optional[Union[str, Path]] = None, crs: str = '102100') -> List[Path]

Download species data from FIA BIGMAP service.

Parameters

output_dir : str or Path, default="downloads" Directory to save downloaded files. species_codes : List[str], optional Specific species codes to download. If None, downloads all. state : str, optional State name or abbreviation. county : str, optional County name (requires state). bbox : Tuple[float, float, float, float], optional Custom bounding box (xmin, ymin, xmax, ymax). location_config : str or Path, optional Path to location configuration file. crs : str, default="102100" Coordinate reference system for bbox.

Returns

List[Path] Paths to downloaded files.

Examples

api = GridFIA()

Download for entire state

files = api.download_species(state="Montana", species_codes=["0202"])

Download for specific county

files = api.download_species( ... state="Texas", ... county="Harris", ... species_codes=["0131", "0068"] ... )

Download with custom bbox

files = api.download_species( ... bbox=(-104, 44, -104.5, 44.5), ... crs="4326" ... )

create_zarr

create_zarr(input_dir: Union[str, Path], output_path: Union[str, Path], species_codes: Optional[List[str]] = None, chunk_size: Tuple[int, int, int] = (1, 1000, 1000), compression: str = 'lz4', compression_level: int = 5, include_total: bool = True) -> Path

Create a Zarr store from GeoTIFF files.

Parameters

input_dir : str or Path Directory containing GeoTIFF files. output_path : str or Path Output path for Zarr store. species_codes : List[str], optional Specific species codes to include. chunk_size : Tuple[int, int, int], default=(1, 1000, 1000) Chunk dimensions (species, height, width). compression : str, default="lz4" Compression algorithm. compression_level : int, default=5 Compression level (1-9). include_total : bool, default=True Whether to include or calculate total biomass.

Returns

Path Path to created Zarr store.

Examples

api = GridFIA() zarr_path = api.create_zarr( ... "downloads/montana_species/", ... "data/montana.zarr", ... chunk_size=(1, 2000, 2000) ... ) print(f"Created Zarr store at {zarr_path}")

calculate_metrics

calculate_metrics(zarr_path: Union[str, Path], calculations: Optional[List[str]] = None, output_dir: Optional[Union[str, Path]] = None, config: Optional[Union[str, Path, GridFIASettings]] = None) -> List[CalculationResult]

Calculate forest metrics from Zarr data.

Parameters

zarr_path : str or Path Path to Zarr store containing biomass data. calculations : List[str], optional Specific calculations to run. If None, uses config or defaults. output_dir : str or Path, optional Output directory for results. config : str, Path, or GridFIASettings, optional Configuration to use for calculations.

Returns

List[CalculationResult] Results from each calculation.

Examples

api = GridFIA() results = api.calculate_metrics( ... "data/forest.zarr", ... calculations=["species_richness", "shannon_diversity", "total_biomass"] ... ) for r in results: ... print(f"{r.name}: {r.output_path}") ... print(f" Stats: {r.statistics}")

create_maps

create_maps(zarr_path: Union[str, Path], map_type: str = 'species', species: Optional[List[str]] = None, output_dir: Union[str, Path] = 'maps', format: str = 'png', dpi: int = 300, cmap: Optional[str] = None, show_all: bool = False, state: Optional[str] = None, basemap: Optional[str] = None) -> List[Path]

Create maps from Zarr data.

Parameters

zarr_path : str or Path Path to Zarr store. map_type : str, default="species" Type of map: "species", "diversity", "richness", "comparison". species : List[str], optional Species codes for species/comparison maps. output_dir : str or Path, default="maps" Output directory for maps. format : str, default="png" Output format. dpi : int, default=300 Output resolution. cmap : str, optional Colormap name. show_all : bool, default=False Create maps for all species. state : str, optional State boundary to overlay. basemap : str, optional Basemap provider.

Returns

List[Path] Paths to created map files.

Examples

api = GridFIA()

Create species map

maps = api.create_maps( ... "data/forest.zarr", ... map_type="species", ... species=["0202"], ... state="MT" ... )

Create diversity maps

maps = api.create_maps( ... "data/forest.zarr", ... map_type="diversity" ... )

Create comparison map

maps = api.create_maps( ... "data/forest.zarr", ... map_type="comparison", ... species=["0202", "0122", "0116"] ... )

get_location_config

get_location_config(state: Optional[str] = None, county: Optional[str] = None, bbox: Optional[Tuple[float, float, float, float]] = None, crs: str = 'EPSG:4326', output_path: Optional[Union[str, Path]] = None) -> LocationConfig

Create or retrieve location configuration.

Parameters

state : str, optional State name or abbreviation. county : str, optional County name (requires state). bbox : Tuple[float, float, float, float], optional Custom bounding box. crs : str, default="EPSG:4326" CRS for custom bbox. output_path : str or Path, optional Path to save configuration.

Returns

LocationConfig Location configuration object.

Examples

api = GridFIA()

Get state configuration

config = api.get_location_config(state="Montana") print(f"Bbox: {config.web_mercator_bbox}")

Get county configuration

config = api.get_location_config(state="Texas", county="Harris")

Custom bbox configuration

config = api.get_location_config( ... bbox=(-104, 44, -104.5, 44.5), ... crs="EPSG:4326" ... )

list_calculations

list_calculations() -> List[str]

List all available calculations.

Returns

List[str] Names of available calculations.

Examples

api = GridFIA() calcs = api.list_calculations() print(f"Available calculations: {calcs}")

validate_zarr

validate_zarr(zarr_path: Union[str, Path]) -> Dict[str, Any]

Validate a Zarr store and return metadata.

Parameters

zarr_path : str or Path Path to Zarr store.

Returns

Dict[str, Any] Zarr store metadata including shape, species, chunks, etc.

Examples

api = GridFIA() info = api.validate_zarr("data/forest.zarr") print(f"Shape: {info['shape']}") print(f"Species: {info['num_species']}")

Method Details

Downloading Species Data

The download_species method supports multiple ways to specify the geographic extent:

# Download all species for an entire state
files = api.download_species(
    state="California",
    output_dir="data/california"
)

# Download specific species
files = api.download_species(
    state="Oregon",
    species_codes=["0202", "0122", "0015"],
    output_dir="data/oregon"
)
# Download for a specific county
files = api.download_species(
    state="North Carolina",
    county="Wake",
    species_codes=["0131", "0068"],
    output_dir="data/wake_county"
)
# Download for a custom bounding box (WGS84)
files = api.download_species(
    bbox=(-123.5, 45.0, -122.0, 46.5),
    crs="4326",
    output_dir="data/custom_region"
)
# Use a pre-configured location
files = api.download_species(
    location_config="config/montana_study_area.yaml",
    output_dir="data/study_area"
)

Working with Zarr Stores

The create_zarr method converts GeoTIFF files to cloud-optimized Zarr arrays:

# Basic usage
zarr_path = api.create_zarr(
    input_dir="downloads/",
    output_path="data/forest.zarr"
)

# With custom chunking for large datasets
zarr_path = api.create_zarr(
    input_dir="downloads/",
    output_path="data/forest.zarr",
    chunk_size=(1, 2000, 2000),  # Larger chunks for faster reads
    compression="zstd",
    compression_level=3
)

# Validate the created store
info = api.validate_zarr(zarr_path)
print(f"Shape: {info['shape']}")
print(f"Species count: {info['num_species']}")
print(f"CRS: {info['crs']}")

Calculating Metrics

GridFIA provides 15+ forest metrics through the calculation registry:

# List all available calculations
calcs = api.list_calculations()
print(f"Available: {calcs}")
# ['species_richness', 'shannon_diversity', 'simpson_diversity',
#  'evenness', 'total_biomass', 'dominant_species', ...]

# Run specific calculations
results = api.calculate_metrics(
    zarr_path,
    calculations=["species_richness", "shannon_diversity", "total_biomass"],
    output_dir="output/metrics"
)

# Process results
for result in results:
    print(f"{result.name}: {result.output_path}")

Creating Visualizations

Generate publication-ready maps with various options:

# Species biomass map
maps = api.create_maps(
    zarr_path,
    map_type="species",
    species=["0202"],
    state="MT",
    dpi=300
)

# Diversity map with basemap
maps = api.create_maps(
    zarr_path,
    map_type="diversity",
    state="MT",
    basemap="CartoDB.Positron"
)

# Species comparison (side-by-side)
maps = api.create_maps(
    zarr_path,
    map_type="comparison",
    species=["0202", "0122", "0116"]
)

# All species in store
maps = api.create_maps(
    zarr_path,
    map_type="species",
    show_all=True,
    output_dir="maps/all_species"
)

Configuration

The GridFIA class accepts an optional configuration:

from gridfia import GridFIA, GridFIASettings
from gridfia.config import CalculationConfig

# Use default settings
api = GridFIA()

# Load from file
api = GridFIA(config="config/production.yaml")

# Programmatic configuration
settings = GridFIASettings(
    output_dir="results",
    calculations=[
        CalculationConfig(name="species_richness", enabled=True),
        CalculationConfig(name="shannon_diversity", enabled=True),
    ]
)
api = GridFIA(config=settings)

Thread Safety

The GridFIA class is thread-safe. Internal components (REST client, processor) use double-checked locking for lazy initialization:

from concurrent.futures import ThreadPoolExecutor
from gridfia import GridFIA

api = GridFIA()

def process_state(state):
    files = api.download_species(state=state, output_dir=f"data/{state}")
    return len(files)

# Safe to use from multiple threads
with ThreadPoolExecutor(max_workers=4) as executor:
    results = executor.map(process_state, ["MT", "WY", "ID", "WA"])

Error Handling

All methods raise domain-specific exceptions for clear error handling:

from gridfia import GridFIA
from gridfia.exceptions import (
    InvalidZarrStructure,
    SpeciesNotFound,
    CalculationFailed,
    APIConnectionError,
    InvalidLocationConfig,
    DownloadError,
)

api = GridFIA()

try:
    files = api.download_species(state="Montana", species_codes=["9999"])
except SpeciesNotFound as e:
    print(f"Species not found: {e.species_code}")

try:
    results = api.calculate_metrics("invalid.zarr")
except InvalidZarrStructure as e:
    print(f"Invalid Zarr store: {e.zarr_path}")

try:
    api.list_species()
except APIConnectionError as e:
    print(f"API error (status {e.status_code}): {e.message}")

See Also