Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions docs/ag-stats/calicropyield.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
title: California Crop Yield
sidebar_position: 3
---

## California Crop Yield Benchmark

`agml.ag_stats.calicropyield` downloads and reads the
[California Crop Yield Benchmark](https://huggingface.co/datasets/hkaman/california-crop-yield-benchmark),
a multi-modal dataset for county-level crop yield prediction. It pairs county crop yield for over
100 crops with satellite, evapotranspiration, irrigation, climate, and soil layers for each of the
58 California counties.

```shell
pip install "agml[calicropyield]"
```

## Quick Start

```python
from agml.ag_stats.calicropyield import CaliCropYieldLoader

cali = CaliCropYieldLoader()

yield_df = cali.load_yield(county="Yolo", crop="tomatoes", years=(2015, 2020))
cdl = cali.load_cdl("Yolo", 2020, crops="Tomatoes")
landsat = cali.load_landsat("Yolo", 2020, months=[6, 7, 8])
weather = cali.load_climate("Yolo", years=2020, monthly=True)
```

## Layers

| Layer | Method | Resolution | Time step | Years | Format |
| --- | --- | --- | --- | --- | --- |
| `cdl` | `load_cdl`, `crop_mask` | 30 m | annual | 2008 to 2024 | GeoTIFF |
| `landsat` | `load_landsat` | 30 m | monthly | 2008 to 2023 | GeoTIFF, 6 bands (SR_B1 to SR_B5, SR_B7) |
| `et` | `load_et` | 30 m | monthly | 2008 to 2023 | GeoTIFF (OpenET) |
| `irrigation` | `load_irrigation` | 30 m | annual | 2008 to 2023 | GeoTIFF (IrrMapper, 1 irrigated, 0 not) |
| `climate` | `load_climate` | 1 km | daily | 2008 to 2022 | Zarr (DayMet) |
| `soil` | `load_soil` | 30 m | static (2020) | | Zarr (17 gNATSGO/SSURGO attributes) |

No layer or table has data for 2012. A year range skips 2012, but asking for 2012 directly raises
an error. All rasters are in EPSG:4326 and are returned as xarray objects.

`CaliCropYieldLoader.layers()`, `years(layer)`, `counties()`, and `cdl_classes()` list what is
available.

## Yield

`load_yield` returns county crop yield as a pandas DataFrame, with one row per county, crop, and
year and the yield in `yield_t_per_ha`. Crops are merged groups such as `"TOMATOES"` or `"GRAPES"`,
and `yield_crops()` lists them. The yield table covers 2008 to 2022.

```python
cali.load_yield(county=["Fresno", "Kern"], crop="almonds")

# The per-commodity report rows, with harvested area, production, price, and value
cali.load_yield(county="Fresno", crop="Tomatoes Processing", detail=True)
```

To find the fields of a yield crop on the CDL map, look up its CDL classes:

```python
codes = cali.yield_crop_cdl_codes("HAY") # [36, 37]
mask = cali.crop_mask("Yolo", 2020, crops=codes)
```

## Reading Less Data

A full county is large. One year of Landsat for a mid-sized county is about 2 GB. To read less:

- Pass `months` to the monthly layers.
- Pass `geometry`, a shapely geometry or GeoJSON-like dict in EPSG:4326, to clip any layer to an
area of interest.
- Pass `variables` to `load_climate` and `load_soil`.

```python
from shapely.geometry import box

field = box(-121.80, 38.52, -121.74, 38.56)
landsat = cali.load_landsat("Yolo", 2020, months=[6, 7], geometry=field)
soil = cali.load_soil("Yolo", variables=["nccpi3all", "aws0100wta"], geometry=field)
```

## Downloading Ahead of Time

The `download_*` methods fetch files in parallel without loading them and return their local
paths. Use them before going offline or before a batch job:

```python
cali.download_landsat(["Yolo", "Fresno"], years=(2018, 2020), months=range(4, 10))
cali.download_yield()
```

Files that are not in the dataset are skipped with a warning. Files that fail to download raise a
`DownloadError` that lists them.

## Local Copy and Versions

```python
# A local copy laid out like the Hub repo, e.g. made with `hf download --local-dir`
cali = CaliCropYieldLoader("/path/to/california-crop-yield-benchmark")

# Pin a commit of the Hugging Face dataset for reproducible results
cali = CaliCropYieldLoader(revision="<commit hash>")
```

The `AGML_CALICROPYIELD_PATH` environment variable sets the default local copy. A branch or tag is
resolved to its commit when the loader is created, so every file comes from the same version of
the dataset.

## Citation

The [calicropyield viewer](https://hkaman7.github.io/calicropyield-viewer/) shows every layer on a
map, county by county. If you use this dataset, please cite:

```bibtex
@InProceedings{Kamangir_2025_CVPR,
author = {Kamangir, Hamid and Hajiesmaeeli, Mona and Earles, J. Mason},
title = {California Crop Yield Benchmark: Combining Satellite Image, Climate,
Evapotranspiration, and Soil Data Layers for County-Level Yield
Forecasting of Over 70 Crops},
booktitle = {Proceedings of the Computer Vision and Pattern Recognition Conference
(CVPR) Workshops},
month = {June},
year = {2025},
pages = {5491--5500}
}
```
84 changes: 84 additions & 0 deletions docs/ag-stats/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
title: Overview
sidebar_position: 1
slug: /ag-stats
---

## Agricultural Statistics

`agml.ag_stats` gives access to agricultural statistics, such as crop yield, area, production,
and crop progress, by crop, place, and year. Each data source is a subpackage with its own
loader. All data is hosted on the [Hugging Face Hub](https://huggingface.co/) and is downloaded
the first time it is used.

To browse every table and layer, and to preview yield trends, open the
[Ag Stats explorer](/ag-stats).

| Source | Module | Loader | Coverage |
| --- | --- | --- | --- |
| [USDA NASS Crop Statistics](./nass.mdx) | `agml.ag_stats.nass` | `NASSDataLoader` | United States, national to county level, 1866 to the current season |
| [California Crop Yield Benchmark](./calicropyield.mdx) | `agml.ag_stats.calicropyield` | `CaliCropYieldLoader` | 58 California counties, 2008 to 2024, yield plus satellite, climate, and soil layers |

## Installation

Each source has its own optional dependencies. Install the ones you need:

```shell
# USDA NASS crop statistics (pandas, pyarrow, huggingface_hub)
pip install "agml[ag_stats]"

# California Crop Yield Benchmark (adds rasterio, xarray, zarr, and geopandas)
pip install "agml[calicropyield]"
```

:::note

`agml.ag_stats` is new in AgML. Until it is part of a release on PyPI, install AgML from the
`nass-usda-yield-data` branch:

```shell
pip install "agml[ag_stats] @ git+https://github.com/Project-AgML/AgML.git@nass-usda-yield-data"
```

:::

## Quick Start

A source is imported only when it is first used, so importing `agml.ag_stats` does not pull in
the dependencies of every source.

```python
from agml.ag_stats.nass import NASSDataLoader
from agml.ag_stats.calicropyield import CaliCropYieldLoader

# County corn yield in Story County, Iowa
nass = NASSDataLoader()
corn = nass.load_yield(crop="corn", utilization="grain", state="IA",
county="Story", years=(2000, 2024))

# County tomato yield in Yolo County, California, and the matching CDL crop map
cali = CaliCropYieldLoader()
tomatoes = cali.load_yield(county="Yolo", crop="tomatoes", years=(2015, 2020))
cdl = cali.load_cdl("Yolo", 2020, crops="Tomatoes")
```

## Shared Conventions

Both loaders follow the same rules:

- **Years** are one year (`2020`), an inclusive range (`(2010, 2020)`), or a list (`[2018, 2020]`).
- **Names are forgiving.** Crops, states, and counties match regardless of letter case. A typo
raises an error that suggests the closest valid names.
- **Hub or local copy.** By default the data comes from the Hugging Face Hub and is kept in the
Hugging Face cache. Pass `root=` (or set `AGML_NASS_PATH` or `AGML_CALICROPYIELD_PATH`) to read
a local copy instead.
- **Reproducible versions.** Pass `revision=` with a commit hash to pin the exact version of
the dataset.

## Adding a Source

A new source is a new subpackage of `agml/ag_stats` with its own loader and optional
dependencies. Add its name to `SOURCES` in `agml/ag_stats/__init__.py`. To list it on this
site, add it to `scripts/generate_ag_stats.py` in the
[website repository](https://github.com/Project-AgML/project-agml.github.io), run the script,
and add a guide page next to this one.
135 changes: 135 additions & 0 deletions docs/ag-stats/nass.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
---
title: USDA NASS
sidebar_position: 2
---

## USDA NASS Crop Statistics

`agml.ag_stats.nass` queries crop statistics from the USDA National Agricultural Statistics
Service (NASS) [Quick Stats](https://quickstats.nass.usda.gov/) database. It covers yield, area,
production, the Census of Agriculture, in-season forecasts, crop progress, and crop condition, at
national, state, agricultural district, and county level.

The data is a set of parquet files on the Hugging Face Hub at
[`Project-AgML/usda_nass_crop_statistics`](https://huggingface.co/datasets/Project-AgML/usda_nass_crop_statistics)
(CC0 1.0). Each table is downloaded the first time it is queried. Filters are pushed down to the
parquet reader, so a query for one county reads only a small part of each file.

```shell
pip install "agml[ag_stats]"
```

## Quick Start

```python
from agml.ag_stats.nass import NASSDataLoader

nass = NASSDataLoader() # reads from the Hugging Face Hub

# County corn yield in Story County, Iowa
df = nass.load_yield(crop="corn", utilization="grain", state="IA",
county="Story", years=(2000, 2024))

# Soybean planting progress in Illinois, returned as a polars DataFrame
nass.load_progress(crop="soybeans", state="IL", years=2023,
stage="planted", format="polars")
```

## Tables

| Table | Method | Levels | Time step | Contents |
| --- | --- | --- | --- | --- |
| `yield` | `load_yield` | national, state, district, county | annual | Yield, with a t/ha column. |
| `county_yield` | `load_county_yield` | county | annual | County yield for the main crop variants, on 2020 county FIPS codes, with QA flags. |
| `area_production` | `load_area_production` | national, state, district, county | annual | Area planted, area harvested, and production (`statistic` column). |
| `census` | `load_census` | national, state, county | every 5 years | Census of Agriculture crop records, from 1997. |
| `forecast` | `load_forecast` | national, state | monthly, in season | In-season yield forecasts by `forecast_month`. |
| `progress` | `load_progress` | national, state | weekly | Crop progress by `stage`, as percent. |
| `condition` | `load_condition` | national, state | weekly | Crop condition, one column per rating. |
| `condition_long` | `load_condition(long=True)` | national, state | weekly | Crop condition, one row per rating. |

`NASSDataLoader.tables()` returns the same list with a one-line description of each table, and
`nass.schema("yield")` returns its columns and types. The [Ag Stats explorer](/ag-stats) lists the
row counts, year ranges, and columns of every table.

## Filters

Every `load_*` method is a shortcut for `query` and takes the same arguments:

```python
nass.query(
"yield",
crop="corn", # commodity, crop label, or crop_id
crop_class=None, # e.g. "winter" for wheat
practice=None, # e.g. "irrigated"
utilization="grain", # e.g. "grain" or "silage"
state=["IA", "Illinois"], # postal codes, names, or FIPS codes
county=None, # 5-digit FIPS codes or names
district=None, # agricultural statistics districts
years=(2010, 2024), # a year, an inclusive range, or a list
level="county", # "national", "state", "district", or "county"
where=None, # extra equality filters, e.g. {"unit": "BU / ACRE"}
columns=None, # a subset of columns
format="pandas", # see Output formats
)
```

A few details are worth knowing:

- `crop="corn"` matches every corn variant, such as grain and silage, and every production
practice. Narrow it with `utilization`, `crop_class`, and `practice`. For example,
`practice="all production practices"` keeps only the all-practices total.
- County names are not unique across states. Pass `state` together with a county name, or use the
5-digit FIPS code.
- NASS reports some values for "other (combined) counties". These rows have no county FIPS code and
are dropped. Pass `include_other_counties=True` to keep them.
- `load_area_production` and `load_census` take `statistic`, one or more of `area_planted`,
`area_harvested`, and `production`. `load_progress` takes `stage`, such as `"planted"`.

## Looking Up Names

`nass.catalog` is a `NASSCatalog` that lists crops and places and turns names into codes:

```python
nass.catalog.commodities() # ['BARLEY', 'BEANS', ..., 'WHEAT']
nass.catalog.crops("CORN") # every corn variant and its crop_id
nass.catalog.resolve_states("Iowa") # ['19']
nass.catalog.resolve_counties("Story", state="IA") # ['19169']
nass.catalog.districts(state="IA") # agricultural statistics districts
```

## Output Formats

`format` is one of `pandas` (default), `polars`, `arrow`, `records`, `csv`, or `parquet`. The `csv`
and `parquet` formats write to `path` and return the file path:

```python
nass.load_county_yield(crop="wheat", state="KS", format="parquet",
path="kansas_wheat.parquet")
```

## Boundaries

`load_boundaries` returns the 2020 Census county or state boundaries. Each row has the FIPS code
(`GEOID`), names, area, and centroid. With `geometry=True` it also has a `geometry` column of WKB
polygons:

```python
import geopandas as gpd

counties = nass.load_boundaries(level="county")
counties = gpd.GeoDataFrame(counties, geometry=gpd.GeoSeries.from_wkb(counties["geometry"]),
crs="EPSG:4326")
```

## Local Copy and Versions

```python
# A local copy of the dataset (the parquet folder or its parent)
nass = NASSDataLoader("/path/to/nass-usda-full-data")

# Pin a commit of the Hugging Face dataset for reproducible results
nass = NASSDataLoader(revision="<commit hash>")
```

The `AGML_NASS_PATH` environment variable sets the default local copy.
6 changes: 6 additions & 0 deletions docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ AgML contains a wide variety of public datasets from various locations across th
Use the [Dataset Search](/datasets) experience for filtering and previews. For programmatic filtering,
`agml.data.public_data_sources(...)` supports task and modality filters.

## Agricultural Statistics

Beyond image datasets, `agml.ag_stats` loads agricultural statistics by crop, place, and year.
It covers USDA NASS crop statistics for the United States and the California Crop Yield Benchmark.
See the [Ag Stats guide](/docs/ag-stats) or browse the tables in the [Ag Stats explorer](/ag-stats).

## iNatAg and iNatAg-mini

AgML provides an API with direct access to iNatAg (and iNatAg-mini), one of the world's largest collections of agricultural images dedicated for the task of image classification. Collectively, this dataset contains over 4 million images along with detailed species classificaations and enables access to a variety of large-scale agricultural machine learning tasks. You can instantiate the iNatAg (or iNatAg-mini, a smaller variant of iNatAg for smaller-scale applications) dataset as follows:
Expand Down
13 changes: 13 additions & 0 deletions docusaurus.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,21 @@ const config: Config = {
position: 'left',
label: 'Docs',
},
{
type: 'html',
position: 'left',
className: 'navbar__divider',
value: '<span aria-hidden="true"></span>',
},
{to: '/datasets', label: 'Datasets', position: 'left'},
{to: '/leaderboard', label: 'Leaderboard', position: 'left'},
{
type: 'html',
position: 'left',
className: 'navbar__divider',
value: '<span aria-hidden="true"></span>',
},
{to: '/ag-stats', label: 'Ag Stats', position: 'left'},
{
href: 'https://github.com/Project-AgML/AgML',
label: 'View on GitHub',
Expand Down
Loading
Loading