From 3a142f8382afb4ccfcd1ce5f06dddd39f4cc37ac Mon Sep 17 00:00:00 2001 From: hkaman7 Date: Mon, 9 Nov 2026 13:45:46 -0800 Subject: [PATCH 1/4] adding nass stattistics dataset --- agml/ag_stats/__init__.py | 30 + agml/ag_stats/ag_stats_check.ipynb | 3261 ++++++++++++++++++++++++++++ agml/ag_stats/catalog.py | 240 ++ agml/ag_stats/loader.py | 527 +++++ tests/ag_stats/conftest.py | 135 ++ tests/ag_stats/nass_fixtures.py | 5 + tests/ag_stats/test_catalog.py | 123 ++ tests/ag_stats/test_loader.py | 254 +++ 8 files changed, 4575 insertions(+) create mode 100644 agml/ag_stats/__init__.py create mode 100644 agml/ag_stats/ag_stats_check.ipynb create mode 100644 agml/ag_stats/catalog.py create mode 100644 agml/ag_stats/loader.py create mode 100644 tests/ag_stats/conftest.py create mode 100644 tests/ag_stats/nass_fixtures.py create mode 100644 tests/ag_stats/test_catalog.py create mode 100644 tests/ag_stats/test_loader.py diff --git a/agml/ag_stats/__init__.py b/agml/ag_stats/__init__.py new file mode 100644 index 00000000..cd1140b8 --- /dev/null +++ b/agml/ag_stats/__init__.py @@ -0,0 +1,30 @@ +# 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` 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 diff --git a/agml/ag_stats/ag_stats_check.ipynb b/agml/ag_stats/ag_stats_check.ipynb new file mode 100644 index 00000000..f6b59e26 --- /dev/null +++ b/agml/ag_stats/ag_stats_check.ipynb @@ -0,0 +1,3261 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cell-00", + "metadata": {}, + "source": [ + "# agml.ag_stats check (temporary)\n", + "\n", + "Exercises every public function of `NASSCatalog` and `NASSDataLoader` on the real dataset.\n", + "Temporary notebook: do not commit it." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "cell-01", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:23.714640Z", + "iopub.status.busy": "2026-10-26T15:48:23.714505Z", + "iopub.status.idle": "2026-10-26T15:48:25.832533Z", + "shell.execute_reply": "2026-10-26T15:48:25.832037Z" + } + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/group/jmearlesgrp/hkaman/envs/agml-nass/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", + " from .autonotebook import tqdm as notebook_tqdm\n" + ] + } + ], + "source": [ + "import os, pickle, tempfile\n", + "import pandas as pd\n", + "pd.set_option(\"display.width\", 160)\n", + "pd.set_option(\"display.max_columns\", 20)\n", + "\n", + "from agml.ag_stats import NASSDataLoader, NASSCatalog, TABLES, FORMATS\n", + "\n", + "ROOT = \"/group/jmearlesgrp/hkaman/dataset/nass-usda-full-data\"\n", + "OUT = tempfile.mkdtemp(prefix=\"nass_check_\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-02", + "metadata": {}, + "source": [ + "## 1. Loader setup" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "cell-03", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.834619Z", + "iopub.status.busy": "2026-10-26T15:48:25.834356Z", + "iopub.status.idle": "2026-10-26T15:48:25.852363Z", + "shell.execute_reply": "2026-10-26T15:48:25.851689Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(,\n", + " '/group/jmearlesgrp/hkaman/dataset/nass-usda-full-data/parquet')" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass = NASSDataLoader(ROOT)\n", + "nass, nass.root" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "cell-04", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.853845Z", + "iopub.status.busy": "2026-10-26T15:48:25.853677Z", + "iopub.status.idle": "2026-10-26T15:48:25.866606Z", + "shell.execute_reply": "2026-10-26T15:48:25.866098Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Same loader from the environment variable.\n", + "os.environ[\"AGML_NASS_PATH\"] = ROOT\n", + "NASSDataLoader().root == nass.root" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "cell-05", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.868535Z", + "iopub.status.busy": "2026-10-26T15:48:25.868379Z", + "iopub.status.idle": "2026-10-26T15:48:25.872583Z", + "shell.execute_reply": "2026-10-26T15:48:25.872128Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "yield Yield at national, state, district, and county...\n", + "county_yield County yield for the main crop variants, on 20...\n", + "area_production Area planted, area harvested, and production (...\n", + "census Census of Agriculture crop records, every five...\n", + "forecast In-season yield forecasts by `forecast_month` ...\n", + "progress Weekly crop progress by `stage`, as percent (s...\n", + "condition Weekly crop condition, one column per rating (...\n", + "condition_long Weekly crop condition, one row per rating (sta...\n", + "Name: description, dtype: object" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Every queryable table and its description.\n", + "pd.Series(NASSDataLoader.tables(), name=\"description\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "cell-06", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.874051Z", + "iopub.status.busy": "2026-10-26T15:48:25.873904Z", + "iopub.status.idle": "2026-10-26T15:48:25.877597Z", + "shell.execute_reply": "2026-10-26T15:48:25.876718Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "('pandas', 'polars', 'arrow', 'records', 'csv', 'parquet')" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "FORMATS" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "cell-07", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.879189Z", + "iopub.status.busy": "2026-10-26T15:48:25.879049Z", + "iopub.status.idle": "2026-10-26T15:48:25.883994Z", + "shell.execute_reply": "2026-10-26T15:48:25.883451Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "crop_id: string\n", + "commodity: string\n", + "class: string\n", + "practice: string\n", + "utilization: string\n", + "unit: string\n", + "agg_level: string\n", + "state_fips: string\n", + "state_alpha: string\n", + "asd_code: string\n", + "county_fips: string\n", + "county_fips_nass: string\n", + "county_name: string\n", + "is_other_counties: bool\n", + "year: int32\n", + "value: double\n", + "value_flag: string\n", + "cv_pct: double\n", + "value_t_ha: double\n", + "per_planted_acre: bool\n", + "load_time: timestamp[us]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Column names and types of one table.\n", + "nass.schema(\"yield\")" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "cell-08", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:25.885686Z", + "iopub.status.busy": "2026-10-26T15:48:25.885539Z", + "iopub.status.idle": "2026-10-26T15:48:26.703993Z", + "shell.execute_reply": "2026-10-26T15:48:26.703395Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(True, 13)" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Pickle round trip (AgMLSerializable): only `root` is stored, the catalog is rebuilt.\n", + "clone = pickle.loads(pickle.dumps(nass))\n", + "clone.root == nass.root, len(clone.yield_data(state=\"IA\", years=2020, level=\"state\"))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-09", + "metadata": {}, + "source": [ + "## 2. Catalog listings" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "cell-10", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.705974Z", + "iopub.status.busy": "2026-10-26T15:48:26.705824Z", + "iopub.status.idle": "2026-10-26T15:48:26.710397Z", + "shell.execute_reply": "2026-10-26T15:48:26.709930Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(159,\n", + " ['ALMONDS',\n", + " 'AMARANTH',\n", + " 'APPLES',\n", + " 'APRICOTS',\n", + " 'ARTICHOKES',\n", + " 'ASPARAGUS',\n", + " 'AVOCADOS',\n", + " 'BANANAS',\n", + " 'BARLEY',\n", + " 'BEANS',\n", + " 'BEETS',\n", + " 'BERRIES, OTHER',\n", + " 'BERRY TOTALS',\n", + " 'BLACKBERRIES',\n", + " 'BLUEBERRIES'])" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat = nass.catalog\n", + "len(cat.commodities()), cat.commodities()[:15]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "cell-11", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.712195Z", + "iopub.status.busy": "2026-10-26T15:48:26.712052Z", + "iopub.status.idle": "2026-10-26T15:48:26.723166Z", + "shell.execute_reply": "2026-10-26T15:48:26.722519Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
crop_idcommodityclasspracticeutilizationcrop_label
0407b68a8ae63CORNALL CLASSESALL PRODUCTION PRACTICESALL UTILIZATION PRACTICESCORN
1c3d805b0e626CORNALL CLASSESBIOTECHALL UTILIZATION PRACTICESCORN (BIOTECH)
20d60d988f714CORNALL CLASSESBIOTECH, BTALL UTILIZATION PRACTICESCORN (BIOTECH, BT)
3bc9ebfaaa3a8CORNALL CLASSESBIOTECH, HERBICIDE RESISTANTALL UTILIZATION PRACTICESCORN (BIOTECH, HERBICIDE RESISTANT)
481f9e75f10e8CORNALL CLASSESBIOTECH, STACKED GENEALL UTILIZATION PRACTICESCORN (BIOTECH, STACKED GENE)
5f3d600275f73CORNALL CLASSESIRRIGATEDALL UTILIZATION PRACTICESCORN (IRRIGATED)
66b2217b8ecc7CORNALL CLASSESNON-IRRIGATEDALL UTILIZATION PRACTICESCORN (NON-IRRIGATED)
79d9f23c859c7CORNALL CLASSESALL PRODUCTION PRACTICESFORAGECORN, FORAGE
8f56a2f05c3bdCORNALL CLASSESALL PRODUCTION PRACTICESGRAINCORN, GRAIN
9789e870f29d8CORNALL CLASSESIRRIGATEDGRAINCORN, GRAIN (IRRIGATED)
104ff8c50986b1CORNALL CLASSESIRRIGATED, ENTIRE CROPGRAINCORN, GRAIN (IRRIGATED, ENTIRE CROP)
11dbf09d4a17e2CORNALL CLASSESIRRIGATED, NONE OF CROPGRAINCORN, GRAIN (IRRIGATED, NONE OF CROP)
124e6e7262bcedCORNALL CLASSESIRRIGATED, PART OF CROPGRAINCORN, GRAIN (IRRIGATED, PART OF CROP)
1389c529b35c0dCORNALL CLASSESIRRIGATED, PART OF CROP, IRRIGATED PORTIONGRAINCORN, GRAIN (IRRIGATED, PART OF CROP, IRRIGATE...
149ed097409ab9CORNALL CLASSESIRRIGATED, PART OF CROP, NON-IRRIGATED PORTIONGRAINCORN, GRAIN (IRRIGATED, PART OF CROP, NON-IRRI...
153a740671eb8eCORNALL CLASSESNON-IRRIGATEDGRAINCORN, GRAIN (NON-IRRIGATED)
1645e465f318caCORNALL CLASSESALL PRODUCTION PRACTICESSILAGECORN, SILAGE
177ef20a007fc2CORNALL CLASSESIRRIGATEDSILAGECORN, SILAGE (IRRIGATED)
18eae7c78b71e8CORNALL CLASSESIRRIGATED, ENTIRE CROPSILAGECORN, SILAGE (IRRIGATED, ENTIRE CROP)
198c53b4741503CORNALL CLASSESIRRIGATED, NONE OF CROPSILAGECORN, SILAGE (IRRIGATED, NONE OF CROP)
20fd177da6fa82CORNALL CLASSESIRRIGATED, PART OF CROPSILAGECORN, SILAGE (IRRIGATED, PART OF CROP)
21b1ed57ec3408CORNALL CLASSESIRRIGATED, PART OF CROP, IRRIGATED PORTIONSILAGECORN, SILAGE (IRRIGATED, PART OF CROP, IRRIGAT...
22fc6c0f42234eCORNALL CLASSESIRRIGATED, PART OF CROP, NON-IRRIGATED PORTIONSILAGECORN, SILAGE (IRRIGATED, PART OF CROP, NON-IRR...
23be284ce79a22CORNALL CLASSESNON-IRRIGATEDSILAGECORN, SILAGE (NON-IRRIGATED)
2400d55d63aff2CORNTRADITIONAL OR INDIANALL PRODUCTION PRACTICESALL UTILIZATION PRACTICESCORN, TRADITIONAL OR INDIAN
25d9d376027b71CORNTRADITIONAL OR INDIANIRRIGATEDALL UTILIZATION PRACTICESCORN, TRADITIONAL OR INDIAN (IRRIGATED)
\n", + "
" + ], + "text/plain": [ + " crop_id commodity class practice utilization \\\n", + "0 407b68a8ae63 CORN ALL CLASSES ALL PRODUCTION PRACTICES ALL UTILIZATION PRACTICES \n", + "1 c3d805b0e626 CORN ALL CLASSES BIOTECH ALL UTILIZATION PRACTICES \n", + "2 0d60d988f714 CORN ALL CLASSES BIOTECH, BT ALL UTILIZATION PRACTICES \n", + "3 bc9ebfaaa3a8 CORN ALL CLASSES BIOTECH, HERBICIDE RESISTANT ALL UTILIZATION PRACTICES \n", + "4 81f9e75f10e8 CORN ALL CLASSES BIOTECH, STACKED GENE ALL UTILIZATION PRACTICES \n", + "5 f3d600275f73 CORN ALL CLASSES IRRIGATED ALL UTILIZATION PRACTICES \n", + "6 6b2217b8ecc7 CORN ALL CLASSES NON-IRRIGATED ALL UTILIZATION PRACTICES \n", + "7 9d9f23c859c7 CORN ALL CLASSES ALL PRODUCTION PRACTICES FORAGE \n", + "8 f56a2f05c3bd CORN ALL CLASSES ALL PRODUCTION PRACTICES GRAIN \n", + "9 789e870f29d8 CORN ALL CLASSES IRRIGATED GRAIN \n", + "10 4ff8c50986b1 CORN ALL CLASSES IRRIGATED, ENTIRE CROP GRAIN \n", + "11 dbf09d4a17e2 CORN ALL CLASSES IRRIGATED, NONE OF CROP GRAIN \n", + "12 4e6e7262bced CORN ALL CLASSES IRRIGATED, PART OF CROP GRAIN \n", + "13 89c529b35c0d CORN ALL CLASSES IRRIGATED, PART OF CROP, IRRIGATED PORTION GRAIN \n", + "14 9ed097409ab9 CORN ALL CLASSES IRRIGATED, PART OF CROP, NON-IRRIGATED PORTION GRAIN \n", + "15 3a740671eb8e CORN ALL CLASSES NON-IRRIGATED GRAIN \n", + "16 45e465f318ca CORN ALL CLASSES ALL PRODUCTION PRACTICES SILAGE \n", + "17 7ef20a007fc2 CORN ALL CLASSES IRRIGATED SILAGE \n", + "18 eae7c78b71e8 CORN ALL CLASSES IRRIGATED, ENTIRE CROP SILAGE \n", + "19 8c53b4741503 CORN ALL CLASSES IRRIGATED, NONE OF CROP SILAGE \n", + "20 fd177da6fa82 CORN ALL CLASSES IRRIGATED, PART OF CROP SILAGE \n", + "21 b1ed57ec3408 CORN ALL CLASSES IRRIGATED, PART OF CROP, IRRIGATED PORTION SILAGE \n", + "22 fc6c0f42234e CORN ALL CLASSES IRRIGATED, PART OF CROP, NON-IRRIGATED PORTION SILAGE \n", + "23 be284ce79a22 CORN ALL CLASSES NON-IRRIGATED SILAGE \n", + "24 00d55d63aff2 CORN TRADITIONAL OR INDIAN ALL PRODUCTION PRACTICES ALL UTILIZATION PRACTICES \n", + "25 d9d376027b71 CORN TRADITIONAL OR INDIAN IRRIGATED ALL UTILIZATION PRACTICES \n", + "\n", + " crop_label \n", + "0 CORN \n", + "1 CORN (BIOTECH) \n", + "2 CORN (BIOTECH, BT) \n", + "3 CORN (BIOTECH, HERBICIDE RESISTANT) \n", + "4 CORN (BIOTECH, STACKED GENE) \n", + "5 CORN (IRRIGATED) \n", + "6 CORN (NON-IRRIGATED) \n", + "7 CORN, FORAGE \n", + "8 CORN, GRAIN \n", + "9 CORN, GRAIN (IRRIGATED) \n", + "10 CORN, GRAIN (IRRIGATED, ENTIRE CROP) \n", + "11 CORN, GRAIN (IRRIGATED, NONE OF CROP) \n", + "12 CORN, GRAIN (IRRIGATED, PART OF CROP) \n", + "13 CORN, GRAIN (IRRIGATED, PART OF CROP, IRRIGATE... \n", + "14 CORN, GRAIN (IRRIGATED, PART OF CROP, NON-IRRI... \n", + "15 CORN, GRAIN (NON-IRRIGATED) \n", + "16 CORN, SILAGE \n", + "17 CORN, SILAGE (IRRIGATED) \n", + "18 CORN, SILAGE (IRRIGATED, ENTIRE CROP) \n", + "19 CORN, SILAGE (IRRIGATED, NONE OF CROP) \n", + "20 CORN, SILAGE (IRRIGATED, PART OF CROP) \n", + "21 CORN, SILAGE (IRRIGATED, PART OF CROP, IRRIGAT... \n", + "22 CORN, SILAGE (IRRIGATED, PART OF CROP, NON-IRR... \n", + "23 CORN, SILAGE (NON-IRRIGATED) \n", + "24 CORN, TRADITIONAL OR INDIAN \n", + "25 CORN, TRADITIONAL OR INDIAN (IRRIGATED) " + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat.crops(\"corn\")" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "cell-12", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.724624Z", + "iopub.status.busy": "2026-10-26T15:48:26.724471Z", + "iopub.status.idle": "2026-10-26T15:48:26.731618Z", + "shell.execute_reply": "2026-10-26T15:48:26.731109Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
state_fipsstate_alphastate_namearea_km2centroid_loncentroid_lat
001ALAlabama133892.90-86.8300132.77881
102AKAlaska1520598.73-152.4419763.78199
204AZArizona295232.40-111.6600434.27701
305ARArkansas137782.04-92.4421834.89482
406CACalifornia409819.66-119.4724837.18624
\n", + "
" + ], + "text/plain": [ + " state_fips state_alpha state_name area_km2 centroid_lon centroid_lat\n", + "0 01 AL Alabama 133892.90 -86.83001 32.77881\n", + "1 02 AK Alaska 1520598.73 -152.44197 63.78199\n", + "2 04 AZ Arizona 295232.40 -111.66004 34.27701\n", + "3 05 AR Arkansas 137782.04 -92.44218 34.89482\n", + "4 06 CA California 409819.66 -119.47248 37.18624" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat.states().head()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "cell-13", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.733370Z", + "iopub.status.busy": "2026-10-26T15:48:26.733229Z", + "iopub.status.idle": "2026-10-26T15:48:26.742283Z", + "shell.execute_reply": "2026-10-26T15:48:26.741755Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
county_fipsstate_fipscounty_codecounty_namestate_alphaarea_km2centroid_loncentroid_lat
01900119001AdairIA1476.97-94.4709441.33066
11900319003AdamsIA1102.19-94.6991941.02896
21900519005AllamakeeIA1706.28-91.3780243.28413
31900719007AppanooseIA1337.00-92.8686440.74311
41900919009AudubonIA1148.29-94.9057841.68446
\n", + "
" + ], + "text/plain": [ + " county_fips state_fips county_code county_name state_alpha area_km2 centroid_lon centroid_lat\n", + "0 19001 19 001 Adair IA 1476.97 -94.47094 41.33066\n", + "1 19003 19 003 Adams IA 1102.19 -94.69919 41.02896\n", + "2 19005 19 005 Allamakee IA 1706.28 -91.37802 43.28413\n", + "3 19007 19 007 Appanoose IA 1337.00 -92.86864 40.74311\n", + "4 19009 19 009 Audubon IA 1148.29 -94.90578 41.68446" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat.counties(state=\"IA\").head()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "cell-14", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.743972Z", + "iopub.status.busy": "2026-10-26T15:48:26.743829Z", + "iopub.status.idle": "2026-10-26T15:48:26.751355Z", + "shell.execute_reply": "2026-10-26T15:48:26.750885Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
state_fipsstate_alphaasd_codeasd_descasd_id
019IA10NORTHWEST1910
119IA20NORTH CENTRAL1920
219IA30NORTHEAST1930
319IA40WEST CENTRAL1940
419IA50CENTRAL1950
519IA60EAST CENTRAL1960
619IA70SOUTHWEST1970
719IA80SOUTH CENTRAL1980
819IA90SOUTHEAST1990
919IA98OTHER DISTRICTS, ALL COUNTIES1998
1019IA99None1999
\n", + "
" + ], + "text/plain": [ + " state_fips state_alpha asd_code asd_desc asd_id\n", + "0 19 IA 10 NORTHWEST 1910\n", + "1 19 IA 20 NORTH CENTRAL 1920\n", + "2 19 IA 30 NORTHEAST 1930\n", + "3 19 IA 40 WEST CENTRAL 1940\n", + "4 19 IA 50 CENTRAL 1950\n", + "5 19 IA 60 EAST CENTRAL 1960\n", + "6 19 IA 70 SOUTHWEST 1970\n", + "7 19 IA 80 SOUTH CENTRAL 1980\n", + "8 19 IA 90 SOUTHEAST 1990\n", + "9 19 IA 98 OTHER DISTRICTS, ALL COUNTIES 1998\n", + "10 19 IA 99 None 1999" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat.districts(state=\"IA\")" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "cell-15", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.753075Z", + "iopub.status.busy": "2026-10-26T15:48:26.752933Z", + "iopub.status.idle": "2026-10-26T15:48:26.766453Z", + "shell.execute_reply": "2026-10-26T15:48:26.765950Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['ALMONDS', 'AMARANTH', 'APPLES', 'APRICOTS', 'ARTICHOKES']" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# The catalog can also be used on its own.\n", + "NASSCatalog(nass.root).commodities()[:5]" + ] + }, + { + "cell_type": "markdown", + "id": "cell-16", + "metadata": {}, + "source": [ + "## 3. Catalog name resolution" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "cell-17", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.768094Z", + "iopub.status.busy": "2026-10-26T15:48:26.767945Z", + "iopub.status.idle": "2026-10-26T15:48:26.773779Z", + "shell.execute_reply": "2026-10-26T15:48:26.773321Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([['19'], ['19'], ['19'], ['19'], ['19']], ['06', '17'])" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[cat.resolve_states(v) for v in [\"IA\", \"ia\", \"Iowa\", \"19\", 19]], cat.resolve_states([\"CA\", \"Illinois\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "cell-18", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.775406Z", + "iopub.status.busy": "2026-10-26T15:48:26.775264Z", + "iopub.status.idle": "2026-10-26T15:48:26.778452Z", + "shell.execute_reply": "2026-10-26T15:48:26.777903Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['IA', 'CA']" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat.state_alphas([\"19\", \"06\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "cell-19", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.780069Z", + "iopub.status.busy": "2026-10-26T15:48:26.779929Z", + "iopub.status.idle": "2026-10-26T15:48:26.788902Z", + "shell.execute_reply": "2026-10-26T15:48:26.788368Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(['19169'], ['19169'], ['19169'], ['06113', '06019'])" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(cat.resolve_counties(\"Story\", state=\"IA\"),\n", + " cat.resolve_counties(\"story county\", state=\"Iowa\"),\n", + " cat.resolve_counties(\"19169\"),\n", + " cat.resolve_counties([\"Yolo\", \"Fresno\"], state=\"CA\"))" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "cell-20", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.790511Z", + "iopub.status.busy": "2026-10-26T15:48:26.790370Z", + "iopub.status.idle": "2026-10-26T15:48:26.793643Z", + "shell.execute_reply": "2026-10-26T15:48:26.793054Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['46102']" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Old NASS code for Shannon County, SD is mapped to its 2020 code (Oglala Lakota).\n", + "cat.resolve_counties(\"46113\")" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "cell-21", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.795082Z", + "iopub.status.busy": "2026-10-26T15:48:26.794945Z", + "iopub.status.idle": "2026-10-26T15:48:26.802503Z", + "shell.execute_reply": "2026-10-26T15:48:26.802016Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'state_fips': '19', 'state_alpha': 'IA', 'asd_code': '10', 'asd_desc': 'NORTHWEST', 'asd_id': '1910'}\n" + ] + }, + { + "data": { + "text/plain": [ + "(['1910'], ['1910'], ['1910'])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "first = cat.districts(state=\"IA\").iloc[0]\n", + "print(first.to_dict())\n", + "(cat.resolve_districts(first[\"asd_id\"]),\n", + " cat.resolve_districts(first[\"asd_code\"], state=\"IA\"),\n", + " cat.resolve_districts(first[\"asd_desc\"].lower(), state=\"IA\"))" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "cell-22", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.804152Z", + "iopub.status.busy": "2026-10-26T15:48:26.804014Z", + "iopub.status.idle": "2026-10-26T15:48:26.811964Z", + "shell.execute_reply": "2026-10-26T15:48:26.811068Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(26, ['f56a2f05c3bd'], ['f56a2f05c3bd'], ['8e3f7fc43681', '6256b3fe85b5'])" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "corn_all = cat.resolve_crops(\"corn\")\n", + "corn_grain = cat.resolve_crops(\"corn\", utilization=\"grain\", practice=\"all production practices\")\n", + "(len(corn_all), corn_grain,\n", + " cat.resolve_crops(\"CORN, GRAIN\"),\n", + " cat.resolve_crops([\"soybeans\", \"wheat\"], crop_class=\"all classes\", practice=\"all production practices\",\n", + " utilization=\"all utilization practices\"))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-23", + "metadata": {}, + "source": [ + "## 4. Error messages" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "cell-24", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.813378Z", + "iopub.status.busy": "2026-10-26T15:48:26.813233Z", + "iopub.status.idle": "2026-10-26T15:48:26.829869Z", + "shell.execute_reply": "2026-10-26T15:48:26.829299Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ValueError: Unknown state 'Iowaa'. Did you mean one of: IOWA?\n", + "ValueError: County name 'Washington' exists in several states (AL, AR, CO, FL, GA, IA, ID, IL, IN, KS, KY, LA, MD, ME, MN, MO, MS, NC, NE, NY, OH, OK, OR, PA, RI, TN, TX, UT, VA, VT, WI). Pass `state` as well.\n", + "ValueError: Unknown county FIPS code '99999'.\n", + "ValueError: District code '10' is only unique within a state. Pass `state` as well.\n", + "ValueError: Unknown crop 'cron'. Did you mean one of: CORN, COTTON?\n", + "ValueError: Unknown utilization 'FIBER'.\n", + "ValueError: Unknown table 'weather'. Choose one of ['yield', 'county_yield', 'area_production', 'census', 'forecast', 'progress', 'condition', 'condition_long'].\n", + "ValueError: Table 'progress' has no county-level data, so `county` cannot be used with it.\n", + "ValueError: Table 'county_yield' has no state-level data, so `level` cannot be used with it.\n", + "ValueError: Table 'yield' has no column 'colour'.\n", + "ValueError: Table 'yield' has no column(s) ['colour'].\n", + "ValueError: Unknown format 'xlsx'. Choose one of ('pandas', 'polars', 'arrow', 'records', 'csv', 'parquet').\n", + "ValueError: The 'csv' format needs an output `path`.\n", + "FileNotFoundError: The NASS dataset directory '/no/such/dir' does not exist.\n" + ] + } + ], + "source": [ + "for call in [\n", + " lambda: cat.resolve_states(\"Iowaa\"),\n", + " lambda: cat.resolve_counties(\"Washington\"),\n", + " lambda: cat.resolve_counties(\"99999\"),\n", + " lambda: cat.resolve_districts(\"10\"),\n", + " lambda: cat.resolve_crops(\"cron\"),\n", + " lambda: cat.resolve_crops(\"corn\", utilization=\"fiber\"),\n", + " lambda: nass.query(\"weather\"),\n", + " lambda: nass.progress(county=\"19169\"),\n", + " lambda: nass.county_yield(level=\"state\"),\n", + " lambda: nass.yield_data(where={\"colour\": \"red\"}),\n", + " lambda: nass.yield_data(columns=[\"colour\"]),\n", + " lambda: nass.yield_data(format=\"xlsx\"),\n", + " lambda: nass.yield_data(format=\"csv\"),\n", + " lambda: NASSDataLoader(\"/no/such/dir\"),\n", + "]:\n", + " try:\n", + " call()\n", + " print(\"NO ERROR (unexpected)\")\n", + " except (ValueError, FileNotFoundError) as e:\n", + " print(f\"{type(e).__name__}: {e}\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-25", + "metadata": {}, + "source": [ + "## 5. `yield` table: filters" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "cell-26", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:26.831644Z", + "iopub.status.busy": "2026-10-26T15:48:26.831497Z", + "iopub.status.idle": "2026-10-26T15:48:27.243619Z", + "shell.execute_reply": "2026-10-26T15:48:27.242957Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearcounty_namevalueunitvalue_t_hacv_pct
02015STORY188.0BU / ACRE11.8003NaN
12016STORY211.9BU / ACRE13.3005NaN
22017STORY200.3BU / ACRE12.5724NaN
32018STORY192.3BU / ACRE12.0702NaN
42019STORY189.3BU / ACRE11.8819NaN
52020STORY148.4BU / ACRE9.31472.6
62021STORY201.2BU / ACRE12.62881.9
72022STORY207.1BU / ACRE12.99922.5
82023STORY211.4BU / ACRE13.26913.2
92024STORY215.5BU / ACRE13.52642.6
\n", + "
" + ], + "text/plain": [ + " year county_name value unit value_t_ha cv_pct\n", + "0 2015 STORY 188.0 BU / ACRE 11.8003 NaN\n", + "1 2016 STORY 211.9 BU / ACRE 13.3005 NaN\n", + "2 2017 STORY 200.3 BU / ACRE 12.5724 NaN\n", + "3 2018 STORY 192.3 BU / ACRE 12.0702 NaN\n", + "4 2019 STORY 189.3 BU / ACRE 11.8819 NaN\n", + "5 2020 STORY 148.4 BU / ACRE 9.3147 2.6\n", + "6 2021 STORY 201.2 BU / ACRE 12.6288 1.9\n", + "7 2022 STORY 207.1 BU / ACRE 12.9992 2.5\n", + "8 2023 STORY 211.4 BU / ACRE 13.2691 3.2\n", + "9 2024 STORY 215.5 BU / ACRE 13.5264 2.6" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# One county, one crop, a year range.\n", + "nass.yield_data(crop=\"corn\", utilization=\"grain\", state=\"IA\", county=\"Story\", years=(2015, 2024), level=\"county\",\n", + " columns=[\"year\", \"county_name\", \"value\", \"unit\", \"value_t_ha\", \"cv_pct\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "cell-27", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:27.245328Z", + "iopub.status.busy": "2026-10-26T15:48:27.245173Z", + "iopub.status.idle": "2026-10-26T15:48:27.773315Z", + "shell.execute_reply": "2026-10-26T15:48:27.772767Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([2020], [1990, 2000, 2010], [2021, 2022, 2023])" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Year forms: single year, list, range object.\n", + "q = dict(crop=\"CORN, GRAIN\", county=\"19169\", level=\"county\", columns=[\"year\", \"value\"])\n", + "(nass.yield_data(years=2020, **q)[\"year\"].tolist(),\n", + " nass.yield_data(years=[1990, 2000, 2010], **q)[\"year\"].tolist(),\n", + " nass.yield_data(years=range(2021, 2024), **q)[\"year\"].tolist())" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "cell-28", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:27.774907Z", + "iopub.status.busy": "2026-10-26T15:48:27.774749Z", + "iopub.status.idle": "2026-10-26T15:48:28.605159Z", + "shell.execute_reply": "2026-10-26T15:48:28.604651Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "agg_level\n", + "COUNTY 95\n", + "STATE 1\n", + "Name: count, dtype: int64" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Every level for one state and year (no `level` given).\n", + "nass.yield_data(crop=\"CORN, GRAIN\", state=\"IA\", years=2020)[\"agg_level\"].value_counts()" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "cell-29", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:28.606732Z", + "iopub.status.busy": "2026-10-26T15:48:28.606580Z", + "iopub.status.idle": "2026-10-26T15:48:28.839909Z", + "shell.execute_reply": "2026-10-26T15:48:28.839367Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
state_alphayearvalueunit
0IA2020177.0BU / ACRE
1IA2021204.0BU / ACRE
2IA2022200.0BU / ACRE
3IA2023201.0BU / ACRE
4IL2020191.0BU / ACRE
5IL2021202.0BU / ACRE
6IL2022214.0BU / ACRE
7IL2023206.0BU / ACRE
8NE2020180.0BU / ACRE
9NE2021194.0BU / ACRE
10NE2022165.0BU / ACRE
11NE2023182.0BU / ACRE
\n", + "
" + ], + "text/plain": [ + " state_alpha year value unit\n", + "0 IA 2020 177.0 BU / ACRE\n", + "1 IA 2021 204.0 BU / ACRE\n", + "2 IA 2022 200.0 BU / ACRE\n", + "3 IA 2023 201.0 BU / ACRE\n", + "4 IL 2020 191.0 BU / ACRE\n", + "5 IL 2021 202.0 BU / ACRE\n", + "6 IL 2022 214.0 BU / ACRE\n", + "7 IL 2023 206.0 BU / ACRE\n", + "8 NE 2020 180.0 BU / ACRE\n", + "9 NE 2021 194.0 BU / ACRE\n", + "10 NE 2022 165.0 BU / ACRE\n", + "11 NE 2023 182.0 BU / ACRE" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# State level, several states.\n", + "nass.yield_data(crop=\"CORN, GRAIN\", state=[\"IA\", \"IL\", \"NE\"], level=\"state\", years=(2020, 2023),\n", + " columns=[\"state_alpha\", \"year\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "cell-30", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:28.841392Z", + "iopub.status.busy": "2026-10-26T15:48:28.841243Z", + "iopub.status.idle": "2026-10-26T15:48:29.067106Z", + "shell.execute_reply": "2026-10-26T15:48:29.066527Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearvalueunit
02019167.5BU / ACRE
12020171.4BU / ACRE
22021176.7BU / ACRE
32022173.4BU / ACRE
42023177.3BU / ACRE
\n", + "
" + ], + "text/plain": [ + " year value unit\n", + "0 2019 167.5 BU / ACRE\n", + "1 2020 171.4 BU / ACRE\n", + "2 2021 176.7 BU / ACRE\n", + "3 2022 173.4 BU / ACRE\n", + "4 2023 177.3 BU / ACRE" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# National level.\n", + "nass.yield_data(crop=\"CORN, GRAIN\", level=\"national\", years=(2019, 2023), columns=[\"year\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "cell-31", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:29.068967Z", + "iopub.status.busy": "2026-10-26T15:48:29.068817Z", + "iopub.status.idle": "2026-10-26T15:48:29.317244Z", + "shell.execute_reply": "2026-10-26T15:48:29.316695Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
state_alphaasd_codeyearvalue
0IA102015202.5
1IA102016205.5
2IA102017203.4
3IA102018188.4
4IA102019195.3
\n", + "
" + ], + "text/plain": [ + " state_alpha asd_code year value\n", + "0 IA 10 2015 202.5\n", + "1 IA 10 2016 205.5\n", + "2 IA 10 2017 203.4\n", + "3 IA 10 2018 188.4\n", + "4 IA 10 2019 195.3" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# District level. District yields in this data stop in 2019.\n", + "nass.yield_data(crop=\"CORN, GRAIN\", district=first[\"asd_id\"], level=\"district\", years=(2015, 2019),\n", + " columns=[\"state_alpha\", \"asd_code\", \"year\", \"value\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "cell-32", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:29.318730Z", + "iopub.status.busy": "2026-10-26T15:48:29.318580Z", + "iopub.status.idle": "2026-10-26T15:48:30.787598Z", + "shell.execute_reply": "2026-10-26T15:48:30.786727Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(95, 96, np.int64(1))" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# \"Other (combined) counties\" rows are dropped by default.\n", + "q = dict(crop=\"CORN, GRAIN\", state=\"IA\", level=\"county\", years=2020)\n", + "kept = nass.yield_data(**q)\n", + "every = nass.yield_data(include_other_counties=True, **q)\n", + "len(kept), len(every), every[\"is_other_counties\"].sum()" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "cell-33", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:30.789136Z", + "iopub.status.busy": "2026-10-26T15:48:30.788973Z", + "iopub.status.idle": "2026-10-26T15:48:31.047141Z", + "shell.execute_reply": "2026-10-26T15:48:31.046405Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
crop_idyearvalueunit
06256b3fe85b5202335.0BU / ACRE
1c66627e9fb28202335.0BU / ACRE
\n", + "
" + ], + "text/plain": [ + " crop_id year value unit\n", + "0 6256b3fe85b5 2023 35.0 BU / ACRE\n", + "1 c66627e9fb28 2023 35.0 BU / ACRE" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# `where` on any column, e.g. one unit only.\n", + "nass.yield_data(crop=\"wheat\", state=\"KS\", level=\"state\", years=2023, where={\"unit\": \"BU / ACRE\"},\n", + " columns=[\"crop_id\", \"year\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "markdown", + "id": "cell-34", + "metadata": {}, + "source": [ + "## 6. Other tables" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "cell-35", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:31.048813Z", + "iopub.status.busy": "2026-10-26T15:48:31.048529Z", + "iopub.status.idle": "2026-10-26T15:48:31.171174Z", + "shell.execute_reply": "2026-10-26T15:48:31.170638Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearcommodityclassutilizationyield_t_haqa_outlier
02018CORNALL CLASSESGRAIN12.3464False
12018WHEATWINTERALL UTILIZATION PRACTICES5.2389False
22018BARLEYALL CLASSESALL UTILIZATION PRACTICES5.4554False
32019CORNALL CLASSESGRAIN12.2271False
42019WHEATWINTERALL UTILIZATION PRACTICES3.1339False
52020WHEATWINTERALL UTILIZATION PRACTICES7.3976False
\n", + "
" + ], + "text/plain": [ + " year commodity class utilization yield_t_ha qa_outlier\n", + "0 2018 CORN ALL CLASSES GRAIN 12.3464 False\n", + "1 2018 WHEAT WINTER ALL UTILIZATION PRACTICES 5.2389 False\n", + "2 2018 BARLEY ALL CLASSES ALL UTILIZATION PRACTICES 5.4554 False\n", + "3 2019 CORN ALL CLASSES GRAIN 12.2271 False\n", + "4 2019 WHEAT WINTER ALL UTILIZATION PRACTICES 3.1339 False\n", + "5 2020 WHEAT WINTER ALL UTILIZATION PRACTICES 7.3976 False" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# county_yield: the curated main-variant county view (filters by state_alpha internally).\n", + "nass.county_yield(state=\"CA\", county=\"Yolo\", years=(2018, 2020),\n", + " columns=[\"year\", \"commodity\", \"class\", \"utilization\", \"yield_t_ha\", \"qa_outlier\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "cell-36", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:31.172667Z", + "iopub.status.busy": "2026-10-26T15:48:31.172510Z", + "iopub.status.idle": "2026-10-26T15:48:31.930600Z", + "shell.execute_reply": "2026-10-26T15:48:31.929812Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
state_alphayearvalueunit
0KS2020281250000.0BU
1KS2021364000000.0BU
2KS2022244200000.0BU
3KS2023201250000.0BU
4KS2024307450000.0BU
5ND2020312587000.0BU
6ND2021196195000.0BU
7ND2022299900000.0BU
8ND2023306390000.0BU
9ND2024368285000.0BU
\n", + "
" + ], + "text/plain": [ + " state_alpha year value unit\n", + "0 KS 2020 281250000.0 BU\n", + "1 KS 2021 364000000.0 BU\n", + "2 KS 2022 244200000.0 BU\n", + "3 KS 2023 201250000.0 BU\n", + "4 KS 2024 307450000.0 BU\n", + "5 ND 2020 312587000.0 BU\n", + "6 ND 2021 196195000.0 BU\n", + "7 ND 2022 299900000.0 BU\n", + "8 ND 2023 306390000.0 BU\n", + "9 ND 2024 368285000.0 BU" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass.area_production(crop=\"wheat\", crop_class=\"all classes\", state=[\"KS\", \"ND\"], level=\"state\",\n", + " statistic=\"production\", years=(2020, 2024), columns=[\"state_alpha\", \"year\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "cell-37", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:31.932099Z", + "iopub.status.busy": "2026-10-26T15:48:31.931946Z", + "iopub.status.idle": "2026-10-26T15:48:32.552035Z", + "shell.execute_reply": "2026-10-26T15:48:32.551192Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearstatisticvalueunit
02022area_harvested156100.0ACRES
12022production32328000.0BU
\n", + "
" + ], + "text/plain": [ + " year statistic value unit\n", + "0 2022 area_harvested 156100.0 ACRES\n", + "1 2022 production 32328000.0 BU" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Several statistics at once.\n", + "nass.area_production(crop=\"CORN, GRAIN\", county=\"Story\", state=\"IA\", years=2022,\n", + " statistic=[\"area_planted\", \"area_harvested\", \"production\"],\n", + " columns=[\"year\", \"statistic\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "cell-38", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.553560Z", + "iopub.status.busy": "2026-10-26T15:48:32.553411Z", + "iopub.status.idle": "2026-10-26T15:48:32.805544Z", + "shell.execute_reply": "2026-10-26T15:48:32.804729Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearstatisticvalueunit
01997area_harvested11930542.0ACRES
12002area_harvested11761392.0ACRES
22007area_harvested13842282.0ACRES
32012area_harvested13709408.0ACRES
42017area_harvested12969645.0ACRES
52022area_harvested12637070.0ACRES
\n", + "
" + ], + "text/plain": [ + " year statistic value unit\n", + "0 1997 area_harvested 11930542.0 ACRES\n", + "1 2002 area_harvested 11761392.0 ACRES\n", + "2 2007 area_harvested 13842282.0 ACRES\n", + "3 2012 area_harvested 13709408.0 ACRES\n", + "4 2017 area_harvested 12969645.0 ACRES\n", + "5 2022 area_harvested 12637070.0 ACRES" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Census of Agriculture: every five years. (The data has no CA almond records, so this uses Iowa corn grain.)\n", + "nass.census(crop=\"CORN, GRAIN\", state=\"IA\", level=\"state\", statistic=\"area_harvested\", where={\"unit\": \"ACRES\"},\n", + " columns=[\"year\", \"statistic\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "cell-39", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.807079Z", + "iopub.status.busy": "2026-10-26T15:48:32.806895Z", + "iopub.status.idle": "2026-10-26T15:48:32.821599Z", + "shell.execute_reply": "2026-10-26T15:48:32.821075Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearforecast_monthvalueunit
02023AUG203.0BU / ACRE
12023SEP200.0BU / ACRE
22023OCT199.0BU / ACRE
32023NOV200.0BU / ACRE
\n", + "
" + ], + "text/plain": [ + " year forecast_month value unit\n", + "0 2023 AUG 203.0 BU / ACRE\n", + "1 2023 SEP 200.0 BU / ACRE\n", + "2 2023 OCT 199.0 BU / ACRE\n", + "3 2023 NOV 200.0 BU / ACRE" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass.forecast(crop=\"CORN, GRAIN\", state=\"IA\", years=2023, columns=[\"year\", \"forecast_month\", \"value\", \"unit\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "cell-40", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.823131Z", + "iopub.status.busy": "2026-10-26T15:48:32.822981Z", + "iopub.status.idle": "2026-10-26T15:48:32.861577Z", + "shell.execute_reply": "2026-10-26T15:48:32.861026Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
week_endingstagepct
02023-04-16PLANTED4.0
12023-04-23PLANTED15.0
22023-04-30PLANTED39.0
32023-05-07PLANTED66.0
42023-05-14PLANTED77.0
52023-05-21PLANTED85.0
62023-05-28PLANTED92.0
72023-06-04PLANTED96.0
82023-06-11PLANTED97.0
\n", + "
" + ], + "text/plain": [ + " week_ending stage pct\n", + "0 2023-04-16 PLANTED 4.0\n", + "1 2023-04-23 PLANTED 15.0\n", + "2 2023-04-30 PLANTED 39.0\n", + "3 2023-05-07 PLANTED 66.0\n", + "4 2023-05-14 PLANTED 77.0\n", + "5 2023-05-21 PLANTED 85.0\n", + "6 2023-05-28 PLANTED 92.0\n", + "7 2023-06-04 PLANTED 96.0\n", + "8 2023-06-11 PLANTED 97.0" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass.progress(crop=\"soybeans\", state=\"IL\", years=2023, stage=\"planted\", columns=[\"week_ending\", \"stage\", \"pct\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "cell-41", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.863149Z", + "iopub.status.busy": "2026-10-26T15:48:32.862999Z", + "iopub.status.idle": "2026-10-26T15:48:32.962946Z", + "shell.execute_reply": "2026-10-26T15:48:32.962282Z" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "stage\n", + "EMERGED 10\n", + "PLANTED 9\n", + "Name: count, dtype: int64" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Several stages, all three spellings accepted.\n", + "nass.progress(crop=\"soybeans\", state=\"IL\", years=2023, stage=[\"PCT PLANTED\", \"emerged\"])[\"stage\"].value_counts()" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "cell-42", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.964511Z", + "iopub.status.busy": "2026-10-26T15:48:32.964278Z", + "iopub.status.idle": "2026-10-26T15:48:32.993166Z", + "shell.execute_reply": "2026-10-26T15:48:32.992566Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
week_endingvery_poorpoorfairgoodexcellentgood_excellent
02023-05-280.02.021.065.012.077.0
12023-06-040.03.025.060.012.072.0
22023-06-111.03.026.058.012.070.0
32023-06-181.07.033.050.09.059.0
42023-06-252.010.032.048.08.056.0
\n", + "
" + ], + "text/plain": [ + " week_ending very_poor poor fair good excellent good_excellent\n", + "0 2023-05-28 0.0 2.0 21.0 65.0 12.0 77.0\n", + "1 2023-06-04 0.0 3.0 25.0 60.0 12.0 72.0\n", + "2 2023-06-11 1.0 3.0 26.0 58.0 12.0 70.0\n", + "3 2023-06-18 1.0 7.0 33.0 50.0 9.0 59.0\n", + "4 2023-06-25 2.0 10.0 32.0 48.0 8.0 56.0" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass.condition(crop=\"CORN\", state=\"IA\", years=2023,\n", + " columns=[\"week_ending\", \"very_poor\", \"poor\", \"fair\", \"good\", \"excellent\", \"good_excellent\"]).head()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "cell-43", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:32.994762Z", + "iopub.status.busy": "2026-10-26T15:48:32.994613Z", + "iopub.status.idle": "2026-10-26T15:48:33.062576Z", + "shell.execute_reply": "2026-10-26T15:48:33.062038Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
week_endingratingpct
02023-05-28EXCELLENT12.0
12023-05-28FAIR21.0
22023-05-28GOOD65.0
32023-05-28POOR2.0
42023-05-28VERY POOR0.0
\n", + "
" + ], + "text/plain": [ + " week_ending rating pct\n", + "0 2023-05-28 EXCELLENT 12.0\n", + "1 2023-05-28 FAIR 21.0\n", + "2 2023-05-28 GOOD 65.0\n", + "3 2023-05-28 POOR 2.0\n", + "4 2023-05-28 VERY POOR 0.0" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "nass.condition(long=True, crop=\"CORN\", state=\"IA\", years=2023, columns=[\"week_ending\", \"rating\", \"pct\"]).head()" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "cell-44", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:33.064046Z", + "iopub.status.busy": "2026-10-26T15:48:33.063895Z", + "iopub.status.idle": "2026-10-26T15:48:33.137350Z", + "shell.execute_reply": "2026-10-26T15:48:33.136811Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
week_endingratingpct
02023-05-28GOOD58.0
12023-06-04GOOD53.0
22023-06-11GOOD51.0
32023-06-18GOOD47.0
42023-06-25GOOD42.0
\n", + "
" + ], + "text/plain": [ + " week_ending rating pct\n", + "0 2023-05-28 GOOD 58.0\n", + "1 2023-06-04 GOOD 53.0\n", + "2 2023-06-11 GOOD 51.0\n", + "3 2023-06-18 GOOD 47.0\n", + "4 2023-06-25 GOOD 42.0" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Generic query() on any table.\n", + "nass.query(\"condition_long\", crop=\"CORN\", level=\"national\", years=2023, where={\"rating\": \"GOOD\"},\n", + " columns=[\"week_ending\", \"rating\", \"pct\"]).head()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-45", + "metadata": {}, + "source": [ + "## 7. Output formats" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "cell-46", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:33.138978Z", + "iopub.status.busy": "2026-10-26T15:48:33.138829Z", + "iopub.status.idle": "2026-10-26T15:48:34.189720Z", + "shell.execute_reply": "2026-10-26T15:48:34.189040Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pandas pandas.core.frame.DataFrame rows=4\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "polars polars.dataframe.frame.DataFrame rows=4\n", + "arrow pyarrow.lib.Table rows=4\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "records builtins.list rows=4\n" + ] + }, + { + "data": { + "text/plain": [ + "[{'year': 2020, 'value': 148.4}, {'year': 2021, 'value': 201.2}]" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "q = dict(crop=\"CORN, GRAIN\", state=\"IA\", county=\"Story\", years=(2020, 2023), columns=[\"year\", \"value\"])\n", + "for fmt in [\"pandas\", \"polars\", \"arrow\", \"records\"]:\n", + " try:\n", + " r = nass.yield_data(format=fmt, **q)\n", + " print(f\"{fmt:8s} {type(r).__module__}.{type(r).__name__} rows={len(r)}\")\n", + " except ImportError as e:\n", + " print(f\"{fmt:8s} skipped: {e}\")\n", + "nass.yield_data(format=\"records\", **q)[:2]" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "cell-47", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:34.191178Z", + "iopub.status.busy": "2026-10-26T15:48:34.191024Z", + "iopub.status.idle": "2026-10-26T15:48:34.532748Z", + "shell.execute_reply": "2026-10-26T15:48:34.532212Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "/tmp/nass_check_qps_bfc6/story_corn.csv 59 bytes\n", + "/tmp/nass_check_qps_bfc6/story_corn.parquet 786 bytes\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
yearvalue
02020148.4
12021201.2
22022207.1
32023211.4
\n", + "
" + ], + "text/plain": [ + " year value\n", + "0 2020 148.4\n", + "1 2021 201.2\n", + "2 2022 207.1\n", + "3 2023 211.4" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for fmt in [\"csv\", \"parquet\"]:\n", + " path = nass.yield_data(format=fmt, path=os.path.join(OUT, f\"story_corn.{fmt}\"), **q)\n", + " print(path, os.path.getsize(path), \"bytes\")\n", + "pd.read_csv(os.path.join(OUT, \"story_corn.csv\"))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-48", + "metadata": {}, + "source": [ + "## 8. Timing on the full tables" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "cell-49", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-26T15:48:34.534693Z", + "iopub.status.busy": "2026-10-26T15:48:34.534539Z", + "iopub.status.idle": "2026-10-26T15:48:37.520802Z", + "shell.execute_reply": "2026-10-26T15:48:37.520207Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "CPU times: user 1.06 s, sys: 551 ms, total: 1.61 s\n", + "Wall time: 830 ms\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "CPU times: user 2.45 s, sys: 243 ms, total: 2.69 s\n", + "Wall time: 1.38 s\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "CPU times: user 1.05 s, sys: 464 ms, total: 1.52 s\n", + "Wall time: 768 ms\n" + ] + } + ], + "source": [ + "%time _ = nass.yield_data(crop=\"CORN, GRAIN\", county=\"Story\", state=\"IA\", years=(2000, 2024))\n", + "%time _ = nass.area_production(crop=\"CORN, GRAIN\", level=\"county\", years=2022)\n", + "%time _ = nass.yield_data(level=\"county\", years=2022)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.20" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/agml/ag_stats/catalog.py b/agml/ag_stats/catalog.py new file mode 100644 index 00000000..538c4f2f --- /dev/null +++ b/agml/ag_stats/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/loader.py b/agml/ag_stats/loader.py new file mode 100644 index 00000000..bbfdfe04 --- /dev/null +++ b/agml/ag_stats/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.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.yield_data(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 yield_data(self, **kwargs): + """Queries the `yield` table. Takes the same arguments as `query`.""" + return self.query("yield", **kwargs) + + def county_yield(self, **kwargs): + """Queries the `county_yield` table. Takes the same arguments as `query`.""" + return self.query("county_yield", **kwargs) + + def 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 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 forecast(self, **kwargs): + """Queries the `forecast` table. Takes the same arguments as `query`.""" + return self.query("forecast", **kwargs) + + def 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 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 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/tests/ag_stats/conftest.py b/tests/ag_stats/conftest.py new file mode 100644 index 00000000..0e4f76dc --- /dev/null +++ b/tests/ag_stats/conftest.py @@ -0,0 +1,135 @@ +import pytest +from nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS + +pa = pytest.importorskip("pyarrow") +pq = pytest.importorskip("pyarrow.parquet") + + +# ── 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): + 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`.""" + 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_fixtures.py b/tests/ag_stats/nass_fixtures.py new file mode 100644 index 00000000..d027865e --- /dev/null +++ b/tests/ag_stats/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/test_catalog.py b/tests/ag_stats/test_catalog.py new file mode 100644 index 00000000..37db0240 --- /dev/null +++ b/tests/ag_stats/test_catalog.py @@ -0,0 +1,123 @@ +import pytest + +pytest.importorskip("pyarrow") + +from agml.ag_stats 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/test_loader.py b/tests/ag_stats/test_loader.py new file mode 100644 index 00000000..f1b4cc76 --- /dev/null +++ b/tests/ag_stats/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 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.yield_data(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.yield_data(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.yield_data(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.yield_data(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.yield_data(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.yield_data(level="county", state="IA", crop=CORN_GRAIN, years=2020) + assert kept["county_fips"].notna().all() + every = nass.yield_data(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.yield_data(district="central", state="IA", level="district", crop=CORN_GRAIN) + assert set(df["asd_code"]) == {"50"} + + def test_where_and_wrapper(self, nass): + df = nass.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.progress(stage=stage, state="IA", years=2021) + assert set(df["stage"]) == {"PLANTED"} + + def test_forecast_months_in_calendar_order(self, nass): + df = nass.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.yield_data(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.condition(state="IA", years=2019) + assert set(df["crop_year"]) == {2019} + + def test_county_yield_filters_by_state_alpha(self, nass): + df = nass.county_yield(state="Iowa", crop=CORN_SILAGE) + assert set(df["state_alpha"]) == {"IA"} + + def test_columns(self, nass): + df = nass.yield_data(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.progress(county="19169") + + def test_level_on_county_only_table(self, nass): + with pytest.raises(ValueError, match="state-level"): + nass.county_yield(level="state") + + def test_unknown_where_column(self, nass): + with pytest.raises(ValueError, match="no column 'colour'"): + nass.yield_data(where={"colour": "red"}) + + def test_unknown_columns(self, nass): + with pytest.raises(ValueError, match="no column"): + nass.yield_data(columns=["colour"]) + + def test_unknown_format(self, nass): + with pytest.raises(ValueError, match="Unknown format"): + nass.yield_data(format="xlsx") + + def test_file_format_needs_path(self, nass): + with pytest.raises(ValueError, match="needs an output"): + nass.yield_data(format="csv") + + +# ── Boundaries ──────────────────────────────────────────────────────────────── + +class TestBoundaries: + def test_county_with_geometry(self, nass): + df = nass.boundaries("county") + assert list(df["GEOID"]) == ["19169"] and "geometry" in df.columns + + def test_state_without_geometry(self, nass): + df = nass.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.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.yield_data(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().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.yield_data(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.yield_data(**self.QUERY), pd.DataFrame) + + def test_arrow(self, nass): + assert isinstance(nass.yield_data(format="arrow", **self.QUERY), pa.Table) + + def test_records(self, nass): + records = nass.yield_data(format="records", **self.QUERY) + assert records[0]["county_fips"] == "19169" + + def test_polars(self, nass): + pl = pytest.importorskip("polars") + assert isinstance(nass.yield_data(format="polars", **self.QUERY), pl.DataFrame) + + @pytest.mark.parametrize("fmt", ["csv", "parquet"]) + def test_files(self, nass, tmp_path, fmt): + path = nass.yield_data(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.yield_data(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() From f5e39d9ea3c062a2744b1f5b67df491c5c80a5d4 Mon Sep 17 00:00:00 2001 From: hkaman7 Date: Mon, 9 Nov 2026 13:45:46 -0800 Subject: [PATCH 2/4] Add California Crop Yield Benchmark loader and restructure ag_stats Move the NASS loader to agml.ag_stats.nass and add agml.ag_stats.calicropyield. Each data source is a subpackage that is imported on first use. Rename the loader methods to the AgML load_* and download_* convention. Add tests for both sources and a calicropyield extra. --- README.md | 80 + agml/__init__.py | 3 + agml/ag_stats/__init__.py | 36 +- agml/ag_stats/ag_stats_check.ipynb | 3261 ----------------- agml/ag_stats/calicropyield/__init__.py | 37 + agml/ag_stats/calicropyield/catalog.py | 206 ++ agml/ag_stats/calicropyield/loader.py | 463 +++ agml/ag_stats/nass/__init__.py | 32 + agml/ag_stats/{ => nass}/catalog.py | 0 agml/ag_stats/{ => nass}/loader.py | 20 +- pyproject.toml | 16 + tests/ag_stats/__init__.py | 0 tests/ag_stats/calicropyield/__init__.py | 0 .../calicropyield/calicropyield_fixtures.py | 19 + tests/ag_stats/calicropyield/conftest.py | 110 + .../test_calicropyield_catalog.py | 66 + .../test_calicropyield_loader.py | 274 ++ tests/ag_stats/nass/__init__.py | 0 tests/ag_stats/{ => nass}/conftest.py | 2 +- tests/ag_stats/{ => nass}/nass_fixtures.py | 0 tests/ag_stats/{ => nass}/test_catalog.py | 4 +- tests/ag_stats/{ => nass}/test_loader.py | 70 +- 22 files changed, 1378 insertions(+), 3321 deletions(-) delete mode 100644 agml/ag_stats/ag_stats_check.ipynb create mode 100644 agml/ag_stats/calicropyield/__init__.py create mode 100644 agml/ag_stats/calicropyield/catalog.py create mode 100644 agml/ag_stats/calicropyield/loader.py create mode 100644 agml/ag_stats/nass/__init__.py rename agml/ag_stats/{ => nass}/catalog.py (100%) rename agml/ag_stats/{ => nass}/loader.py (96%) create mode 100644 tests/ag_stats/__init__.py create mode 100644 tests/ag_stats/calicropyield/__init__.py create mode 100644 tests/ag_stats/calicropyield/calicropyield_fixtures.py create mode 100644 tests/ag_stats/calicropyield/conftest.py create mode 100644 tests/ag_stats/calicropyield/test_calicropyield_catalog.py create mode 100644 tests/ag_stats/calicropyield/test_calicropyield_loader.py create mode 100644 tests/ag_stats/nass/__init__.py rename tests/ag_stats/{ => nass}/conftest.py (98%) rename tests/ag_stats/{ => nass}/nass_fixtures.py (100%) rename tests/ag_stats/{ => nass}/test_catalog.py (97%) rename tests/ag_stats/{ => nass}/test_loader.py (79%) 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 index cd1140b8..11a177e5 100644 --- a/agml/ag_stats/__init__.py +++ b/agml/ag_stats/__init__.py @@ -13,18 +13,30 @@ # 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. +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`. """ -try: - import pandas # noqa: F401 - import pyarrow # noqa: F401 -except ImportError: - raise ImportError( - "The `agml.ag_stats` module needs pandas and pyarrow. Install them with `pip install agml[ag_stats]`." - ) +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}") + -from .catalog import NASSCatalog -from .loader import DEFAULT_REPO_ID, FORMATS, TABLES, NASSDataLoader +def __dir__(): + return sorted(list(globals()) + list(SOURCES)) diff --git a/agml/ag_stats/ag_stats_check.ipynb b/agml/ag_stats/ag_stats_check.ipynb deleted file mode 100644 index f6b59e26..00000000 --- a/agml/ag_stats/ag_stats_check.ipynb +++ /dev/null @@ -1,3261 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "cell-00", - "metadata": {}, - "source": [ - "# agml.ag_stats check (temporary)\n", - "\n", - "Exercises every public function of `NASSCatalog` and `NASSDataLoader` on the real dataset.\n", - "Temporary notebook: do not commit it." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "cell-01", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:23.714640Z", - "iopub.status.busy": "2026-10-26T15:48:23.714505Z", - "iopub.status.idle": "2026-10-26T15:48:25.832533Z", - "shell.execute_reply": "2026-10-26T15:48:25.832037Z" - } - }, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/group/jmearlesgrp/hkaman/envs/agml-nass/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", - " from .autonotebook import tqdm as notebook_tqdm\n" - ] - } - ], - "source": [ - "import os, pickle, tempfile\n", - "import pandas as pd\n", - "pd.set_option(\"display.width\", 160)\n", - "pd.set_option(\"display.max_columns\", 20)\n", - "\n", - "from agml.ag_stats import NASSDataLoader, NASSCatalog, TABLES, FORMATS\n", - "\n", - "ROOT = \"/group/jmearlesgrp/hkaman/dataset/nass-usda-full-data\"\n", - "OUT = tempfile.mkdtemp(prefix=\"nass_check_\")" - ] - }, - { - "cell_type": "markdown", - "id": "cell-02", - "metadata": {}, - "source": [ - "## 1. Loader setup" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "cell-03", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.834619Z", - "iopub.status.busy": "2026-10-26T15:48:25.834356Z", - "iopub.status.idle": "2026-10-26T15:48:25.852363Z", - "shell.execute_reply": "2026-10-26T15:48:25.851689Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(,\n", - " '/group/jmearlesgrp/hkaman/dataset/nass-usda-full-data/parquet')" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass = NASSDataLoader(ROOT)\n", - "nass, nass.root" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "cell-04", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.853845Z", - "iopub.status.busy": "2026-10-26T15:48:25.853677Z", - "iopub.status.idle": "2026-10-26T15:48:25.866606Z", - "shell.execute_reply": "2026-10-26T15:48:25.866098Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Same loader from the environment variable.\n", - "os.environ[\"AGML_NASS_PATH\"] = ROOT\n", - "NASSDataLoader().root == nass.root" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "cell-05", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.868535Z", - "iopub.status.busy": "2026-10-26T15:48:25.868379Z", - "iopub.status.idle": "2026-10-26T15:48:25.872583Z", - "shell.execute_reply": "2026-10-26T15:48:25.872128Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "yield Yield at national, state, district, and county...\n", - "county_yield County yield for the main crop variants, on 20...\n", - "area_production Area planted, area harvested, and production (...\n", - "census Census of Agriculture crop records, every five...\n", - "forecast In-season yield forecasts by `forecast_month` ...\n", - "progress Weekly crop progress by `stage`, as percent (s...\n", - "condition Weekly crop condition, one column per rating (...\n", - "condition_long Weekly crop condition, one row per rating (sta...\n", - "Name: description, dtype: object" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Every queryable table and its description.\n", - "pd.Series(NASSDataLoader.tables(), name=\"description\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "cell-06", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.874051Z", - "iopub.status.busy": "2026-10-26T15:48:25.873904Z", - "iopub.status.idle": "2026-10-26T15:48:25.877597Z", - "shell.execute_reply": "2026-10-26T15:48:25.876718Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "('pandas', 'polars', 'arrow', 'records', 'csv', 'parquet')" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "FORMATS" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "cell-07", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.879189Z", - "iopub.status.busy": "2026-10-26T15:48:25.879049Z", - "iopub.status.idle": "2026-10-26T15:48:25.883994Z", - "shell.execute_reply": "2026-10-26T15:48:25.883451Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "crop_id: string\n", - "commodity: string\n", - "class: string\n", - "practice: string\n", - "utilization: string\n", - "unit: string\n", - "agg_level: string\n", - "state_fips: string\n", - "state_alpha: string\n", - "asd_code: string\n", - "county_fips: string\n", - "county_fips_nass: string\n", - "county_name: string\n", - "is_other_counties: bool\n", - "year: int32\n", - "value: double\n", - "value_flag: string\n", - "cv_pct: double\n", - "value_t_ha: double\n", - "per_planted_acre: bool\n", - "load_time: timestamp[us]" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Column names and types of one table.\n", - "nass.schema(\"yield\")" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "cell-08", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:25.885686Z", - "iopub.status.busy": "2026-10-26T15:48:25.885539Z", - "iopub.status.idle": "2026-10-26T15:48:26.703993Z", - "shell.execute_reply": "2026-10-26T15:48:26.703395Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, 13)" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Pickle round trip (AgMLSerializable): only `root` is stored, the catalog is rebuilt.\n", - "clone = pickle.loads(pickle.dumps(nass))\n", - "clone.root == nass.root, len(clone.yield_data(state=\"IA\", years=2020, level=\"state\"))" - ] - }, - { - "cell_type": "markdown", - "id": "cell-09", - "metadata": {}, - "source": [ - "## 2. Catalog listings" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "cell-10", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.705974Z", - "iopub.status.busy": "2026-10-26T15:48:26.705824Z", - "iopub.status.idle": "2026-10-26T15:48:26.710397Z", - "shell.execute_reply": "2026-10-26T15:48:26.709930Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(159,\n", - " ['ALMONDS',\n", - " 'AMARANTH',\n", - " 'APPLES',\n", - " 'APRICOTS',\n", - " 'ARTICHOKES',\n", - " 'ASPARAGUS',\n", - " 'AVOCADOS',\n", - " 'BANANAS',\n", - " 'BARLEY',\n", - " 'BEANS',\n", - " 'BEETS',\n", - " 'BERRIES, OTHER',\n", - " 'BERRY TOTALS',\n", - " 'BLACKBERRIES',\n", - " 'BLUEBERRIES'])" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat = nass.catalog\n", - "len(cat.commodities()), cat.commodities()[:15]" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "cell-11", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.712195Z", - "iopub.status.busy": "2026-10-26T15:48:26.712052Z", - "iopub.status.idle": "2026-10-26T15:48:26.723166Z", - "shell.execute_reply": "2026-10-26T15:48:26.722519Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
crop_idcommodityclasspracticeutilizationcrop_label
0407b68a8ae63CORNALL CLASSESALL PRODUCTION PRACTICESALL UTILIZATION PRACTICESCORN
1c3d805b0e626CORNALL CLASSESBIOTECHALL UTILIZATION PRACTICESCORN (BIOTECH)
20d60d988f714CORNALL CLASSESBIOTECH, BTALL UTILIZATION PRACTICESCORN (BIOTECH, BT)
3bc9ebfaaa3a8CORNALL CLASSESBIOTECH, HERBICIDE RESISTANTALL UTILIZATION PRACTICESCORN (BIOTECH, HERBICIDE RESISTANT)
481f9e75f10e8CORNALL CLASSESBIOTECH, STACKED GENEALL UTILIZATION PRACTICESCORN (BIOTECH, STACKED GENE)
5f3d600275f73CORNALL CLASSESIRRIGATEDALL UTILIZATION PRACTICESCORN (IRRIGATED)
66b2217b8ecc7CORNALL CLASSESNON-IRRIGATEDALL UTILIZATION PRACTICESCORN (NON-IRRIGATED)
79d9f23c859c7CORNALL CLASSESALL PRODUCTION PRACTICESFORAGECORN, FORAGE
8f56a2f05c3bdCORNALL CLASSESALL PRODUCTION PRACTICESGRAINCORN, GRAIN
9789e870f29d8CORNALL CLASSESIRRIGATEDGRAINCORN, GRAIN (IRRIGATED)
104ff8c50986b1CORNALL CLASSESIRRIGATED, ENTIRE CROPGRAINCORN, GRAIN (IRRIGATED, ENTIRE CROP)
11dbf09d4a17e2CORNALL CLASSESIRRIGATED, NONE OF CROPGRAINCORN, GRAIN (IRRIGATED, NONE OF CROP)
124e6e7262bcedCORNALL CLASSESIRRIGATED, PART OF CROPGRAINCORN, GRAIN (IRRIGATED, PART OF CROP)
1389c529b35c0dCORNALL CLASSESIRRIGATED, PART OF CROP, IRRIGATED PORTIONGRAINCORN, GRAIN (IRRIGATED, PART OF CROP, IRRIGATE...
149ed097409ab9CORNALL CLASSESIRRIGATED, PART OF CROP, NON-IRRIGATED PORTIONGRAINCORN, GRAIN (IRRIGATED, PART OF CROP, NON-IRRI...
153a740671eb8eCORNALL CLASSESNON-IRRIGATEDGRAINCORN, GRAIN (NON-IRRIGATED)
1645e465f318caCORNALL CLASSESALL PRODUCTION PRACTICESSILAGECORN, SILAGE
177ef20a007fc2CORNALL CLASSESIRRIGATEDSILAGECORN, SILAGE (IRRIGATED)
18eae7c78b71e8CORNALL CLASSESIRRIGATED, ENTIRE CROPSILAGECORN, SILAGE (IRRIGATED, ENTIRE CROP)
198c53b4741503CORNALL CLASSESIRRIGATED, NONE OF CROPSILAGECORN, SILAGE (IRRIGATED, NONE OF CROP)
20fd177da6fa82CORNALL CLASSESIRRIGATED, PART OF CROPSILAGECORN, SILAGE (IRRIGATED, PART OF CROP)
21b1ed57ec3408CORNALL CLASSESIRRIGATED, PART OF CROP, IRRIGATED PORTIONSILAGECORN, SILAGE (IRRIGATED, PART OF CROP, IRRIGAT...
22fc6c0f42234eCORNALL CLASSESIRRIGATED, PART OF CROP, NON-IRRIGATED PORTIONSILAGECORN, SILAGE (IRRIGATED, PART OF CROP, NON-IRR...
23be284ce79a22CORNALL CLASSESNON-IRRIGATEDSILAGECORN, SILAGE (NON-IRRIGATED)
2400d55d63aff2CORNTRADITIONAL OR INDIANALL PRODUCTION PRACTICESALL UTILIZATION PRACTICESCORN, TRADITIONAL OR INDIAN
25d9d376027b71CORNTRADITIONAL OR INDIANIRRIGATEDALL UTILIZATION PRACTICESCORN, TRADITIONAL OR INDIAN (IRRIGATED)
\n", - "
" - ], - "text/plain": [ - " crop_id commodity class practice utilization \\\n", - "0 407b68a8ae63 CORN ALL CLASSES ALL PRODUCTION PRACTICES ALL UTILIZATION PRACTICES \n", - "1 c3d805b0e626 CORN ALL CLASSES BIOTECH ALL UTILIZATION PRACTICES \n", - "2 0d60d988f714 CORN ALL CLASSES BIOTECH, BT ALL UTILIZATION PRACTICES \n", - "3 bc9ebfaaa3a8 CORN ALL CLASSES BIOTECH, HERBICIDE RESISTANT ALL UTILIZATION PRACTICES \n", - "4 81f9e75f10e8 CORN ALL CLASSES BIOTECH, STACKED GENE ALL UTILIZATION PRACTICES \n", - "5 f3d600275f73 CORN ALL CLASSES IRRIGATED ALL UTILIZATION PRACTICES \n", - "6 6b2217b8ecc7 CORN ALL CLASSES NON-IRRIGATED ALL UTILIZATION PRACTICES \n", - "7 9d9f23c859c7 CORN ALL CLASSES ALL PRODUCTION PRACTICES FORAGE \n", - "8 f56a2f05c3bd CORN ALL CLASSES ALL PRODUCTION PRACTICES GRAIN \n", - "9 789e870f29d8 CORN ALL CLASSES IRRIGATED GRAIN \n", - "10 4ff8c50986b1 CORN ALL CLASSES IRRIGATED, ENTIRE CROP GRAIN \n", - "11 dbf09d4a17e2 CORN ALL CLASSES IRRIGATED, NONE OF CROP GRAIN \n", - "12 4e6e7262bced CORN ALL CLASSES IRRIGATED, PART OF CROP GRAIN \n", - "13 89c529b35c0d CORN ALL CLASSES IRRIGATED, PART OF CROP, IRRIGATED PORTION GRAIN \n", - "14 9ed097409ab9 CORN ALL CLASSES IRRIGATED, PART OF CROP, NON-IRRIGATED PORTION GRAIN \n", - "15 3a740671eb8e CORN ALL CLASSES NON-IRRIGATED GRAIN \n", - "16 45e465f318ca CORN ALL CLASSES ALL PRODUCTION PRACTICES SILAGE \n", - "17 7ef20a007fc2 CORN ALL CLASSES IRRIGATED SILAGE \n", - "18 eae7c78b71e8 CORN ALL CLASSES IRRIGATED, ENTIRE CROP SILAGE \n", - "19 8c53b4741503 CORN ALL CLASSES IRRIGATED, NONE OF CROP SILAGE \n", - "20 fd177da6fa82 CORN ALL CLASSES IRRIGATED, PART OF CROP SILAGE \n", - "21 b1ed57ec3408 CORN ALL CLASSES IRRIGATED, PART OF CROP, IRRIGATED PORTION SILAGE \n", - "22 fc6c0f42234e CORN ALL CLASSES IRRIGATED, PART OF CROP, NON-IRRIGATED PORTION SILAGE \n", - "23 be284ce79a22 CORN ALL CLASSES NON-IRRIGATED SILAGE \n", - "24 00d55d63aff2 CORN TRADITIONAL OR INDIAN ALL PRODUCTION PRACTICES ALL UTILIZATION PRACTICES \n", - "25 d9d376027b71 CORN TRADITIONAL OR INDIAN IRRIGATED ALL UTILIZATION PRACTICES \n", - "\n", - " crop_label \n", - "0 CORN \n", - "1 CORN (BIOTECH) \n", - "2 CORN (BIOTECH, BT) \n", - "3 CORN (BIOTECH, HERBICIDE RESISTANT) \n", - "4 CORN (BIOTECH, STACKED GENE) \n", - "5 CORN (IRRIGATED) \n", - "6 CORN (NON-IRRIGATED) \n", - "7 CORN, FORAGE \n", - "8 CORN, GRAIN \n", - "9 CORN, GRAIN (IRRIGATED) \n", - "10 CORN, GRAIN (IRRIGATED, ENTIRE CROP) \n", - "11 CORN, GRAIN (IRRIGATED, NONE OF CROP) \n", - "12 CORN, GRAIN (IRRIGATED, PART OF CROP) \n", - "13 CORN, GRAIN (IRRIGATED, PART OF CROP, IRRIGATE... \n", - "14 CORN, GRAIN (IRRIGATED, PART OF CROP, NON-IRRI... \n", - "15 CORN, GRAIN (NON-IRRIGATED) \n", - "16 CORN, SILAGE \n", - "17 CORN, SILAGE (IRRIGATED) \n", - "18 CORN, SILAGE (IRRIGATED, ENTIRE CROP) \n", - "19 CORN, SILAGE (IRRIGATED, NONE OF CROP) \n", - "20 CORN, SILAGE (IRRIGATED, PART OF CROP) \n", - "21 CORN, SILAGE (IRRIGATED, PART OF CROP, IRRIGAT... \n", - "22 CORN, SILAGE (IRRIGATED, PART OF CROP, NON-IRR... \n", - "23 CORN, SILAGE (NON-IRRIGATED) \n", - "24 CORN, TRADITIONAL OR INDIAN \n", - "25 CORN, TRADITIONAL OR INDIAN (IRRIGATED) " - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat.crops(\"corn\")" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "cell-12", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.724624Z", - "iopub.status.busy": "2026-10-26T15:48:26.724471Z", - "iopub.status.idle": "2026-10-26T15:48:26.731618Z", - "shell.execute_reply": "2026-10-26T15:48:26.731109Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
state_fipsstate_alphastate_namearea_km2centroid_loncentroid_lat
001ALAlabama133892.90-86.8300132.77881
102AKAlaska1520598.73-152.4419763.78199
204AZArizona295232.40-111.6600434.27701
305ARArkansas137782.04-92.4421834.89482
406CACalifornia409819.66-119.4724837.18624
\n", - "
" - ], - "text/plain": [ - " state_fips state_alpha state_name area_km2 centroid_lon centroid_lat\n", - "0 01 AL Alabama 133892.90 -86.83001 32.77881\n", - "1 02 AK Alaska 1520598.73 -152.44197 63.78199\n", - "2 04 AZ Arizona 295232.40 -111.66004 34.27701\n", - "3 05 AR Arkansas 137782.04 -92.44218 34.89482\n", - "4 06 CA California 409819.66 -119.47248 37.18624" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat.states().head()" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "cell-13", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.733370Z", - "iopub.status.busy": "2026-10-26T15:48:26.733229Z", - "iopub.status.idle": "2026-10-26T15:48:26.742283Z", - "shell.execute_reply": "2026-10-26T15:48:26.741755Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
county_fipsstate_fipscounty_codecounty_namestate_alphaarea_km2centroid_loncentroid_lat
01900119001AdairIA1476.97-94.4709441.33066
11900319003AdamsIA1102.19-94.6991941.02896
21900519005AllamakeeIA1706.28-91.3780243.28413
31900719007AppanooseIA1337.00-92.8686440.74311
41900919009AudubonIA1148.29-94.9057841.68446
\n", - "
" - ], - "text/plain": [ - " county_fips state_fips county_code county_name state_alpha area_km2 centroid_lon centroid_lat\n", - "0 19001 19 001 Adair IA 1476.97 -94.47094 41.33066\n", - "1 19003 19 003 Adams IA 1102.19 -94.69919 41.02896\n", - "2 19005 19 005 Allamakee IA 1706.28 -91.37802 43.28413\n", - "3 19007 19 007 Appanoose IA 1337.00 -92.86864 40.74311\n", - "4 19009 19 009 Audubon IA 1148.29 -94.90578 41.68446" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat.counties(state=\"IA\").head()" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "cell-14", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.743972Z", - "iopub.status.busy": "2026-10-26T15:48:26.743829Z", - "iopub.status.idle": "2026-10-26T15:48:26.751355Z", - "shell.execute_reply": "2026-10-26T15:48:26.750885Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
state_fipsstate_alphaasd_codeasd_descasd_id
019IA10NORTHWEST1910
119IA20NORTH CENTRAL1920
219IA30NORTHEAST1930
319IA40WEST CENTRAL1940
419IA50CENTRAL1950
519IA60EAST CENTRAL1960
619IA70SOUTHWEST1970
719IA80SOUTH CENTRAL1980
819IA90SOUTHEAST1990
919IA98OTHER DISTRICTS, ALL COUNTIES1998
1019IA99None1999
\n", - "
" - ], - "text/plain": [ - " state_fips state_alpha asd_code asd_desc asd_id\n", - "0 19 IA 10 NORTHWEST 1910\n", - "1 19 IA 20 NORTH CENTRAL 1920\n", - "2 19 IA 30 NORTHEAST 1930\n", - "3 19 IA 40 WEST CENTRAL 1940\n", - "4 19 IA 50 CENTRAL 1950\n", - "5 19 IA 60 EAST CENTRAL 1960\n", - "6 19 IA 70 SOUTHWEST 1970\n", - "7 19 IA 80 SOUTH CENTRAL 1980\n", - "8 19 IA 90 SOUTHEAST 1990\n", - "9 19 IA 98 OTHER DISTRICTS, ALL COUNTIES 1998\n", - "10 19 IA 99 None 1999" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat.districts(state=\"IA\")" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "cell-15", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.753075Z", - "iopub.status.busy": "2026-10-26T15:48:26.752933Z", - "iopub.status.idle": "2026-10-26T15:48:26.766453Z", - "shell.execute_reply": "2026-10-26T15:48:26.765950Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['ALMONDS', 'AMARANTH', 'APPLES', 'APRICOTS', 'ARTICHOKES']" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# The catalog can also be used on its own.\n", - "NASSCatalog(nass.root).commodities()[:5]" - ] - }, - { - "cell_type": "markdown", - "id": "cell-16", - "metadata": {}, - "source": [ - "## 3. Catalog name resolution" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "cell-17", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.768094Z", - "iopub.status.busy": "2026-10-26T15:48:26.767945Z", - "iopub.status.idle": "2026-10-26T15:48:26.773779Z", - "shell.execute_reply": "2026-10-26T15:48:26.773321Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "([['19'], ['19'], ['19'], ['19'], ['19']], ['06', '17'])" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "[cat.resolve_states(v) for v in [\"IA\", \"ia\", \"Iowa\", \"19\", 19]], cat.resolve_states([\"CA\", \"Illinois\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "cell-18", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.775406Z", - "iopub.status.busy": "2026-10-26T15:48:26.775264Z", - "iopub.status.idle": "2026-10-26T15:48:26.778452Z", - "shell.execute_reply": "2026-10-26T15:48:26.777903Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['IA', 'CA']" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cat.state_alphas([\"19\", \"06\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "cell-19", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.780069Z", - "iopub.status.busy": "2026-10-26T15:48:26.779929Z", - "iopub.status.idle": "2026-10-26T15:48:26.788902Z", - "shell.execute_reply": "2026-10-26T15:48:26.788368Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(['19169'], ['19169'], ['19169'], ['06113', '06019'])" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "(cat.resolve_counties(\"Story\", state=\"IA\"),\n", - " cat.resolve_counties(\"story county\", state=\"Iowa\"),\n", - " cat.resolve_counties(\"19169\"),\n", - " cat.resolve_counties([\"Yolo\", \"Fresno\"], state=\"CA\"))" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "cell-20", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.790511Z", - "iopub.status.busy": "2026-10-26T15:48:26.790370Z", - "iopub.status.idle": "2026-10-26T15:48:26.793643Z", - "shell.execute_reply": "2026-10-26T15:48:26.793054Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['46102']" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Old NASS code for Shannon County, SD is mapped to its 2020 code (Oglala Lakota).\n", - "cat.resolve_counties(\"46113\")" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "cell-21", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.795082Z", - "iopub.status.busy": "2026-10-26T15:48:26.794945Z", - "iopub.status.idle": "2026-10-26T15:48:26.802503Z", - "shell.execute_reply": "2026-10-26T15:48:26.802016Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'state_fips': '19', 'state_alpha': 'IA', 'asd_code': '10', 'asd_desc': 'NORTHWEST', 'asd_id': '1910'}\n" - ] - }, - { - "data": { - "text/plain": [ - "(['1910'], ['1910'], ['1910'])" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "first = cat.districts(state=\"IA\").iloc[0]\n", - "print(first.to_dict())\n", - "(cat.resolve_districts(first[\"asd_id\"]),\n", - " cat.resolve_districts(first[\"asd_code\"], state=\"IA\"),\n", - " cat.resolve_districts(first[\"asd_desc\"].lower(), state=\"IA\"))" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "cell-22", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.804152Z", - "iopub.status.busy": "2026-10-26T15:48:26.804014Z", - "iopub.status.idle": "2026-10-26T15:48:26.811964Z", - "shell.execute_reply": "2026-10-26T15:48:26.811068Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(26, ['f56a2f05c3bd'], ['f56a2f05c3bd'], ['8e3f7fc43681', '6256b3fe85b5'])" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "corn_all = cat.resolve_crops(\"corn\")\n", - "corn_grain = cat.resolve_crops(\"corn\", utilization=\"grain\", practice=\"all production practices\")\n", - "(len(corn_all), corn_grain,\n", - " cat.resolve_crops(\"CORN, GRAIN\"),\n", - " cat.resolve_crops([\"soybeans\", \"wheat\"], crop_class=\"all classes\", practice=\"all production practices\",\n", - " utilization=\"all utilization practices\"))" - ] - }, - { - "cell_type": "markdown", - "id": "cell-23", - "metadata": {}, - "source": [ - "## 4. Error messages" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "cell-24", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.813378Z", - "iopub.status.busy": "2026-10-26T15:48:26.813233Z", - "iopub.status.idle": "2026-10-26T15:48:26.829869Z", - "shell.execute_reply": "2026-10-26T15:48:26.829299Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "ValueError: Unknown state 'Iowaa'. Did you mean one of: IOWA?\n", - "ValueError: County name 'Washington' exists in several states (AL, AR, CO, FL, GA, IA, ID, IL, IN, KS, KY, LA, MD, ME, MN, MO, MS, NC, NE, NY, OH, OK, OR, PA, RI, TN, TX, UT, VA, VT, WI). Pass `state` as well.\n", - "ValueError: Unknown county FIPS code '99999'.\n", - "ValueError: District code '10' is only unique within a state. Pass `state` as well.\n", - "ValueError: Unknown crop 'cron'. Did you mean one of: CORN, COTTON?\n", - "ValueError: Unknown utilization 'FIBER'.\n", - "ValueError: Unknown table 'weather'. Choose one of ['yield', 'county_yield', 'area_production', 'census', 'forecast', 'progress', 'condition', 'condition_long'].\n", - "ValueError: Table 'progress' has no county-level data, so `county` cannot be used with it.\n", - "ValueError: Table 'county_yield' has no state-level data, so `level` cannot be used with it.\n", - "ValueError: Table 'yield' has no column 'colour'.\n", - "ValueError: Table 'yield' has no column(s) ['colour'].\n", - "ValueError: Unknown format 'xlsx'. Choose one of ('pandas', 'polars', 'arrow', 'records', 'csv', 'parquet').\n", - "ValueError: The 'csv' format needs an output `path`.\n", - "FileNotFoundError: The NASS dataset directory '/no/such/dir' does not exist.\n" - ] - } - ], - "source": [ - "for call in [\n", - " lambda: cat.resolve_states(\"Iowaa\"),\n", - " lambda: cat.resolve_counties(\"Washington\"),\n", - " lambda: cat.resolve_counties(\"99999\"),\n", - " lambda: cat.resolve_districts(\"10\"),\n", - " lambda: cat.resolve_crops(\"cron\"),\n", - " lambda: cat.resolve_crops(\"corn\", utilization=\"fiber\"),\n", - " lambda: nass.query(\"weather\"),\n", - " lambda: nass.progress(county=\"19169\"),\n", - " lambda: nass.county_yield(level=\"state\"),\n", - " lambda: nass.yield_data(where={\"colour\": \"red\"}),\n", - " lambda: nass.yield_data(columns=[\"colour\"]),\n", - " lambda: nass.yield_data(format=\"xlsx\"),\n", - " lambda: nass.yield_data(format=\"csv\"),\n", - " lambda: NASSDataLoader(\"/no/such/dir\"),\n", - "]:\n", - " try:\n", - " call()\n", - " print(\"NO ERROR (unexpected)\")\n", - " except (ValueError, FileNotFoundError) as e:\n", - " print(f\"{type(e).__name__}: {e}\")" - ] - }, - { - "cell_type": "markdown", - "id": "cell-25", - "metadata": {}, - "source": [ - "## 5. `yield` table: filters" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "cell-26", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:26.831644Z", - "iopub.status.busy": "2026-10-26T15:48:26.831497Z", - "iopub.status.idle": "2026-10-26T15:48:27.243619Z", - "shell.execute_reply": "2026-10-26T15:48:27.242957Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearcounty_namevalueunitvalue_t_hacv_pct
02015STORY188.0BU / ACRE11.8003NaN
12016STORY211.9BU / ACRE13.3005NaN
22017STORY200.3BU / ACRE12.5724NaN
32018STORY192.3BU / ACRE12.0702NaN
42019STORY189.3BU / ACRE11.8819NaN
52020STORY148.4BU / ACRE9.31472.6
62021STORY201.2BU / ACRE12.62881.9
72022STORY207.1BU / ACRE12.99922.5
82023STORY211.4BU / ACRE13.26913.2
92024STORY215.5BU / ACRE13.52642.6
\n", - "
" - ], - "text/plain": [ - " year county_name value unit value_t_ha cv_pct\n", - "0 2015 STORY 188.0 BU / ACRE 11.8003 NaN\n", - "1 2016 STORY 211.9 BU / ACRE 13.3005 NaN\n", - "2 2017 STORY 200.3 BU / ACRE 12.5724 NaN\n", - "3 2018 STORY 192.3 BU / ACRE 12.0702 NaN\n", - "4 2019 STORY 189.3 BU / ACRE 11.8819 NaN\n", - "5 2020 STORY 148.4 BU / ACRE 9.3147 2.6\n", - "6 2021 STORY 201.2 BU / ACRE 12.6288 1.9\n", - "7 2022 STORY 207.1 BU / ACRE 12.9992 2.5\n", - "8 2023 STORY 211.4 BU / ACRE 13.2691 3.2\n", - "9 2024 STORY 215.5 BU / ACRE 13.5264 2.6" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# One county, one crop, a year range.\n", - "nass.yield_data(crop=\"corn\", utilization=\"grain\", state=\"IA\", county=\"Story\", years=(2015, 2024), level=\"county\",\n", - " columns=[\"year\", \"county_name\", \"value\", \"unit\", \"value_t_ha\", \"cv_pct\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "cell-27", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:27.245328Z", - "iopub.status.busy": "2026-10-26T15:48:27.245173Z", - "iopub.status.idle": "2026-10-26T15:48:27.773315Z", - "shell.execute_reply": "2026-10-26T15:48:27.772767Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "([2020], [1990, 2000, 2010], [2021, 2022, 2023])" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Year forms: single year, list, range object.\n", - "q = dict(crop=\"CORN, GRAIN\", county=\"19169\", level=\"county\", columns=[\"year\", \"value\"])\n", - "(nass.yield_data(years=2020, **q)[\"year\"].tolist(),\n", - " nass.yield_data(years=[1990, 2000, 2010], **q)[\"year\"].tolist(),\n", - " nass.yield_data(years=range(2021, 2024), **q)[\"year\"].tolist())" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "cell-28", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:27.774907Z", - "iopub.status.busy": "2026-10-26T15:48:27.774749Z", - "iopub.status.idle": "2026-10-26T15:48:28.605159Z", - "shell.execute_reply": "2026-10-26T15:48:28.604651Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "agg_level\n", - "COUNTY 95\n", - "STATE 1\n", - "Name: count, dtype: int64" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Every level for one state and year (no `level` given).\n", - "nass.yield_data(crop=\"CORN, GRAIN\", state=\"IA\", years=2020)[\"agg_level\"].value_counts()" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "cell-29", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:28.606732Z", - "iopub.status.busy": "2026-10-26T15:48:28.606580Z", - "iopub.status.idle": "2026-10-26T15:48:28.839909Z", - "shell.execute_reply": "2026-10-26T15:48:28.839367Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
state_alphayearvalueunit
0IA2020177.0BU / ACRE
1IA2021204.0BU / ACRE
2IA2022200.0BU / ACRE
3IA2023201.0BU / ACRE
4IL2020191.0BU / ACRE
5IL2021202.0BU / ACRE
6IL2022214.0BU / ACRE
7IL2023206.0BU / ACRE
8NE2020180.0BU / ACRE
9NE2021194.0BU / ACRE
10NE2022165.0BU / ACRE
11NE2023182.0BU / ACRE
\n", - "
" - ], - "text/plain": [ - " state_alpha year value unit\n", - "0 IA 2020 177.0 BU / ACRE\n", - "1 IA 2021 204.0 BU / ACRE\n", - "2 IA 2022 200.0 BU / ACRE\n", - "3 IA 2023 201.0 BU / ACRE\n", - "4 IL 2020 191.0 BU / ACRE\n", - "5 IL 2021 202.0 BU / ACRE\n", - "6 IL 2022 214.0 BU / ACRE\n", - "7 IL 2023 206.0 BU / ACRE\n", - "8 NE 2020 180.0 BU / ACRE\n", - "9 NE 2021 194.0 BU / ACRE\n", - "10 NE 2022 165.0 BU / ACRE\n", - "11 NE 2023 182.0 BU / ACRE" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# State level, several states.\n", - "nass.yield_data(crop=\"CORN, GRAIN\", state=[\"IA\", \"IL\", \"NE\"], level=\"state\", years=(2020, 2023),\n", - " columns=[\"state_alpha\", \"year\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "cell-30", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:28.841392Z", - "iopub.status.busy": "2026-10-26T15:48:28.841243Z", - "iopub.status.idle": "2026-10-26T15:48:29.067106Z", - "shell.execute_reply": "2026-10-26T15:48:29.066527Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearvalueunit
02019167.5BU / ACRE
12020171.4BU / ACRE
22021176.7BU / ACRE
32022173.4BU / ACRE
42023177.3BU / ACRE
\n", - "
" - ], - "text/plain": [ - " year value unit\n", - "0 2019 167.5 BU / ACRE\n", - "1 2020 171.4 BU / ACRE\n", - "2 2021 176.7 BU / ACRE\n", - "3 2022 173.4 BU / ACRE\n", - "4 2023 177.3 BU / ACRE" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# National level.\n", - "nass.yield_data(crop=\"CORN, GRAIN\", level=\"national\", years=(2019, 2023), columns=[\"year\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "cell-31", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:29.068967Z", - "iopub.status.busy": "2026-10-26T15:48:29.068817Z", - "iopub.status.idle": "2026-10-26T15:48:29.317244Z", - "shell.execute_reply": "2026-10-26T15:48:29.316695Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
state_alphaasd_codeyearvalue
0IA102015202.5
1IA102016205.5
2IA102017203.4
3IA102018188.4
4IA102019195.3
\n", - "
" - ], - "text/plain": [ - " state_alpha asd_code year value\n", - "0 IA 10 2015 202.5\n", - "1 IA 10 2016 205.5\n", - "2 IA 10 2017 203.4\n", - "3 IA 10 2018 188.4\n", - "4 IA 10 2019 195.3" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# District level. District yields in this data stop in 2019.\n", - "nass.yield_data(crop=\"CORN, GRAIN\", district=first[\"asd_id\"], level=\"district\", years=(2015, 2019),\n", - " columns=[\"state_alpha\", \"asd_code\", \"year\", \"value\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "cell-32", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:29.318730Z", - "iopub.status.busy": "2026-10-26T15:48:29.318580Z", - "iopub.status.idle": "2026-10-26T15:48:30.787598Z", - "shell.execute_reply": "2026-10-26T15:48:30.786727Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(95, 96, np.int64(1))" - ] - }, - "execution_count": 27, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# \"Other (combined) counties\" rows are dropped by default.\n", - "q = dict(crop=\"CORN, GRAIN\", state=\"IA\", level=\"county\", years=2020)\n", - "kept = nass.yield_data(**q)\n", - "every = nass.yield_data(include_other_counties=True, **q)\n", - "len(kept), len(every), every[\"is_other_counties\"].sum()" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "cell-33", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:30.789136Z", - "iopub.status.busy": "2026-10-26T15:48:30.788973Z", - "iopub.status.idle": "2026-10-26T15:48:31.047141Z", - "shell.execute_reply": "2026-10-26T15:48:31.046405Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
crop_idyearvalueunit
06256b3fe85b5202335.0BU / ACRE
1c66627e9fb28202335.0BU / ACRE
\n", - "
" - ], - "text/plain": [ - " crop_id year value unit\n", - "0 6256b3fe85b5 2023 35.0 BU / ACRE\n", - "1 c66627e9fb28 2023 35.0 BU / ACRE" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# `where` on any column, e.g. one unit only.\n", - "nass.yield_data(crop=\"wheat\", state=\"KS\", level=\"state\", years=2023, where={\"unit\": \"BU / ACRE\"},\n", - " columns=[\"crop_id\", \"year\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "markdown", - "id": "cell-34", - "metadata": {}, - "source": [ - "## 6. Other tables" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "cell-35", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:31.048813Z", - "iopub.status.busy": "2026-10-26T15:48:31.048529Z", - "iopub.status.idle": "2026-10-26T15:48:31.171174Z", - "shell.execute_reply": "2026-10-26T15:48:31.170638Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearcommodityclassutilizationyield_t_haqa_outlier
02018CORNALL CLASSESGRAIN12.3464False
12018WHEATWINTERALL UTILIZATION PRACTICES5.2389False
22018BARLEYALL CLASSESALL UTILIZATION PRACTICES5.4554False
32019CORNALL CLASSESGRAIN12.2271False
42019WHEATWINTERALL UTILIZATION PRACTICES3.1339False
52020WHEATWINTERALL UTILIZATION PRACTICES7.3976False
\n", - "
" - ], - "text/plain": [ - " year commodity class utilization yield_t_ha qa_outlier\n", - "0 2018 CORN ALL CLASSES GRAIN 12.3464 False\n", - "1 2018 WHEAT WINTER ALL UTILIZATION PRACTICES 5.2389 False\n", - "2 2018 BARLEY ALL CLASSES ALL UTILIZATION PRACTICES 5.4554 False\n", - "3 2019 CORN ALL CLASSES GRAIN 12.2271 False\n", - "4 2019 WHEAT WINTER ALL UTILIZATION PRACTICES 3.1339 False\n", - "5 2020 WHEAT WINTER ALL UTILIZATION PRACTICES 7.3976 False" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# county_yield: the curated main-variant county view (filters by state_alpha internally).\n", - "nass.county_yield(state=\"CA\", county=\"Yolo\", years=(2018, 2020),\n", - " columns=[\"year\", \"commodity\", \"class\", \"utilization\", \"yield_t_ha\", \"qa_outlier\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "cell-36", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:31.172667Z", - "iopub.status.busy": "2026-10-26T15:48:31.172510Z", - "iopub.status.idle": "2026-10-26T15:48:31.930600Z", - "shell.execute_reply": "2026-10-26T15:48:31.929812Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
state_alphayearvalueunit
0KS2020281250000.0BU
1KS2021364000000.0BU
2KS2022244200000.0BU
3KS2023201250000.0BU
4KS2024307450000.0BU
5ND2020312587000.0BU
6ND2021196195000.0BU
7ND2022299900000.0BU
8ND2023306390000.0BU
9ND2024368285000.0BU
\n", - "
" - ], - "text/plain": [ - " state_alpha year value unit\n", - "0 KS 2020 281250000.0 BU\n", - "1 KS 2021 364000000.0 BU\n", - "2 KS 2022 244200000.0 BU\n", - "3 KS 2023 201250000.0 BU\n", - "4 KS 2024 307450000.0 BU\n", - "5 ND 2020 312587000.0 BU\n", - "6 ND 2021 196195000.0 BU\n", - "7 ND 2022 299900000.0 BU\n", - "8 ND 2023 306390000.0 BU\n", - "9 ND 2024 368285000.0 BU" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass.area_production(crop=\"wheat\", crop_class=\"all classes\", state=[\"KS\", \"ND\"], level=\"state\",\n", - " statistic=\"production\", years=(2020, 2024), columns=[\"state_alpha\", \"year\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "cell-37", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:31.932099Z", - "iopub.status.busy": "2026-10-26T15:48:31.931946Z", - "iopub.status.idle": "2026-10-26T15:48:32.552035Z", - "shell.execute_reply": "2026-10-26T15:48:32.551192Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearstatisticvalueunit
02022area_harvested156100.0ACRES
12022production32328000.0BU
\n", - "
" - ], - "text/plain": [ - " year statistic value unit\n", - "0 2022 area_harvested 156100.0 ACRES\n", - "1 2022 production 32328000.0 BU" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Several statistics at once.\n", - "nass.area_production(crop=\"CORN, GRAIN\", county=\"Story\", state=\"IA\", years=2022,\n", - " statistic=[\"area_planted\", \"area_harvested\", \"production\"],\n", - " columns=[\"year\", \"statistic\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "cell-38", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.553560Z", - "iopub.status.busy": "2026-10-26T15:48:32.553411Z", - "iopub.status.idle": "2026-10-26T15:48:32.805544Z", - "shell.execute_reply": "2026-10-26T15:48:32.804729Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearstatisticvalueunit
01997area_harvested11930542.0ACRES
12002area_harvested11761392.0ACRES
22007area_harvested13842282.0ACRES
32012area_harvested13709408.0ACRES
42017area_harvested12969645.0ACRES
52022area_harvested12637070.0ACRES
\n", - "
" - ], - "text/plain": [ - " year statistic value unit\n", - "0 1997 area_harvested 11930542.0 ACRES\n", - "1 2002 area_harvested 11761392.0 ACRES\n", - "2 2007 area_harvested 13842282.0 ACRES\n", - "3 2012 area_harvested 13709408.0 ACRES\n", - "4 2017 area_harvested 12969645.0 ACRES\n", - "5 2022 area_harvested 12637070.0 ACRES" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Census of Agriculture: every five years. (The data has no CA almond records, so this uses Iowa corn grain.)\n", - "nass.census(crop=\"CORN, GRAIN\", state=\"IA\", level=\"state\", statistic=\"area_harvested\", where={\"unit\": \"ACRES\"},\n", - " columns=[\"year\", \"statistic\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "cell-39", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.807079Z", - "iopub.status.busy": "2026-10-26T15:48:32.806895Z", - "iopub.status.idle": "2026-10-26T15:48:32.821599Z", - "shell.execute_reply": "2026-10-26T15:48:32.821075Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearforecast_monthvalueunit
02023AUG203.0BU / ACRE
12023SEP200.0BU / ACRE
22023OCT199.0BU / ACRE
32023NOV200.0BU / ACRE
\n", - "
" - ], - "text/plain": [ - " year forecast_month value unit\n", - "0 2023 AUG 203.0 BU / ACRE\n", - "1 2023 SEP 200.0 BU / ACRE\n", - "2 2023 OCT 199.0 BU / ACRE\n", - "3 2023 NOV 200.0 BU / ACRE" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass.forecast(crop=\"CORN, GRAIN\", state=\"IA\", years=2023, columns=[\"year\", \"forecast_month\", \"value\", \"unit\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "cell-40", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.823131Z", - "iopub.status.busy": "2026-10-26T15:48:32.822981Z", - "iopub.status.idle": "2026-10-26T15:48:32.861577Z", - "shell.execute_reply": "2026-10-26T15:48:32.861026Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
week_endingstagepct
02023-04-16PLANTED4.0
12023-04-23PLANTED15.0
22023-04-30PLANTED39.0
32023-05-07PLANTED66.0
42023-05-14PLANTED77.0
52023-05-21PLANTED85.0
62023-05-28PLANTED92.0
72023-06-04PLANTED96.0
82023-06-11PLANTED97.0
\n", - "
" - ], - "text/plain": [ - " week_ending stage pct\n", - "0 2023-04-16 PLANTED 4.0\n", - "1 2023-04-23 PLANTED 15.0\n", - "2 2023-04-30 PLANTED 39.0\n", - "3 2023-05-07 PLANTED 66.0\n", - "4 2023-05-14 PLANTED 77.0\n", - "5 2023-05-21 PLANTED 85.0\n", - "6 2023-05-28 PLANTED 92.0\n", - "7 2023-06-04 PLANTED 96.0\n", - "8 2023-06-11 PLANTED 97.0" - ] - }, - "execution_count": 34, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass.progress(crop=\"soybeans\", state=\"IL\", years=2023, stage=\"planted\", columns=[\"week_ending\", \"stage\", \"pct\"])" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "cell-41", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.863149Z", - "iopub.status.busy": "2026-10-26T15:48:32.862999Z", - "iopub.status.idle": "2026-10-26T15:48:32.962946Z", - "shell.execute_reply": "2026-10-26T15:48:32.962282Z" - } - }, - "outputs": [ - { - "data": { - "text/plain": [ - "stage\n", - "EMERGED 10\n", - "PLANTED 9\n", - "Name: count, dtype: int64" - ] - }, - "execution_count": 35, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Several stages, all three spellings accepted.\n", - "nass.progress(crop=\"soybeans\", state=\"IL\", years=2023, stage=[\"PCT PLANTED\", \"emerged\"])[\"stage\"].value_counts()" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "cell-42", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.964511Z", - "iopub.status.busy": "2026-10-26T15:48:32.964278Z", - "iopub.status.idle": "2026-10-26T15:48:32.993166Z", - "shell.execute_reply": "2026-10-26T15:48:32.992566Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
week_endingvery_poorpoorfairgoodexcellentgood_excellent
02023-05-280.02.021.065.012.077.0
12023-06-040.03.025.060.012.072.0
22023-06-111.03.026.058.012.070.0
32023-06-181.07.033.050.09.059.0
42023-06-252.010.032.048.08.056.0
\n", - "
" - ], - "text/plain": [ - " week_ending very_poor poor fair good excellent good_excellent\n", - "0 2023-05-28 0.0 2.0 21.0 65.0 12.0 77.0\n", - "1 2023-06-04 0.0 3.0 25.0 60.0 12.0 72.0\n", - "2 2023-06-11 1.0 3.0 26.0 58.0 12.0 70.0\n", - "3 2023-06-18 1.0 7.0 33.0 50.0 9.0 59.0\n", - "4 2023-06-25 2.0 10.0 32.0 48.0 8.0 56.0" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass.condition(crop=\"CORN\", state=\"IA\", years=2023,\n", - " columns=[\"week_ending\", \"very_poor\", \"poor\", \"fair\", \"good\", \"excellent\", \"good_excellent\"]).head()" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "cell-43", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:32.994762Z", - "iopub.status.busy": "2026-10-26T15:48:32.994613Z", - "iopub.status.idle": "2026-10-26T15:48:33.062576Z", - "shell.execute_reply": "2026-10-26T15:48:33.062038Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
week_endingratingpct
02023-05-28EXCELLENT12.0
12023-05-28FAIR21.0
22023-05-28GOOD65.0
32023-05-28POOR2.0
42023-05-28VERY POOR0.0
\n", - "
" - ], - "text/plain": [ - " week_ending rating pct\n", - "0 2023-05-28 EXCELLENT 12.0\n", - "1 2023-05-28 FAIR 21.0\n", - "2 2023-05-28 GOOD 65.0\n", - "3 2023-05-28 POOR 2.0\n", - "4 2023-05-28 VERY POOR 0.0" - ] - }, - "execution_count": 37, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "nass.condition(long=True, crop=\"CORN\", state=\"IA\", years=2023, columns=[\"week_ending\", \"rating\", \"pct\"]).head()" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "cell-44", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:33.064046Z", - "iopub.status.busy": "2026-10-26T15:48:33.063895Z", - "iopub.status.idle": "2026-10-26T15:48:33.137350Z", - "shell.execute_reply": "2026-10-26T15:48:33.136811Z" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
week_endingratingpct
02023-05-28GOOD58.0
12023-06-04GOOD53.0
22023-06-11GOOD51.0
32023-06-18GOOD47.0
42023-06-25GOOD42.0
\n", - "
" - ], - "text/plain": [ - " week_ending rating pct\n", - "0 2023-05-28 GOOD 58.0\n", - "1 2023-06-04 GOOD 53.0\n", - "2 2023-06-11 GOOD 51.0\n", - "3 2023-06-18 GOOD 47.0\n", - "4 2023-06-25 GOOD 42.0" - ] - }, - "execution_count": 38, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Generic query() on any table.\n", - "nass.query(\"condition_long\", crop=\"CORN\", level=\"national\", years=2023, where={\"rating\": \"GOOD\"},\n", - " columns=[\"week_ending\", \"rating\", \"pct\"]).head()" - ] - }, - { - "cell_type": "markdown", - "id": "cell-45", - "metadata": {}, - "source": [ - "## 7. Output formats" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "cell-46", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:33.138978Z", - "iopub.status.busy": "2026-10-26T15:48:33.138829Z", - "iopub.status.idle": "2026-10-26T15:48:34.189720Z", - "shell.execute_reply": "2026-10-26T15:48:34.189040Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pandas pandas.core.frame.DataFrame rows=4\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "polars polars.dataframe.frame.DataFrame rows=4\n", - "arrow pyarrow.lib.Table rows=4\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "records builtins.list rows=4\n" - ] - }, - { - "data": { - "text/plain": [ - "[{'year': 2020, 'value': 148.4}, {'year': 2021, 'value': 201.2}]" - ] - }, - "execution_count": 39, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "q = dict(crop=\"CORN, GRAIN\", state=\"IA\", county=\"Story\", years=(2020, 2023), columns=[\"year\", \"value\"])\n", - "for fmt in [\"pandas\", \"polars\", \"arrow\", \"records\"]:\n", - " try:\n", - " r = nass.yield_data(format=fmt, **q)\n", - " print(f\"{fmt:8s} {type(r).__module__}.{type(r).__name__} rows={len(r)}\")\n", - " except ImportError as e:\n", - " print(f\"{fmt:8s} skipped: {e}\")\n", - "nass.yield_data(format=\"records\", **q)[:2]" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "cell-47", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:34.191178Z", - "iopub.status.busy": "2026-10-26T15:48:34.191024Z", - "iopub.status.idle": "2026-10-26T15:48:34.532748Z", - "shell.execute_reply": "2026-10-26T15:48:34.532212Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/tmp/nass_check_qps_bfc6/story_corn.csv 59 bytes\n", - "/tmp/nass_check_qps_bfc6/story_corn.parquet 786 bytes\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
yearvalue
02020148.4
12021201.2
22022207.1
32023211.4
\n", - "
" - ], - "text/plain": [ - " year value\n", - "0 2020 148.4\n", - "1 2021 201.2\n", - "2 2022 207.1\n", - "3 2023 211.4" - ] - }, - "execution_count": 40, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "for fmt in [\"csv\", \"parquet\"]:\n", - " path = nass.yield_data(format=fmt, path=os.path.join(OUT, f\"story_corn.{fmt}\"), **q)\n", - " print(path, os.path.getsize(path), \"bytes\")\n", - "pd.read_csv(os.path.join(OUT, \"story_corn.csv\"))" - ] - }, - { - "cell_type": "markdown", - "id": "cell-48", - "metadata": {}, - "source": [ - "## 8. Timing on the full tables" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "cell-49", - "metadata": { - "execution": { - "iopub.execute_input": "2026-10-26T15:48:34.534693Z", - "iopub.status.busy": "2026-10-26T15:48:34.534539Z", - "iopub.status.idle": "2026-10-26T15:48:37.520802Z", - "shell.execute_reply": "2026-10-26T15:48:37.520207Z" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1.06 s, sys: 551 ms, total: 1.61 s\n", - "Wall time: 830 ms\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 2.45 s, sys: 243 ms, total: 2.69 s\n", - "Wall time: 1.38 s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CPU times: user 1.05 s, sys: 464 ms, total: 1.52 s\n", - "Wall time: 768 ms\n" - ] - } - ], - "source": [ - "%time _ = nass.yield_data(crop=\"CORN, GRAIN\", county=\"Story\", state=\"IA\", years=(2000, 2024))\n", - "%time _ = nass.area_production(crop=\"CORN, GRAIN\", level=\"county\", years=2022)\n", - "%time _ = nass.yield_data(level=\"county\", years=2022)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.20" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/agml/ag_stats/calicropyield/__init__.py b/agml/ag_stats/calicropyield/__init__.py new file mode 100644 index 00000000..f32eeab2 --- /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 + +__all__ = ["CaliCropYieldLoader", "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..dcb59032 --- /dev/null +++ b/agml/ag_stats/calicropyield/catalog.py @@ -0,0 +1,206 @@ +"""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" + +# 2012 is missing from every layer. +_YEARS = tuple(y for y in range(2008, 2024) if y != 2012) + + +@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 a layer has. + + Raises an error for years the layer does not have, so a typo is not + silently skipped. `None` means every year. + """ + available = layer(name).years + if years is None: + return list(available) + if isinstance(years, int): + wanted = [years] + elif isinstance(years, tuple) and len(years) == 2: + wanted = [y for y in available if years[0] <= y <= years[1]] + else: + wanted = [int(y) for y in years] + missing = [y for y in wanted if y not in available] + if missing: + raise ValueError(f"Layer '{name}' has no data for {missing}. It covers {available[0]}-{available[-1]} except 2012.") + 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..b0c4adf3 --- /dev/null +++ b/agml/ag_stats/calicropyield/loader.py @@ -0,0 +1,463 @@ +"""Downloads and reads the California Crop Yield Benchmark.""" + +import os +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]] + + +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`. 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 + -------- + >>> 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` is only kept in Hub mode; `None` marks a local copy. + self._repo_id = None if root is not None else repo_id + self._revision = revision + self._cache_dir = cache_dir + self._token = token + + 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 revision of `repo_id` the data comes from.""" + 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 missing from the dataset are skipped with a warning. 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 = list(months) if months is not None else list(range(1, 13)) + paths, missing = [], [] + for county in _as_list(counties): + slug = catalog.county_slug(county) + for year in catalog.resolve_years(layer, years): + for month in months if spec.monthly else [None]: + try: + paths.append(self._layer_path(layer, slug, year, month)) + except FileNotFoundError: + missing.append(spec.path(layer, slug, year, month)) + if missing: + log(f"{len(missing)} file(s) are not in the dataset and were skipped: {missing[:5]}") + return paths + + 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.""" + 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(_years_list(years, df[year_col])) + 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) + else: + from huggingface_hub import snapshot_download + + # A store is a directory of small files, so fetch it in one call. + folder = snapshot_download( + repo_id=self._repo_id, + repo_type="dataset", + revision=self._revision, + cache_dir=self._cache_dir, + token=getattr(self, "_token", None), + allow_patterns=[f"{path}/*"], + ) + local = os.path.join(folder, path) + if not os.path.isdir(local): + raise FileNotFoundError(f"The Zarr store '{path}' is not in the dataset.") + return local + + 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: + if geometry is None: + data, transform = src.read(), src.transform + else: + fill = np.nan if np.issubdtype(np.dtype(src.dtypes[0]), np.floating) else (src.nodata or 0) + data, transform = rasterio.mask.mask(src, [geometry], crop=True, nodata=fill) + 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": src.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 = 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}.") + 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 _years_list(years: YearSpec, available: pd.Series) -> List[int]: + if isinstance(years, int): + return [years] + if isinstance(years, tuple) and len(years) == 2: + return [y for y in available.unique() if years[0] <= y <= years[1]] + return [int(y) for y in years] 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/catalog.py b/agml/ag_stats/nass/catalog.py similarity index 100% rename from agml/ag_stats/catalog.py rename to agml/ag_stats/nass/catalog.py diff --git a/agml/ag_stats/loader.py b/agml/ag_stats/nass/loader.py similarity index 96% rename from agml/ag_stats/loader.py rename to agml/ag_stats/nass/loader.py index bbfdfe04..904c9d3c 100644 --- a/agml/ag_stats/loader.py +++ b/agml/ag_stats/nass/loader.py @@ -9,7 +9,7 @@ import pyarrow.dataset as ds from agml.framework import AgMLSerializable -from agml.ag_stats.catalog import _DIM_FILES, NASSCatalog, StrOrList, _as_list +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" @@ -142,7 +142,7 @@ class NASSDataLoader(AgMLSerializable): -------- >>> nass = NASSDataLoader() # reads from the Hugging Face Hub >>> nass = NASSDataLoader("/path/to/nass-usda-full-data") # a local copy - >>> df = nass.yield_data(crop="corn", utilization="grain", state="IA", + >>> 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") @@ -288,15 +288,15 @@ def query( # Convenience wrappers, one per table. - def yield_data(self, **kwargs): + def load_yield(self, **kwargs): """Queries the `yield` table. Takes the same arguments as `query`.""" return self.query("yield", **kwargs) - def county_yield(self, **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 area_production(self, statistic: StrOrList = None, **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 @@ -305,16 +305,16 @@ def area_production(self, statistic: StrOrList = None, **kwargs): where = self._merge_where(kwargs, statistic=statistic) return self.query("area_production", where=where, **kwargs) - def census(self, statistic: StrOrList = None, **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 forecast(self, **kwargs): + def load_forecast(self, **kwargs): """Queries the `forecast` table. Takes the same arguments as `query`.""" return self.query("forecast", **kwargs) - def progress(self, stage: StrOrList = None, **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 @@ -325,11 +325,11 @@ def progress(self, stage: StrOrList = None, **kwargs): where = self._merge_where(kwargs, stage=stage) return self.query("progress", where=where, **kwargs) - def condition(self, long: bool = False, **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 boundaries(self, level: str = "county", geometry: bool = True, format: str = "pandas", path: Optional[str] = None): + 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. 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..e889a6bd --- /dev/null +++ b/tests/ag_stats/calicropyield/conftest.py @@ -0,0 +1,110 @@ +import json + +import numpy as np +import pandas as pd +import pytest + +pytest.importorskip("rasterio") +pytest.importorskip("xarray") + +import rasterio +import xarray as xr +from rasterio.transform import from_origin + +from .calicropyield_fixtures import CDL, LANDSAT_BANDS, RES + +# A 4x6 pixel grid at the CDL resolution, in the corner of Yolo County. +_TRANSFORM = from_origin(-122.0, 38.6, RES, RES) +_HEIGHT, _WIDTH = CDL.shape + + +def _write_tif(path, data, nodata=None, descriptions=None): + 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=_TRANSFORM, 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.""" + 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 / "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..b5957f8c --- /dev/null +++ b/tests/ag_stats/calicropyield/test_calicropyield_catalog.py @@ -0,0 +1,66 @@ +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 + + @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..cf672481 --- /dev/null +++ b/tests/ag_stats/calicropyield/test_calicropyield_loader.py @@ -0,0 +1,274 @@ +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 + +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") + + +@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, monkeypatch): + monkeypatch.delenv("AGML_CALICROPYIELD_PATH", raising=False) + 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_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): + triangle = {"type": "Polygon", "coordinates": [[[-122.0, 38.6], [-122.0 + 4 * RES, 38.6], [-122.0, 38.6 - 4 * RES], [-122.0, 38.6]]]} + 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_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 from a folder.""" + + def __init__(self, cali_root, tmp_path): + self.folder = tmp_path / "snapshot" + shutil.copytree(cali_root, self.folder) + self.downloads = [] + + 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 not (self.folder / filename).is_file(): + raise EntryNotFoundError(filename) + self.downloads.append(filename) + return str(self.folder / filename) + + def snapshot_download(self, repo_id, repo_type, revision, cache_dir, token, allow_patterns): + self.downloads.extend(allow_patterns) + return str(self.folder) + + +@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, "snapshot_download", fake.snapshot_download) + 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.downloads == ["counties/Yolo/soil/2020/Yolo_soil.zarr/*"] + + def test_missing_file(self, hub): + with pytest.raises(FileNotFoundError, match="not in the dataset"): + CaliCropYieldLoader().load_cdl("Fresno", 2020) + + def test_pickle_keeps_repo(self, hub): + clone = pickle.loads(pickle.dumps(CaliCropYieldLoader(revision="abc123"))) + assert clone.repo_id == DEFAULT_REPO_ID and clone.revision == "abc123" 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/conftest.py b/tests/ag_stats/nass/conftest.py similarity index 98% rename from tests/ag_stats/conftest.py rename to tests/ag_stats/nass/conftest.py index 0e4f76dc..1e4eb570 100644 --- a/tests/ag_stats/conftest.py +++ b/tests/ag_stats/nass/conftest.py @@ -1,5 +1,5 @@ import pytest -from nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS pa = pytest.importorskip("pyarrow") pq = pytest.importorskip("pyarrow.parquet") diff --git a/tests/ag_stats/nass_fixtures.py b/tests/ag_stats/nass/nass_fixtures.py similarity index 100% rename from tests/ag_stats/nass_fixtures.py rename to tests/ag_stats/nass/nass_fixtures.py diff --git a/tests/ag_stats/test_catalog.py b/tests/ag_stats/nass/test_catalog.py similarity index 97% rename from tests/ag_stats/test_catalog.py rename to tests/ag_stats/nass/test_catalog.py index 37db0240..9fac2344 100644 --- a/tests/ag_stats/test_catalog.py +++ b/tests/ag_stats/nass/test_catalog.py @@ -2,9 +2,9 @@ pytest.importorskip("pyarrow") -from agml.ag_stats import NASSCatalog +from agml.ag_stats.nass import NASSCatalog -from nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS @pytest.fixture(scope="module") diff --git a/tests/ag_stats/test_loader.py b/tests/ag_stats/nass/test_loader.py similarity index 79% rename from tests/ag_stats/test_loader.py rename to tests/ag_stats/nass/test_loader.py index f1b4cc76..b12f72cc 100644 --- a/tests/ag_stats/test_loader.py +++ b/tests/ag_stats/nass/test_loader.py @@ -9,9 +9,9 @@ import pandas as pd import pyarrow as pa -from agml.ag_stats import DEFAULT_REPO_ID, NASSDataLoader +from agml.ag_stats.nass import DEFAULT_REPO_ID, NASSDataLoader -from nass_fixtures import CORN_GRAIN, CORN_SILAGE +from .nass_fixtures import CORN_GRAIN, CORN_SILAGE @pytest.fixture(scope="module") @@ -38,7 +38,7 @@ def test_missing_dir(self, tmp_path): def test_pickle_round_trip(self, nass): clone = pickle.loads(pickle.dumps(nass)) assert clone.root == nass.root - assert len(clone.yield_data(state="IA", years=2020)) > 0 + assert len(clone.load_yield(state="IA", years=2020)) > 0 def test_tables_listing(self): assert "yield" in NASSDataLoader.tables() @@ -48,14 +48,14 @@ def test_tables_listing(self): class TestFilters: def test_one_county(self, nass): - df = nass.yield_data(crop="corn", utilization="grain", county="Story", state="IA") + 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.yield_data(county="19169", crop="corn, grain", years=spec)["year"]) + return sorted(nass.load_yield(county="19169", crop="corn, grain", years=spec)["year"]) assert years(2020) == [2020] assert years((2019, 2020)) == [2019, 2020] @@ -63,54 +63,54 @@ def years(spec): assert years(range(2020, 2022)) == [2020, 2021] def test_level(self, nass): - df = nass.yield_data(crop="corn", utilization="grain", level="state") + 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.yield_data(crop="corn", utilization="grain", state="IA", years=2020) + 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.yield_data(level="county", state="IA", crop=CORN_GRAIN, years=2020) + kept = nass.load_yield(level="county", state="IA", crop=CORN_GRAIN, years=2020) assert kept["county_fips"].notna().all() - every = nass.yield_data(level="county", state="IA", crop=CORN_GRAIN, years=2020, include_other_counties=True) + 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.yield_data(district="central", state="IA", level="district", crop=CORN_GRAIN) + 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.area_production(statistic="production", crop="soybeans", state="IL", level="state") + 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.progress(stage=stage, state="IA", years=2021) + 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.forecast(state="IA", crop=CORN_GRAIN, years=2020) + 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.yield_data(crop=CORN_GRAIN, level="county") + 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.condition(state="IA", years=2019) + 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.county_yield(state="Iowa", crop=CORN_SILAGE) + df = nass.load_county_yield(state="Iowa", crop=CORN_SILAGE) assert set(df["state_alpha"]) == {"IA"} def test_columns(self, nass): - df = nass.yield_data(county="19169", crop=CORN_GRAIN, columns=["year", "value"]) + df = nass.load_yield(county="19169", crop=CORN_GRAIN, columns=["year", "value"]) assert list(df.columns) == ["year", "value"] @@ -123,43 +123,43 @@ def test_unknown_table(self, nass): def test_county_on_state_only_table(self, nass): with pytest.raises(ValueError, match="county-level"): - nass.progress(county="19169") + nass.load_progress(county="19169") def test_level_on_county_only_table(self, nass): with pytest.raises(ValueError, match="state-level"): - nass.county_yield(level="state") + nass.load_county_yield(level="state") def test_unknown_where_column(self, nass): with pytest.raises(ValueError, match="no column 'colour'"): - nass.yield_data(where={"colour": "red"}) + nass.load_yield(where={"colour": "red"}) def test_unknown_columns(self, nass): with pytest.raises(ValueError, match="no column"): - nass.yield_data(columns=["colour"]) + nass.load_yield(columns=["colour"]) def test_unknown_format(self, nass): with pytest.raises(ValueError, match="Unknown format"): - nass.yield_data(format="xlsx") + nass.load_yield(format="xlsx") def test_file_format_needs_path(self, nass): with pytest.raises(ValueError, match="needs an output"): - nass.yield_data(format="csv") + nass.load_yield(format="csv") # ── Boundaries ──────────────────────────────────────────────────────────────── class TestBoundaries: def test_county_with_geometry(self, nass): - df = nass.boundaries("county") + df = nass.load_boundaries("county") assert list(df["GEOID"]) == ["19169"] and "geometry" in df.columns def test_state_without_geometry(self, nass): - df = nass.boundaries("state", geometry=False) + 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.boundaries("district") + nass.load_boundaries("district") # ── Hugging Face Hub ────────────────────────────────────────────────────────── @@ -205,18 +205,18 @@ def test_defaults_to_hub(self, hub): 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.yield_data(state="IA", years=2020)) > 0 + 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().boundaries("county")["GEOID"]) == ["19169"] + 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.yield_data(state="IA", years=2020)) > 0 + assert len(clone.load_yield(state="IA", years=2020)) > 0 # ── Output formats ──────────────────────────────────────────────────────────── @@ -225,22 +225,22 @@ class TestFormats: QUERY = dict(county="19169", crop=CORN_GRAIN, years=2020) def test_pandas(self, nass): - assert isinstance(nass.yield_data(**self.QUERY), pd.DataFrame) + assert isinstance(nass.load_yield(**self.QUERY), pd.DataFrame) def test_arrow(self, nass): - assert isinstance(nass.yield_data(format="arrow", **self.QUERY), pa.Table) + assert isinstance(nass.load_yield(format="arrow", **self.QUERY), pa.Table) def test_records(self, nass): - records = nass.yield_data(format="records", **self.QUERY) + 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.yield_data(format="polars", **self.QUERY), pl.DataFrame) + 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.yield_data(format=fmt, path=str(tmp_path / f"out.{fmt}"), **self.QUERY) + path = nass.load_yield(format=fmt, path=str(tmp_path / f"out.{fmt}"), **self.QUERY) assert os.path.getsize(path) > 0 @@ -249,6 +249,6 @@ def test_files(self, nass, tmp_path, fmt): @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.yield_data(crop="corn, grain", state="IA", county="Story", years=(2015, 2020), level="county") + 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() From c2820950624e9be5241772005aa4e28e7d06fed1 Mon Sep 17 00:00:00 2001 From: hkaman7 Date: Mon, 9 Nov 2026 13:45:46 -0800 Subject: [PATCH 3/4] Fix test collection when optional dependencies are missing CI does not install rasterio or xarray. The calicropyield conftest called pytest.importorskip at module level. A skip while loading a conftest aborts the whole test run, so every CI job failed. The import checks now run inside the fixtures. The NASS conftest gets the same change. --- tests/ag_stats/calicropyield/conftest.py | 16 +++++++--------- tests/ag_stats/nass/conftest.py | 8 +++++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/ag_stats/calicropyield/conftest.py b/tests/ag_stats/calicropyield/conftest.py index e889a6bd..9167e8fd 100644 --- a/tests/ag_stats/calicropyield/conftest.py +++ b/tests/ag_stats/calicropyield/conftest.py @@ -4,26 +4,21 @@ import pandas as pd import pytest -pytest.importorskip("rasterio") -pytest.importorskip("xarray") - -import rasterio -import xarray as xr -from rasterio.transform import from_origin - from .calicropyield_fixtures import CDL, LANDSAT_BANDS, RES # A 4x6 pixel grid at the CDL resolution, in the corner of Yolo County. -_TRANSFORM = from_origin(-122.0, 38.6, RES, RES) _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=_TRANSFORM, nodata=nodata, + 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 []): @@ -37,6 +32,9 @@ def _grid_coords(n_y, n_x, step): @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" diff --git a/tests/ag_stats/nass/conftest.py b/tests/ag_stats/nass/conftest.py index 1e4eb570..ed9e5376 100644 --- a/tests/ag_stats/nass/conftest.py +++ b/tests/ag_stats/nass/conftest.py @@ -1,9 +1,6 @@ import pytest from .nass_fixtures import CORN_GRAIN, CORN_SILAGE, SOYBEANS -pa = pytest.importorskip("pyarrow") -pq = pytest.importorskip("pyarrow.parquet") - # ── Fixture dataset ────────────────────────────────────────────────────────── # A few rows per table, shaped like the real NASS parquet files. @@ -84,6 +81,9 @@ def _fact_rows(years): 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) @@ -91,6 +91,8 @@ def _write(path, data): @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() From 162330bdbada001b1ea881124ce0426e9c48a11e Mon Sep 17 00:00:00 2001 From: hkaman7 Date: Sun, 15 Nov 2026 18:28:15 -0800 Subject: [PATCH 4/4] Address review comments on the calicropyield loader Pin the dataset to a commit when the loader is created, like the NASS loader. Batch downloads: list each county layer folder once and download files in parallel. Files missing from the dataset are skipped with a warning, and files that fail to download raise a DownloadError that lists them. Cropped rasters without a no-data value now use the dtype maximum, so 0 in the irrigation layer still means "not irrigated". Year ranges that reach past the data now raise an error instead of being cut short. 2012, which no layer has, is still skipped inside a range. --- agml/ag_stats/calicropyield/__init__.py | 4 +- agml/ag_stats/calicropyield/catalog.py | 32 ++- agml/ag_stats/calicropyield/loader.py | 187 ++++++++++++++---- tests/ag_stats/calicropyield/conftest.py | 1 + .../test_calicropyield_catalog.py | 12 ++ .../test_calicropyield_loader.py | 131 ++++++++++-- 6 files changed, 299 insertions(+), 68 deletions(-) diff --git a/agml/ag_stats/calicropyield/__init__.py b/agml/ag_stats/calicropyield/__init__.py index f32eeab2..7bfc6557 100644 --- a/agml/ag_stats/calicropyield/__init__.py +++ b/agml/ag_stats/calicropyield/__init__.py @@ -32,6 +32,6 @@ ) from .catalog import CDL_CLASSES, COUNTIES, DEFAULT_REPO_ID, LAYERS -from .loader import CaliCropYieldLoader +from .loader import CaliCropYieldLoader, DownloadError -__all__ = ["CaliCropYieldLoader", "CDL_CLASSES", "COUNTIES", "DEFAULT_REPO_ID", "LAYERS"] +__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 index dcb59032..a8968d67 100644 --- a/agml/ag_stats/calicropyield/catalog.py +++ b/agml/ag_stats/calicropyield/catalog.py @@ -18,9 +18,13 @@ 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 != 2012) +_YEARS = tuple(y for y in range(2008, 2024) if y != MISSING_YEAR) @dataclass(frozen=True) @@ -158,23 +162,39 @@ def county_slug(county: str) -> str: 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 a layer has. + """Turns a year, an inclusive `(start, end)` range, or a list into the years of a layer. - Raises an error for years the layer does not have, so a typo is not - silently skipped. `None` means every year. + `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: - wanted = [y for y in available if years[0] <= y <= years[1]] + 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"Layer '{name}' has no data for {missing}. It covers {available[0]}-{available[-1]} except 2012.") + raise ValueError( + f"{what} has no data for {missing}. It covers {available[0]}-{available[-1]} except {MISSING_YEAR}." + ) return wanted diff --git a/agml/ag_stats/calicropyield/loader.py b/agml/ag_stats/calicropyield/loader.py index b0c4adf3..ab016653 100644 --- a/agml/ag_stats/calicropyield/loader.py +++ b/agml/ag_stats/calicropyield/loader.py @@ -1,6 +1,8 @@ """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 @@ -21,6 +23,27 @@ 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. @@ -53,8 +76,10 @@ class CaliCropYieldLoader(AgMLSerializable): 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. + 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 @@ -85,15 +110,15 @@ def __init__( if not os.path.isdir(root): raise FileNotFoundError(f"The California Crop Yield Benchmark directory '{root}' does not exist.") self._root = root - # `repo_id` is only kept in Hub mode; `None` marks a local copy. + # `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._revision = revision 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"" return f"" @property @@ -108,7 +133,7 @@ def repo_id(self) -> Optional[str]: @property def revision(self) -> Optional[str]: - """The revision of `repo_id` the data comes from.""" + """The commit of `repo_id` the data comes from, or `None` for a local copy.""" return self._revision # Listings. @@ -145,8 +170,10 @@ def download( """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 missing from the dataset are skipped with a warning. Zarr - layers return the path of each store (a directory). + 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 ---------- @@ -161,19 +188,21 @@ def download( Months of the monthly layers (`landsat`, `et`). Defaults to all. """ spec = catalog.layer(layer) - months = list(months) if months is not None else list(range(1, 13)) - paths, missing = [], [] - for county in _as_list(counties): - slug = catalog.county_slug(county) - for year in catalog.resolve_years(layer, years): - for month in months if spec.monthly else [None]: - try: - paths.append(self._layer_path(layer, slug, year, month)) - except FileNotFoundError: - missing.append(spec.path(layer, slug, year, month)) + 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 paths + 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`.""" @@ -228,7 +257,10 @@ class (no urban, water, or natural land cover). 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.""" + """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: @@ -319,7 +351,7 @@ def load_yield( 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(_years_list(years, df[year_col])) + 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]: @@ -379,22 +411,89 @@ 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) - else: - from huggingface_hub import snapshot_download + 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. - # A store is a directory of small files, so fetch it in one call. - folder = snapshot_download( + 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=getattr(self, "_token", None), - allow_patterns=[f"{path}/*"], + token=token, ) - local = os.path.join(folder, path) - if not os.path.isdir(local): - raise FileNotFoundError(f"The Zarr store '{path}' is not in the dataset.") - return local + + 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] @@ -406,13 +505,18 @@ def _read_raster(self, layer: str, county: str, year: int, month: Optional[int] 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: - fill = np.nan if np.issubdtype(np.dtype(src.dtypes[0]), np.floating) else (src.nodata or 0) - data, transform = rasterio.mask.mask(src, [geometry], crop=True, nodata=fill) + # 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": src.nodata} + 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) @@ -422,9 +526,7 @@ def _read_raster(self, layer: str, county: str, year: int, month: Optional[int] ) def _read_monthly(self, layer, county, year, months, geometry) -> xr.DataArray: - 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}.") + 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") @@ -455,9 +557,8 @@ def _as_list(value) -> list: return [value] if isinstance(value, str) else list(value) -def _years_list(years: YearSpec, available: pd.Series) -> List[int]: - if isinstance(years, int): - return [years] - if isinstance(years, tuple) and len(years) == 2: - return [y for y in available.unique() if years[0] <= y <= years[1]] - return [int(y) for y in years] +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/tests/ag_stats/calicropyield/conftest.py b/tests/ag_stats/calicropyield/conftest.py index 9167e8fd..bd675eb1 100644 --- a/tests/ag_stats/calicropyield/conftest.py +++ b/tests/ag_stats/calicropyield/conftest.py @@ -101,6 +101,7 @@ def cali_root(tmp_path_factory): } ).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]}} diff --git a/tests/ag_stats/calicropyield/test_calicropyield_catalog.py b/tests/ag_stats/calicropyield/test_calicropyield_catalog.py index b5957f8c..670e7683 100644 --- a/tests/ag_stats/calicropyield/test_calicropyield_catalog.py +++ b/tests/ag_stats/calicropyield/test_calicropyield_catalog.py @@ -32,6 +32,18 @@ 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)): diff --git a/tests/ag_stats/calicropyield/test_calicropyield_loader.py b/tests/ag_stats/calicropyield/test_calicropyield_loader.py index cf672481..5930a9d3 100644 --- a/tests/ag_stats/calicropyield/test_calicropyield_loader.py +++ b/tests/ag_stats/calicropyield/test_calicropyield_loader.py @@ -10,7 +10,7 @@ from shapely.geometry import box -from agml.ag_stats.calicropyield import DEFAULT_REPO_ID, CaliCropYieldLoader +from agml.ag_stats.calicropyield import DEFAULT_REPO_ID, CaliCropYieldLoader, DownloadError from .calicropyield_fixtures import CDL, LANDSAT_BANDS, RES @@ -21,6 +21,13 @@ 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)) @@ -33,8 +40,7 @@ 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, monkeypatch): - monkeypatch.delenv("AGML_CALICROPYIELD_PATH", raising=False) + def test_defaults_to_hub(self, hub): loader = CaliCropYieldLoader() assert loader.repo_id == DEFAULT_REPO_ID and loader.root is None @@ -80,6 +86,18 @@ def test_crop_mask_default_is_cropland(self, cali): 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") @@ -99,8 +117,7 @@ def test_geometry_crops(self, cali): assert (cdl.values == 54).all() def test_geometry_fills_floats_with_nan(self, cali): - triangle = {"type": "Polygon", "coordinates": [[[-122.0, 38.6], [-122.0 + 4 * RES, 38.6], [-122.0, 38.6 - 4 * RES], [-122.0, 38.6]]]} - et = cali.load_et("Yolo", 2020, months=[1], geometry=triangle) + 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): @@ -169,6 +186,10 @@ 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] @@ -218,25 +239,45 @@ def test_missing_files_are_skipped(self, cali): # ── Hugging Face Hub ────────────────────────────────────────────────────────── class FakeHub: - """Stands in for `huggingface_hub`, serving the fixture dataset from a folder.""" + """Stands in for `huggingface_hub`, serving the fixture dataset as one commit.""" + + COMMIT = "0123456789abcdef0123456789abcdef01234567" def __init__(self, cali_root, tmp_path): - self.folder = tmp_path / "snapshot" + # 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.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) - self.downloads.append(filename) return str(self.folder / filename) - def snapshot_download(self, repo_id, repo_type, revision, cache_dir, token, allow_patterns): - self.downloads.extend(allow_patterns) - return str(self.folder) + 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 @@ -246,7 +287,7 @@ def hub(cali_root, tmp_path, monkeypatch): 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, "snapshot_download", fake.snapshot_download) + monkeypatch.setattr(huggingface_hub, "list_repo_tree", fake.list_repo_tree) return fake @@ -263,12 +304,68 @@ def test_yield(self, hub): def test_zarr_store(self, hub): ds = CaliCropYieldLoader().load_soil("Yolo") assert "soc0_100" in ds - assert hub.downloads == ["counties/Yolo/soil/2020/Yolo_soil.zarr/*"] + 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) - def test_pickle_keeps_repo(self, hub): - clone = pickle.loads(pickle.dumps(CaliCropYieldLoader(revision="abc123"))) - assert clone.repo_id == DEFAULT_REPO_ID and clone.revision == "abc123" + +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])