Repository navigation
Add ag_stats module with USDA NASS and California Crop Yield Benchmark loaders - #94
Conversation
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.
4278ac7 to
c282095
Compare
| try: | ||
| paths.append(self._layer_path(layer, slug, year, month)) | ||
| except FileNotFoundError: | ||
| missing.append(spec.path(layer, slug, year, month)) |
There was a problem hiding this comment.
can we change this to have finer error handling for when downloads fail, instead of marking them as missing files?
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
should this be pinned to a commit the way the nass loader does?
AgML/agml/ag_stats/nass/loader.py
Line 365 in c282095
There was a problem hiding this comment.
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.
| from huggingface_hub import snapshot_download | ||
|
|
||
| # A store is a directory of small files, so fetch it in one call. | ||
| folder = snapshot_download( |
There was a problem hiding this comment.
can this download be batched, instead of downloading each zarr store individually?
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
Is filling with 0s safe or does it ever get used as an actual class in the raster maps?
There was a problem hiding this comment.
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.
| 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]] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Summary
This PR adds
agml.ag_stats, a new module for agricultural statistics. Each data source is a subpackage underagml.ag_stats, so new sources can be added the same way. This PR adds two sources.agml.ag_stats.nassreads 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 theProject-AgML/usda_nass_crop_statisticsdataset on Hugging Face.agml.ag_stats.calicropyieldreads the California Crop Yield Benchmark. It covers county crop yield with CDL, Landsat, OpenET, irrigation, DayMet climate, and soil layers. The data comes from thehkaman/california-crop-yield-benchmarkdataset 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
Changes
agml/ag_stats/__init__.pylists the sources inSOURCES. Each source is imported on first use, soimport agmldoes not need the optional dependencies.agml/__init__.pyimportsag_stats, soagml.ag_stats.nassworks afterimport agml.load_*methods return data in memory.download_*methods return local file paths.pyproject.tomladds two optional extras.ag_statsinstalls the NASS dependencies.calicropyieldadds rasterio, xarray, zarr, and geopandas.Tests
tests/ag_stats/nassandtests/ag_stats/calicropyield. They use small fixture datasets and a fake Hugging Face client, so they run offline.Notes for reviewers
uv sync --dev, which does not install the new extras. As a result, CI skips the calicropyield tests. Adding--extra ag_stats --extra calicropyieldtoci.ymlwould run them.