Metadata-Version: 2.4
Name: ObsChainCC
Version: 0.1.0
Summary: Reproducible precipitation observation-chain and C-C scaling diagnostics
Author: xiongyuup
License-Expression: MIT
Project-URL: Homepage, https://github.com/xiongyuup/ObsChainCC
Project-URL: Repository, https://github.com/xiongyuup/ObsChainCC
Project-URL: Issues, https://github.com/xiongyuup/ObsChainCC/issues
Keywords: precipitation,Clausius-Clapeyron scaling,extremes,observation chains,dew point temperature,bootstrap
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: scipy>=1.10
Requires-Dist: statsmodels>=0.14
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pytest-cov>=5; extra == "test"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Dynamic: license-file

# ObsChainCC

[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

**ObsChainCC** is the reusable analysis package accompanying the study
*Observation Chains Reshape the Inferred Warming Sensitivity of Hourly Precipitation Extremes*.

> This package provides reproducible tools for quantifying how precipitation observation chains influence inferred extreme precipitation-temperature scaling.

The package implements the statistical definitions used in the study without
shipping station observations, proprietary inputs, manuscript working files, or
figure-specific paths. Functions accept NumPy arrays, pandas time series, and
simple product mappings, so the methods can be applied to independent observing
systems.

## Scientific background

Extreme hourly precipitation is often summarized by a conditional scaling rate
with temperature. In this study, the conditioning variable is dew-point
temperature, and the response is a high conditional precipitation percentile.
Different stages of a precipitation observation chain (radar-only retrievals,
successive bias-adjustment products, and gauge analyses) can produce different
scaling rates even for nominally matched events.

ObsChainCC separates three levels of the analysis:

1. **Hourly-event level:** temporal matching and ALL, WET, COMMON WET, or
   STRICT NO-HAIL sampling.
2. **Site-product level:** conditional quantiles and the scaling rate
   \(\beta\).
3. **Cross-product/site level:** \(S_3\), \(S_4\), observation-chain
   transformations, hotspot overlap, bootstrap inference, and warming
   propagation.

Keeping these levels explicit prevents row-wise resampling from being used when
the inferential unit is a site and prevents matched-event controls from being
confused with independent product-specific wet samples.

## Installation

After a distribution release is published on PyPI, install it with:

```bash
pip install ObsChainCC
```

The initial public source release can be installed directly from GitHub:

```bash
pip install git+https://github.com/xiongyuup/ObsChainCC.git
```

For development and tests:

```bash
git clone https://github.com/xiongyuup/ObsChainCC.git
cd ObsChainCC
python -m pip install -e ".[test]"
python -m pytest
```

## Quick start

```python
import numpy as np
from obschaincc import fit_cc_scaling

# One-dimensional, aligned hourly arrays.
precipitation = np.asarray(...)  # mm h^-1
dew_point_temperature = np.asarray(...)  # degrees C

result = fit_cc_scaling(
    precipitation,
    dew_point_temperature,
    percentile=99.0,
    quantile_sample="wet",
)

print(result.beta)  # % K^-1
print(result.confidence_interval)  # regression-based 95% CI
print(result.r_squared)
print(result.stable, result.unstable_reason)
```

The complete synthetic examples are:

```bash
python examples/example_scaling.py
python examples/example_product_compare.py
```

They generate their own data and require no manuscript source data.

## Core methods

### 1. Conditional precipitation-temperature scaling

For temperature bin \(b\), ObsChainCC estimates the requested conditional
precipitation percentile \(Q_{q,b}\). The default paper bins are
\([-25,35]\ ^\circ\mathrm{C}\) with width 2 degrees C. The fit is

\[
\log Q_{q,b} = \alpha + \gamma T_{d,b} + \varepsilon_b,
\]

using `sqrt(n_wet)` as the `numpy.polyfit` weight. Because NumPy applies this
factor to the residual before squaring, the effective weighted-squares weight is
\(n_{\mathrm{wet},b}\). The exact reported scaling rate is

\[
\beta = 100\{\exp(\gamma)-1\}\quad (\%\ \mathrm{K}^{-1}),
\]

not the small-slope approximation \(100\gamma\). The confidence interval is
formed on \(\gamma\) using its weighted-regression covariance and then passed
through the same exponential transformation.

Paper-default site-product quality control requires:

- valid precipitation in 0--500 mm h\(^{-1}\);
- a wet threshold of 0.1 mm h\(^{-1}\);
- at least 30 wet hours in every fitted temperature bin;
- at least six fitted bins;
- at least 12 degrees C between the lowest and highest fitted bin centers;
- \(|\beta|\leq 30\%\ \mathrm{K}^{-1}\);
- beta confidence-interval width no greater than 20 percentage points per K;
- unweighted \(R^2\) of the log-quantile fit at least 0.2.

Whole-sample support thresholds are percentile specific: 100 samples for P75,
P90 and P95; 300 for P99; 500 for P99.5; and 1000 for P99.9. An unsupported
percentile remains available if `min_total_samples` is supplied explicitly.

Relevant API:

- `conditional_quantiles`
- `fit_cc_scaling` / `conditional_scaling`
- `log_slope_to_beta`
- `beta_to_log_slope`

### 2. Sampling controls

`sampling_mask` and `apply_sampling_control` implement four explicit sampling
definitions:

| Mode | Retained hourly observations |
|---|---|
| `ALL` | Complete, physically valid target/product hours; zeros retained. |
| `WET` | `ALL` plus target precipitation >= 0.1 mm h\(^{-1}\). |
| `COMMON_WET` | All supplied products simultaneously >= the wet threshold. |
| `STRICT_NO_HAIL` | `COMMON_WET` plus a valid `no_hail=True` classification. |

Missing hydrometeor classification must be encoded as false/not eligible. It is
never silently interpreted as no hail. The package consumes a no-hail flag; it
does not prescribe a radar-HCA file format.

`match_hourly_series` aligns pandas time series exactly or by a user-specified
nearest-time tolerance. It does not interpolate physical values.

### 3. Multi-product comparison

For a selected product set \(\mathcal P_k\),

\[
S_k = \max_{p\in\mathcal P_k}\beta_p-
      \min_{p\in\mathcal P_k}\beta_p.
\]

`compute_s3` and `compute_s4` implement the three- and four-product versions.
The canonical modern four-product order is `RadarOnly`, `PASS1`, `PASS2`, and
`StageIV`; user-defined product names can also be supplied.

### 4. State-dependent observation-chain transformation

For a matched product pair \(i,j\), the package defines

\[
D_t=\log\frac{P_{i,t}+\epsilon}{P_{j,t}+\epsilon},\qquad
I_{\mathrm{ref},t}=\frac{1}{2}\{\log P_{i,t}+\log P_{j,t}\},
\]

on COMMON-WET hours, with \(\epsilon=10^{-6}\). The fixed magnitude offset is

\[
A=\operatorname{median}(D_t),
\]

and the state-dependence diagnostic is the dew-point coefficient in a Huber
robust regression,

\[
D_t=a+\lambda_{T,\mathrm{cond}}(T_{d,t}-\bar T_d)
       +\lambda_I(I_{\mathrm{ref},t}-\bar I_{\mathrm{ref}})+e_t.
\]

Use `fit_observation_chain_contrast`. The paper predictor QC defaults are at
least 1000 COMMON-WET hours and at least 12 degrees C of dew-point support.

### 5. Cross-epoch agreement and hotspot recurrence

`cross_epoch_analysis` computes Spearman rank correlation on paired finite sites
and selects an exact fixed top-\(k\) set in each epoch, with
\(k=\lceil f n\rceil\). It reports both:

\[
J=\frac{|H_L\cap H_M|}{|H_L\cup H_M|}
\]

(Jaccard overlap) and

\[
R=\frac{|H_L\cap H_M|}{|H_L|}
\]

(Legacy-to-Modern recurrence). These quantities have different denominators and
should not be described interchangeably.

Additional hotspot tools provide percentile ranks, cross-product rank spread,
and product-pair Jaccard matrices.

### 6. Warm-season modulation

For a scaling-spread diagnostic \(S\), the centered warm-season modulation is

\[
C=S_{\mathrm{JJAS}}-S_{\mathrm{annual}}.
\]

Use `warm_season_modulation`. The caller remains responsible for fitting annual
and JJAS beta values with identical product and quality-control definitions.

### 7. Warming propagation

A scaling rate is propagated to a hypothetical temperature increment by

\[
\mathcal A_p(\Delta T)=100\left[\left(1+\frac{\beta_p}{100}\right)^{\Delta T}-1\right].
\]

The four-product propagation spread is

\[
W_4(\Delta T)=\max_p \mathcal A_p(\Delta T)-
               \min_p \mathcal A_p(\Delta T).
\]

Use `warming_amplification` (`A`) and `w4` (`W4`). These are diagnostic
propagations of fitted observation-chain differences, not future climate-model
projections.

### 8. Uncertainty and randomization

`bootstrap_ci` returns the actual bootstrap distribution in addition to the
point statistic and equal-tailed interval. If `clusters` are supplied, unique
clusters are sampled with replacement and every row from each sampled cluster
is retained. This supports site-cluster resampling of repeated product-pair rows.

`paired_bootstrap_ci` preserves pairs. `permutation_test` implements either
unpaired label permutation or paired sign flips and reports the finite Monte
Carlo p value

\[
p=\frac{1+\#\{T^{\mathrm{perm}}\text{ at least as extreme as }T^{\mathrm{obs}}\}}
        {B+1}.
\]

No function fabricates a distribution from a point estimate and confidence
interval.

## API overview

| Module | Main public functions |
|---|---|
| `obschaincc.quantile` | `conditional_quantiles`, `temperature_bin_edges` |
| `obschaincc.scaling` | `fit_cc_scaling`, `log_slope_to_beta`, `beta_to_log_slope` |
| `obschaincc.preprocessing` | `match_hourly_series`, `sampling_mask`, `apply_sampling_control` |
| `obschaincc.products` | `compute_s3`, `compute_s4`, `product_spread`, `fit_observation_chain_contrast`, `warm_season_modulation` |
| `obschaincc.uncertainty` | `bootstrap_ci`, `paired_bootstrap_ci`, `permutation_test` |
| `obschaincc.propagation` | `warming_amplification`, `warming_spread`, `w4` |
| `obschaincc.hotspot` | `cross_epoch_analysis`, `top_fraction_mask`, `hotspot_overlap`, `hotspot_jaccard_matrix`, `product_rank_spread` |

All result objects are frozen dataclasses. Array-valued diagnostics remain
available for independent plotting and audit.

## Correspondence with the article

| Article analysis | Package implementation |
|---|---|
| Site/product conditional percentile curves and beta | `conditional_quantiles`, `fit_cc_scaling` |
| Three- and four-product spread | `compute_s3`, `compute_s4` |
| ALL/WET/COMMON-WET/no-hail controls | `sampling_mask`, `apply_sampling_control` |
| Legacy--Modern rank agreement and hotspot recurrence | `cross_epoch_analysis`, `hotspot_overlap` |
| Warm-season centered shift | `warm_season_modulation` |
| Fixed magnitude offset and state dependence | `fit_observation_chain_contrast` |
| Bootstrap confidence intervals | `bootstrap_ci`, `paired_bootstrap_ci` |
| Permutation/randomization inference | `permutation_test` |
| Hypothetical warming amplification and W4 | `warming_amplification`, `w4` |
| Product-specific hotspot agreement | `hotspot_jaccard_matrix`, `product_rank_spread` |

Manuscript figures also contain fixed cohorts, geographic selections, locked
fold assignments, and source datasets. Those article-specific inputs are not
embedded in this general-purpose package. Reproducing an exact published number
requires the corresponding source data and cohort definition in addition to
these methods.

## Reproducibility recommendations

- Preserve timestamps and site identifiers before any filtering.
- Record the product set used to construct `COMMON_WET`.
- Fit annual and seasonal estimates using the same percentile and QC settings.
- Resample sites, not individual product-pair rows, when a site is the
  inferential unit.
- Keep models being compared within the same bootstrap draw.
- Store raw bootstrap/permutation draws when they are used for distribution
  plots.
- Report both point estimates and eligibility counts.
- Set and report `random_state`; paper-oriented defaults use `20260819`.

## Data and code availability

ObsChainCC contains analysis methods and synthetic examples only. It does not
redistribute precipitation products, radar hydrometeor classifications, station
metadata, or manuscript working data. Users must obtain those data from their
original providers and comply with the applicable licenses. The public code is
platform independent and contains no absolute or personal filesystem paths.

## Testing

The test suite covers:

- exact beta/log-slope conversion;
- recovery of a known synthetic conditional scaling rate;
- ALL/WET/COMMON-WET/STRICT-NO-HAIL masks;
- S3/S4 and state-dependent pair diagnostics;
- bootstrap, cluster bootstrap, paired bootstrap, and permutation inference;
- exact warming propagation and W4;
- cross-epoch recurrence and Jaccard overlap.

Run:

```bash
python -m pytest
```

## License

ObsChainCC is released under the [MIT License](LICENSE).

## Citation

If this software contributes to a publication, cite both the associated article
and the archived software release. Citation metadata are provided in
[`CITATION.cff`](CITATION.cff).
