diff --git a/README.md b/README.md index b912e29e..ea177943 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,86 @@ The cache is bounded by total size, 256 MiB by default; pass `cache_max_bytes=` If you're using this with a PyTorch `DataLoader`, prefer `num_workers > 0`. Each worker process opens its own shard handles (and keeps its own byte cache), whether workers are forked or spawned. +### Agricultural Statistics + +`agml.ag_stats` holds crop statistics, one subpackage per data source. Each source has its own extra, so only the +packages for the sources you use are installed: + +| Source | Module | Data | +|---|---|---| +| USDA NASS | `agml.ag_stats.nass` | United States crop statistics at national, state, district, and county level | +| California Crop Yield Benchmark | `agml.ag_stats.calicropyield` | California county crop yield with satellite, ET, climate, and soil layers | + +#### USDA NASS Crop Statistics + +`agml.ag_stats.nass` queries USDA NASS crop statistics (yield, area and production, Census of Agriculture, crop progress, +crop condition, and yield forecasts) at national, state, district, and county level. It needs the `ag_stats` extra +(`pip install agml[ag_stats]`). The data is read from the +[Project-AgML/usda_nass_crop_statistics](https://huggingface.co/datasets/Project-AgML/usda_nass_crop_statistics) +dataset on Hugging Face. Each table is downloaded the first time it is queried and cached after that: + +```python +from agml.ag_stats.nass import NASSDataLoader + +nass = NASSDataLoader() # or NASSDataLoader("/path/to/local/copy"), or set AGML_NASS_PATH + +# Corn grain yield for one county, 2000 to 2024, as a pandas DataFrame. +df = nass.load_yield(crop="corn", utilization="grain", state="IA", county="Story", years=(2000, 2024)) + +# Weekly planting progress for soybeans in Illinois, as a polars DataFrame. +nass.load_progress(crop="soybeans", state="IL", years=2023, stage="planted", format="polars") + +# State-level wheat production for several states, written to a CSV file. +nass.load_area_production(crop="wheat", state=["KS", "ND"], level="state", statistic="production", + format="csv", path="wheat_production.csv") + +# Look up names and codes. +nass.catalog.crops("corn") +nass.catalog.counties(state="IA") + +# 2020 Census county boundaries, with WKB geometry. +nass.load_boundaries("county") +``` + +`NASSDataLoader.tables()` lists every table. `nass.query(table, ...)` takes the same filters as the per-table methods: +`crop`, `crop_class`, `practice`, `utilization`, `state`, `county`, `district`, `years`, `level`, `where`, and +`columns`. Results come back as `pandas` (default), `polars`, `arrow`, or `records`, or are written to a `csv` or +`parquet` file. Pass `revision=` (a commit hash) to `NASSDataLoader` to pin a version of the dataset, and `cache_dir=` +to choose where downloads are kept. + +#### California Crop Yield Benchmark + +`agml.ag_stats.calicropyield` reads the [California Crop Yield Benchmark](https://huggingface.co/datasets/hkaman/california-crop-yield-benchmark): +county crop yield (t/ha) for over 100 crops in the 58 California counties (2008-2022), with Cropland Data Layer, +monthly Landsat and OpenET, irrigation, daily DayMet climate, and soil layers for each county. It needs the +`calicropyield` extra (`pip install agml[calicropyield]`; the climate and soil layers need zarr 3, so Python 3.11 or +newer). Each file is downloaded from Hugging Face the first time it is read and cached after that: + +```python +from agml.ag_stats.calicropyield import CaliCropYieldLoader + +cali = CaliCropYieldLoader() # or CaliCropYieldLoader("/path/to/local/copy"), or set AGML_CALICROPYIELD_PATH + +# County yield as a pandas DataFrame. +cali.load_yield(county="Yolo", crop="tomatoes", years=(2015, 2022)) + +# Rasters as xarray DataArrays in EPSG:4326, optionally cropped to a shapely geometry. +cdl = cali.load_cdl("Yolo", 2020) # (y, x) CDL class codes +tomatoes = cali.crop_mask("Yolo", 2020, crops=cali.yield_crop_cdl_codes("TOMATOES")) +landsat = cali.load_landsat("Yolo", 2020, months=[6, 7, 8]) # (month, band, y, x) +et = cali.load_et("Yolo", 2020) # (month, y, x) + +# Climate and soil as xarray Datasets. +weather = cali.load_climate("Yolo", years=[2019, 2020], variables=["prcp", "tmax"], monthly=True) +soil = cali.load_soil("Yolo", variables=["soc0_100", "nccpi3all"]) + +# Fetch files ahead of time, e.g. before working offline. +cali.download("cdl", ["Fresno", "Kern"], years=(2018, 2022)) +``` + +`CaliCropYieldLoader.layers()` lists the layers and `years(layer)` their years. `load_boundaries()` returns the county +polygons as a GeoDataFrame. + ## Public Datasets AgML contains a wide variety of public datasets from various locations across the world: diff --git a/agml/__init__.py b/agml/__init__.py index a8fff9f9..5da2404a 100644 --- a/agml/__init__.py +++ b/agml/__init__.py @@ -42,3 +42,6 @@ def _setup(): # since it is the entry point for loading AgML image-text-to-text datasets from the Hub. from . import backend, data, io, synthetic, viz from .data import loadImageTextToTextDataset + +# Each `ag_stats` source loads its optional dependencies on first use, e.g. `agml.ag_stats.nass`. +from . import ag_stats # noqa: E402, F401 diff --git a/agml/ag_stats/__init__.py b/agml/ag_stats/__init__.py new file mode 100644 index 00000000..11a177e5 --- /dev/null +++ b/agml/ag_stats/__init__.py @@ -0,0 +1,42 @@ +# Copyright 2021 UC Davis Plant AI and Biophysics Lab +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Agricultural statistics, one subpackage per data source: + +- `agml.ag_stats.nass`: USDA NASS crop statistics for the United States. +- `agml.ag_stats.calicropyield`: the California Crop Yield Benchmark + (county crop yield with satellite, ET, climate, and soil layers). + +Each source has its own optional dependencies, so a source is only +imported when it is first used, e.g. `agml.ag_stats.nass.NASSDataLoader()` +or `from agml.ag_stats.calicropyield import CaliCropYieldLoader`. +""" + +import importlib as _importlib + +# Every data source. Add a new source's subpackage name here. +SOURCES = ("nass", "calicropyield") + +__all__ = list(SOURCES) + + +def __getattr__(name): + if name in SOURCES: + return _importlib.import_module(f".{name}", __name__) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def __dir__(): + return sorted(list(globals()) + list(SOURCES)) diff --git a/agml/ag_stats/calicropyield/__init__.py b/agml/ag_stats/calicropyield/__init__.py new file mode 100644 index 00000000..7bfc6557 --- /dev/null +++ b/agml/ag_stats/calicropyield/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2021 UC Davis Plant AI and Biophysics Lab +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module downloads and reads the California Crop Yield Benchmark: +county crop yield for California with Cropland Data Layer, Landsat, +OpenET, irrigation, DayMet climate, and soil layers for each county, +hosted on the Hugging Face Hub. +""" + +try: + import huggingface_hub # noqa: F401 + import pandas # noqa: F401 + import pyarrow # noqa: F401 + import rasterio # noqa: F401 + import xarray # noqa: F401 +except ImportError: + raise ImportError( + "The `agml.ag_stats.calicropyield` module needs huggingface_hub, pandas, pyarrow, rasterio, " + "and xarray. Install them with `pip install agml[calicropyield]`." + ) + +from .catalog import CDL_CLASSES, COUNTIES, DEFAULT_REPO_ID, LAYERS +from .loader import CaliCropYieldLoader, DownloadError + +__all__ = ["CaliCropYieldLoader", "DownloadError", "CDL_CLASSES", "COUNTIES", "DEFAULT_REPO_ID", "LAYERS"] diff --git a/agml/ag_stats/calicropyield/catalog.py b/agml/ag_stats/calicropyield/catalog.py new file mode 100644 index 00000000..a8968d67 --- /dev/null +++ b/agml/ag_stats/calicropyield/catalog.py @@ -0,0 +1,226 @@ +"""Layout of the California Crop Yield Benchmark dataset on the Hugging Face Hub. + +Every county has one folder per data layer, `counties////`, +where `` is the county name without spaces (`ContraCosta`). Rasters +are GeoTIFFs, and the climate and soil layers are Zarr stores. Crop yield is +one statewide table, `yield/county_crop_yield.parquet`, with a more detailed +table and lookup files next to it. +""" + +import difflib +from dataclasses import dataclass +from typing import Dict, Iterable, List, Optional, Tuple, Union + +DEFAULT_REPO_ID = "hkaman/california-crop-yield-benchmark" + +# Files outside the county folders. +YIELD_TABLE = "yield/county_crop_yield.parquet" +YIELD_DETAIL_TABLE = "yield/county_crop_yield_detail.parquet" +CDL_CROSSWALK = "yield/metadata/cdl_crop_crosswalk.csv" +COUNTY_BOUNDARIES = "reference/California_Counties.geojson" +DATASET_CARD = "README.md" + +# No layer or table has data for this year. +MISSING_YEAR = 2012 + +# 2012 is missing from every layer. +_YEARS = tuple(y for y in range(2008, 2024) if y != MISSING_YEAR) + + +@dataclass(frozen=True) +class Layer: + """Describes how one data layer is stored.""" + + filename: str + years: Tuple[int, ...] + monthly: bool = False + zarr: bool = False + description: str = "" + + def path(self, name: str, slug: str, year: int, month: Optional[int] = None) -> str: + """Returns the repo path of one file, e.g. `counties/Yolo/et/2020/Yolo_ET_2020_07.tif`.""" + filename = self.filename.format(county=slug, year=year, month=month) + return f"counties/{slug}/{name}/{year}/{filename}" + + +# Every gridded layer. The keys are the names used by the loader. +LAYERS: Dict[str, Layer] = { + "cdl": Layer( + "{county}_{year}.tif", + years=_YEARS + (2024,), + description="USDA Cropland Data Layer, one crop class code per 30 m pixel.", + ), + "landsat": Layer( + "{county}_LT_{year}_{month:02d}.tif", + years=_YEARS, + monthly=True, + description="Monthly Landsat surface reflectance, bands SR_B1-SR_B5 and SR_B7.", + ), + "et": Layer( + "{county}_ET_{year}_{month:02d}.tif", + years=_YEARS, + monthly=True, + description="Monthly OpenET evapotranspiration.", + ), + "irrigation": Layer( + "{county}_{year}.tif", + years=_YEARS, + description="IrrMapper irrigated land (1) and not irrigated (0), on the CDL grid.", + ), + "climate": Layer( + "DayMet_{county}_{year}.zarr", + years=tuple(y for y in _YEARS if y <= 2022), + zarr=True, + description="Daily DayMet weather at 1 km: prcp, tmax, tmin, srad, vp, dayl, pet, swe, snow.", + ), + "soil": Layer( + "{county}_soil.zarr", + years=(2020,), + zarr=True, + description="17 gNATSGO/SSURGO soil attributes (2020 vintage), on a 30 m grid.", + ), +} + +COUNTIES: Tuple[str, ...] = ( + "Alameda", "Alpine", "Amador", "Butte", "Calaveras", "Colusa", + "Contra Costa", "Del Norte", "El Dorado", "Fresno", "Glenn", "Humboldt", + "Imperial", "Inyo", "Kern", "Kings", "Lake", "Lassen", "Los Angeles", + "Madera", "Marin", "Mariposa", "Mendocino", "Merced", "Modoc", "Mono", + "Monterey", "Napa", "Nevada", "Orange", "Placer", "Plumas", "Riverside", + "Sacramento", "San Benito", "San Bernardino", "San Diego", + "San Francisco", "San Joaquin", "San Luis Obispo", "San Mateo", + "Santa Barbara", "Santa Clara", "Santa Cruz", "Shasta", "Sierra", + "Siskiyou", "Solano", "Sonoma", "Stanislaus", "Sutter", "Tehama", + "Trinity", "Tulare", "Tuolumne", "Ventura", "Yolo", "Yuba", +) + +# USDA CDL class codes used in California. Codes 62-65, 81-91, and 94-199 +# are non-agricultural or NLCD land cover. +CDL_CLASSES: Dict[int, str] = { + 0: "Other", 1: "Corn", 2: "Cotton", 3: "Rice", 4: "Sorghum", 5: "Soybeans", + 6: "Sunflower", 10: "Peanuts", 11: "Tobacco", 12: "Sweet Corn", + 13: "Pop or Orn Corn", 14: "Mint", 21: "Barley", 22: "Durum Wheat", + 23: "Spring Wheat", 24: "Winter Wheat", 25: "Other Small Grains", + 26: "Dbl Crop WinWht/Soybeans", 27: "Rye", 28: "Oats", 29: "Millet", + 30: "Speltz", 31: "Canola", 32: "Flaxseed", 33: "Safflower", 34: "Rape Seed", + 35: "Mustard", 36: "Alfalfa", 37: "Other Hay/Non Alfalfa", 38: "Camelina", + 39: "Buckwheat", 41: "Sugarbeets", 42: "Dry Beans", 43: "Potatoes", + 44: "Other Crops", 45: "Sugarcane", 46: "Sweet Potatoes", + 47: "Misc Vegs & Fruits", 48: "Watermelons", 49: "Onions", 50: "Cucumbers", + 51: "Chick Peas", 52: "Lentils", 53: "Peas", 54: "Tomatoes", + 55: "Caneberries", 56: "Hops", 57: "Herbs", 58: "Clover/Wildflowers", + 59: "Sod/Grass Seed", 60: "Switchgrass", 61: "Fallow/Idle Cropland", + **{code: "Non-agricultural" for code in (62, 63, 64, 65, *range(81, 92))}, + 66: "Cherries", 67: "Peaches", 68: "Apples", 69: "Grapes", + 70: "Christmas Trees", 71: "Other Tree Crops", 72: "Citrus", 74: "Pecans", + 75: "Almonds", 76: "Walnuts", 77: "Pears", + **{code: "NLCD-sampled categories" for code in range(93, 200)}, + 121: "Urban", 141: "Water", + 204: "Pistachios", 205: "Triticale", 206: "Carrots", 207: "Asparagus", + 208: "Garlic", 209: "Cantaloupes", 210: "Prunes", 211: "Olives", + 212: "Oranges", 213: "Honeydew Melons", 214: "Broccoli", 215: "Avocados", + 216: "Peppers", 217: "Pomegranates", 218: "Nectarines", 219: "Greens", + 220: "Plums", 221: "Strawberries", 222: "Squash", 223: "Apricots", + 224: "Vetch", 225: "Dbl Crop WinWht/Corn", 226: "Dbl Crop Oats/Corn", + 227: "Lettuce", 228: "Dbl Crop Triticale/Corn", 229: "Pumpkins", + 230: "Dbl Crop Lettuce/Durum Wht", 231: "Dbl Crop Lettuce/Cantaloupe", + 232: "Dbl Crop Lettuce/Cotton", 233: "Dbl Crop Lettuce/Barley", + 234: "Dbl Crop Durum Wht/Sorghum", 235: "Dbl Crop Barley/Sorghum", + 236: "Dbl Crop WinWht/Sorghum", 237: "Dbl Crop Barley/Corn", + 238: "Dbl Crop WinWht/Cotton", 239: "Dbl Crop Soybeans/Cotton", + 240: "Dbl Crop Soybeans/Oats", 241: "Dbl Crop Corn/Soybeans", + 242: "Blueberries", 243: "Cabbage", 244: "Cauliflower", 245: "Celery", + 246: "Radishes", 247: "Turnips", 248: "Eggplants", 249: "Gourds", + 250: "Cranberries", 254: "Dbl Crop Barley/Soybeans", +} + +# CDL classes that are not cropland. +NON_CROP_CLASSES = frozenset(("Other", "Non-agricultural", "NLCD-sampled categories", "Urban", "Water")) + + +def layer(name: str) -> Layer: + """Returns the description of a layer, or raises a helpful error.""" + if name not in LAYERS: + raise ValueError(f"Unknown layer '{name}'. Choose one of {list(LAYERS)}.") + return LAYERS[name] + + +def resolve_county(county: str) -> str: + """Returns the canonical county name, ignoring case, spaces, and a ` County` suffix.""" + key = _county_key(county) + for name in COUNTIES: + if _county_key(name) == key: + return name + close = difflib.get_close_matches(county.strip().title(), COUNTIES, n=3) + hint = f" Did you mean {close}?" if close else "" + raise ValueError(f"Unknown California county '{county}'.{hint}") + + +def county_slug(county: str) -> str: + """Returns the folder name of a county on the Hub, e.g. `ContraCosta`.""" + return resolve_county(county).replace(" ", "") + + +def resolve_years(name: str, years: Union[None, int, Tuple[int, int], Iterable[int]]) -> List[int]: + """Turns a year, an inclusive `(start, end)` range, or a list into the years of a layer. + + `None` means every year. See `check_years` for how missing years are handled. + """ + available = layer(name).years + if years is None: + return list(available) + return check_years(years, available, f"Layer '{name}'") + + +def check_years(years: Union[int, Tuple[int, int], Iterable[int]], available: Iterable[int], what: str) -> List[int]: + """Returns the requested years, or raises an error naming the years that have no data. + + A `(start, end)` range means every year from `start` to `end`, so a + range that reaches past the data raises an error instead of being cut + short. The one exception is 2012, which no layer or table has: a range + skips it, but asking for 2012 directly raises an error. + """ + available = sorted(int(y) for y in available) + if isinstance(years, int): + wanted = [years] + elif isinstance(years, tuple) and len(years) == 2: + start, end = (int(y) for y in years) + if start > end: + raise ValueError(f"The year range {years} is reversed. Pass it as (start, end).") + wanted = [y for y in range(start, end + 1) if y != MISSING_YEAR] + else: + wanted = [int(y) for y in years] + missing = [y for y in wanted if y not in available] + if missing: + raise ValueError( + f"{what} has no data for {missing}. It covers {available[0]}-{available[-1]} except {MISSING_YEAR}." + ) + return wanted + + +def cdl_codes(crops: Union[str, int, Iterable[Union[str, int]], None]) -> List[int]: + """Returns the CDL codes for class names or codes. `None` means every cropland class.""" + if crops is None: + return [code for code, name in CDL_CLASSES.items() if name not in NON_CROP_CLASSES] + if isinstance(crops, (str, int)): + crops = [crops] + by_name = {} + for code, name in CDL_CLASSES.items(): + by_name.setdefault(name.lower(), []).append(code) + codes = [] + for crop in crops: + if isinstance(crop, int): + codes.append(crop) + elif crop.strip().lower() in by_name: + codes.extend(by_name[crop.strip().lower()]) + else: + close = difflib.get_close_matches(crop, sorted(set(CDL_CLASSES.values())), n=3) + hint = f" Did you mean {close}?" if close else "" + raise ValueError(f"Unknown CDL class '{crop}'.{hint}") + return codes + + +def _county_key(name: str) -> str: + name = name.strip().lower() + name = name[: -len(" county")] if name.endswith(" county") else name + return name.replace(" ", "") diff --git a/agml/ag_stats/calicropyield/loader.py b/agml/ag_stats/calicropyield/loader.py new file mode 100644 index 00000000..ab016653 --- /dev/null +++ b/agml/ag_stats/calicropyield/loader.py @@ -0,0 +1,564 @@ +"""Downloads and reads the California Crop Yield Benchmark.""" + +import os +import re +from concurrent.futures import ThreadPoolExecutor +from typing import Dict, Iterable, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd +import rasterio +import rasterio.features +import rasterio.mask +import xarray as xr + +from agml.framework import AgMLSerializable +from agml.utils.logging import log +from agml.ag_stats.calicropyield import catalog +from agml.ag_stats.calicropyield.catalog import DEFAULT_REPO_ID + +# The environment variable read when no `root` is passed to the loader. +_ROOT_ENV_VAR = "AGML_CALICROPYIELD_PATH" + +StrOrList = Union[str, Iterable[str], None] +YearSpec = Union[None, int, Tuple[int, int], Iterable[int]] + +# Files downloaded at the same time from the Hub. +_DOWNLOAD_WORKERS = 8 + + +class DownloadError(RuntimeError): + """Raised when files that are in the dataset fail to download. + + `failed` maps each repo path that failed to the exception it raised. + Files that finished are kept in the cache, so running the same call + again only downloads the rest. + """ + + def __init__(self, failed: Dict[str, Exception]): + self.failed = failed + first_path, first_error = next(iter(failed.items())) + super().__init__( + f"{len(failed)} file(s) failed to download, e.g. '{first_path}' " + f"({type(first_error).__name__}: {first_error}). Files that finished are cached, " + f"so running the same call again only downloads the rest. See `.failed` for every file." + ) + + +class CaliCropYieldLoader(AgMLSerializable): + """Downloads and reads the California Crop Yield Benchmark. + + The benchmark covers the 58 California counties from 2008 to 2023 + (2012 is missing) with these layers: + + - `cdl`: USDA Cropland Data Layer, yearly, 30 m. + - `landsat`: Landsat surface reflectance, monthly, 30 m, 6 bands. + - `et`: OpenET evapotranspiration, monthly, 30 m. + - `irrigation`: IrrMapper irrigated land, yearly, on the CDL grid. + - `climate`: DayMet weather, daily, 1 km (Zarr). + - `soil`: 17 gNATSGO/SSURGO soil attributes, 2020 vintage, 30 m (Zarr). + + and county crop yield (t/ha) for over 100 crops from the CDFA county + agricultural commissioner reports. + + By default the files come from the Hugging Face Hub. Each file is + downloaded the first time it is read and kept in the Hugging Face + cache. All rasters are in EPSG:4326, and `geometry` arguments are + shapely geometries or GeoJSON-like dicts in that CRS. + + Parameters + ---------- + root : str, optional + A local copy of the dataset, laid out like the Hub repo (e.g. made + with `hf download --local-dir`). Defaults to the + `AGML_CALICROPYIELD_PATH` environment variable. When neither is + set, the dataset is read from `repo_id`. + repo_id : str, optional + The Hugging Face dataset repo to read from. + revision : str, optional + A branch, tag, or commit of `repo_id`. Defaults to the latest + version. 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. Pass a commit hash to make results reproducible. + cache_dir : str, optional + Where downloaded files are kept. Defaults to the Hugging Face cache. + token : str, optional + A Hugging Face token. Not needed for the public dataset. + + Examples + -------- + >>> cali = CaliCropYieldLoader() + >>> 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) + """ + + serializable = frozenset(("root", "repo_id", "revision", "cache_dir")) + + def __init__( + self, + root: Optional[str] = None, + repo_id: str = DEFAULT_REPO_ID, + revision: Optional[str] = None, + cache_dir: Optional[str] = None, + token: Optional[str] = None, + ): + root = root or os.environ.get(_ROOT_ENV_VAR) + if root is not None: + root = os.path.realpath(os.path.expanduser(root)) + if not os.path.isdir(root): + raise FileNotFoundError(f"The California Crop Yield Benchmark directory '{root}' does not exist.") + self._root = root + # `repo_id` and `revision` are only kept in Hub mode; `None` marks a local copy. + self._repo_id = None if root is not None else repo_id + self._cache_dir = cache_dir + self._token = token + self._revision = None if root is not None else self._resolve_commit(revision) + + def __repr__(self): + if self._repo_id is not None: + return f"" + return f"" + + @property + def root(self) -> Optional[str]: + """The local copy of the dataset, or `None` when reading from the Hub.""" + return self._root + + @property + def repo_id(self) -> Optional[str]: + """The Hugging Face repo the data comes from, or `None` for a local copy.""" + return self._repo_id + + @property + def revision(self) -> Optional[str]: + """The commit of `repo_id` the data comes from, or `None` for a local copy.""" + return self._revision + + # Listings. + + @staticmethod + def counties() -> List[str]: + """Returns the names of the 58 California counties.""" + return list(catalog.COUNTIES) + + @staticmethod + def layers() -> Dict[str, str]: + """Returns the name and a one-line description of every gridded layer.""" + return {name: spec.description for name, spec in catalog.LAYERS.items()} + + @staticmethod + def years(layer: str) -> List[int]: + """Returns the years a layer covers.""" + return list(catalog.layer(layer).years) + + @staticmethod + def cdl_classes() -> Dict[int, str]: + """Returns the CDL class name of every code.""" + return dict(catalog.CDL_CLASSES) + + # Downloads. + + def download( + self, + layer: str, + counties: StrOrList, + years: YearSpec = None, + months: Optional[Iterable[int]] = None, + ) -> List[str]: + """Downloads layer files without loading them, and returns their local paths. + + Use this to fetch data ahead of time, e.g. before going offline. + Files are downloaded in parallel. Files that are not in the dataset + are skipped with a warning. Files that are in the dataset but fail + to download raise a `DownloadError` that lists them. Zarr layers + return the path of each store (a directory). + + Parameters + ---------- + layer : str + One of the names in `CaliCropYieldLoader.layers()`. + counties : str or list of str + County names, e.g. `"Yolo"` or `["Fresno", "Contra Costa"]`. + years : int, tuple, or list of int, optional + A year, an inclusive `(start, end)` range, or a list of + years. Defaults to every year of the layer. + months : list of int, optional + Months of the monthly layers (`landsat`, `et`). Defaults to all. + """ + spec = catalog.layer(layer) + months = _check_months(months) if spec.monthly else [None] + targets = [ + spec.path(layer, catalog.county_slug(county), year, month) + for county in _as_list(counties) + for year in catalog.resolve_years(layer, years) + for month in months + ] + if self._repo_id is None: + found = {t: os.path.join(self._root, t) for t in targets if os.path.exists(os.path.join(self._root, t))} + missing = [t for t in targets if t not in found] + else: + found, missing = self._fetch(targets) + if missing: + log(f"{len(missing)} file(s) are not in the dataset and were skipped: {missing[:5]}") + return [found[t] for t in targets if t in found] + + def download_cdl(self, counties: StrOrList, years: YearSpec = None) -> List[str]: + """Downloads Cropland Data Layer GeoTIFFs. See `download`.""" + return self.download("cdl", counties, years) + + def download_landsat(self, counties: StrOrList, years: YearSpec = None, months: Optional[Iterable[int]] = None) -> List[str]: + """Downloads monthly Landsat GeoTIFFs. See `download`.""" + return self.download("landsat", counties, years, months) + + def download_et(self, counties: StrOrList, years: YearSpec = None, months: Optional[Iterable[int]] = None) -> List[str]: + """Downloads monthly OpenET GeoTIFFs. See `download`.""" + return self.download("et", counties, years, months) + + def download_irrigation(self, counties: StrOrList, years: YearSpec = None) -> List[str]: + """Downloads irrigated land GeoTIFFs. See `download`.""" + return self.download("irrigation", counties, years) + + def download_climate(self, counties: StrOrList, years: YearSpec = None) -> List[str]: + """Downloads DayMet Zarr stores, one per county and year. See `download`.""" + return self.download("climate", counties, years) + + def download_soil(self, counties: StrOrList) -> List[str]: + """Downloads soil Zarr stores, one per county. See `download`.""" + return self.download("soil", counties) + + def download_yield(self) -> List[str]: + """Downloads the yield tables and the CDL crosswalk, and returns their local paths.""" + return [self._file(path) for path in (catalog.YIELD_TABLE, catalog.YIELD_DETAIL_TABLE, catalog.CDL_CROSSWALK)] + + # Loading. + + def load_cdl(self, county: str, year: int, crops=None, geometry=None) -> xr.DataArray: + """Reads the Cropland Data Layer of a county as a `(y, x)` array of class codes. + + `crops` keeps only the given CDL classes, as names (`"Tomatoes"`) + or codes (`54`), and sets every other pixel to 0. Look up names + with `cdl_classes()`, or use `yield_crop_cdl_codes` to go from a + yield crop to its CDL classes. + """ + cdl = self._read_raster("cdl", county, year, geometry=geometry)[0] + if crops is not None: + cdl = cdl.where(cdl.isin(catalog.cdl_codes(crops)), 0).astype(cdl.dtype) + return cdl.assign_attrs(classes=catalog.CDL_CLASSES) + + def crop_mask(self, county: str, year: int, crops=None, geometry=None) -> xr.DataArray: + """Returns a boolean `(y, x)` mask of the CDL pixels of the given crops. + + `crops` takes CDL names or codes. `None` means every cropland + class (no urban, water, or natural land cover). + """ + cdl = self._read_raster("cdl", county, year, geometry=geometry)[0] + return cdl.isin(catalog.cdl_codes(crops)).rename("crop_mask") + + def load_irrigation(self, county: str, year: int, geometry=None) -> xr.DataArray: + """Reads irrigated land as a `(y, x)` array: 1 irrigated, 0 not irrigated. + + With `geometry`, pixels outside it are 255, the value in `attrs["nodata"]`. + """ + return self._read_raster("irrigation", county, year, geometry=geometry)[0] + + def load_landsat(self, county: str, year: int, months: Optional[Iterable[int]] = None, geometry=None) -> xr.DataArray: + """Reads monthly Landsat reflectance as a `(month, band, y, x)` array. + + Values are returned as stored in the dataset, without rescaling to + reflectance. A full county is large (about 2 GB for one year of a mid-sized + county), so pass `months` or `geometry` to read less. + """ + return self._read_monthly("landsat", county, year, months, geometry) + + def load_et(self, county: str, year: int, months: Optional[Iterable[int]] = None, geometry=None) -> xr.DataArray: + """Reads monthly OpenET evapotranspiration as a `(month, y, x)` array. + + The ET grid can differ from the CDL and Landsat grid by a pixel at + the edges, so align the arrays before stacking them. + """ + return self._read_monthly("et", county, year, months, geometry).isel(band=0, drop=True) + + # Zarr layers. + + def load_climate( + self, + county: str, + years: YearSpec = None, + variables: StrOrList = None, + monthly: bool = False, + geometry=None, + ) -> xr.Dataset: + """Reads DayMet weather as an xarray Dataset with `(time, y, x)` variables. + + Variables are `prcp`, `tmax`, `tmin`, `srad`, `vp`, `dayl`, `pet`, + `swe`, and `snow`. Several years are joined along `time`. + `monthly=True` returns monthly means instead of daily values. + DayMet years have 365 days, so leap years end on December 30. + `geometry` keeps the grid cells inside its bounding box. + """ + slug = catalog.county_slug(county) + datasets = [ + self._open_zarr("climate", slug, year, variables, geometry) + for year in catalog.resolve_years("climate", years) + ] + ds = datasets[0] if len(datasets) == 1 else xr.concat(datasets, dim="time") + if monthly: + ds = ds.resample(time="MS").mean() + return ds + + def load_soil(self, county: str, variables: StrOrList = None, geometry=None) -> xr.Dataset: + """Reads the soil attributes as an xarray Dataset with `(y, x)` variables. + + Categorical variables carry their code labels in + `ds[name].attrs["categories"]`. `geometry` keeps the grid cells + inside its bounding box. + """ + slug = catalog.county_slug(county) + return self._open_zarr("soil", slug, catalog.LAYERS["soil"].years[0], variables, geometry) + + # Tables. + + def load_yield( + self, + county: StrOrList = None, + crop: StrOrList = None, + years: YearSpec = None, + detail: bool = False, + ) -> pd.DataFrame: + """Returns county crop yield as a pandas DataFrame. + + The default table has one row per county, crop, and year, with + `yield_t_per_ha` and the crop group. Crops are merged groups such + as `"TOMATOES"` or `"GRAPES"`, matched ignoring case. `detail=True` + returns the per-commodity report rows instead, with harvested + area, production, price, and value; there `crop` matches + `Crop_Name_Clean` (e.g. `"Tomatoes Processing"`). + """ + if detail: + df = pd.read_parquet(self._file(catalog.YIELD_DETAIL_TABLE)) + county_col, crop_col, year_col = "County", "Crop_Name_Clean", "Year" + else: + df = pd.read_parquet(self._file(catalog.YIELD_TABLE)) + county_col, crop_col, year_col = "county", "crop", "year" + + keep = pd.Series(True, index=df.index) + if county is not None: + names = [catalog.resolve_county(c) for c in _as_list(county)] + keep &= df[county_col].isin(names) + if crop is not None: + crops = {c.strip().lower() for c in _as_list(crop)} + keep &= df[crop_col].str.lower().isin(crops) + if years is not None: + keep &= df[year_col].isin(catalog.check_years(years, df[year_col].unique(), "The yield table")) + return df[keep].sort_values([county_col, crop_col, year_col]).reset_index(drop=True) + + def yield_crops(self) -> List[str]: + """Returns the crop names used in the yield table.""" + return sorted(pd.read_parquet(self._file(catalog.YIELD_TABLE), columns=["crop"])["crop"].unique()) + + def cdl_crosswalk(self) -> pd.DataFrame: + """Returns the table that maps each yield crop to its CDL classes.""" + return pd.read_csv(self._file(catalog.CDL_CROSSWALK)) + + def yield_crop_cdl_codes(self, crop: str) -> List[int]: + """Returns the CDL codes of a yield crop, e.g. `"HAY"` -> `[36, 37]`. + + Returns an empty list for crops that have no CDL class. + """ + crosswalk = self.cdl_crosswalk() + row = crosswalk[crosswalk["yield_crop"].str.lower() == crop.strip().lower()] + if row.empty: + raise ValueError(f"Unknown yield crop '{crop}'. See `yield_crops()`.") + codes = row["cdl_codes"].iloc[0] + return [] if pd.isna(codes) else [int(c) for c in str(codes).split(";")] + + def load_boundaries(self): + """Returns the California county boundaries as a geopandas GeoDataFrame (EPSG:4326).""" + try: + import geopandas as gpd + except ImportError: + raise ImportError("County boundaries need geopandas. Install it with `pip install geopandas`.") + return gpd.read_file(self._file(catalog.COUNTY_BOUNDARIES)) + + # Internals. + + def _file(self, path: str) -> str: + """Returns the local path of a dataset file, downloading it from the Hub if needed.""" + if self._repo_id is None: + local = os.path.join(self._root, path) + if not os.path.exists(local): + raise FileNotFoundError(f"The dataset file '{path}' is missing: '{local}'.") + return local + + from huggingface_hub import hf_hub_download + from huggingface_hub.errors import EntryNotFoundError + + try: + return hf_hub_download( + repo_id=self._repo_id, + repo_type="dataset", + filename=path, + revision=self._revision, + cache_dir=self._cache_dir, + token=getattr(self, "_token", None), # not serialized + ) + except EntryNotFoundError: + raise FileNotFoundError(f"The file '{path}' is not in the dataset '{self._repo_id}'.") + + def _store(self, path: str) -> str: + """Returns the local path of a Zarr store, downloading it from the Hub if needed.""" + if self._repo_id is None: + local = os.path.join(self._root, path) + if not os.path.isdir(local): + raise FileNotFoundError(f"The Zarr store '{path}' is missing: '{local}'.") + return local + found, missing = self._fetch([path]) + if missing: + raise FileNotFoundError(f"The Zarr store '{path}' is not in the dataset '{self._repo_id}'.") + return found[path] + + def _resolve_commit(self, revision: Optional[str]) -> str: + """Returns the commit hash of `revision`, so every file comes from one version of the dataset.""" + if revision is not None and re.fullmatch(r"[0-9a-f]{40}", revision): + return revision + from huggingface_hub import hf_hub_download + + # The Hugging Face cache names each snapshot folder after its commit. This + # also works offline once the dataset card is cached. + card = hf_hub_download( + repo_id=self._repo_id, + repo_type="dataset", + filename=catalog.DATASET_CARD, + revision=revision, + cache_dir=self._cache_dir, + token=self._token, + ) + return os.path.basename(os.path.dirname(card)) + + def _fetch(self, targets: List[str]) -> Tuple[Dict[str, str], List[str]]: + """Downloads files and Zarr stores from the Hub in one batch. + + Returns the local path of every target in the dataset, and the + targets that are not in it. Raises a `DownloadError` that lists + every file that is in the dataset but failed to download. + """ + from huggingface_hub import hf_hub_download, list_repo_tree + from huggingface_hub.errors import EntryNotFoundError + from huggingface_hub.hf_api import RepoFile + + token = getattr(self, "_token", None) # not serialized + + # List each layer folder (`counties//`) once to see which files exist. + listed = set() + for folder in sorted({"/".join(t.split("/")[:3]) for t in targets}): + try: + entries = list_repo_tree( + self._repo_id, folder, recursive=True, repo_type="dataset", revision=self._revision, token=token + ) + listed.update(entry.path for entry in entries if isinstance(entry, RepoFile)) + except EntryNotFoundError: + pass # The whole folder is missing. + + # A target is either one file or a Zarr store, i.e. every file under it. + files = {t: [t] if t in listed else sorted(f for f in listed if f.startswith(t + "/")) for t in targets} + wanted = [f for names in files.values() for f in names] + + def download(filename): + return hf_hub_download( + repo_id=self._repo_id, + repo_type="dataset", + filename=filename, + revision=self._revision, + cache_dir=self._cache_dir, + token=token, + ) + + local, failed = {}, {} + with ThreadPoolExecutor(max_workers=_DOWNLOAD_WORKERS) as pool: + futures = {f: pool.submit(download, f) for f in wanted} + for f, future in futures.items(): + try: + local[f] = future.result() + except Exception as error: + failed[f] = error + if failed: + raise DownloadError(failed) + + found = {} + for target, names in files.items(): + if names: + # The cache keeps the repo layout, so a store's folder sits above its files. + first = local[names[0]] + found[target] = first if names == [target] else first[: len(first) - len(names[0])] + target + missing = [t for t, names in files.items() if not names] + return found, missing + + def _layer_path(self, layer: str, slug: str, year: int, month: Optional[int]) -> str: + spec = catalog.LAYERS[layer] + path = spec.path(layer, slug, year, month) + return self._store(path) if spec.zarr else self._file(path) + + def _read_raster(self, layer: str, county: str, year: int, month: Optional[int] = None, geometry=None) -> xr.DataArray: + """Reads one GeoTIFF as a `(band, y, x)` array, optionally cropped to a geometry.""" + catalog.resolve_years(layer, year) + path = self._layer_path(layer, catalog.county_slug(county), year, month) + with rasterio.open(path) as src: + nodata = src.nodata + if geometry is None: + data, transform = src.read(), src.transform + else: + # Pixels outside the geometry get the file's no-data value. Files without + # one get NaN or the dtype's maximum, never a value that could be a class. + if nodata is None: + dtype = np.dtype(src.dtypes[0]) + nodata = np.nan if np.issubdtype(dtype, np.floating) else np.iinfo(dtype).max + data, transform = rasterio.mask.mask(src, [geometry], crop=True, nodata=nodata) + bands = list(src.descriptions) if all(src.descriptions) else list(range(1, src.count + 1)) + attrs = {"crs": src.crs.to_string(), "transform": tuple(transform)[:6], "nodata": nodata} + + height, width = data.shape[1:] + x = transform.c + transform.a * (np.arange(width) + 0.5) + y = transform.f + transform.e * (np.arange(height) + 0.5) + return xr.DataArray( + data, dims=("band", "y", "x"), coords={"band": bands, "y": y, "x": x}, name=layer, attrs=attrs + ) + + def _read_monthly(self, layer, county, year, months, geometry) -> xr.DataArray: + months = _check_months(months) + arrays = [self._read_raster(layer, county, year, month, geometry) for month in months] + return xr.concat(arrays, dim=pd.Index(months, name="month"), join="override") + + def _open_zarr(self, layer: str, slug: str, year: int, variables: StrOrList, geometry) -> xr.Dataset: + try: + import zarr # noqa: F401 + except ImportError: + raise ImportError("The climate and soil layers need zarr 3. Install it with `pip install 'zarr>=3'`.") + path = self._layer_path(layer, slug, year, None) + ds = xr.open_dataset(path, engine="zarr", consolidated=False, chunks=None, decode_coords="all") + # The CRS is stored in a `spatial_ref` variable; keep it as a coordinate, not data. + if "spatial_ref" in ds.data_vars: + ds = ds.set_coords("spatial_ref") + if variables is not None: + names = list(_as_list(variables)) + unknown = [v for v in names if v not in ds.data_vars] + if unknown: + raise ValueError(f"Layer '{layer}' has no variable(s) {unknown}. It has {list(ds.data_vars)}.") + ds = ds[names] + if geometry is not None: + minx, miny, maxx, maxy = rasterio.features.bounds(geometry) + y_slice = slice(maxy, miny) if ds["y"][0] > ds["y"][-1] else slice(miny, maxy) + ds = ds.sel(x=slice(minx, maxx), y=y_slice) + return ds.load() + + +def _as_list(value) -> list: + return [value] if isinstance(value, str) else list(value) + + +def _check_months(months: Optional[Iterable[int]]) -> List[int]: + months = list(months) if months is not None else list(range(1, 13)) + if any(m not in range(1, 13) for m in months): + raise ValueError(f"Months must be between 1 and 12, got {months}.") + return months diff --git a/agml/ag_stats/nass/__init__.py b/agml/ag_stats/nass/__init__.py new file mode 100644 index 00000000..18372ce5 --- /dev/null +++ b/agml/ag_stats/nass/__init__.py @@ -0,0 +1,32 @@ +# Copyright 2021 UC Davis Plant AI and Biophysics Lab +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module gives access to USDA NASS crop statistics (yield, area, +production, crop progress, crop condition, and forecasts) at national, +state, district, and county level, with queries by crop, place, and year. +""" + +try: + import pandas # noqa: F401 + import pyarrow # noqa: F401 +except ImportError: + raise ImportError( + "The `agml.ag_stats.nass` module needs pandas and pyarrow. Install them with `pip install agml[ag_stats]`." + ) + +from .catalog import NASSCatalog +from .loader import DEFAULT_REPO_ID, FORMATS, TABLES, NASSDataLoader + +__all__ = ["NASSDataLoader", "NASSCatalog", "DEFAULT_REPO_ID", "FORMATS", "TABLES"] diff --git a/agml/ag_stats/nass/catalog.py b/agml/ag_stats/nass/catalog.py new file mode 100644 index 00000000..538c4f2f --- /dev/null +++ b/agml/ag_stats/nass/catalog.py @@ -0,0 +1,240 @@ +"""Lookup tables and name resolution for the NASS crop statistics. + +The NASS fact tables are keyed by codes (a 12-character `crop_id`, 2-digit +state FIPS, 5-digit county FIPS, and agricultural statistics district +codes). The `NASSCatalog` reads the small dimension tables that ship with +the dataset and turns what a user types ("corn", "Iowa", "Story") into +those codes. +""" + +import difflib +import os +from typing import Iterable, List, Optional, Union + +import pandas as pd +import pyarrow.parquet as pq + +# Dimension tables, keyed by the name used inside the catalog. +_DIM_FILES = { + "crop": "dim_crop.parquet", + "state": "dim_state.parquet", + "county": "dim_county.parquet", + "district": "dim_asd.parquet", + "county_remap": "county_fips_remap.parquet", +} + +# Columns of `dim_crop` that a user can filter on besides the commodity. +_CROP_ATTRIBUTES = ("class", "practice", "utilization") + +StrOrList = Optional[Union[str, int, Iterable[Union[str, int]]]] + + +def _as_list(value: StrOrList) -> List[str]: + """Turns a scalar or an iterable of values into a list of strings.""" + if value is None: + return [] + if isinstance(value, (str, int)): + return [str(value)] + return [str(v) for v in value] + + +def _no_match(kind: str, value: str, choices: Iterable[str]) -> ValueError: + """Builds a `ValueError` that suggests the closest valid choices.""" + unique = sorted({str(c).upper() for c in choices}) + close = difflib.get_close_matches(value.upper(), unique, n=5, cutoff=0.6) + hint = f" Did you mean one of: {', '.join(close)}?" if close else "" + return ValueError(f"Unknown {kind} '{value}'.{hint}") + + +class NASSCatalog(object): + """Resolves crop, state, county, and district names to NASS codes. + + Parameters + ---------- + root : str + The directory holding the NASS parquet files (`dim_crop.parquet`, + `dim_state.parquet`, and so on). + + Examples + -------- + >>> catalog = NASSCatalog("/path/to/nass-usda-full-data/parquet") + >>> catalog.resolve_states("Iowa") + ['19'] + >>> catalog.resolve_counties("Story", state="IA") + ['19169'] + """ + + def __init__(self, root: str): + self.root = root + self._dims = {} + for name, filename in _DIM_FILES.items(): + path = os.path.join(root, filename) + if not os.path.exists(path): + raise FileNotFoundError(f"Could not find the NASS dimension table '{filename}' in '{root}'.") + self._dims[name] = pq.read_table(path).to_pandas() + + # Listings. + + def crops(self, commodity: Optional[str] = None) -> pd.DataFrame: + """Returns the crop table, optionally only the rows of one commodity.""" + df = self._dims["crop"] + if commodity is not None: + df = df[df["commodity"] == commodity.upper()] + return df.reset_index(drop=True) + + def commodities(self) -> List[str]: + """Returns the sorted list of commodity names (e.g., `CORN`).""" + return sorted(self._dims["crop"]["commodity"].unique()) + + def states(self) -> pd.DataFrame: + """Returns the state table sorted by state FIPS code.""" + return self._dims["state"].sort_values("state_fips").reset_index(drop=True) + + def counties(self, state: StrOrList = None) -> pd.DataFrame: + """Returns the county table, optionally only for the given states.""" + df = self._dims["county"] + if state is not None: + df = df[df["state_fips"].isin(self.resolve_states(state))] + return df.sort_values("county_fips").reset_index(drop=True) + + def districts(self, state: StrOrList = None) -> pd.DataFrame: + """Returns the agricultural statistics district table.""" + df = self._dims["district"] + if state is not None: + df = df[df["state_fips"].isin(self.resolve_states(state))] + return df.sort_values("asd_id").reset_index(drop=True) + + # Name resolution. + + def resolve_states(self, state: StrOrList) -> List[str]: + """Resolves states to 2-digit FIPS codes. + + Each value can be a postal code (`"IA"`), a name (`"Iowa"`), or a + FIPS code (`"19"` or `19`), in any letter case. + """ + df = self._dims["state"] + by_alpha = dict(zip(df["state_alpha"].str.upper(), df["state_fips"])) + by_name = dict(zip(df["state_name"].str.upper(), df["state_fips"])) + fips = set(df["state_fips"]) + + out = [] + for value in _as_list(state): + key = value.strip().upper() + if key.isdigit() and key.zfill(2) in fips: + out.append(key.zfill(2)) + elif key in by_alpha: + out.append(by_alpha[key]) + elif key in by_name: + out.append(by_name[key]) + else: + raise _no_match("state", value, list(by_alpha) + list(by_name)) + return out + + def state_alphas(self, state_fips: Iterable[str]) -> List[str]: + """Maps 2-digit state FIPS codes to postal codes.""" + df = self._dims["state"] + lookup = dict(zip(df["state_fips"], df["state_alpha"])) + return [lookup[f] for f in state_fips] + + def resolve_counties(self, county: StrOrList, state: StrOrList = None) -> List[str]: + """Resolves counties to 5-digit 2020 county FIPS codes. + + Each value can be a 5-digit FIPS code or a county name. Names are + not unique across states (there are 31 Washington counties), so a + name needs `state` unless it occurs in only one state. Old NASS + codes for renamed or merged counties are mapped to their 2020 code. + """ + df = self._dims["county"] + remap = dict(zip(self._dims["county_remap"]["fips_nass"], self._dims["county_remap"]["fips_2020"])) + fips = set(df["county_fips"]) + if state is not None: + df = df[df["state_fips"].isin(self.resolve_states(state))] + + out = [] + for value in _as_list(county): + key = value.strip() + if key.isdigit(): + code = remap.get(key.zfill(5), key.zfill(5)) + if code not in fips: + raise ValueError(f"Unknown county FIPS code '{value}'.") + out.append(code) + continue + + name = key.upper().removesuffix(" COUNTY") + matches = df[df["county_name"].str.upper() == name] + if matches.empty: + raise _no_match("county", value, df["county_name"]) + if matches["state_fips"].nunique() > 1: + states = ", ".join(sorted(matches["state_alpha"])) + raise ValueError(f"County name '{value}' exists in several states ({states}). Pass `state` as well.") + out.extend(matches["county_fips"]) + return out + + def resolve_districts(self, district: StrOrList, state: StrOrList = None) -> List[str]: + """Resolves agricultural statistics districts to 4-digit `asd_id` codes. + + Each value can be a 4-digit `asd_id` (state FIPS + district code), + or a 2-digit district code or a district name together with `state`. + """ + df = self._dims["district"] + if state is not None: + df = df[df["state_fips"].isin(self.resolve_states(state))] + + out = [] + for value in _as_list(district): + key = value.strip().upper() + if key.isdigit() and len(key) == 4: + matches = self._dims["district"][self._dims["district"]["asd_id"] == key] + elif key.isdigit(): + if state is None: + raise ValueError(f"District code '{value}' is only unique within a state. Pass `state` as well.") + matches = df[df["asd_code"] == key.zfill(2)] + else: + matches = df[df["asd_desc"].str.upper() == key] + if matches["state_fips"].nunique() > 1: + raise ValueError(f"District name '{value}' exists in several states. Pass `state` as well.") + if matches.empty: + raise _no_match("district", value, df["asd_desc"]) + out.extend(matches["asd_id"]) + return out + + def resolve_crops( + self, + crop: StrOrList = None, + crop_class: StrOrList = None, + practice: StrOrList = None, + utilization: StrOrList = None, + ) -> List[str]: + """Resolves a crop description to the matching `crop_id` codes. + + `crop` is matched against the commodity first (`"corn"` gives every + corn variant), then against the full crop label (`"CORN, GRAIN"`), + then against `crop_id` itself. `crop_class`, `practice`, and + `utilization` narrow the result further (e.g., `utilization="grain"`). + All matches ignore letter case. + """ + df = self._dims["crop"] + if crop is not None: + keep = pd.Series(False, index=df.index) + for value in _as_list(crop): + key = value.strip().upper() + for column in ("commodity", "crop_label"): + hit = df[column] == key + if hit.any(): + break + else: + hit = df["crop_id"] == value.strip() + if not hit.any(): + raise _no_match("crop", value, list(df["commodity"].unique()) + list(df["crop_label"])) + keep |= hit + df = df[keep] + + for column, value in zip(_CROP_ATTRIBUTES, (crop_class, practice, utilization)): + if value is None: + continue + wanted = [v.strip().upper() for v in _as_list(value)] + narrowed = df[df[column].isin(wanted)] + if narrowed.empty: + raise _no_match(column, ", ".join(wanted), df[column].unique()) + df = narrowed + return list(df["crop_id"]) diff --git a/agml/ag_stats/nass/loader.py b/agml/ag_stats/nass/loader.py new file mode 100644 index 00000000..904c9d3c --- /dev/null +++ b/agml/ag_stats/nass/loader.py @@ -0,0 +1,527 @@ +"""Query interface for the USDA NASS crop statistics.""" + +import os +from dataclasses import dataclass +from typing import Dict, Iterable, Optional, Sequence, Tuple, Union + +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.dataset as ds + +from agml.framework import AgMLSerializable +from agml.ag_stats.nass.catalog import _DIM_FILES, NASSCatalog, StrOrList, _as_list + +# The environment variable read when no `root` is passed to the loader. +_ROOT_ENV_VAR = "AGML_NASS_PATH" + +# The Hugging Face dataset repo used when no local copy is given. +DEFAULT_REPO_ID = "Project-AgML/usda_nass_crop_statistics" + +# The 2020 Census boundary files, in `boundaries/` next to `parquet/`. +_BOUNDARY_FILES = { + ("county", True): "us_county_2020.parquet", + ("county", False): "us_county_2020_attributes.parquet", + ("state", True): "us_state_2020.parquet", + ("state", False): "us_state_2020_attributes.parquet", +} + +# Maps the `level` argument to the NASS `agg_level` values. +_LEVELS = { + "national": "NATIONAL", + "state": "STATE", + "district": "AGRICULTURAL DISTRICT", + "county": "COUNTY", +} + + +# Results are sorted by these columns (when present), then by year and time within the year. +_SORT_COLUMNS = ("crop_id", "agg_level", "state_fips", "state_alpha", "asd_code", "county_fips") +_TIME_COLUMNS = ("forecast_month", "week_ending", "stage", "rating", "statistic") +_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") + +YearSpec = Optional[Union[int, Tuple[int, int], Iterable[int]]] + + +@dataclass(frozen=True) +class _Table: + """Describes where a fact table lives and which filters it supports.""" + + filename: str + year_column: str = "year" + has_agg_level: bool = True + has_state_fips: bool = True + has_county: bool = True + has_district: bool = True + has_other_counties: bool = True + description: str = "" + + +# Every fact table in the dataset. The keys are the names used in `query`. +TABLES: Dict[str, _Table] = { + "yield": _Table( + "yield.parquet", + description="Yield at national, state, district, and county level, with a t/ha column.", + ), + "county_yield": _Table( + "v_county_yield_main.parquet", + has_agg_level=False, + has_state_fips=False, + has_district=False, + has_other_counties=False, + description="County yield for the main crop variants, on 2020 county FIPS codes, with QA flags.", + ), + "area_production": _Table( + "area_production.parquet", + description="Area planted, area harvested, and production (`statistic` column).", + ), + "census": _Table( + "census_crops.parquet", + description="Census of Agriculture crop records, every five years from 1997.", + ), + "forecast": _Table( + "yield_forecast.parquet", + has_county=False, + has_district=False, + has_other_counties=False, + description="In-season yield forecasts by `forecast_month` (state and national).", + ), + "progress": _Table( + "crop_progress.parquet", + has_county=False, + has_district=False, + has_other_counties=False, + description="Weekly crop progress by `stage`, as percent (state and national).", + ), + "condition": _Table( + "crop_condition.parquet", + year_column="crop_year", + has_county=False, + has_district=False, + has_other_counties=False, + description="Weekly crop condition, one column per rating (state and national).", + ), + "condition_long": _Table( + "crop_condition_long.parquet", + has_county=False, + has_district=False, + has_other_counties=False, + description="Weekly crop condition, one row per rating (state and national).", + ), +} + +FORMATS = ("pandas", "polars", "arrow", "records", "csv", "parquet") + + +class NASSDataLoader(AgMLSerializable): + """Queries USDA NASS crop statistics by crop, place, and year. + + The loader reads the AgML NASS dataset, a set of parquet files built + from the USDA NASS Quick Stats database. By default the files come + from the Hugging Face Hub: each table is downloaded the first time it + is queried and read from the local Hugging Face cache after that. + Filters are pushed down to the parquet reader, so a query for one + county reads only a small part of each file. + + Parameters + ---------- + root : str, optional + A local copy of the dataset. Either the `parquet` folder itself or + its parent. Defaults to the `AGML_NASS_PATH` environment variable. + When neither is set, the dataset is read from `repo_id`. + repo_id : str, optional + The Hugging Face dataset repo to read from. + revision : str, optional + A branch, tag, or commit of `repo_id`. Pin a commit to make + results reproducible. Defaults to the latest version. + cache_dir : str, optional + Where downloaded files are kept. Defaults to the Hugging Face cache. + token : str, optional + A Hugging Face token. Not needed for the public dataset. + + Examples + -------- + >>> nass = NASSDataLoader() # reads from the Hugging Face Hub + >>> nass = NASSDataLoader("/path/to/nass-usda-full-data") # a local copy + >>> df = nass.load_yield(crop="corn", utilization="grain", state="IA", + ... county="Story", years=(2000, 2024)) + >>> nass.query("progress", crop="soybeans", state="IL", years=2023, + ... where={"stage": "PLANTED"}, format="polars") + """ + + serializable = frozenset(("root", "repo_id", "revision", "cache_dir")) + + def __init__( + self, + root: Optional[str] = None, + repo_id: str = DEFAULT_REPO_ID, + revision: Optional[str] = None, + cache_dir: Optional[str] = None, + token: Optional[str] = None, + ): + self._cache_dir = cache_dir + self._token = token + root = root or os.environ.get(_ROOT_ENV_VAR) + if root is None: + # `repo_id` is only kept in Hub mode; `None` marks a local copy. + self._repo_id = repo_id + root = self._download_dimension_tables(revision) + else: + self._repo_id = None + self._revision = None + root = os.path.realpath(os.path.expanduser(root)) + if os.path.isdir(os.path.join(root, "parquet")): + root = os.path.join(root, "parquet") + if not os.path.isdir(root): + raise FileNotFoundError(f"The NASS dataset directory '{root}' does not exist.") + self._root = root + self._catalog = NASSCatalog(root) + + def __repr__(self): + if self._repo_id is not None: + return f"" + return f"" + + @property + def root(self) -> str: + """The directory holding the NASS parquet files.""" + return self._root + + @property + def repo_id(self) -> Optional[str]: + """The Hugging Face repo the data comes from, or `None` for a local copy.""" + return self._repo_id + + @property + def revision(self) -> Optional[str]: + """The commit of `repo_id` the data comes from, or `None` for a local copy.""" + return self._revision + + @property + def catalog(self) -> NASSCatalog: + """The `NASSCatalog` used to resolve crop and place names.""" + # Only `root` is serialized, so the catalog is rebuilt after unpickling. + if getattr(self, "_catalog", None) is None: + self._catalog = NASSCatalog(self._root) + return self._catalog + + @staticmethod + def tables() -> Dict[str, str]: + """Returns the name and a one-line description of every queryable table.""" + return {name: table.description for name, table in TABLES.items()} + + def schema(self, table: str) -> pa.Schema: + """Returns the column names and types of a table.""" + return self._dataset(table).schema + + def query( + self, + table: str, + crop: StrOrList = None, + crop_class: StrOrList = None, + practice: StrOrList = None, + utilization: StrOrList = None, + state: StrOrList = None, + county: StrOrList = None, + district: StrOrList = None, + years: YearSpec = None, + level: Optional[str] = None, + where: Optional[Dict[str, Union[str, int, float, bool, Sequence]]] = None, + columns: Optional[Sequence[str]] = None, + include_other_counties: bool = False, + format: str = "pandas", + path: Optional[str] = None, + ): + """Returns the rows of a table that match every given filter. + + Parameters + ---------- + table : str + One of the names in `NASSDataLoader.tables()`. + crop, crop_class, practice, utilization : str or list, optional + The crop, resolved with `NASSCatalog.resolve_crops`. `crop` + matches a commodity (`"corn"`), a crop label (`"CORN, GRAIN"`), + or a `crop_id`. + state : str, int, or list, optional + Postal codes, names, or FIPS codes. + county : str, int, or list, optional + 5-digit FIPS codes or county names (names need `state` when + they are not unique). + district : str or list, optional + Agricultural statistics districts, as 4-digit `asd_id` codes or + as codes or names together with `state`. + years : int, tuple, or list, optional + One year, an inclusive `(start, end)` range, or a list of years. + level : str, optional + One of `national`, `state`, `district`, or `county`. + where : dict, optional + Extra equality filters on any column, e.g. + `{"statistic": "production"}`. A list value matches any of its items. + columns : list of str, optional + The columns to return. Defaults to every column. + include_other_counties : bool + Whether to keep the NASS "other (combined) counties" rows. + These have no county FIPS code and are dropped by default. + format : str + One of `pandas`, `polars`, `arrow`, `records`, `csv`, or `parquet`. + path : str, optional + The output file, required for the `csv` and `parquet` formats. + + Returns + ------- + The matching rows in the requested format, sorted by crop, place, + and time, or the output file path for the `csv` and `parquet` formats. + """ + spec = self._table_spec(table) + self._check_format(format, path) + + dataset = self._dataset(table) + expression = self._build_filter( + table, spec, dataset.schema, crop, crop_class, practice, utilization, + state, county, district, years, level, where, include_other_counties, + ) + if columns is not None: + missing = [c for c in columns if c not in dataset.schema.names] + if missing: + raise ValueError(f"Table '{table}' has no column(s) {missing}.") + result = dataset.to_table(filter=expression, columns=list(columns) if columns else None) + return self._convert(self._sort(result, spec), format, path) + + # Convenience wrappers, one per table. + + def load_yield(self, **kwargs): + """Queries the `yield` table. Takes the same arguments as `query`.""" + return self.query("yield", **kwargs) + + def load_county_yield(self, **kwargs): + """Queries the `county_yield` table. Takes the same arguments as `query`.""" + return self.query("county_yield", **kwargs) + + def load_area_production(self, statistic: StrOrList = None, **kwargs): + """Queries the `area_production` table. + + `statistic` is one or more of `area_planted`, `area_harvested`, and + `production`. The other arguments are the same as for `query`. + """ + where = self._merge_where(kwargs, statistic=statistic) + return self.query("area_production", where=where, **kwargs) + + def load_census(self, statistic: StrOrList = None, **kwargs): + """Queries the `census` table. See `area_production` for `statistic`.""" + where = self._merge_where(kwargs, statistic=statistic) + return self.query("census", where=where, **kwargs) + + def load_forecast(self, **kwargs): + """Queries the `forecast` table. Takes the same arguments as `query`.""" + return self.query("forecast", **kwargs) + + def load_progress(self, stage: StrOrList = None, **kwargs): + """Queries the `progress` table, e.g. `stage="planted"`. + + `stage` ignores letter case and an optional `PCT ` prefix, so + `"planted"`, `"PLANTED"`, and `"PCT PLANTED"` are the same. + """ + if stage is not None: + stage = [s.strip().upper().removeprefix("PCT ") for s in _as_list(stage)] + where = self._merge_where(kwargs, stage=stage) + return self.query("progress", where=where, **kwargs) + + def load_condition(self, long: bool = False, **kwargs): + """Queries the weekly condition ratings, wide (default) or long.""" + return self.query("condition_long" if long else "condition", **kwargs) + + def load_boundaries(self, level: str = "county", geometry: bool = True, format: str = "pandas", path: Optional[str] = None): + """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, e.g. for `geopandas.GeoSeries.from_wkb`. + """ + if level not in ("county", "state"): + raise ValueError(f"Unknown boundary level '{level}'. Choose 'county' or 'state'.") + self._check_format(format, path) + filename = _BOUNDARY_FILES[(level, geometry)] + result = ds.dataset(self._file("boundaries", filename), format="parquet").to_table() + return self._convert(result, format, path) + + # Internals. + + def _download_dimension_tables(self, revision: Optional[str]) -> str: + """Downloads the small lookup tables and returns their local directory. + + The commit they come from is kept in `_revision`, so every table + downloaded later comes from the same version of the dataset. + """ + from huggingface_hub import snapshot_download + + folder = snapshot_download( + repo_id=self._repo_id, + repo_type="dataset", + revision=revision, + cache_dir=self._cache_dir, + token=self._token, + allow_patterns=[f"parquet/{name}" for name in _DIM_FILES.values()], + ) + # The Hugging Face cache names each snapshot folder after its commit. + self._revision = os.path.basename(folder) + return os.path.join(folder, "parquet") + + def _file(self, folder: str, filename: str) -> str: + """Returns the local path of a dataset file, downloading it from the Hub if needed.""" + if self._repo_id is None: + base = self.root if folder == "parquet" else os.path.join(os.path.dirname(self.root), folder) + path = os.path.join(base, filename) + if not os.path.exists(path): + raise FileNotFoundError(f"The dataset file '{filename}' is missing: '{path}'.") + return path + + from huggingface_hub import hf_hub_download + + return hf_hub_download( + repo_id=self._repo_id, + repo_type="dataset", + filename=f"{folder}/{filename}", + revision=self._revision, + cache_dir=self._cache_dir, + token=getattr(self, "_token", None), # not serialized + ) + + @staticmethod + def _table_spec(table: str) -> _Table: + if table not in TABLES: + raise ValueError(f"Unknown table '{table}'. Choose one of {list(TABLES)}.") + return TABLES[table] + + def _dataset(self, table: str) -> ds.Dataset: + return ds.dataset(self._file("parquet", self._table_spec(table).filename), format="parquet") + + @staticmethod + def _sort(result: pa.Table, spec: _Table) -> pa.Table: + """Sorts rows by crop, place, and time. Forecast months sort in calendar order.""" + names = result.schema.names + order = [c for c in (*_SORT_COLUMNS, spec.year_column, *_TIME_COLUMNS) if c in names] + if not order: + return result + if "forecast_month" in names: + month = pc.index_in(result["forecast_month"], value_set=pa.array(_MONTHS)) + result = result.append_column("_month", month) + order = ["_month" if c == "forecast_month" else c for c in order] + result = result.sort_by([(c, "ascending") for c in order]) + return result.drop_columns(["_month"]) if "_month" in result.schema.names else result + + @staticmethod + def _merge_where(kwargs: dict, **extra) -> Optional[dict]: + """Combines a wrapper's own column filter with any `where` the caller passed.""" + where = dict(kwargs.pop("where", None) or {}) + where.update({k: v for k, v in extra.items() if v is not None}) + return where or None + + @staticmethod + def _years_filter(column: str, years: YearSpec) -> ds.Expression: + field = pc.field(column) + if isinstance(years, int): + return field == years + if isinstance(years, tuple) and len(years) == 2: + start, end = years + return (field >= start) & (field <= end) + return field.isin([int(y) for y in years]) + + def _build_filter( + self, table, spec, schema, crop, crop_class, practice, utilization, + state, county, district, years, level, where, include_other_counties, + ) -> Optional[ds.Expression]: + """Turns the query arguments into one pyarrow filter expression.""" + + def unsupported(argument, what): + return ValueError(f"Table '{table}' has no {what} data, so `{argument}` cannot be used with it.") + + filters = [] + + if any(v is not None for v in (crop, crop_class, practice, utilization)): + crop_ids = self.catalog.resolve_crops(crop, crop_class, practice, utilization) + filters.append(pc.field("crop_id").isin(crop_ids)) + + state_fips = self.catalog.resolve_states(state) if state is not None else None + if state_fips is not None: + if spec.has_state_fips: + filters.append(pc.field("state_fips").isin(state_fips)) + else: + filters.append(pc.field("state_alpha").isin(self.catalog.state_alphas(state_fips))) + + if county is not None: + if not spec.has_county: + raise unsupported("county", "county-level") + filters.append(pc.field("county_fips").isin(self.catalog.resolve_counties(county, state=state))) + + if district is not None: + if not spec.has_district: + raise unsupported("district", "district-level") + asd_ids = self.catalog.resolve_districts(district, state=state) + by_state = {} + for asd_id in asd_ids: + by_state.setdefault(asd_id[:2], []).append(asd_id[2:]) + district_filter = None + for fips, codes in by_state.items(): + part = (pc.field("state_fips") == fips) & pc.field("asd_code").isin(codes) + district_filter = part if district_filter is None else district_filter | part + filters.append(district_filter) + + if years is not None: + filters.append(self._years_filter(spec.year_column, years)) + + if level is not None: + if level not in _LEVELS: + raise ValueError(f"Unknown level '{level}'. Choose one of {list(_LEVELS)}.") + if spec.has_agg_level: + filters.append(pc.field("agg_level") == _LEVELS[level]) + elif level != "county": + raise unsupported("level", f"{level}-level") + + if spec.has_other_counties and not include_other_counties: + filters.append(pc.field("is_other_counties").is_null() | ~pc.field("is_other_counties")) + + for column, value in (where or {}).items(): + if column not in schema.names: + raise ValueError(f"Table '{table}' has no column '{column}'.") + values = value if isinstance(value, (list, tuple, set)) else [value] + filters.append(pc.field(column).isin(list(values))) + + if not filters: + return None + expression = filters[0] + for f in filters[1:]: + expression = expression & f + return expression + + @staticmethod + def _check_format(format: str, path: Optional[str]): + if format not in FORMATS: + raise ValueError(f"Unknown format '{format}'. Choose one of {FORMATS}.") + if format in ("csv", "parquet") and path is None: + raise ValueError(f"The '{format}' format needs an output `path`.") + + @staticmethod + def _convert(result: pa.Table, format: str, path: Optional[str]): + """Converts an Arrow table into the requested output format.""" + if format == "arrow": + return result + if format == "pandas": + return result.to_pandas() + if format == "records": + return result.to_pylist() + if format == "polars": + try: + import polars as pl + except ImportError: + raise ImportError("The 'polars' format needs polars. Install it with `pip install polars`.") + return pl.from_arrow(result) + + os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) + if format == "csv": + import pyarrow.csv as pacsv + + pacsv.write_csv(result, path) + else: + import pyarrow.parquet as pq + + pq.write_table(result, path) + return path diff --git a/pyproject.toml b/pyproject.toml index ac811873..7cc6dce6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,22 @@ dependencies = [ "rich>=14.0.0", "datasets", ] + +[project.optional-dependencies] +ag_stats = [ + "huggingface_hub>=0.23.0", + "pandas>=2.0.3", + "pyarrow>=14.0.0", +] +calicropyield = [ + "huggingface_hub>=0.23.0", + "pandas>=2.0.3", + "pyarrow>=14.0.0", + "rasterio>=1.3", + "xarray>=2023.1", + "zarr>=3.0; python_version >= '3.11'", + "geopandas>=0.12", +] [project.urls] diff --git a/tests/ag_stats/__init__.py b/tests/ag_stats/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/ag_stats/calicropyield/__init__.py b/tests/ag_stats/calicropyield/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/ag_stats/calicropyield/calicropyield_fixtures.py b/tests/ag_stats/calicropyield/calicropyield_fixtures.py new file mode 100644 index 00000000..0e49800e --- /dev/null +++ b/tests/ag_stats/calicropyield/calicropyield_fixtures.py @@ -0,0 +1,19 @@ +"""Values shared by the California Crop Yield Benchmark fixture dataset and the tests.""" + +import numpy as np + +# The CDL pixel size, in degrees. +RES = 0.00026949458523585647 + +# CDL codes on the fixture grid: tomatoes (54), almonds (75), alfalfa (36), urban (121), water (141). +CDL = np.array( + [ + [54, 54, 75, 75, 121, 141], + [54, 54, 75, 75, 121, 141], + [36, 36, 0, 0, 121, 141], + [36, 36, 0, 0, 121, 141], + ], + dtype="uint8", +) + +LANDSAT_BANDS = ("SR_B1", "SR_B2", "SR_B3", "SR_B4", "SR_B5", "SR_B7") diff --git a/tests/ag_stats/calicropyield/conftest.py b/tests/ag_stats/calicropyield/conftest.py new file mode 100644 index 00000000..bd675eb1 --- /dev/null +++ b/tests/ag_stats/calicropyield/conftest.py @@ -0,0 +1,109 @@ +import json + +import numpy as np +import pandas as pd +import pytest + +from .calicropyield_fixtures import CDL, LANDSAT_BANDS, RES + +# A 4x6 pixel grid at the CDL resolution, in the corner of Yolo County. +_HEIGHT, _WIDTH = CDL.shape + + +def _write_tif(path, data, nodata=None, descriptions=None): + import rasterio + from rasterio.transform import from_origin + + path.parent.mkdir(parents=True, exist_ok=True) + data = data if data.ndim == 3 else data[None] + with rasterio.open( + path, "w", driver="GTiff", height=_HEIGHT, width=_WIDTH, count=data.shape[0], + dtype=data.dtype, crs="EPSG:4326", transform=from_origin(-122.0, 38.6, RES, RES), nodata=nodata, + ) as dst: + dst.write(data) + for i, name in enumerate(descriptions or []): + dst.set_band_description(i + 1, name) + + +def _grid_coords(n_y, n_x, step): + return {"y": 38.6 - step * (np.arange(n_y) + 0.5), "x": -122.0 + step * (np.arange(n_x) + 0.5)} + + +@pytest.fixture(scope="session") +def cali_root(tmp_path_factory): + """A directory laid out like the Hub repo, with Yolo 2020 and 2021 data.""" + # Skipped here, not at module level: a skip while loading a conftest aborts the whole run. + pytest.importorskip("rasterio") + xr = pytest.importorskip("xarray") + root = tmp_path_factory.mktemp("calicropyield") + county = root / "counties" / "Yolo" + + for year in (2020, 2021): + _write_tif(county / "cdl" / str(year) / f"Yolo_{year}.tif", CDL, nodata=0) + _write_tif(county / "irrigation" / str(year) / f"Yolo_{year}.tif", (CDL > 0).astype("uint8")) + for month in range(1, 13): + landsat = np.full((6, _HEIGHT, _WIDTH), month, dtype="float32") + np.arange(6, dtype="float32")[:, None, None] / 10 + _write_tif(county / "landsat" / str(year) / f"Yolo_LT_{year}_{month:02d}.tif", landsat, descriptions=LANDSAT_BANDS) + et = np.full((_HEIGHT, _WIDTH), 10.0 * month, dtype="float32") + _write_tif(county / "et" / str(year) / f"Yolo_ET_{year}_{month:02d}.tif", et, nodata=np.nan) + + try: + import zarr # noqa: F401 + except ImportError: + pass + else: + for year in (2020, 2021): + time = pd.date_range(f"{year}-01-01", f"{year}-12-31", freq="D") + coords = {"time": time, **_grid_coords(3, 4, 0.01)} + values = np.broadcast_to(np.arange(len(time), dtype="float32")[:, None, None], (len(time), 3, 4)) + climate = xr.Dataset({v: (("time", "y", "x"), values.copy()) for v in ("prcp", "tmax", "tmin")}, coords=coords) + climate.to_zarr(county / "climate" / str(year) / f"DayMet_Yolo_{year}.zarr", consolidated=False) + soil = xr.Dataset( + { + "soc0_100": (("y", "x"), np.full((_HEIGHT, _WIDTH), 5000.0, dtype="float32")), + "hydgrpdcd": (("y", "x"), np.ones((_HEIGHT, _WIDTH), dtype="float32"), {"categories": "1=A,2=B"}), + }, + coords=_grid_coords(_HEIGHT, _WIDTH, RES), + ) + # The real stores carry their CRS in a `spatial_ref` variable. + soil["spatial_ref"] = xr.DataArray(0, attrs={"crs_wkt": "EPSG:4326"}) + soil.to_zarr(county / "soil" / "2020" / "Yolo_soil.zarr", consolidated=False) + + (root / "yield" / "metadata").mkdir(parents=True) + pd.DataFrame( + { + "state": "CA", + "county": ["Yolo", "Yolo", "Yolo", "Contra Costa", "Fresno"], + "year": [2019, 2020, 2020, 2020, 2021], + "crop": ["TOMATOES", "TOMATOES", "ALMONDS", "TOMATOES", "HAY"], + "group_desc": ["VEGETABLE CROPS", "VEGETABLE CROPS", "TREE NUTS & FRUITS", "VEGETABLE CROPS", "FIELD CROPS"], + "yield_t_per_ha": [90.0, 95.0, 2.5, 80.0, 15.0], + "yield_std": 0.0, + "n_subtypes_merged": 1, + "contains_flagged_outlier": False, + } + ).to_parquet(root / "yield" / "county_crop_yield.parquet") + pd.DataFrame( + { + "Year": [2020, 2020], + "County": ["Yolo", "Yolo"], + "Crop_Name_Clean": ["Tomatoes Processing", "Almonds All"], + "Yield_Tons_Per_Hectare": [95.0, 2.5], + } + ).to_parquet(root / "yield" / "county_crop_yield_detail.parquet") + pd.DataFrame( + { + "yield_crop": ["TOMATOES", "HAY", "ANISE"], + "cdl_codes": ["54", "36;37", None], + "cdl_names": ["Tomatoes", "Alfalfa;Other Hay/Non Alfalfa", None], + "confidence": ["high", "manual", "unmatched"], + "note": [None, None, "no CDL class"], + } + ).to_csv(root / "yield" / "metadata" / "cdl_crop_crosswalk.csv", index=False) + + (root / "README.md").write_text("Dataset card") + (root / "reference").mkdir() + square = [[-122.0, 38.6], [-121.9, 38.6], [-121.9, 38.5], [-122.0, 38.5], [-122.0, 38.6]] + feature = {"type": "Feature", "properties": {"NAME": "Yolo County"}, "geometry": {"type": "Polygon", "coordinates": [square]}} + (root / "reference" / "California_Counties.geojson").write_text(json.dumps({"type": "FeatureCollection", "features": [feature]})) + return root diff --git a/tests/ag_stats/calicropyield/test_calicropyield_catalog.py b/tests/ag_stats/calicropyield/test_calicropyield_catalog.py new file mode 100644 index 00000000..670e7683 --- /dev/null +++ b/tests/ag_stats/calicropyield/test_calicropyield_catalog.py @@ -0,0 +1,78 @@ +import pytest + +pytest.importorskip("rasterio") +pytest.importorskip("xarray") + +from agml.ag_stats.calicropyield import catalog + + +class TestCounties: + @pytest.mark.parametrize("name", ["Contra Costa", "contra costa", "ContraCosta", "Contra Costa County"]) + def test_resolve(self, name): + assert catalog.resolve_county(name) == "Contra Costa" + assert catalog.county_slug(name) == "ContraCosta" + + def test_unknown_suggests(self): + with pytest.raises(ValueError, match="Yolo"): + catalog.resolve_county("Yollo") + + def test_count(self): + assert len(catalog.COUNTIES) == 58 + + +class TestYears: + def test_all(self): + years = catalog.resolve_years("landsat", None) + assert years[0] == 2008 and years[-1] == 2023 and 2012 not in years + + def test_range_skips_2012(self): + assert catalog.resolve_years("cdl", (2011, 2013)) == [2011, 2013] + + def test_layer_specific_years(self): + assert catalog.resolve_years("cdl", 2024) == [2024] + assert catalog.LAYERS["climate"].years[-1] == 2022 + + def test_range_past_data_raises(self): + with pytest.raises(ValueError, match=r"\[2023\]"): + catalog.resolve_years("climate", (2020, 2023)) + + def test_range_outside_data_raises(self): + with pytest.raises(ValueError, match="2030"): + catalog.resolve_years("et", (2030, 2031)) + + def test_reversed_range_raises(self): + with pytest.raises(ValueError, match="reversed"): + catalog.resolve_years("et", (2021, 2019)) + + @pytest.mark.parametrize("year", [2012, 2030]) + def test_missing_year(self, year): + with pytest.raises(ValueError, match=str(year)): + catalog.resolve_years("et", year) + + def test_unknown_layer(self): + with pytest.raises(ValueError, match="Unknown layer"): + catalog.resolve_years("ndvi", 2020) + + +class TestPaths: + def test_monthly(self): + assert catalog.LAYERS["landsat"].path("landsat", "Yolo", 2021, 7) == "counties/Yolo/landsat/2021/Yolo_LT_2021_07.tif" + + def test_zarr(self): + assert catalog.LAYERS["climate"].path("climate", "Yolo", 2020) == "counties/Yolo/climate/2020/DayMet_Yolo_2020.zarr" + + +class TestCdlCodes: + def test_names_and_codes(self): + assert catalog.cdl_codes(["tomatoes", 75]) == [54, 75] + + def test_shared_name_returns_every_code(self): + assert set(catalog.cdl_codes("Non-agricultural")) == {62, 63, 64, 65, *range(81, 92)} + + def test_default_is_cropland_only(self): + codes = catalog.cdl_codes(None) + assert 54 in codes and 121 not in codes and 141 not in codes and 0 not in codes + + def test_unknown(self): + with pytest.raises(ValueError, match="Tomatoes"): + catalog.cdl_codes("tomatos") diff --git a/tests/ag_stats/calicropyield/test_calicropyield_loader.py b/tests/ag_stats/calicropyield/test_calicropyield_loader.py new file mode 100644 index 00000000..5930a9d3 --- /dev/null +++ b/tests/ag_stats/calicropyield/test_calicropyield_loader.py @@ -0,0 +1,371 @@ +import os +import pickle +import shutil + +import numpy as np +import pytest + +pytest.importorskip("rasterio") +pytest.importorskip("xarray") + +from shapely.geometry import box + +from agml.ag_stats.calicropyield import DEFAULT_REPO_ID, CaliCropYieldLoader, DownloadError + +from .calicropyield_fixtures import CDL, LANDSAT_BANDS, RES + +try: + import zarr # noqa: F401 +except ImportError: + zarr = None +needs_zarr = pytest.mark.skipif(zarr is None, reason="zarr is not installed") + + +# A triangle over the top-left 4x4 pixels, so part of the crop is outside it. +TRIANGLE = { + "type": "Polygon", + "coordinates": [[[-122.0, 38.6], [-122.0 + 4 * RES, 38.6], [-122.0, 38.6 - 4 * RES], [-122.0, 38.6]]], +} + + +@pytest.fixture(scope="module") +def cali(cali_root): + return CaliCropYieldLoader(str(cali_root)) + + +# ── Initialisation ──────────────────────────────────────────────────────────── + +class TestInit: + def test_reads_env_var(self, cali_root, monkeypatch): + monkeypatch.setenv("AGML_CALICROPYIELD_PATH", str(cali_root)) + assert CaliCropYieldLoader().root == os.path.realpath(cali_root) + + def test_defaults_to_hub(self, hub): + loader = CaliCropYieldLoader() + assert loader.repo_id == DEFAULT_REPO_ID and loader.root is None + + def test_missing_dir(self, tmp_path): + with pytest.raises(FileNotFoundError): + CaliCropYieldLoader(str(tmp_path / "nope")) + + def test_pickle_round_trip(self, cali): + clone = pickle.loads(pickle.dumps(cali)) + assert clone.root == cali.root + assert clone.load_cdl("Yolo", 2020).shape == CDL.shape + + def test_listings(self): + assert len(CaliCropYieldLoader.counties()) == 58 + assert "landsat" in CaliCropYieldLoader.layers() + assert CaliCropYieldLoader.cdl_classes()[54] == "Tomatoes" + + +# ── Rasters ─────────────────────────────────────────────────────────────────── + +class TestRasters: + def test_cdl(self, cali): + cdl = cali.load_cdl("yolo", 2020) + assert cdl.dims == ("y", "x") + np.testing.assert_array_equal(cdl.values, CDL) + assert cdl.attrs["crs"] == "EPSG:4326" + + def test_cdl_keeps_only_crops(self, cali): + cdl = cali.load_cdl("Yolo", 2020, crops=["Tomatoes", "Almonds"]) + assert set(np.unique(cdl.values)) == {0, 54, 75} + assert cdl.dtype == CDL.dtype + + def test_coordinates_are_pixel_centers(self, cali): + cdl = cali.load_cdl("Yolo", 2020) + assert cdl["x"].values[0] == pytest.approx(-122.0 + RES / 2) + assert cdl["y"].values[0] == pytest.approx(38.6 - RES / 2) + + def test_crop_mask_default_is_cropland(self, cali): + mask = cali.crop_mask("Yolo", 2020) + assert mask.dtype == bool + assert mask.values.sum() == ((CDL == 54) | (CDL == 75) | (CDL == 36)).sum() + + def test_irrigation(self, cali): + assert cali.load_irrigation("Yolo", 2021).dims == ("y", "x") + + def test_irrigation_geometry_fill_is_not_a_class(self, cali): + # Irrigation has no no-data value and uses 0 for "not irrigated", so 0 cannot mark "outside". + irrigation = cali.load_irrigation("Yolo", 2020, geometry=TRIANGLE) + assert irrigation.attrs["nodata"] == 255 + outside = irrigation.values == 255 + assert outside.any() and not outside.all() + full = cali.load_irrigation("Yolo", 2020).sel(x=irrigation.x, y=irrigation.y) + np.testing.assert_array_equal(irrigation.values[~outside], full.values[~outside]) + + def test_cdl_geometry_fill_is_files_nodata(self, cali): + assert cali.load_cdl("Yolo", 2020, geometry=TRIANGLE).attrs["nodata"] == 0 + + def test_landsat(self, cali): + landsat = cali.load_landsat("Yolo", 2020, months=[6, 7]) + assert landsat.dims == ("month", "band", "y", "x") + assert list(landsat["month"].values) == [6, 7] + assert list(landsat["band"].values) == list(LANDSAT_BANDS) + assert float(landsat.sel(month=7, band="SR_B1").mean()) == pytest.approx(7.0) + + def test_et(self, cali): + et = cali.load_et("Yolo", 2020) + assert et.dims == ("month", "y", "x") and et.sizes["month"] == 12 + assert float(et.sel(month=3).mean()) == pytest.approx(30.0) + + def test_geometry_crops(self, cali): + # Kept inside the pixel edges; a box exactly on an edge may include the next row. + cdl = cali.load_cdl("Yolo", 2020, geometry=box(-122.0 + 0.1 * RES, 38.6 - 1.9 * RES, -122.0 + 1.9 * RES, 38.6 - 0.1 * RES)) + assert cdl.shape == (2, 2) + assert (cdl.values == 54).all() + + def test_geometry_fills_floats_with_nan(self, cali): + et = cali.load_et("Yolo", 2020, months=[1], geometry=TRIANGLE) + assert np.isnan(et.values).any() and not np.isnan(et.values).all() + + def test_bad_month(self, cali): + with pytest.raises(ValueError, match="Months"): + cali.load_landsat("Yolo", 2020, months=[13]) + + def test_year_not_in_layer(self, cali): + with pytest.raises(ValueError, match="2012"): + cali.load_cdl("Yolo", 2012) + + def test_file_missing_from_copy(self, cali): + with pytest.raises(FileNotFoundError): + cali.load_cdl("Fresno", 2020) + + +# ── Zarr layers ─────────────────────────────────────────────────────────────── + +@needs_zarr +class TestZarr: + def test_climate_one_year(self, cali): + ds = cali.load_climate("Yolo", years=2020) + assert set(ds.data_vars) == {"prcp", "tmax", "tmin"} + assert ds.sizes["time"] == 366 + + def test_climate_years_are_joined(self, cali): + ds = cali.load_climate("Yolo", years=[2020, 2021], variables="prcp") + assert list(ds.data_vars) == ["prcp"] + assert ds.sizes["time"] == 366 + 365 + + def test_climate_monthly(self, cali): + ds = cali.load_climate("Yolo", years=2020, monthly=True) + assert ds.sizes["time"] == 12 + assert float(ds["prcp"].isel(time=0).mean()) == pytest.approx(15.0) + + def test_climate_geometry_bbox(self, cali): + ds = cali.load_climate("Yolo", years=2020, geometry=box(-122.0, 38.58, -121.98, 38.6)) + assert ds.sizes["y"] == 2 and ds.sizes["x"] == 2 + + def test_soil(self, cali): + ds = cali.load_soil("Yolo", variables=["hydgrpdcd"]) + assert list(ds.data_vars) == ["hydgrpdcd"] + assert ds["hydgrpdcd"].attrs["categories"] == "1=A,2=B" + + def test_crs_variable_is_a_coordinate(self, cali): + ds = cali.load_soil("Yolo") + assert set(ds.data_vars) == {"soc0_100", "hydgrpdcd"} + assert "spatial_ref" in ds.coords + + def test_unknown_variable(self, cali): + with pytest.raises(ValueError, match="soc0_100"): + cali.load_soil("Yolo", variables="carbon") + + +# ── Tables ──────────────────────────────────────────────────────────────────── + +class TestTables: + def test_yield_filters(self, cali): + df = cali.load_yield(county="yolo", crop="tomatoes") + assert list(df["year"]) == [2019, 2020] + + def test_yield_county_with_space(self, cali): + df = cali.load_yield(county="ContraCosta") + assert list(df["county"]) == ["Contra Costa"] + + def test_yield_year_range(self, cali): + df = cali.load_yield(years=(2020, 2021)) + assert set(df["year"]) == {2020, 2021} + + def test_yield_range_past_data_raises(self, cali): + with pytest.raises(ValueError, match=r"\[2022, 2023\]"): + cali.load_yield(years=(2020, 2023)) + + def test_yield_detail(self, cali): + df = cali.load_yield(crop="tomatoes processing", detail=True) + assert list(df["Yield_Tons_Per_Hectare"]) == [95.0] + + def test_yield_crops(self, cali): + assert cali.yield_crops() == ["ALMONDS", "HAY", "TOMATOES"] + + def test_crosswalk_codes(self, cali): + assert cali.yield_crop_cdl_codes("hay") == [36, 37] + assert cali.yield_crop_cdl_codes("ANISE") == [] + with pytest.raises(ValueError, match="yield crop"): + cali.yield_crop_cdl_codes("kiwi") + + def test_crosswalk_feeds_crop_mask(self, cali): + mask = cali.crop_mask("Yolo", 2020, crops=cali.yield_crop_cdl_codes("HAY")) + assert mask.values.sum() == (CDL == 36).sum() + + def test_county_boundaries(self, cali): + pytest.importorskip("geopandas") + assert list(cali.load_boundaries()["NAME"]) == ["Yolo County"] + + +# ── Downloads ───────────────────────────────────────────────────────────────── + +class TestDownload: + def test_monthly_paths(self, cali): + paths = cali.download("et", "Yolo", years=2020, months=[1, 2]) + assert [os.path.basename(p) for p in paths] == ["Yolo_ET_2020_01.tif", "Yolo_ET_2020_02.tif"] + + def test_layer_methods(self, cali): + assert len(cali.download_landsat("Yolo", years=2020, months=[7])) == 1 + assert len(cali.download_irrigation("Yolo", years=(2020, 2021))) == 2 + assert [os.path.basename(p) for p in cali.download_yield()] == [ + "county_crop_yield.parquet", "county_crop_yield_detail.parquet", "cdl_crop_crosswalk.csv", + ] + + @needs_zarr + def test_zarr_layer_methods(self, cali): + assert os.path.isdir(cali.download_soil("Yolo")[0]) + assert len(cali.download_climate("Yolo", years=[2020, 2021])) == 2 + + def test_missing_files_are_skipped(self, cali): + paths = cali.download("cdl", ["Yolo", "Fresno"], years=(2020, 2021)) + assert len(paths) == 2 + + +# ── Hugging Face Hub ────────────────────────────────────────────────────────── + +class FakeHub: + """Stands in for `huggingface_hub`, serving the fixture dataset as one commit.""" + + COMMIT = "0123456789abcdef0123456789abcdef01234567" + + def __init__(self, cali_root, tmp_path): + # Like the Hugging Face cache, files sit in a folder named after the commit. + self.folder = tmp_path / "snapshots" / self.COMMIT + shutil.copytree(cali_root, self.folder) + self.downloads, self.listings, self.card_requests = [], [], 0 + self.fail = set() + + def hf_hub_download(self, repo_id, repo_type, filename, revision, cache_dir, token): + from huggingface_hub.errors import EntryNotFoundError + + assert repo_id == DEFAULT_REPO_ID and repo_type == "dataset" + if filename == "README.md": + assert revision in (None, "main", self.COMMIT) + self.card_requests += 1 + else: + assert revision == self.COMMIT, "files must come from the pinned commit" + self.downloads.append(filename) + if filename in self.fail: + raise ConnectionError("connection reset") + if not (self.folder / filename).is_file(): + raise EntryNotFoundError(filename) + return str(self.folder / filename) + + def list_repo_tree(self, repo_id, path_in_repo, recursive, repo_type, revision, token): + from huggingface_hub.errors import EntryNotFoundError + from huggingface_hub.hf_api import RepoFile, RepoFolder + + assert recursive and revision == self.COMMIT + self.listings.append(path_in_repo) + base = self.folder / path_in_repo + if not base.is_dir(): + raise EntryNotFoundError(path_in_repo) + for path in sorted(base.rglob("*")): + rel = str(path.relative_to(self.folder)) + yield RepoFile(path=rel, size=1, oid="x") if path.is_file() else RepoFolder(path=rel, oid="x") + + +@pytest.fixture +def hub(cali_root, tmp_path, monkeypatch): + import huggingface_hub + + fake = FakeHub(cali_root, tmp_path) + monkeypatch.delenv("AGML_CALICROPYIELD_PATH", raising=False) + monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake.hf_hub_download) + monkeypatch.setattr(huggingface_hub, "list_repo_tree", fake.list_repo_tree) + return fake + + +class TestHub: + def test_downloads_only_what_is_read(self, hub): + CaliCropYieldLoader().load_et("Yolo", 2020, months=[7]) + assert hub.downloads == ["counties/Yolo/et/2020/Yolo_ET_2020_07.tif"] + + def test_yield(self, hub): + assert len(CaliCropYieldLoader().load_yield(county="Yolo")) == 3 + assert hub.downloads == ["yield/county_crop_yield.parquet"] + + @needs_zarr + def test_zarr_store(self, hub): + ds = CaliCropYieldLoader().load_soil("Yolo") + assert "soc0_100" in ds + assert hub.listings == ["counties/Yolo/soil"] + assert all(d.startswith("counties/Yolo/soil/2020/Yolo_soil.zarr/") for d in hub.downloads) + + @needs_zarr + def test_missing_store(self, hub): + with pytest.raises(FileNotFoundError, match="not in the dataset"): + CaliCropYieldLoader().load_climate("Fresno", years=2020) + + def test_missing_file(self, hub): + with pytest.raises(FileNotFoundError, match="not in the dataset"): + CaliCropYieldLoader().load_cdl("Fresno", 2020) + + +class TestRevision: + def test_latest_is_pinned_to_its_commit(self, hub): + loader = CaliCropYieldLoader() + assert loader.revision == FakeHub.COMMIT + assert FakeHub.COMMIT[:7] in repr(loader) + + def test_branch_is_resolved(self, hub): + assert CaliCropYieldLoader(revision="main").revision == FakeHub.COMMIT + + def test_commit_is_used_as_is(self, hub): + assert CaliCropYieldLoader(revision=FakeHub.COMMIT).revision == FakeHub.COMMIT + assert hub.card_requests == 0 + + def test_local_copy_has_no_revision(self, cali): + assert cali.revision is None + + def test_pickle_keeps_commit(self, hub): + clone = pickle.loads(pickle.dumps(CaliCropYieldLoader())) + assert clone.repo_id == DEFAULT_REPO_ID and clone.revision == FakeHub.COMMIT + assert len(clone.load_yield(county="Yolo")) == 3 + + +class TestBatchedDownload: + def test_one_listing_per_county_layer(self, hub): + paths = CaliCropYieldLoader().download_landsat("Yolo", years=(2020, 2021), months=[1, 2]) + assert len(paths) == 4 and all(os.path.isfile(p) for p in paths) + assert hub.listings == ["counties/Yolo/landsat"] + + @needs_zarr + def test_zarr_stores_in_one_batch(self, hub): + paths = CaliCropYieldLoader().download_climate("Yolo", years=[2020, 2021]) + assert [os.path.basename(p) for p in paths] == ["DayMet_Yolo_2020.zarr", "DayMet_Yolo_2021.zarr"] + assert all(os.path.isdir(p) for p in paths) + assert hub.listings == ["counties/Yolo/climate"] + + def test_missing_files_are_skipped(self, hub): + paths = CaliCropYieldLoader().download("cdl", ["Yolo", "Fresno"], years=2020) + assert [os.path.basename(p) for p in paths] == ["Yolo_2020.tif"] + assert hub.listings == ["counties/Fresno/cdl", "counties/Yolo/cdl"] + + def test_failed_downloads_raise_and_others_finish(self, hub): + failing = "counties/Yolo/cdl/2021/Yolo_2021.tif" + hub.fail.add(failing) + with pytest.raises(DownloadError, match="1 file") as info: + CaliCropYieldLoader().download_cdl("Yolo", years=(2020, 2021)) + assert list(info.value.failed) == [failing] + assert isinstance(info.value.failed[failing], ConnectionError) + assert "counties/Yolo/cdl/2020/Yolo_2020.tif" in hub.downloads + + def test_bad_month(self, hub): + with pytest.raises(ValueError, match="Months"): + CaliCropYieldLoader().download_et("Yolo", years=2020, months=[0]) diff --git a/tests/ag_stats/nass/__init__.py b/tests/ag_stats/nass/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/ag_stats/nass/conftest.py b/tests/ag_stats/nass/conftest.py new file mode 100644 index 00000000..ed9e5376 --- /dev/null +++ b/tests/ag_stats/nass/conftest.py @@ -0,0 +1,137 @@ +import pytest +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS + + +# ── Fixture dataset ────────────────────────────────────────────────────────── +# A few rows per table, shaped like the real NASS parquet files. + + +_CROPS = { + "crop_id": [CORN_GRAIN, CORN_SILAGE, SOYBEANS], + "commodity": ["CORN", "CORN", "SOYBEANS"], + "class": ["ALL CLASSES"] * 3, + "practice": ["ALL PRODUCTION PRACTICES"] * 3, + "utilization": ["GRAIN", "SILAGE", "ALL UTILIZATION PRACTICES"], + "crop_label": ["CORN, GRAIN", "CORN, SILAGE", "SOYBEANS"], +} + +_STATES = { + "state_fips": ["19", "17", "53"], + "state_alpha": ["IA", "IL", "WA"], + "state_name": ["Iowa", "Illinois", "Washington"], + "area_km2": [145746.0, 143793.0, 172119.0], + "centroid_lon": [-93.5, -89.2, -120.4], + "centroid_lat": [42.1, 40.0, 47.4], +} + +_COUNTIES = { + "county_fips": ["19169", "19183", "17183", "17189", "53071"], + "state_fips": ["19", "19", "17", "17", "53"], + "county_code": ["169", "183", "183", "189", "071"], + "county_name": ["Story", "Washington", "Vermilion", "Washington", "Walla Walla"], + "state_alpha": ["IA", "IA", "IL", "IL", "WA"], + "area_km2": [1490.0, 1474.0, 2329.0, 1458.0, 3349.0], + "centroid_lon": [-93.4, -91.7, -87.7, -89.4, -118.5], + "centroid_lat": [42.0, 41.3, 40.2, 38.4, 46.2], +} + +_DISTRICTS = { + "state_fips": ["19", "19", "17"], + "state_alpha": ["IA", "IA", "IL"], + "asd_code": ["50", "90", "60"], + "asd_desc": ["CENTRAL", "SOUTHEAST", "EAST"], + "asd_id": ["1950", "1990", "1760"], +} + +# An old NASS county code mapped to its 2020 code. +_REMAP = {"fips_nass": ["19999"], "fips_2020": ["19169"], "note": ["Old Story County code"]} + + +def _fact_rows(years): + """One row per crop, place, and year, at county, district, state, and national level.""" + places = [ + ("COUNTY", "19", "IA", "50", "19169", False), + ("COUNTY", "19", "IA", "90", "19183", False), + ("COUNTY", "17", "IL", "60", "17183", False), + ("COUNTY", "19", "IA", "90", None, True), + ("AGRICULTURAL DISTRICT", "19", "IA", "50", None, False), + ("STATE", "19", "IA", None, None, False), + ("STATE", "17", "IL", None, None, False), + ("NATIONAL", "99", "US", None, None, False), + ] + rows = [] + for crop_id, commodity in [(CORN_GRAIN, "CORN"), (CORN_SILAGE, "CORN"), (SOYBEANS, "SOYBEANS")]: + for level, state_fips, state_alpha, asd, county, other in places: + for year in years: + rows.append( + { + "crop_id": crop_id, + "commodity": commodity, + "agg_level": level, + "state_fips": state_fips, + "state_alpha": state_alpha, + "asd_code": asd, + "county_fips": county, + "is_other_counties": other, + "year": year, + "value": float(year - 1900), + } + ) + return rows + + +def _write(path, data): + import pyarrow as pa + import pyarrow.parquet as pq + + table = pa.Table.from_pylist(data) if isinstance(data, list) else pa.table(data) + pq.write_table(table, path) + + +@pytest.fixture(scope="session") +def nass_root(tmp_path_factory): + """A directory laid out like the real dataset: `/parquet/*.parquet`.""" + # Skipped here, not at module level: a skip while loading a conftest aborts the whole run. + pytest.importorskip("pyarrow") + root = tmp_path_factory.mktemp("nass") + parquet = root / "parquet" + parquet.mkdir() + + _write(parquet / "dim_crop.parquet", _CROPS) + _write(parquet / "dim_state.parquet", _STATES) + _write(parquet / "dim_county.parquet", _COUNTIES) + _write(parquet / "dim_asd.parquet", _DISTRICTS) + _write(parquet / "county_fips_remap.parquet", _REMAP) + + years = [2018, 2019, 2020, 2021] + _write(parquet / "yield.parquet", _fact_rows(years)) + _write( + parquet / "area_production.parquet", + [dict(r, statistic=s) for r in _fact_rows(years) for s in ("area_planted", "production")], + ) + county_rows = [r for r in _fact_rows(years) if r["agg_level"] == "COUNTY" and r["county_fips"]] + _write( + parquet / "v_county_yield_main.parquet", + [{k: r[k] for k in ("county_fips", "state_alpha", "year", "crop_id", "commodity", "value")} for r in county_rows], + ) + state_rows = [r for r in _fact_rows(years) if r["agg_level"] in ("STATE", "NATIONAL")] + _write( + parquet / "crop_progress.parquet", + [dict(r, crop_year=r["year"], stage=s) for r in state_rows for s in ("PLANTED", "HARVESTED")], + ) + _write( + parquet / "yield_forecast.parquet", + [dict(r, forecast_month=m) for r in state_rows for m in ("NOV", "AUG", "OCT", "SEP")], + ) + _write( + parquet / "crop_condition.parquet", + [{**{k: r[k] for k in ("crop_id", "agg_level", "state_fips", "state_alpha")}, "crop_year": r["year"], "good": 50.0} for r in state_rows], + ) + + boundaries = root / "boundaries" + boundaries.mkdir() + for level, geoid in (("county", "19169"), ("state", "19")): + attributes = {"GEOID": [geoid], "NAME": ["Story" if level == "county" else "Iowa"]} + _write(boundaries / f"us_{level}_2020_attributes.parquet", attributes) + _write(boundaries / f"us_{level}_2020.parquet", dict(attributes, geometry=[b"\x01"])) + return root diff --git a/tests/ag_stats/nass/nass_fixtures.py b/tests/ag_stats/nass/nass_fixtures.py new file mode 100644 index 00000000..d027865e --- /dev/null +++ b/tests/ag_stats/nass/nass_fixtures.py @@ -0,0 +1,5 @@ +"""Crop IDs shared by the NASS fixture dataset and the tests.""" + +CORN_GRAIN = "f56a2f05c3bd" +CORN_SILAGE = "45e465f318ca" +SOYBEANS = "a1b2c3d4e5f6" diff --git a/tests/ag_stats/nass/test_catalog.py b/tests/ag_stats/nass/test_catalog.py new file mode 100644 index 00000000..9fac2344 --- /dev/null +++ b/tests/ag_stats/nass/test_catalog.py @@ -0,0 +1,123 @@ +import pytest + +pytest.importorskip("pyarrow") + +from agml.ag_stats.nass import NASSCatalog + +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS + + +@pytest.fixture(scope="module") +def catalog(nass_root): + return NASSCatalog(str(nass_root / "parquet")) + + +# ── Listings ────────────────────────────────────────────────────────────────── + +class TestListings: + def test_commodities(self, catalog): + assert catalog.commodities() == ["CORN", "SOYBEANS"] + + def test_crops_for_one_commodity(self, catalog): + assert set(catalog.crops("corn")["crop_id"]) == {CORN_GRAIN, CORN_SILAGE} + + def test_counties_for_one_state(self, catalog): + assert list(catalog.counties("IA")["county_fips"]) == ["19169", "19183"] + + def test_districts_for_one_state(self, catalog): + assert list(catalog.districts("Illinois")["asd_id"]) == ["1760"] + + def test_missing_dimension_table(self, tmp_path): + with pytest.raises(FileNotFoundError): + NASSCatalog(str(tmp_path)) + + +# ── States ──────────────────────────────────────────────────────────────────── + +class TestStates: + @pytest.mark.parametrize("value", ["IA", "ia", "Iowa", "IOWA", "19", 19]) + def test_accepted_forms(self, catalog, value): + assert catalog.resolve_states(value) == ["19"] + + def test_list(self, catalog): + assert catalog.resolve_states(["IA", "Illinois"]) == ["19", "17"] + + def test_unknown_suggests(self, catalog): + with pytest.raises(ValueError, match="IOWA") as error: + catalog.resolve_states("Iowaa") + assert str(error.value).count("IOWA") == 1 + + +# ── Counties ────────────────────────────────────────────────────────────────── + +class TestCounties: + def test_by_fips(self, catalog): + assert catalog.resolve_counties("19169") == ["19169"] + assert catalog.resolve_counties(19169) == ["19169"] + + def test_by_name(self, catalog): + assert catalog.resolve_counties("Story") == ["19169"] + assert catalog.resolve_counties("story county") == ["19169"] + + def test_ambiguous_name_needs_state(self, catalog): + with pytest.raises(ValueError, match="several states"): + catalog.resolve_counties("Washington") + assert catalog.resolve_counties("Washington", state="IL") == ["17189"] + + def test_old_nass_code_is_remapped(self, catalog): + assert catalog.resolve_counties("19999") == ["19169"] + + def test_unknown_fips(self, catalog): + with pytest.raises(ValueError, match="Unknown county FIPS"): + catalog.resolve_counties("99999") + + def test_unknown_name(self, catalog): + with pytest.raises(ValueError, match="Unknown county"): + catalog.resolve_counties("Atlantis", state="IA") + + +# ── Districts ───────────────────────────────────────────────────────────────── + +class TestDistricts: + def test_by_asd_id(self, catalog): + assert catalog.resolve_districts("1950") == ["1950"] + + def test_by_code_with_state(self, catalog): + assert catalog.resolve_districts("50", state="IA") == ["1950"] + + def test_code_without_state(self, catalog): + with pytest.raises(ValueError, match="Pass `state`"): + catalog.resolve_districts("50") + + def test_by_name(self, catalog): + assert catalog.resolve_districts("southeast", state="IA") == ["1990"] + + +# ── Crops ───────────────────────────────────────────────────────────────────── + +class TestCrops: + def test_commodity_gives_every_variant(self, catalog): + assert set(catalog.resolve_crops("corn")) == {CORN_GRAIN, CORN_SILAGE} + + def test_label(self, catalog): + assert catalog.resolve_crops("Corn, Grain") == [CORN_GRAIN] + + def test_crop_id(self, catalog): + assert catalog.resolve_crops(SOYBEANS) == [SOYBEANS] + + def test_narrow_by_utilization(self, catalog): + assert catalog.resolve_crops("corn", utilization="silage") == [CORN_SILAGE] + + def test_several_crops(self, catalog): + assert set(catalog.resolve_crops(["corn", "soybeans"], utilization=["grain", "all utilization practices"])) == { + CORN_GRAIN, + SOYBEANS, + } + + def test_unknown_crop(self, catalog): + with pytest.raises(ValueError, match="Unknown crop"): + catalog.resolve_crops("unobtainium") + + def test_unknown_utilization(self, catalog): + with pytest.raises(ValueError, match="Unknown utilization"): + catalog.resolve_crops("corn", utilization="fiber") diff --git a/tests/ag_stats/nass/test_loader.py b/tests/ag_stats/nass/test_loader.py new file mode 100644 index 00000000..b12f72cc --- /dev/null +++ b/tests/ag_stats/nass/test_loader.py @@ -0,0 +1,254 @@ +import os +import pickle +import shutil + +import pytest + +pytest.importorskip("pyarrow") + +import pandas as pd +import pyarrow as pa + +from agml.ag_stats.nass import DEFAULT_REPO_ID, NASSDataLoader + +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE + + +@pytest.fixture(scope="module") +def nass(nass_root): + return NASSDataLoader(str(nass_root)) + + +# ── Initialisation ──────────────────────────────────────────────────────────── + +class TestInit: + def test_accepts_parent_or_parquet_dir(self, nass_root): + a = NASSDataLoader(str(nass_root)) + b = NASSDataLoader(str(nass_root / "parquet")) + assert a.root == b.root + + def test_reads_env_var(self, nass_root, monkeypatch): + monkeypatch.setenv("AGML_NASS_PATH", str(nass_root)) + assert NASSDataLoader().root.endswith("parquet") + + def test_missing_dir(self, tmp_path): + with pytest.raises(FileNotFoundError): + NASSDataLoader(str(tmp_path / "nope")) + + def test_pickle_round_trip(self, nass): + clone = pickle.loads(pickle.dumps(nass)) + assert clone.root == nass.root + assert len(clone.load_yield(state="IA", years=2020)) > 0 + + def test_tables_listing(self): + assert "yield" in NASSDataLoader.tables() + + +# ── Filters ─────────────────────────────────────────────────────────────────── + +class TestFilters: + def test_one_county(self, nass): + df = nass.load_yield(crop="corn", utilization="grain", county="Story", state="IA") + assert set(df["county_fips"]) == {"19169"} + assert set(df["crop_id"]) == {CORN_GRAIN} + assert sorted(df["year"]) == [2018, 2019, 2020, 2021] + + def test_year_forms(self, nass): + def years(spec): + return sorted(nass.load_yield(county="19169", crop="corn, grain", years=spec)["year"]) + + assert years(2020) == [2020] + assert years((2019, 2020)) == [2019, 2020] + assert years([2018, 2021]) == [2018, 2021] + assert years(range(2020, 2022)) == [2020, 2021] + + def test_level(self, nass): + df = nass.load_yield(crop="corn", utilization="grain", level="state") + assert set(df["agg_level"]) == {"STATE"} + assert set(df["state_fips"]) == {"19", "17"} + + def test_state_without_level_keeps_all_levels(self, nass): + df = nass.load_yield(crop="corn", utilization="grain", state="IA", years=2020) + assert set(df["agg_level"]) == {"COUNTY", "AGRICULTURAL DISTRICT", "STATE"} + + def test_other_counties_dropped_by_default(self, nass): + kept = nass.load_yield(level="county", state="IA", crop=CORN_GRAIN, years=2020) + assert kept["county_fips"].notna().all() + every = nass.load_yield(level="county", state="IA", crop=CORN_GRAIN, years=2020, include_other_counties=True) + assert len(every) == len(kept) + 1 + + def test_district(self, nass): + df = nass.load_yield(district="central", state="IA", level="district", crop=CORN_GRAIN) + assert set(df["asd_code"]) == {"50"} + + def test_where_and_wrapper(self, nass): + df = nass.load_area_production(statistic="production", crop="soybeans", state="IL", level="state") + assert set(df["statistic"]) == {"production"} + assert len(df) == 4 + + @pytest.mark.parametrize("stage", ["planted", "PLANTED", "PCT PLANTED"]) + def test_progress_stage(self, nass, stage): + df = nass.load_progress(stage=stage, state="IA", years=2021) + assert set(df["stage"]) == {"PLANTED"} + + def test_forecast_months_in_calendar_order(self, nass): + df = nass.load_forecast(state="IA", crop=CORN_GRAIN, years=2020) + assert list(df["forecast_month"]) == ["AUG", "SEP", "OCT", "NOV"] + assert "_month" not in df.columns + + def test_results_are_sorted(self, nass): + df = nass.load_yield(crop=CORN_GRAIN, level="county") + keys = list(zip(df["state_fips"], df["county_fips"], df["year"])) + assert keys == sorted(keys) + + def test_condition_uses_crop_year(self, nass): + df = nass.load_condition(state="IA", years=2019) + assert set(df["crop_year"]) == {2019} + + def test_county_yield_filters_by_state_alpha(self, nass): + df = nass.load_county_yield(state="Iowa", crop=CORN_SILAGE) + assert set(df["state_alpha"]) == {"IA"} + + def test_columns(self, nass): + df = nass.load_yield(county="19169", crop=CORN_GRAIN, columns=["year", "value"]) + assert list(df.columns) == ["year", "value"] + + +# ── Errors ──────────────────────────────────────────────────────────────────── + +class TestErrors: + def test_unknown_table(self, nass): + with pytest.raises(ValueError, match="Unknown table"): + nass.query("weather") + + def test_county_on_state_only_table(self, nass): + with pytest.raises(ValueError, match="county-level"): + nass.load_progress(county="19169") + + def test_level_on_county_only_table(self, nass): + with pytest.raises(ValueError, match="state-level"): + nass.load_county_yield(level="state") + + def test_unknown_where_column(self, nass): + with pytest.raises(ValueError, match="no column 'colour'"): + nass.load_yield(where={"colour": "red"}) + + def test_unknown_columns(self, nass): + with pytest.raises(ValueError, match="no column"): + nass.load_yield(columns=["colour"]) + + def test_unknown_format(self, nass): + with pytest.raises(ValueError, match="Unknown format"): + nass.load_yield(format="xlsx") + + def test_file_format_needs_path(self, nass): + with pytest.raises(ValueError, match="needs an output"): + nass.load_yield(format="csv") + + +# ── Boundaries ──────────────────────────────────────────────────────────────── + +class TestBoundaries: + def test_county_with_geometry(self, nass): + df = nass.load_boundaries("county") + assert list(df["GEOID"]) == ["19169"] and "geometry" in df.columns + + def test_state_without_geometry(self, nass): + df = nass.load_boundaries("state", geometry=False) + assert list(df["GEOID"]) == ["19"] and "geometry" not in df.columns + + def test_unknown_level(self, nass): + with pytest.raises(ValueError, match="boundary level"): + nass.load_boundaries("district") + + +# ── Hugging Face Hub ────────────────────────────────────────────────────────── + +class FakeHub: + """Stands in for `huggingface_hub`, serving the fixture dataset as one commit.""" + + COMMIT = "0123456789abcdef0123456789abcdef01234567" + + def __init__(self, nass_root, tmp_path): + self.folder = tmp_path / self.COMMIT + shutil.copytree(nass_root, self.folder) + self.downloads = [] + + def snapshot_download(self, repo_id, repo_type, revision, cache_dir, token, allow_patterns): + assert repo_type == "dataset" and all(p.startswith("parquet/") for p in allow_patterns) + self.downloads.extend(allow_patterns) + return str(self.folder) + + def hf_hub_download(self, repo_id, repo_type, filename, revision, cache_dir, token): + assert revision == self.COMMIT + self.downloads.append(filename) + return str(self.folder / filename) + + +@pytest.fixture +def hub(nass_root, tmp_path, monkeypatch): + import huggingface_hub + + fake = FakeHub(nass_root, tmp_path) + monkeypatch.delenv("AGML_NASS_PATH", raising=False) + monkeypatch.setattr(huggingface_hub, "snapshot_download", fake.snapshot_download) + monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake.hf_hub_download) + return fake + + +class TestHub: + def test_defaults_to_hub(self, hub): + nass = NASSDataLoader() + assert nass.repo_id == DEFAULT_REPO_ID + assert nass.revision == FakeHub.COMMIT + + def test_downloads_only_queried_tables(self, hub): + nass = NASSDataLoader() + assert not any(d.endswith("yield.parquet") for d in hub.downloads) + assert len(nass.load_yield(state="IA", years=2020)) > 0 + assert "parquet/yield.parquet" in hub.downloads + assert "parquet/area_production.parquet" not in hub.downloads + + def test_boundaries(self, hub): + assert list(NASSDataLoader().load_boundaries("county")["GEOID"]) == ["19169"] + assert "boundaries/us_county_2020.parquet" in hub.downloads + + def test_pickle_keeps_commit(self, hub): + clone = pickle.loads(pickle.dumps(NASSDataLoader())) + assert clone.revision == FakeHub.COMMIT + assert len(clone.load_yield(state="IA", years=2020)) > 0 + + +# ── Output formats ──────────────────────────────────────────────────────────── + +class TestFormats: + QUERY = dict(county="19169", crop=CORN_GRAIN, years=2020) + + def test_pandas(self, nass): + assert isinstance(nass.load_yield(**self.QUERY), pd.DataFrame) + + def test_arrow(self, nass): + assert isinstance(nass.load_yield(format="arrow", **self.QUERY), pa.Table) + + def test_records(self, nass): + records = nass.load_yield(format="records", **self.QUERY) + assert records[0]["county_fips"] == "19169" + + def test_polars(self, nass): + pl = pytest.importorskip("polars") + assert isinstance(nass.load_yield(format="polars", **self.QUERY), pl.DataFrame) + + @pytest.mark.parametrize("fmt", ["csv", "parquet"]) + def test_files(self, nass, tmp_path, fmt): + path = nass.load_yield(format=fmt, path=str(tmp_path / f"out.{fmt}"), **self.QUERY) + assert os.path.getsize(path) > 0 + + +# ── Real dataset (only when AGML_NASS_PATH points at it) ────────────────────── + +@pytest.mark.skipif("AGML_NASS_PATH" not in os.environ, reason="AGML_NASS_PATH is not set") +def test_real_dataset_story_county_corn(): + nass = NASSDataLoader() + df = nass.load_yield(crop="corn, grain", state="IA", county="Story", years=(2015, 2020), level="county") + assert sorted(df["year"]) == list(range(2015, 2021)) + assert (df["value"] > 100).all()