Metadata-Version: 2.4
Name: agrometpy
Version: 0.9.0
Summary: Scientific Agro-Meteorology for Python
Author-email: Deep Mohan Mahala <deep.mohan@icar.org.in>
Maintainer-email: Deep Mohan Mahala <deep.mohan@icar.org.in>
License-Expression: MIT
Project-URL: Homepage, https://github.com/deep-mahala/AgroMetPy
Project-URL: Repository, https://github.com/deep-mahala/AgroMetPy
Project-URL: Issues, https://github.com/deep-mahala/AgroMetPy/issues
Project-URL: Documentation, https://github.com/deep-mahala/AgroMetPy/tree/main/docs
Project-URL: Changelog, https://github.com/deep-mahala/AgroMetPy/blob/main/CHANGELOG.md
Keywords: agriculture,agrometeorology,meteorology,weather,climate,python,crop,research,climate-analysis,feature-engineering
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Education
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26
Requires-Dist: pandas>=2.2
Requires-Dist: requests>=2.32
Requires-Dist: openpyxl>=3.1
Requires-Dist: matplotlib>=3.9
Requires-Dist: scipy>=1.13
Requires-Dist: PyYAML>=6.0
Requires-Dist: statsmodels>=0.14
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: black>=24.0; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "dev"
Provides-Extra: parquet
Requires-Dist: pyarrow>=15.0; extra == "parquet"
Provides-Extra: netcdf
Requires-Dist: xarray>=2024.1; extra == "netcdf"
Requires-Dist: netCDF4>=1.6; extra == "netcdf"
Provides-Extra: maps
Requires-Dist: cartopy>=0.23; extra == "maps"
Requires-Dist: geopandas>=0.14; extra == "maps"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.6; extra == "docs"
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Provides-Extra: notebooks
Requires-Dist: jupyterlab>=4.2; extra == "notebooks"
Requires-Dist: ipykernel>=6.29; extra == "notebooks"
Dynamic: license-file

# AgroMetPy

[![tests](https://github.com/deep-mahala/AgroMetPy/actions/workflows/tests.yml/badge.svg)](https://github.com/deep-mahala/AgroMetPy/actions/workflows/tests.yml)

> **Scientific agro-meteorology for Python**

AgroMetPy is an open-source Python toolkit for **scientifically defensible
agro-meteorological research**: acquiring weather data, establishing what those
data represent, checking their quality, computing documented indices, aligning
them with field-trial observations and analysing the results with
design-aware statistics.

```text
weather provider → standardization → provenance → QC → cross-provider check
      → meteorological variables → agro-meteorological indices
      → alignment with crop / experimental observations → statistics → research outputs
```

It is **crop-, region- and provider-independent**. Maize, wheat, a Punjab
station or NASA POWER are examples, never assumptions built into the code.

**Current version: 0.9.0 (alpha).** 0.9.0 adds a drift check for long
records (a trend or step in the yearly difference between two sources), says
"planned, not implemented" for providers such as CHIRPS, and documents how to
choose a data source; no computed result changes. 0.8.1 aligned frost days and
tropical nights with ETCCDI's strict definitions. 0.8.0 contained
**breaking changes** in the plotting API: some column arguments are now
required, the ET plots default to the standard `ETo` column, and two
unimplemented violin classes and an unused parameter were removed. 0.7.0 made
crop, region and site parameters explicit and corrected two reference-ET
formulas. See [CHANGELOG.md](https://github.com/deep-mahala/AgroMetPy/blob/main/CHANGELOG.md).

---

## Design principles

* **Parameters are supplied, not assumed.** A base temperature, a heat-stress
  threshold, a wet-day threshold, a canopy extinction coefficient or a site
  elevation depends on the crop, the region or the site. AgroMetPy never
  defaults them: you pass them, from a source you can cite. Constants that
  *define* a method (e.g. FAO-56 grass albedo 0.23, ETCCDI frost days at 0 °C,
  the Priestley–Taylor α = 1.26) keep their defaults, and each docstring names
  where the value comes from.
* **One method, one implementation, one reference.** Formulas live in
  `agrometpy.indices`, summaries and inference in `agrometpy.statistics`, and
  workflows in `agrometpy.climate`. Each formula has a single implementation
  that can be cited and tested against published reference values.
* **Clear boundaries.** *Standardization* changes representation only;
  *provenance* records where data came from; *QC* reports findings without
  changing data; *crosscheck* compares independently sourced datasets without
  merging them or ranking providers.
* **Experimental units are preserved.** Crop observations are plot-level
  records. Replicates are never averaged silently; reduction to treatment
  means, and ANOVA with the right error strata, are explicit steps.

---

## Installation

AgroMetPy requires **Python ≥ 3.10**. Install it from PyPI:

```bash
pip install agrometpy
pip install "agrometpy[netcdf,parquet,maps]"   # with optional extras
```

Or install from source, for development:

```bash
git clone https://github.com/deep-mahala/AgroMetPy.git
cd AgroMetPy
pip install -e .              # core
pip install -e ".[dev]"       # + test / lint tooling
pip install -e ".[parquet]"   # + Parquet I/O (pyarrow)
pip install -e ".[netcdf]"    # + NetCDF I/O (xarray, netCDF4)
pip install -e ".[maps]"      # + map plots (cartopy, geopandas)
```

To build a wheel: `python -m build`, then `pip install dist/agrometpy-0.9.0-py3-none-any.whl`.

---

## Quick start

All snippets below were run against live NASA POWER and Open-Meteo data for the
0.8.0 release.

### 1. Weather from two providers, QC and cross-provider comparison

```python
from agrometpy.datasets import crosscheck, download_nasa_power, download_open_meteo
from agrometpy.qc import validate_weather

LAT, LON = 28.61, 77.21          # any site: coordinates in decimal degrees
START, END = "2024-01-01", "2024-03-31"

nasa = download_nasa_power(latitude=LAT, longitude=LON, start=START, end=END)
om = download_open_meteo(latitude=LAT, longitude=LON, start=START, end=END)

qc = validate_weather(nasa)
print(qc.status)                  # PASS / WARNING / ERROR; the data are not modified

report = crosscheck([nasa, om], labels=["NASA POWER", "Open-Meteo"])
print(report.status)              # agreement / disagreement / comparability, never a "winner"
```

Both downloads return the standard schema (below). Per-variable provenance is
in `df.attrs["variables"]`: native name and unit, conversion, measurement
height, temporal aggregation and source product.

For records of a decade or more, check whether the difference between two
sources drifts or jumps before you trust a trend from either:

```python
from agrometpy.datasets import CrossCheckConfig
from agrometpy.statistics import trend_and_change_point

report = crosscheck([om, nasa], labels=["Open-Meteo", "NASA POWER"],
                    config=CrossCheckConfig(annual_breakdown=True))
table = report.annual_differences("Tmax")       # one row per year: mean of NASA POWER − Open-Meteo
result = trend_and_change_point(table["mean_difference"], x=table.index)
print(result["sens_slope"]["slope"], result["pettitt"]["change_after"])
```

At Ludhiana, 1991–2024, this gives a drift of −0.74 °C per decade in
NASA POWER − Open-Meteo `Tmax`, with a step after 2005. See
[Choosing a data source](https://github.com/deep-mahala/AgroMetPy/blob/main/docs/providers/README.md#choosing-a-data-source-for-your-analysis).

### 2. Indices, with the parameters stated

```python
from agrometpy.indices import extraterrestrial_radiation, gdd, hargreaves_et0, modified_gdd

TBASE = 10.0                      # the crop's base temperature, from a cited source

daily_gdd = gdd(nasa["Tmax"], nasa["Tmin"], base_temperature=TBASE)       # McMaster & Wilhelm Method 1
daily_mgdd = modified_gdd(nasa["Tmax"], nasa["Tmin"],
                          base_temperature=TBASE, upper_temperature=30.0)  # Method 2, capped

ra = extraterrestrial_radiation(LAT, nasa["Date"].dt.day_of_year)            # MJ m⁻² day⁻¹
et0 = hargreaves_et0(nasa["Tmin"], nasa["Tmax"], nasa["Tmean"], ra)         # FAO-56 Eq. 52
```

Leaving out a crop, region or site parameter raises `TypeError`; there is no
hidden default.

### 3. Statistics

```python
from agrometpy.statistics import consecutive_dry_days, monthly_summary

cdd = consecutive_dry_days(nasa["Rain"], threshold=1.0, missing="break")   # ETCCDI CDD, 1 mm wet day
monthly = monthly_summary(nasa, variables=["Tmax", "Tmin", "Rain"])
```

`missing="break"` ends a spell at a missing day; the default `"raise"` refuses
data with gaps.

### 4. A model-ready feature table

```python
from agrometpy.features import FeatureConfig, generate_features

cfg = FeatureConfig(gdd_base_temperature=TBASE)            # the crop parameter is required
features = generate_features(nasa.assign(PET=et0), cfg)    # PET from the method you chose
```

A provider download goes in as it is: a frame without `Location` is one site,
and only the columns the enabled steps read are required. The PET step never
computes PET itself. Supply a `PET` column, set `pet_column="ETo"` to use
Open-Meteo's FAO-56 reference ET, or set `enable_pet=False`.

Gaps in the weather data are kept, never filled. A missing day gives missing
features on that day: NaN for values, `<NA>` for flags (nullable `boolean`) and
for spell counters (the spell ends at the gap). Per-column counts are in
`FeatureEngineer.summary.missing_values`. Rolling sums (`RainSum7`, `PETSum30`, …)
add the days that have data by default. Set `complete_window_sums=True` to get
NaN unless every day in the window has data.

### 5. Field-trial observations and a design-aware ANOVA

```python
import pandas as pd
from agrometpy.observations import run_anova, summarize_by_treatment, validate_observations

obs = pd.DataFrame({
    "experiment_id": "E1",
    "plot_id": [f"P{i}" for i in range(1, 10)],
    "date": "2024-04-15",
    "variable": "grain_yield",
    "value": [5.1, 5.6, 4.7, 6.2, 6.1, 5.6, 6.4, 7.2, 6.6],
    "unit": "t/ha",
    "treatment_id": ["N0"] * 3 + ["N60"] * 3 + ["N120"] * 3,
    "block": ["B1", "B2", "B3"] * 3,
})

validate_observations(obs).status                                 # plot-level QC
means = summarize_by_treatment(obs, variables=["grain_yield"])    # explicit reduction: mean, SE, CI
table = run_anova(obs, variables=["grain_yield"], block="block")  # RCBD: Treatment F = 27.0, p = 0.005
```

Observations can be aligned with weather (accumulated GDD, cumulative radiation,
water balance or photothermal quotient from sowing to each observation date)
using `align_observations`, which takes the crop parameters explicitly.

---

## What is in the package

| Subpackage | Purpose | Public names |
| --- | --- | ---: |
| `agrometpy.datasets` | Providers (NASA POWER, Open-Meteo), standardization, provenance, `crosscheck` | 74 |
| `agrometpy.io` | Read/write CSV, Excel, Parquet, NetCDF; column standardization | 41 |
| `agrometpy.qc` | Weather quality control (`validate_weather` → PASS / WARNING / ERROR findings) | 4 |
| `agrometpy.indices` | Scientific formulas: thermal time, ET0, radiation, humidity, wind, moisture, stress, crop indices | 129 |
| `agrometpy.statistics` | Descriptive, aggregation, climatology, correlation, extremes (ETCCDI-style), trends (Mann–Kendall, Sen's slope), ANOVA tables | 78 |
| `agrometpy.observations` | Crop / experimental observations: ingest, schema, provenance, QC, weather alignment, treatment summaries, ANOVA workflows | 35 |
| `agrometpy.climate` | DataFrame-level workflows and summaries composed from `indices` and `statistics`; `ClimateAnalyzer` | 219 |
| `agrometpy.plotting` | Time-series, distribution, relationship, spatial and publication figures | 488 |
| `agrometpy.features` | Wide, model-ready feature table (rolling windows, flags, calendar encodings) | 7 |

The top-level `agrometpy` namespace exposes only `__version__`; import from the
subpackages.

### Selected methods and their references

* **Reference ET:** FAO-56 Penman–Monteith (`fao56_et0`, `penman_monteith_et0`;
  verified against FAO-56 Example 18), Hargreaves (FAO-56 Eq. 52),
  Priestley & Taylor (1972).
* **Thermal time:** GDD as McMaster & Wilhelm (1997) Method 1 (`gdd`) and Method 2
  with an upper threshold (`modified_gdd`); Baskerville–Emin and double-sine
  methods; Ontario corn heat units; photothermal (Nuttonson 1955) and
  heliothermal units.
* **Moisture:** dry/wet-spell run lengths and ETCCDI CDD/CWD; aridity index
  (UNEP 1992); Selyaninov hydrothermal coefficient; water balance.
* **Experimental designs** (`observations` / `statistics.anova`): one-way, RCBD,
  factorial (Type I/II/III), split-plot, split-split-plot, strip-plot,
  strip-split-plot, CRD split-plot variants, and nested ANOVA tables. Each uses
  its own error strata.

---

## Data model

### Standard weather dataset

| Column | Unit | Column | Unit |
| --- | --- | --- | --- |
| `Date` | date | `RH` / `RHmax` / `RHmin` | % |
| `Location` | text | `Wind` | m s⁻¹ |
| `Latitude`, `Longitude` | decimal degrees | `Solar` | MJ m⁻² day⁻¹ |
| `Elevation` | m | `Sunshine` | h |
| `Tmax`, `Tmin`, `Tmean` | °C | `Pressure` | kPa |
| `Rain` | mm | `PET`, `ETo` | mm day⁻¹ |

Not every column is needed; each function checks the columns it uses. Full
specification: [docs/standard-weather-dataset.md](https://github.com/deep-mahala/AgroMetPy/blob/main/docs/standard-weather-dataset.md).

### Crop observations

Long, plot-atomic records. The required columns are `experiment_id`, `plot_id`,
`date` or `growth_stage`, `variable`, `value` and `unit`. Optional design and
metadata columns include `treatment_id`, `block`, `replication`, `crop`,
`cultivar` and `sowing_date`. `read_observations` maps CSV/Excel layouts, long
or wide, onto this schema.

---

## Known limitations

* **Alpha.** Public APIs can still change between minor versions (0.7.0 and 0.8.0 did).
* **Plotting** is large. The weather, crop and temporal plots are tested on real
  provider, gappy and feature data (STEP 14). Many generic relationship and
  spatial classes have only smoke coverage.
* **Heliothermal units:** the HTU formula is standard, but its primary source
  (usually given as Rajput 1980) is cited inconsistently and is not verified;
  cite the source your analysis follows.
* **Gridded weather and long-term trends.** NASA POWER `Tmax` warmed less
  than nearby stations at every one of 11 sites tested (0.1–1.3 °C per
  decade, in steps), and its rainfall has site-specific steps. Open-Meteo
  drifts at some sites too. Check decade-scale trends against a station or
  gauge-based record. See
  [Choosing a data source](https://github.com/deep-mahala/AgroMetPy/blob/main/docs/providers/README.md#choosing-a-data-source-for-your-analysis).
* **Institutional observation sources** (e.g. AICRP, CIMMYT) have no adapters
  yet. No suitable source has been identified.

---

## Testing

```bash
pip install -e ".[dev,netcdf,parquet]"
pytest -q -m "not network"     # everything except live provider calls
pytest -q -m network           # the 9 tests that call NASA POWER live
```

The suite has **3,737 tests**. The NetCDF round-trip tests are skipped
when the `netcdf` extra is not installed. CI (GitHub Actions,
`.github/workflows/tests.yml`) runs the non-network tests on Python 3.10–3.14
(Linux) and 3.12 (Windows) on every push and pull request, builds and checks
the sdist / wheel, and runs the live provider tests weekly. Reference tests check against published worked
examples (FAO-56 Examples 8 and 18, McMaster & Wilhelm Method 1 vs 2), and
architecture tests enforce package boundaries, single implementations and the
no-silent-default rule.

---

## Documentation

* [docs/standard-weather-dataset.md](https://github.com/deep-mahala/AgroMetPy/blob/main/docs/standard-weather-dataset.md): the weather schema
* [docs/providers/](https://github.com/deep-mahala/AgroMetPy/tree/main/docs/providers/): what each weather provider is, the
  evidence on each, and how to choose one for your analysis
* [docs/indices/](https://github.com/deep-mahala/AgroMetPy/tree/main/docs/indices/): index definitions and APIs
* [docs/adr/](https://github.com/deep-mahala/AgroMetPy/tree/main/docs/adr/): architecture decision records (scientific scope,
  package boundaries, provider authority, crop and region independence)
* [docs/architecture/](https://github.com/deep-mahala/AgroMetPy/tree/main/docs/architecture/): step-by-step audit and
  implementation records (the `STEP12*` files cover the 0.7.0 changes)
* [CHANGELOG.md](https://github.com/deep-mahala/AgroMetPy/blob/main/CHANGELOG.md)

---

## Project layout

```text
AgroMetPy/
├── agrometpy/
│   ├── datasets/       providers, standardization, provenance, crosscheck
│   ├── io/             file readers / writers
│   ├── qc/             weather quality control
│   ├── indices/        scientific formulas
│   ├── statistics/     summaries, climatology, extremes, trends, ANOVA
│   ├── observations/   crop / experimental observations
│   ├── climate/        DataFrame workflows and summaries
│   ├── plotting/       figures
│   ├── core/           constants, validation, exceptions, config
│   ├── features.py     feature engineering
│   └── utils.py
├── tests/
├── docs/
├── validation/
├── CHANGELOG.md · CITATION.cff · CONTRIBUTING.md · CODE_OF_CONDUCT.md · SECURITY.md · LICENSE
└── pyproject.toml
```

---

## Version history

| Version | Milestone |
| --- | --- |
| `v0.1.0` | Foundation |
| `v0.2.0` | Feature engineering |
| `v0.3.0` | Plotting subsystem |
| `v0.4.0` | Datasets public API |
| `v0.5.0` | Climate indices public API |
| `v0.6.0` | Statistics subsystem |
| `v0.7.0` | Provenance, Open-Meteo and crosscheck; crop observations and ANOVA designs; `climate` ↔ `indices` reconciliation (corrected ET0, required parameters) |
| `v0.8.0` | Plotting audit and fixes (gaps drawn, no global style changes, Weibull duration curves); plotting API aligned with the package's own outputs; `netcdf` and `maps` extras |
| `v0.8.1` | ETCCDI frost-day / tropical-night boundaries; IMD and HTU reference checks; CI; pandas 3.1 compatibility |
| `v0.9.0` | Drift check for long records; planned-provider error; provider admission audit and data-source guidance; release workflow, citation metadata; first PyPI release |

---

## Citation

If AgroMetPy contributes to your research, please cite it using
[CITATION.cff](https://github.com/deep-mahala/AgroMetPy/blob/main/CITATION.cff), and report the methods and parameters you used
(e.g. "GDD, McMaster & Wilhelm Method 1, Tbase = 8 °C").

## Contributing

Bug reports, scientific-methodology corrections and contributions are welcome.
See [CONTRIBUTING.md](https://github.com/deep-mahala/AgroMetPy/blob/main/CONTRIBUTING.md). A new method needs a cited formulation
and a reference test.

## License

MIT. See [LICENSE](https://github.com/deep-mahala/AgroMetPy/blob/main/LICENSE).

## Author

**Deep Mohan Mahala**, ICAR – Indian Institute of Maize Research ·
[deep.mohan@icar.org.in](mailto:deep.mohan@icar.org.in)
