Skip to main content

Comprehensive toolkit for precision agriculture analysis using satellite imagery and remote sensing

Project description

๐ŸŒพ Precision Agriculture Analysis Toolkit

A comprehensive Python toolkit for precision agriculture analysis using satellite imagery and remote sensing data. This project provides both analysis libraries and educational notebooks to help farmers, researchers, and agronomists make data-driven decisions.

๐ŸŽฏ Project Vision

This toolkit aims to provide accessible, open-source tools for:

  • ๐Ÿ“Š Agricultural Monitoring: Track crop health, growth stages, and field conditions
  • ๐Ÿ›ฐ๏ธ Remote Sensing Analysis: Process and analyze satellite imagery at scale
  • ๐Ÿ’ง Resource Management: Optimize irrigation, fertilization, and other inputs
  • ๐Ÿ“ˆ Yield Prediction: Forecast crop yields using multi-temporal analysis
  • ๐ŸŒ Environmental Impact: Monitor soil health, carbon sequestration, and sustainability metrics

๐Ÿš€ Current Capabilities

Agricultural Index Analysis (Available Now)

Compute multiple agricultural indices from free satellite data (Sentinel-2, Landsat) to monitor crops, soil, and water resources.

๐ŸŒฑ Vegetation Indices:

  • NDVI - Normalized Difference Vegetation Index (general vegetation health)
  • EVI - Enhanced Vegetation Index (dense vegetation, atmospheric correction)
  • SAVI - Soil Adjusted Vegetation Index (sparse vegetation, early season)
  • NDRE - Normalized Difference Red Edge (chlorophyll, nitrogen status) Sentinel-2 only
  • GNDVI - Green NDVI (photosynthetic activity, nitrogen)

๐Ÿœ๏ธ Soil Indices:

  • BSI - Bare Soil Index (soil exposure, texture patterns)
  • SI - Soil Index/Brightness Index (soil brightness, texture classification)

๐Ÿ’ง Water/Moisture Indices:

  • NDMI - Normalized Difference Moisture Index (vegetation water content, irrigation management)
  • NDWI - Normalized Difference Water Index (water bodies, flood mapping)
  • MNDWI - Modified NDWI (enhanced water detection, wetlands)

Key Features:

  • Automatic data retrieval via STAC APIs
  • Support for multiple AOI formats (GeoJSON, bounding boxes, coordinates)
  • Efficient multi-index computation (loads each band once)
  • Built-in side-by-side visualizations and statistics
  • Interactive Jupyter tutorials for learning

Elevation & Terrain Analysis (Available Now)

Fetch digital elevation models and compute terrain-derived products for drainage analysis, erosion risk, and zone-based field management.

Data Sources:

  • Copernicus GLO-30 โ€” 30m resolution, global coverage
  • USGS 3DEP โ€” Up to 1m resolution, US only
  • Auto source selection โ€” Automatically picks the best source based on AOI location

Terrain Products:

  • Slope โ€” Terrain steepness in degrees (Horn method)
  • Aspect โ€” Downhill direction (0-360ยฐ from north)
  • Hillshade โ€” Simulated illumination for visualization
  • TWI โ€” Topographic Wetness Index (water accumulation and drainage)
  • Roughness โ€” Local elevation variability (3x3 std dev)

Features:

  • Batch point sampling โ€” efficiently query terrain at many lat/lon locations with a single DEM fetch
  • Automatic CRS handling (geographic and projected)
  • Windowed COG reads for fast remote data access

Water Feature Data (Available Now)

Query federal water body and wetland datasets to identify known water features within a field.

Data Sources:

  • NHD โ€” USGS National Hydrography Dataset (lakes, ponds, reservoirs, swamps, playas)
  • NWI โ€” US Fish & Wildlife Service National Wetlands Inventory (all wetland types)

Features:

  • Query by field AOI (GeoJSON polygon) via ArcGIS REST APIs
  • Automatic pagination for large result sets
  • Results clipped to AOI boundary and returned as Shapely geometries
  • Combined WaterFeatures class unions both sources in a single call
  • Non-fatal error handling โ€” service outages don't break your pipeline

Crop & Weather Data (Available Now)

Integrate USDA crop history and NASA weather data to filter analyses by crop type and growing-season conditions.

Crop Data (CropScape / Cropland Data Layer):

  • Query the USDA NASS CropScape API to determine which crop was planted in a field for a given year
  • Identify dominant crop by acreage within a field AOI (no full raster download)
  • Filter to years when a target crop (e.g., corn) was grownโ€”recommended for crop-specific NDVI analysis
  • 30 m resolution CDL for the continental US; data typically available by February of the following year

Weather Data (NASA POWER):

  • Query the NASA POWER API for daily weather at a point (precipitation, temperature, solar radiation, humidity, wind)
  • Classify years by growing-season precipitation using 30-year climatological normals (dry / normal / wet)
  • Filter NDVI or other analyses to exclude abnormally dry or wet years
  • Growing-season and monthly queries; no API key required

๐Ÿ”ฎ Coming Soon

  • Time Series Analysis: Track changes over growing seasons
  • Yield Modeling: Predictive analytics for crop production
  • Field Boundary Detection: Automated field delineation
  • Crop Classification: Machine learning-based crop type identification
  • Integration with Ground Data: Combine satellite indices with EC mapping, soil samples

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/chris/precision-ag.git
cd precision-ag

# Create and activate a virtual environment (recommended)
# Option 1: Using uv (fastest)
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Option 2: Using virtualenv
virtualenv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install the package
pip install -e .

# Or with optional dependencies for development and notebooks
pip install -e ".[dev,notebook]"

Usage Examples

Simple NDVI Analysis

from precision_ag import compute_ndvi_for_aoi

results = compute_ndvi_for_aoi(
    aoi_input=[-121.0, 37.0, -120.5, 37.5],
    start_date="2024-06-01",
    end_date="2024-06-30"
)

Multi-Index Agricultural Analysis

from precision_ag import compute_agricultural_indices_for_aoi

# Compute multiple indices efficiently (loads each band once)
results = compute_agricultural_indices_for_aoi(
    aoi_input="field.geojson",
    start_date="2024-06-01",
    end_date="2024-06-30",
    indices=['ndvi', 'evi', 'bsi', 'ndmi', 'ndwi'],
    output_dir="my_analysis",
    visualize=True  # Creates side-by-side comparison plots
)

Crop History (CropScape)

Filter analyses to years when a target crop was actually grown:

from precision_ag.crop_data import CroplandCROS, CROP_CODES

# Field AOI as GeoJSON (WGS84)
cros = CroplandCROS(field_aoi_wgs84=field_geojson)

# Years when corn was the dominant crop
corn_years = cros.get_corn_years([2019, 2020, 2021, 2022, 2023])

# Or filter by any CDL crop code
soy_years = cros.get_crop_years([2019, 2020, 2021, 2022, 2023], target_crop_code=CROP_CODES["soybeans"])

Weather Classification (NASA POWER)

Classify years by growing-season precipitation and fetch weather parameters:

from precision_ag.weather_data import NASAPowerWeather

# Field centroid (lat, lon)
weather = NASAPowerWeather(latitude=41.5, longitude=-93.5)

# Classify years by precipitation vs 30-year normals
classification = weather.classify_years([2019, 2020, 2021, 2022, 2023])
# e.g. {"dry": [2021], "normal": [2019, 2022], "wet": [2020, 2023]}

# Growing-season weather for a single year
precip_mm = weather.get_growing_season_precipitation(2023)
all_params = weather.get_all_weather_parameters(2023)  # precip, temp, solar, humidity, wind

Water Feature Query (NHD + NWI)

Identify known water bodies and wetlands within a field:

from precision_ag.water_data import WaterFeatures, NHDWaterBodies

# Query both NHD and NWI in one call
wf = WaterFeatures()
water_geom = wf.query(field_aoi_geojson)
if water_geom:
    print(f"Found water: {water_geom.geom_type}")

# Or query individually
nhd = NHDWaterBodies()
nhd_water = nhd.query(field_aoi_geojson)

Elevation & Terrain Analysis

Fetch DEMs and compute terrain products for any field:

from precision_ag import ElevationComputer, compute_elevation_for_aoi

# Quick elevation fetch for an AOI
dem, meta = compute_elevation_for_aoi([-96.56, 38.44, -96.55, 38.45])

# Full terrain analysis with visualization and statistics
ec = ElevationComputer()  # auto-selects USGS 3DEP (~1m) for US, Copernicus (30m) elsewhere
results = ec.compute_terrain_products(
    [-96.56, 38.44, -96.55, 38.45],  # bbox
    products=["elevation", "slope", "aspect", "twi"],
    visualize=True,
    print_stats=True,
)

# Batch sample at specific points (one DEM fetch for all points)
points = [(38.45, -96.55), (38.46, -96.54), (38.47, -96.53)]
point_data = ec.sample_points(points, products=["elevation", "slope", "twi"])
# [{"lat": 38.45, "lon": -96.55, "elevation": 412.3, "slope": 2.1, "twi": 11.8}, ...]

Interactive Tutorials

Launch the Jupyter notebooks to learn interactively:

# Tutorial 1: Introduction to NDVI
jupyter notebook notebooks/NDVI_Tutorial.ipynb

# Tutorial 2: Comprehensive Vegetation Health Analysis
jupyter notebook notebooks/Vegetation_Health_Tutorial.ipynb

# Tutorial 3: Elevation & Terrain Analysis
jupyter notebook notebooks/Elevation_Data_Tutorial.ipynb

Documentation:

๐Ÿ“ Project Structure

precision-ag/
โ”œโ”€โ”€ precision-ag/                      # Analysis libraries
โ”‚   โ”œโ”€โ”€ satellite_indices.py          # Agricultural indices (vegetation, soil, water)
โ”‚   โ”œโ”€โ”€ crop_data.py                  # USDA CropScape / Cropland Data Layer (crop history by field)
โ”‚   โ”œโ”€โ”€ weather_data.py               # NASA POWER weather and growing-season classification
โ”‚   โ”œโ”€โ”€ elevation_data.py             # DEM retrieval and terrain analysis (slope, aspect, TWI)
โ”‚   โ”œโ”€โ”€ water_data.py                 # NHD + NWI water feature queries (ArcGIS REST APIs)
โ”œโ”€โ”€ notebooks/                         # Educational tutorials
โ”‚   โ”œโ”€โ”€ NDVI_Tutorial.ipynb           # Tutorial 1: NDVI basics
โ”‚   โ”œโ”€โ”€ Vegetation_Health_Tutorial.ipynb  # Tutorial 2: Multi-index analysis
โ”‚   โ”œโ”€โ”€ GeoTIFF_Deep_Dive_Tutorial.ipynb  # Tutorial 3: Working with GeoTIFFs
โ”‚   โ””โ”€โ”€ Elevation_Data_Tutorial.ipynb   # Tutorial 4: Elevation & terrain analysis
โ”œโ”€โ”€ tests/                             # Unit tests
โ”œโ”€โ”€ .github/workflows/                 # CI/CD (GitHub Actions)
โ”œโ”€โ”€ pyproject.toml                     # Project configuration
โ”œโ”€โ”€ Makefile                           # Development commands
โ””โ”€โ”€ README.md                          # This file

๐Ÿ”ง Requirements

  • Python >= 3.9
  • numpy >= 1.20.0
  • scipy >= 1.7.0
  • rasterio >= 1.3.0
  • matplotlib >= 3.5.0
  • pystac-client >= 0.7.0
  • planetary-computer >= 1.0.0
  • requests >= 2.28.0
  • shapely >= 2.0.0

๐ŸŒ Data Sources

This tool uses free, public data from the following sources:

Satellite imagery (STAC APIs):

Satellite Resolution Revisit Coverage STAC Catalog
Sentinel-2 10m 5 days Global Microsoft Planetary Computer
Landsat 8/9 30m 16 days Global Earth Search AWS

Elevation:

Source Resolution Coverage STAC Catalog
Copernicus GLO-30 30m Global Microsoft Planetary Computer
USGS 3DEP 1-60m US Microsoft Planetary Computer

Water features:

  • USGS NHD โ€” National Hydrography Dataset (lakes, ponds, reservoirs, swamps)
  • USFWS NWI โ€” National Wetlands Inventory (all wetland types)

Crop and weather:

  • USDA CropScape / NASS CDL โ€” Cropland Data Layer (30 m, continental US, annual)
  • NASA POWER โ€” Daily weather (precipitation, temperature, solar, etc.) at 0.5ยฐ resolution; no API key required

๐Ÿ’ก Use Cases

This toolkit supports various precision agriculture applications:

  • ๐ŸŒพ Crop Health Monitoring: Detect stress, disease, and nutrient deficiencies early
  • ๐Ÿ’ง Irrigation Management: Optimize water usage based on vegetation and soil data
  • ๐ŸŒฑ Growth Stage Tracking: Monitor crop development throughout the season
  • ๐Ÿ“Š Yield Forecasting: Predict harvest outcomes using multi-temporal analysis
  • ๐Ÿ”๏ธ Terrain Analysis: Assess drainage patterns, erosion risk, and water accumulation from DEMs
  • ๐ŸŒ Sustainability Reporting: Track environmental metrics and carbon footprint
  • ๐Ÿ”ฌ Research & Development: Support agricultural research with reproducible analysis

๐Ÿ› ๏ธ Development

# Set up development environment
make install-dev

# Run all tests (unit + notebooks)
make test

# Run only unit tests
make test-unit

# Format code
make format

# Run linters
make lint

# Start Jupyter
make jupyter

# See all commands
make help

๐Ÿ“ Outputs

Analysis tools generate georeferenced raster files (GeoTIFF), visualizations (PNG/PDF), and statistical summaries. All outputs are compatible with standard GIS software (QGIS, ArcGIS) and can be used for further analysis or reporting.

๐Ÿ“š Learning & Documentation

This project emphasizes both practical tools and educational resources:

  • Analysis Libraries: Production-ready Python modules for data processing
  • Tutorial Notebooks: Interactive Jupyter notebooks explaining concepts, methods, and best practices
  • Documentation: Inline code documentation and detailed docstrings
  • Examples: Real-world use cases demonstrating various agricultural scenarios

Whether you're a researcher, agronomist, or developer, you'll find resources suited to your needs.

๐Ÿค Contributing

Contributions are welcome! This project is in active development. Areas where you can help:

  • Adding new analysis modules (vegetation indices, soil metrics, yield models)
  • Creating educational notebooks and tutorials
  • Improving documentation and examples
  • Bug fixes and performance improvements

Please feel free to submit a Pull Request or open an issue to discuss new features.

๐Ÿ“„ License

MIT License - see LICENSE file for details

๐Ÿ™ Acknowledgments

๐Ÿ“ง Contact

For questions or issues, please open an issue on GitHub.


Building the future of precision agriculture, one pixel at a time ๐ŸŒพ๐Ÿ›ฐ๏ธ

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

precision_ag-0.2.8.tar.gz (70.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

precision_ag-0.2.8-py3-none-any.whl (48.5 kB view details)

Uploaded Python 3

File details

Details for the file precision_ag-0.2.8.tar.gz.

File metadata

  • Download URL: precision_ag-0.2.8.tar.gz
  • Upload date:
  • Size: 70.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for precision_ag-0.2.8.tar.gz
Algorithm Hash digest
SHA256 2ce4325412a1427fa22d797d5f9de83232e40af6a7be58b252aaf47eed3a3231
MD5 01fb5ded198364adb33164c2daab3c76
BLAKE2b-256 a016e7ea6b06d86be7875d0dde3d10c03a75e9ee13956094eef833ff5bdbde32

See more details on using hashes here.

Provenance

The following attestation bundles were made for precision_ag-0.2.8.tar.gz:

Publisher: publish.yml on Agrihand-AI/precision-ag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file precision_ag-0.2.8-py3-none-any.whl.

File metadata

  • Download URL: precision_ag-0.2.8-py3-none-any.whl
  • Upload date:
  • Size: 48.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for precision_ag-0.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 cf1e38e70bf8bdbbbd375ebc8ab92c64be5ee7126449c82e02a480cc42efe139
MD5 8d45f8203fb4081748301d334fde5635
BLAKE2b-256 cb07d975887137563b96b2dec8016df3238f8e131110acfe5cbbc769440636d0

See more details on using hashes here.

Provenance

The following attestation bundles were made for precision_ag-0.2.8-py3-none-any.whl:

Publisher: publish.yml on Agrihand-AI/precision-ag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page