Skip to content

Add ag_stats module with USDA NASS and California Crop Yield Benchmark loaders - #94

Merged
js2552 merged 4 commits into
mainfrom
nass-usda-yield-data
Nov 24, 2026
Merged

js2552 merged 4 commits into
mainfrom
nass-usda-yield-data

Conversation

@hkaman7

@hkaman7 hkaman7 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR adds agml.ag_stats, a new module for agricultural statistics. Each data source is a subpackage under agml.ag_stats, so new sources can be added the same way. This PR adds two sources.

  • agml.ag_stats.nass reads USDA NASS crop statistics for the United States. It covers yield, area and production, the Census of Agriculture, crop progress, crop condition, and yield forecasts. The data comes from the Project-AgML/usda_nass_crop_statistics dataset on Hugging Face.
  • agml.ag_stats.calicropyield reads the California Crop Yield Benchmark. It covers county crop yield with CDL, Landsat, OpenET, irrigation, DayMet climate, and soil layers. The data comes from the hkaman/california-crop-yield-benchmark dataset on Hugging Face.

Both loaders download each file the first time it is used. After that, they read it from the Hugging Face cache. Both loaders also accept a local copy of the data.

Usage

import agml

nass = agml.ag_stats.nass.NASSDataLoader()
corn = nass.load_yield(crop="corn", utilization="grain", state="IA", county="Story", years=(2000, 2024))

cali = agml.ag_stats.calicropyield.CaliCropYieldLoader()
tomatoes = cali.load_yield(county="Yolo", crop="tomatoes", years=(2015, 2022))
cdl = cali.load_cdl("Yolo", 2020)
landsat = cali.load_landsat("Yolo", 2020, months=[6, 7, 8])
weather = cali.load_climate("Yolo", years=2020, monthly=True)

Changes

  • agml/ag_stats/__init__.py lists the sources in SOURCES. Each source is imported on first use, so import agml does not need the optional dependencies.
  • agml/__init__.py imports ag_stats, so agml.ag_stats.nass works after import agml.
  • Method names follow the AgML convention. load_* methods return data in memory. download_* methods return local file paths.
  • pyproject.toml adds two optional extras. ag_stats installs the NASS dependencies. calicropyield adds rasterio, xarray, zarr, and geopandas.
  • The README has a new "Agricultural Statistics" section.

Tests

  • New tests are in tests/ag_stats/nass and tests/ag_stats/calicropyield. They use small fixture datasets and a fake Hugging Face client, so they run offline.
  • With Python 3.12, 130 tests passed. With Python 3.10, 121 tests passed and the zarr tests were skipped.
  • I also checked the calicropyield loader against the real Hugging Face data. Its outputs match direct rasterio, xarray, and pandas reads of the same files.

Notes for reviewers

  • The climate and soil layers are Zarr v3 stores. They need zarr 3, which requires Python 3.11 or newer. The rest of the module works on Python 3.10.
  • CI runs uv sync --dev, which does not install the new extras. As a result, CI skips the calicropyield tests. Adding --extra ag_stats --extra calicropyield to ci.yml would run them.

Move the NASS loader to agml.ag_stats.nass and add agml.ag_stats.calicropyield.
Each data source is a subpackage that is imported on first use.
Rename the loader methods to the AgML load_* and download_* convention.
Add tests for both sources and a calicropyield extra.
CI does not install rasterio or xarray. The calicropyield conftest called
pytest.importorskip at module level. A skip while loading a conftest aborts
the whole test run, so every CI job failed. The import checks now run inside
the fixtures. The NASS conftest gets the same change.
@hkaman7
hkaman7 force-pushed the nass-usda-yield-data branch from 4278ac7 to c282095 Compare November 9, 2026 21:46
Comment thread agml/ag_stats/calicropyield/loader.py Outdated
try:
paths.append(self._layer_path(layer, slug, year, month))
except FileNotFoundError:
missing.append(spec.path(layer, slug, year, month))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we change this to have finer error handling for when downloads fail, instead of marking them as missing files?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

download() now separates the two cases. Files that are not in the dataset are skipped with a warning. Files that are in the dataset but fail to download raise a new DownloadError. Its .failed attribute maps each failed file to its exception. The other files still finish and stay in the cache, so running the same call again only downloads the rest.

Comment thread agml/ag_stats/calicropyield/loader.py Outdated
self._root = root
# `repo_id` is only kept in Hub mode; `None` marks a local copy.
self._repo_id = None if root is not None else repo_id
self._revision = revision

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be pinned to a commit the way the nass loader does?

self._revision = os.path.basename(folder)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The loader now resolves revision to a commit hash when it is created, so every file comes from the same version of the dataset. A commit hash passed in directly is used as is. The pinned commit is kept when the loader is pickled.

Comment thread agml/ag_stats/calicropyield/loader.py Outdated
from huggingface_hub import snapshot_download

# A store is a directory of small files, so fetch it in one call.
folder = snapshot_download(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this download be batched, instead of downloading each zarr store individually?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

download() now lists each county layer folder once and downloads all files in one parallel batch. This covers the zarr stores and the GeoTIFFs. Loading a single store uses the same path.

Comment thread agml/ag_stats/calicropyield/loader.py Outdated
if geometry is None:
data, transform = src.read(), src.transform
else:
fill = np.nan if np.issubdtype(np.dtype(src.dtypes[0]), np.floating) else (src.nodata or 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is filling with 0s safe or does it ever get used as an actual class in the raster maps?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was not safe for the irrigation layer. Irrigation uses 0 for "not irrigated" and has no no-data value, so cropped pixels looked like real data. Cropping now uses the file's own no-data value when it has one. Otherwise it uses NaN for floats or the dtype maximum for integers (255 for irrigation). The value is stored in attrs["nodata"]. CDL keeps 0, since that is its no-data value.

Comment thread agml/ag_stats/calicropyield/catalog.py Outdated
if isinstance(years, int):
wanted = [years]
elif isinstance(years, tuple) and len(years) == 2:
wanted = [y for y in available if years[0] <= y <= years[1]]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This filtering should be changed to raise an error if the years aren't contained in the dataset, since right now it just passes an empty list through, since the wanted list is built from years that are available already.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A (start, end) range now means every year in it, so a range that reaches past the data raises an error that names the missing years. A reversed range also raises. The one exception is 2012, which no layer has. A range skips it, but asking for 2012 directly still raises. The yield table follows the same rule.

Pin the dataset to a commit when the loader is created, like the NASS loader.
Batch downloads: list each county layer folder once and download files in
parallel. Files missing from the dataset are skipped with a warning, and files
that fail to download raise a DownloadError that lists them.
Cropped rasters without a no-data value now use the dtype maximum, so 0 in the
irrigation layer still means "not irrigated".
Year ranges that reach past the data now raise an error instead of being cut
short. 2012, which no layer has, is still skipped inside a range.
@js2552
js2552 merged commit f1816ae into main Nov 24, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants