Metadata-Version: 2.4
Name: precision-ag
Version: 0.2.2
Summary: Comprehensive toolkit for precision agriculture analysis using satellite imagery and remote sensing
Author-email: Chris <chris@agrihand.ai>
License: MIT
Project-URL: Homepage, https://github.com/Agrihand-AI/precision-ag
Project-URL: Bug Tracker, https://github.com/Agrihand-AI/precision-ag/issues
Project-URL: Documentation, https://github.com/Agrihand-AI/precision-ag#readme
Project-URL: Repository, https://github.com/Agrihand-AI/precision-ag
Keywords: agriculture,precision-agriculture,satellite,ndvi,remote-sensing,stac,sentinel-2,landsat,crop-monitoring
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20.0
Requires-Dist: scipy>=1.7.0
Requires-Dist: rasterio>=1.3.0
Requires-Dist: pyproj>=3.0.0
Requires-Dist: matplotlib>=3.5.0
Requires-Dist: pystac-client>=0.7.0
Requires-Dist: planetary-computer>=1.0.0
Requires-Dist: requests>=2.28.0
Requires-Dist: shapely>=2.0.0
Requires-Dist: scikit-learn>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pytest-xdist>=3.0.0; extra == "dev"
Requires-Dist: nbmake>=1.4.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Provides-Extra: notebook
Requires-Dist: jupyter>=1.0.0; extra == "notebook"
Requires-Dist: ipykernel>=6.20.0; extra == "notebook"
Dynamic: license-file

# 🌾 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)

### Management Zone Analysis (Available Now)
Create precision agriculture management zones using clustering analysis on satellite indices. Inspired by research from Ali Mirzakhani Nafchi (SDSU Extension) on soil variability and zone-based management.

**Zone Analysis Features:**
- K-means clustering on multi-index data
- Automated zone statistics and characterization
- Georeferenced zone maps (GeoTIFF export)
- Management recommendations by zone
- Integration with variable rate application systems

**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
- Both CLI and Python library interfaces
- Interactive Jupyter tutorials for learning
- Management zone creation and export

### 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 management zone creation and 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

```bash
# 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

**Command Line:**
```bash
# Quick NDVI computation using a bounding box
ndvi-compute \
    --aoi "-121.0,37.0,-120.5,37.5" \
    --start-date 2024-06-01 \
    --end-date 2024-06-30
```

**Python Library:**
```python
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

**Command Line:**
```bash
# Compute multiple indices at once (vegetation, soil, water)
ag-index-compute \
    --aoi my_field.geojson \
    --start-date 2024-06-01 \
    --end-date 2024-06-30 \
    --indices ndvi evi bsi ndmi ndwi

# Compute soil indices for bare soil period
ag-index-compute \
    --aoi my_field.geojson \
    --start-date 2024-03-15 \
    --end-date 2024-04-01 \
    --indices bsi si ndmi

# List available indices for your satellite collection
ag-index-compute --list-indices
```

**Python Library:**
```python
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
)
```

#### Management Zone Creation

**Python Library:**
```python
from precision_ag import compute_agricultural_indices_for_aoi, create_management_zones_for_field

# Step 1: Compute indices for bare soil period
soil_indices = compute_agricultural_indices_for_aoi(
    aoi_input="field.geojson",
    start_date="2024-03-15",  # Pre-planting
    end_date="2024-04-01",
    indices=['bsi', 'si', 'ndmi'],
    visualize=False
)

# Step 2: Create management zones
zones = create_management_zones_for_field(
    indices_results=soil_indices[0][1],  # First scene's results
    n_zones=3,  # Low, Medium, High productivity zones
    output_dir="management_zones",
    visualize=True,
    export=True  # Creates GeoTIFF for use in farm management software
)
```

#### Crop History (CropScape)

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

```python
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:

```python
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
```

### Interactive Tutorials

Launch the Jupyter notebooks to learn interactively:

```bash
# 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: Soil & Water Analysis with Management Zones
jupyter notebook notebooks/Soil_Water_Zones_Tutorial.ipynb
```

**Documentation:**
- [Satellite Indices Module](precision-ag/satellite_indices.py) - Agricultural indices (vegetation, soil, water)
- [Zone Analysis Module](precision-ag/zone_analysis.py) - Management zone creation
- [Crop Data Module](precision-ag/crop_data.py) - USDA CropScape / Cropland Data Layer integration
- [Weather Data Module](precision-ag/weather_data.py) - NASA POWER weather and growing-season classification
- Run `ag-index-compute --help` for CLI options

## 📁 Project Structure

```
precision-ag/
├── precision-ag/                      # Analysis libraries
│   ├── satellite_indices.py          # Agricultural indices (vegetation, soil, water)
│   ├── zone_analysis.py              # Management zone creation and analysis
│   ├── crop_data.py                  # USDA CropScape / Cropland Data Layer (crop history by field)
│   ├── weather_data.py               # NASA POWER weather and growing-season classification
├── notebooks/                         # Educational tutorials
│   ├── NDVI_Tutorial.ipynb           # Tutorial 1: NDVI basics
│   ├── Vegetation_Health_Tutorial.ipynb  # Tutorial 2: Multi-index analysis
│   ├── Soil_Water_Zones_Tutorial.ipynb  # Tutorial 3: Soil, water, zones
│   └── GeoTIFF_Deep_Dive_Tutorial.ipynb  # Tutorial 4: Working with GeoTIFFs
├── 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
- scikit-learn >= 1.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](https://planetarycomputer.microsoft.com/) |
| **Landsat 8/9** | 30m | 16 days | Global | [Earth Search AWS](https://earth-search.aws.element84.com/) |

**Crop and weather:**
- **[USDA CropScape / NASS CDL](https://nassgeodata.gmu.edu/CropScape)** — Cropland Data Layer (30 m, continental US, annual)
- **[NASA POWER](https://power.larc.nasa.gov/)** — 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
- 🗺️ **Field Mapping**: Delineate management zones for variable rate applications (inspired by Nafchi et al. research at SDSU)
- 🌍 **Sustainability Reporting**: Track environmental metrics and carbon footprint
- 🔬 **Research & Development**: Support agricultural research with reproducible analysis

## 🛠️ Development

```bash
# 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

- [Microsoft Planetary Computer](https://planetarycomputer.microsoft.com/) - Free satellite data access
- [STAC](https://stacspec.org/) - Standardized geospatial data catalog
- [ESA Copernicus](https://www.copernicus.eu/) - Sentinel missions
- [NASA/USGS](https://www.usgs.gov/landsat-missions) - Landsat program
- [USDA NASS CropScape](https://nassgeodata.gmu.edu/CropScape) - Cropland Data Layer
- [NASA POWER](https://power.larc.nasa.gov/) - Weather and solar radiation data

## 📧 Contact

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

---

**Building the future of precision agriculture, one pixel at a time 🌾🛰️**

