wrtds-py 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wrtds_py-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manuel Álvarez Chaves
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: wrtds-py
3
+ Version: 1.0.0
4
+ Summary: Python implementation of the WRTDS and WRTDS-Kalman water quality models, adapted from the USGS EGRET R package
5
+ Keywords: WRTDS,WRTDS-Kalman,EGRET,water quality,hydrology,concentration,flux,time series
6
+ Author: Manuel Alvarez Chaves
7
+ Author-email: Manuel Alvarez Chaves <malvarez062@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Hydrology
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: numpy>=2.4.6
19
+ Requires-Dist: pandas>=3.0.3
20
+ Requires-Dist: scipy>=1.18.0
21
+ Requires-Dist: tqdm>=4.68.4
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/Basu-Lab/WRTDS-Py
24
+ Project-URL: Repository, https://github.com/Basu-Lab/WRTDS-Py
25
+ Project-URL: Issues, https://github.com/Basu-Lab/WRTDS-Py/issues
26
+ Project-URL: Changelog, https://github.com/Basu-Lab/WRTDS-Py/blob/main/CHANGELOG.md
27
+ Project-URL: Documentation, https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/methodology.md
28
+ Description-Content-Type: text/markdown
29
+
30
+ # wrtds-py
31
+
32
+ [![PyPI version](https://img.shields.io/pypi/v/wrtds-py.svg)](https://pypi.org/project/wrtds-py/)
33
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
34
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
+
36
+ `wrtds-py` is a Python implementation of the **Weighted Regressions on Time, Discharge, and Season (WRTDS)** model, including the **WRTDS-Kalman (WRTDS-K)** autoregressive filter.
37
+
38
+ It is adapted from the official USGS [`EGRET`](https://github.com/DOI-USGS/EGRET) R package.
39
+
40
+ ---
41
+
42
+ ## Status
43
+
44
+ **Current Version: 1.0.0**
45
+
46
+ `wrtds-py` is stable and validated against the USGS `EGRET` R package (v3.0.11) on its reference example (the Choptank River). Releases are published on [PyPI](https://pypi.org/project/wrtds-py/) and archived on Zenodo. See [CHANGELOG.md](https://github.com/Basu-Lab/WRTDS-Py/blob/main/CHANGELOG.md) for the release history.
47
+
48
+ ## Key Features
49
+
50
+ * **Classic WRTDS (`WRTDS`):** Pre-computes the prediction surface. Log-concentration, standard error and concentration are calculated using linear regression where the coefficients are estimated using maximum likelihood considering left-censored data.
51
+ * **WRTDS-Kalman (`WRTDSK`):** Implements a filtering method that smoothes the residuals using an AR(1) process.
52
+
53
+ > Note: WRTDS-Kalman is not actually a Kalman filter in the strictest sense. In Zhang and Hirsch (2019) the authors derive this approach from the theory of Kalman fitering, but a more accurate description is AR(1) smoothing with Monte Carlo simulations for censored samples.
54
+
55
+
56
+ ## Background
57
+
58
+ For a detailed explanation of the underlying statistical methods, including the design matrix of the linear model, left-censored (Tobit) maximum likelihood estimation, weighting functions, and the AR(1) smoother, see [docs/methodology.md](https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/methodology.md).
59
+
60
+
61
+ ## Installation
62
+
63
+ `wrtds-py` requires Python 3.12 or newer and is available on [PyPI](https://pypi.org/project/wrtds-py/).
64
+
65
+ ### Using `uv` (Recommended)
66
+
67
+ ```bash
68
+ uv add wrtds-py
69
+ ```
70
+
71
+ ### Using standard `pip`
72
+
73
+ ```bash
74
+ pip install wrtds-py
75
+ ```
76
+
77
+ ### From source
78
+
79
+ ```bash
80
+ git clone https://github.com/Basu-Lab/WRTDS-Py
81
+ cd WRTDS-Py
82
+ uv sync
83
+ ```
84
+
85
+ ---
86
+
87
+ ## Quickstart
88
+ Also have a look at the [example Jupyter notebook](https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/example.ipynb) for a more detailed demonstration.
89
+
90
+ ### 1. Classic WRTDS
91
+
92
+ ```python
93
+ import pandas as pd
94
+ from wrtds_py import WRTDS
95
+
96
+ # Load discharge (df_q) and water quality (df_wq) data
97
+ # DataFrames must have a DatetimeIndex
98
+ df_q = pd.read_csv("discharge.csv", parse_dates=["Date"], index_col="Date")
99
+ df_wq = pd.read_csv("water_quality.csv", parse_dates=["Date"], index_col="Date")
100
+
101
+ # Initialize and fit the base WRTDS model
102
+ model = WRTDS(
103
+ window_time=7.0, # Half-window for time (years)
104
+ window_discharge=2.0, # Half-window for discharge (log-units)
105
+ window_season=0.5, # Half-window for season (years)
106
+ min_num_obs=50,
107
+ min_num_uncen=30
108
+ )
109
+
110
+ model.fit(df_wq=df_wq, df_q=df_q)
111
+
112
+ # Generate daily predictions
113
+ df_pred = model.predict(df_q)
114
+ print(df_pred[["yHat", "SE", "ConcHat"]].head())
115
+ ```
116
+
117
+ ### 2. WRTDS-Kalman (Autoregressive Filter)
118
+
119
+ ```python
120
+ from wrtds_py import WRTDSK
121
+
122
+ # Pass the fitted base model into the Kalman filter
123
+ kalman = WRTDSK(
124
+ base_model=model,
125
+ rho=0.9, # Daily correlation coefficient (decay factor)
126
+ niter=200, # Monte Carlo iterations (default 200, as in EGRET)
127
+ seed=42 # Seed for reproducibility
128
+ )
129
+
130
+ # Run the filter on the daily discharge record
131
+ df_kalman = kalman.filter(df_wq=df_wq, df_q=df_q)
132
+ print(df_kalman[["ConcHat", "ConcKalman"]].head())
133
+ ```
134
+
135
+ ## Testing & Benchmarking
136
+
137
+ To run the test suite from a source checkout:
138
+
139
+ ```bash
140
+ uv run pytest
141
+ ```
142
+
143
+ `tests/test_r_reference.py` validates the models against USGS `EGRET` v3.0.11 by running it live through `rpy2`, so it requires a working R installation with the `EGRET` package installed. To run only the pure-Python tests:
144
+
145
+ ```bash
146
+ uv run pytest tests/test_components.py tests/test_models.py
147
+ ```
148
+
149
+ ## Citation
150
+
151
+ If you use `wrtds-py` in your research, please cite it using the metadata in [CITATION.cff](https://github.com/Basu-Lab/WRTDS-Py/blob/main/CITATION.cff) (GitHub's "Cite this repository" button generates APA and BibTeX entries from it):
152
+
153
+ > Álvarez Chaves, M. (2026). *wrtds-py: Weighted Regressions on Time, Discharge, and Season in Python* (Version 1.0.0) [Computer software]. https://doi.org/10.5281/zenodo.XXXXXXX <!-- TODO: replace with the Zenodo DOI -->
154
+
155
+ Please also cite the original WRTDS and WRTDS-K publications listed under [References](#references).
156
+
157
+ ## License
158
+
159
+ Distributed under the MIT License. See [`LICENSE`](https://github.com/Basu-Lab/WRTDS-Py/blob/main/LICENSE) for more information.
160
+
161
+ ## References
162
+
163
+ * **Hirsch, R. M., Moyer, D. L., & Archfield, S. A. (2010).** *Weighted Regressions on Time, Discharge, and Season (WRTDS), with an Application to Chesapeake Bay River Inputs*. JAWRA. [https://doi.org/10.1111/j.1752-1688.2010.00482.x](https://doi.org/10.1111/j.1752-1688.2010.00482.x)
164
+ * **Zhang, Q., & Hirsch, R. M. (2019).** *River Water-Quality Concentration and Flux Estimation Can be Improved by Accounting for Serial Correlation Through an Autoregressive Model*. Water Resources Research. [https://doi.org/10.1029/2019WR025338](https://doi.org/10.1029/2019WR025338)
165
+ * **Hirsch, R., DeCicco, L., & Murphy, J. (2025).** *Exploration and Graphics for RivEr Trends (EGRET)*. U.S. Geological Survey. [https://pubs.usgs.gov/tm/04/a10/](https://pubs.usgs.gov/tm/04/a10/)
@@ -0,0 +1,136 @@
1
+ # wrtds-py
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/wrtds-py.svg)](https://pypi.org/project/wrtds-py/)
4
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ `wrtds-py` is a Python implementation of the **Weighted Regressions on Time, Discharge, and Season (WRTDS)** model, including the **WRTDS-Kalman (WRTDS-K)** autoregressive filter.
8
+
9
+ It is adapted from the official USGS [`EGRET`](https://github.com/DOI-USGS/EGRET) R package.
10
+
11
+ ---
12
+
13
+ ## Status
14
+
15
+ **Current Version: 1.0.0**
16
+
17
+ `wrtds-py` is stable and validated against the USGS `EGRET` R package (v3.0.11) on its reference example (the Choptank River). Releases are published on [PyPI](https://pypi.org/project/wrtds-py/) and archived on Zenodo. See [CHANGELOG.md](https://github.com/Basu-Lab/WRTDS-Py/blob/main/CHANGELOG.md) for the release history.
18
+
19
+ ## Key Features
20
+
21
+ * **Classic WRTDS (`WRTDS`):** Pre-computes the prediction surface. Log-concentration, standard error and concentration are calculated using linear regression where the coefficients are estimated using maximum likelihood considering left-censored data.
22
+ * **WRTDS-Kalman (`WRTDSK`):** Implements a filtering method that smoothes the residuals using an AR(1) process.
23
+
24
+ > Note: WRTDS-Kalman is not actually a Kalman filter in the strictest sense. In Zhang and Hirsch (2019) the authors derive this approach from the theory of Kalman fitering, but a more accurate description is AR(1) smoothing with Monte Carlo simulations for censored samples.
25
+
26
+
27
+ ## Background
28
+
29
+ For a detailed explanation of the underlying statistical methods, including the design matrix of the linear model, left-censored (Tobit) maximum likelihood estimation, weighting functions, and the AR(1) smoother, see [docs/methodology.md](https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/methodology.md).
30
+
31
+
32
+ ## Installation
33
+
34
+ `wrtds-py` requires Python 3.12 or newer and is available on [PyPI](https://pypi.org/project/wrtds-py/).
35
+
36
+ ### Using `uv` (Recommended)
37
+
38
+ ```bash
39
+ uv add wrtds-py
40
+ ```
41
+
42
+ ### Using standard `pip`
43
+
44
+ ```bash
45
+ pip install wrtds-py
46
+ ```
47
+
48
+ ### From source
49
+
50
+ ```bash
51
+ git clone https://github.com/Basu-Lab/WRTDS-Py
52
+ cd WRTDS-Py
53
+ uv sync
54
+ ```
55
+
56
+ ---
57
+
58
+ ## Quickstart
59
+ Also have a look at the [example Jupyter notebook](https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/example.ipynb) for a more detailed demonstration.
60
+
61
+ ### 1. Classic WRTDS
62
+
63
+ ```python
64
+ import pandas as pd
65
+ from wrtds_py import WRTDS
66
+
67
+ # Load discharge (df_q) and water quality (df_wq) data
68
+ # DataFrames must have a DatetimeIndex
69
+ df_q = pd.read_csv("discharge.csv", parse_dates=["Date"], index_col="Date")
70
+ df_wq = pd.read_csv("water_quality.csv", parse_dates=["Date"], index_col="Date")
71
+
72
+ # Initialize and fit the base WRTDS model
73
+ model = WRTDS(
74
+ window_time=7.0, # Half-window for time (years)
75
+ window_discharge=2.0, # Half-window for discharge (log-units)
76
+ window_season=0.5, # Half-window for season (years)
77
+ min_num_obs=50,
78
+ min_num_uncen=30
79
+ )
80
+
81
+ model.fit(df_wq=df_wq, df_q=df_q)
82
+
83
+ # Generate daily predictions
84
+ df_pred = model.predict(df_q)
85
+ print(df_pred[["yHat", "SE", "ConcHat"]].head())
86
+ ```
87
+
88
+ ### 2. WRTDS-Kalman (Autoregressive Filter)
89
+
90
+ ```python
91
+ from wrtds_py import WRTDSK
92
+
93
+ # Pass the fitted base model into the Kalman filter
94
+ kalman = WRTDSK(
95
+ base_model=model,
96
+ rho=0.9, # Daily correlation coefficient (decay factor)
97
+ niter=200, # Monte Carlo iterations (default 200, as in EGRET)
98
+ seed=42 # Seed for reproducibility
99
+ )
100
+
101
+ # Run the filter on the daily discharge record
102
+ df_kalman = kalman.filter(df_wq=df_wq, df_q=df_q)
103
+ print(df_kalman[["ConcHat", "ConcKalman"]].head())
104
+ ```
105
+
106
+ ## Testing & Benchmarking
107
+
108
+ To run the test suite from a source checkout:
109
+
110
+ ```bash
111
+ uv run pytest
112
+ ```
113
+
114
+ `tests/test_r_reference.py` validates the models against USGS `EGRET` v3.0.11 by running it live through `rpy2`, so it requires a working R installation with the `EGRET` package installed. To run only the pure-Python tests:
115
+
116
+ ```bash
117
+ uv run pytest tests/test_components.py tests/test_models.py
118
+ ```
119
+
120
+ ## Citation
121
+
122
+ If you use `wrtds-py` in your research, please cite it using the metadata in [CITATION.cff](https://github.com/Basu-Lab/WRTDS-Py/blob/main/CITATION.cff) (GitHub's "Cite this repository" button generates APA and BibTeX entries from it):
123
+
124
+ > Álvarez Chaves, M. (2026). *wrtds-py: Weighted Regressions on Time, Discharge, and Season in Python* (Version 1.0.0) [Computer software]. https://doi.org/10.5281/zenodo.XXXXXXX <!-- TODO: replace with the Zenodo DOI -->
125
+
126
+ Please also cite the original WRTDS and WRTDS-K publications listed under [References](#references).
127
+
128
+ ## License
129
+
130
+ Distributed under the MIT License. See [`LICENSE`](https://github.com/Basu-Lab/WRTDS-Py/blob/main/LICENSE) for more information.
131
+
132
+ ## References
133
+
134
+ * **Hirsch, R. M., Moyer, D. L., & Archfield, S. A. (2010).** *Weighted Regressions on Time, Discharge, and Season (WRTDS), with an Application to Chesapeake Bay River Inputs*. JAWRA. [https://doi.org/10.1111/j.1752-1688.2010.00482.x](https://doi.org/10.1111/j.1752-1688.2010.00482.x)
135
+ * **Zhang, Q., & Hirsch, R. M. (2019).** *River Water-Quality Concentration and Flux Estimation Can be Improved by Accounting for Serial Correlation Through an Autoregressive Model*. Water Resources Research. [https://doi.org/10.1029/2019WR025338](https://doi.org/10.1029/2019WR025338)
136
+ * **Hirsch, R., DeCicco, L., & Murphy, J. (2025).** *Exploration and Graphics for RivEr Trends (EGRET)*. U.S. Geological Survey. [https://pubs.usgs.gov/tm/04/a10/](https://pubs.usgs.gov/tm/04/a10/)
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "wrtds-py"
3
+ version = "1.0.0"
4
+ description = "Python implementation of the WRTDS and WRTDS-Kalman water quality models, adapted from the USGS EGRET R package"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ keywords = [
10
+ "WRTDS",
11
+ "WRTDS-Kalman",
12
+ "EGRET",
13
+ "water quality",
14
+ "hydrology",
15
+ "concentration",
16
+ "flux",
17
+ "time series",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 5 - Production/Stable",
21
+ "Intended Audience :: Science/Research",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3 :: Only",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Scientific/Engineering :: Hydrology",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "numpy>=2.4.6",
31
+ "pandas>=3.0.3",
32
+ "scipy>=1.18.0",
33
+ "tqdm>=4.68.4",
34
+ ]
35
+
36
+ [[project.authors]]
37
+ name = "Manuel Alvarez Chaves"
38
+ email = "malvarez062@gmail.com"
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/Basu-Lab/WRTDS-Py"
42
+ Repository = "https://github.com/Basu-Lab/WRTDS-Py"
43
+ Issues = "https://github.com/Basu-Lab/WRTDS-Py/issues"
44
+ Changelog = "https://github.com/Basu-Lab/WRTDS-Py/blob/main/CHANGELOG.md"
45
+ Documentation = "https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/methodology.md"
46
+
47
+ [build-system]
48
+ requires = ["uv_build>=0.11.22,<0.12.0"]
49
+ build-backend = "uv_build"
50
+
51
+ [dependency-groups]
52
+ dev = [
53
+ "ipykernel>=7.3.0",
54
+ "matplotlib>=3.11.0",
55
+ "pytest>=9.1.1",
56
+ "rpy2>=3.6.7",
57
+ ]
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "wrtds-py"
3
+ version = "1.0.0"
4
+ description = "Python implementation of the WRTDS and WRTDS-Kalman water quality models, adapted from the USGS EGRET R package"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Manuel Alvarez Chaves", email = "malvarez062@gmail.com" }
10
+ ]
11
+ requires-python = ">=3.12"
12
+ keywords = [
13
+ "WRTDS",
14
+ "WRTDS-Kalman",
15
+ "EGRET",
16
+ "water quality",
17
+ "hydrology",
18
+ "concentration",
19
+ "flux",
20
+ "time series",
21
+ ]
22
+ classifiers = [
23
+ "Development Status :: 5 - Production/Stable",
24
+ "Intended Audience :: Science/Research",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3 :: Only",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Topic :: Scientific/Engineering :: Hydrology",
30
+ "Typing :: Typed",
31
+ ]
32
+ dependencies = [
33
+ "numpy>=2.4.6",
34
+ "pandas>=3.0.3",
35
+ "scipy>=1.18.0",
36
+ "tqdm>=4.68.4",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/Basu-Lab/WRTDS-Py"
41
+ Repository = "https://github.com/Basu-Lab/WRTDS-Py"
42
+ Issues = "https://github.com/Basu-Lab/WRTDS-Py/issues"
43
+ Changelog = "https://github.com/Basu-Lab/WRTDS-Py/blob/main/CHANGELOG.md"
44
+ Documentation = "https://github.com/Basu-Lab/WRTDS-Py/blob/main/docs/methodology.md"
45
+ # TODO: uncomment once the Zenodo DOI has been minted
46
+ # DOI = "https://doi.org/10.5281/zenodo.XXXXXXX"
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.11.22,<0.12.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "ipykernel>=7.3.0",
55
+ "matplotlib>=3.11.0",
56
+ "pytest>=9.1.1",
57
+ "rpy2>=3.6.7",
58
+ ]
@@ -0,0 +1,8 @@
1
+ from importlib.metadata import version
2
+
3
+ from wrtds_py.models.classic import WRTDS
4
+ from wrtds_py.models.kalman import WRTDSK
5
+
6
+ __version__ = version("wrtds-py")
7
+
8
+ __all__ = ["WRTDS", "WRTDSK", "__version__"]
@@ -0,0 +1,78 @@
1
+ import warnings
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ # Fraction of the mean discharge added to every day when there are zero-flow days (as in EGRET)
7
+ ZERO_FLOW_SHIFT = 0.001
8
+
9
+ def _log_discharge(q: pd.Series) -> pd.Series:
10
+ """Log of discharge. If any day has zero flow, 0.1% of the mean discharge is added to every
11
+ day before taking the log, following EGRET; 'Q' itself is left unchanged."""
12
+ num_zeros = int((q == 0).sum())
13
+ if num_zeros > 0:
14
+ shift = ZERO_FLOW_SHIFT * q.mean()
15
+ warnings.warn(
16
+ f"There were {num_zeros} zero flow days. LogQ was computed with {shift:.6g} "
17
+ f"({ZERO_FLOW_SHIFT:.1%} of mean discharge) added to every day.",
18
+ UserWarning,
19
+ )
20
+ q = q + shift
21
+ return np.log(q)
22
+
23
+ def prepare_data(df_wq: pd.DataFrame | None = None, df_q: pd.DataFrame | None = None) -> tuple[pd.DataFrame | None, pd.DataFrame | None]:
24
+
25
+ df_wq = df_wq.copy() if df_wq is not None else None
26
+ df_q = df_q.copy() if df_q is not None else None
27
+
28
+ def _set_index(df: pd.DataFrame | None) -> pd.DataFrame | None:
29
+ if df is None:
30
+ return None
31
+
32
+ # Check if the index is already a DatetimeIndex; if not, attempt to set it
33
+ if not isinstance(df.index, pd.DatetimeIndex):
34
+ valid_index_cols = {'date', 'datetime', 'time', 'timestamp'}
35
+ cols_lower = {col.lower() for col in df.columns}
36
+ index_col = valid_index_cols.intersection(cols_lower) # match columns
37
+ if index_col:
38
+ date_col = next(iter(index_col))
39
+ df.index = pd.to_datetime(df[date_col])
40
+
41
+ if not df.index.is_monotonic_increasing:
42
+ df = df.sort_index()
43
+
44
+ if 'DecYear' not in df.columns:
45
+ days_in_year = np.where(df.index.is_leap_year, 366.0, 365.0)
46
+ df['DecYear'] = df.index.year + (df.index.dayofyear - 0.5) / days_in_year
47
+
48
+ return df
49
+
50
+ df_wq = _set_index(df_wq)
51
+ df_q = _set_index(df_q)
52
+
53
+ if df_q is not None:
54
+ if 'LogQ' not in df_q.columns:
55
+ if 'Q' not in df_q.columns:
56
+ raise ValueError("df_q must contain 'Q' or 'LogQ'.")
57
+ df_q['LogQ'] = _log_discharge(df_q['Q'])
58
+
59
+ # If df_wq doesn't have 'LogQ', map it from df_q using the index
60
+ if df_wq is not None and 'LogQ' not in df_wq.columns:
61
+ df_wq['LogQ'] = df_q['LogQ'].reindex(df_wq.index)
62
+ if df_wq['LogQ'].isna().any():
63
+ raise ValueError("Sample dates missing corresponding discharge in df_q.")
64
+ else:
65
+ if df_wq is not None and 'LogQ' not in df_wq.columns:
66
+ if 'Q' in df_wq.columns:
67
+ df_wq['LogQ'] = _log_discharge(df_wq['Q'])
68
+ else:
69
+ raise ValueError("If df_q is None, df_wq must contain 'Q' or 'LogQ'.")
70
+
71
+ if df_wq is not None:
72
+ if 'Conc' in df_wq.columns and 'Uncen' in df_wq.columns:
73
+ df_wq['LogConc'] = np.log(df_wq['Conc'].replace(0, np.nan))
74
+ df_wq['Uncen'] = df_wq['Uncen'].astype(int)
75
+ else:
76
+ raise ValueError("df_wq must contain both 'Conc' and 'Uncen'.")
77
+
78
+ return df_wq, df_q
@@ -0,0 +1,213 @@
1
+ from dataclasses import dataclass
2
+ from typing import NamedTuple
3
+
4
+ import numpy as np
5
+ from scipy.optimize import minimize
6
+ from scipy.special import log_ndtr
7
+
8
+ from wrtds_py.weighting import cyclic_distance, tricube_weight
9
+
10
+ _LOG_SQRT_2_PI = 0.5 * np.log(2 * np.pi)
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class WindowParams:
15
+ time: float
16
+ discharge: float
17
+ season: float
18
+
19
+ def as_tuple(self) -> tuple[float, float, float]:
20
+ return (self.time, self.discharge, self.season)
21
+
22
+ def expand(self, factor: float = 1.1, season_cap: float = 0.5) -> "WindowParams":
23
+ max_time_window = 15.0 # years
24
+ max_discharge_window = 5.0 # log units
25
+ return WindowParams(
26
+ time=min(self.time * factor, max_time_window),
27
+ discharge=min(self.discharge * factor, max_discharge_window),
28
+ season=min(self.season * factor, season_cap),
29
+ )
30
+
31
+
32
+ class NodeConfig(NamedTuple):
33
+ target_logq: float
34
+ target_time: float
35
+ min_obs: int
36
+ min_uncen: int
37
+ adjust_edges: bool
38
+ allow_expansion: bool = True
39
+
40
+
41
+ class NodeResult(NamedTuple):
42
+ y_hat: float
43
+ sigma: float
44
+ conc_hat: float
45
+ final_windows: WindowParams
46
+
47
+
48
+ def _tobit_neg_log_likelihood(x: np.ndarray, model_data: dict) -> tuple[float, np.ndarray]:
49
+ """Weighted negative log-likelihood of the left-censored regression and its gradient."""
50
+ betas = x[:-1]
51
+ sigma = x[-1] # kept positive by the optimizer bounds
52
+
53
+ weights = model_data["weights"]
54
+ is_uncen = model_data["uncen"] == 1
55
+
56
+ mu = model_data["X"] @ betas
57
+
58
+ z = (model_data["y"] - mu) / sigma
59
+
60
+ # Gaussian log-PDF for uncensored data
61
+ log_pdf = -0.5 * (z**2) - _LOG_SQRT_2_PI
62
+ # Gaussian log-CDF for left-censored data
63
+ # Because this is a detection limit, the CDF gives the total probability of the distribution up to the detection
64
+ # limit. log_ndtr stays accurate far into the lower tail, where the CDF itself underflows
65
+ log_cdf = log_ndtr(z)
66
+
67
+ loglik = np.where(is_uncen, log_pdf - np.log(sigma), log_cdf)
68
+
69
+ # Derivatives of each log-likelihood term with respect to z and sigma, using dz/dbeta = -X / sigma
70
+ # and dz/dsigma = -z / sigma. For censored data, d(log CDF)/dz is the inverse Mills ratio PDF / CDF
71
+ mills = np.exp(log_pdf - log_cdf)
72
+ dloglik_dz = np.where(is_uncen, -z, mills)
73
+ dloglik_dsigma = np.where(is_uncen, (z**2 - 1.0) / sigma, -mills * z / sigma)
74
+
75
+ # Gradient of the negative log-likelihood
76
+ grad_betas = (weights * dloglik_dz / sigma) @ model_data["X"]
77
+ grad_sigma = -np.sum(weights * dloglik_dsigma)
78
+
79
+ return -np.sum(weights * loglik), np.append(grad_betas, grad_sigma)
80
+
81
+
82
+ def estimate_surface_node(
83
+ node: NodeConfig, sample_data: dict, initial_window: WindowParams
84
+ ) -> NodeResult:
85
+
86
+ current_windows = initial_window
87
+
88
+ # Calculate the distance to the nearest edge of the sample data
89
+ dec_low = np.min(sample_data["time"])
90
+ dec_high = np.max(sample_data["time"])
91
+ dist_time = min(node.target_time - dec_low, dec_high - node.target_time)
92
+
93
+ # If edge_adjust is True, expand the time window if the target is near the edges of the observations
94
+ # This is to prevent having too few observations on one side of the target time, and many in the other,
95
+ # which can bias the regression.
96
+ if node.adjust_edges and not np.isnan(dist_time):
97
+ if dist_time <= current_windows.time:
98
+ current_windows = WindowParams(
99
+ time=(2 * current_windows.time) - dist_time,
100
+ discharge=current_windows.discharge,
101
+ season=current_windows.season,
102
+ )
103
+
104
+ # Calculate distances between target and sample data for time, logq, and season
105
+ dist_t = node.target_time - sample_data["time"]
106
+ dist_q = node.target_logq - sample_data["logq"]
107
+ dist_s = cyclic_distance(node.target_time, sample_data["time"])
108
+
109
+ # Early exit: verify the sample dataset as a whole satisfies requirements
110
+ min_required = max(node.min_obs, 5) # Ensure at least 5 observations for 5 regression parameters
111
+ total_samples = len(sample_data["time"])
112
+ total_uncen = int(np.sum(sample_data["uncen"]))
113
+ if total_samples < min_required or total_uncen < node.min_uncen:
114
+ return NodeResult(np.nan, np.nan, np.nan, current_windows)
115
+
116
+ # Search for the smallest window that meets the minimum required number of observations and uncensored data
117
+ max_k = 50 # 1.1^50 is >117x the initial window size
118
+ k = 1
119
+ while True:
120
+ w_t, w_q, w_s = current_windows.as_tuple()
121
+
122
+ weight_t = tricube_weight(dist_t, w_t)
123
+ weight_q = tricube_weight(dist_q, w_q)
124
+ weight_s = tricube_weight(dist_s, w_s)
125
+
126
+ total_weights = weight_t * weight_q * weight_s
127
+ active_mask = total_weights > 0
128
+ n_active = np.sum(active_mask)
129
+ n_uncen = np.sum(sample_data["uncen"][active_mask])
130
+
131
+ # Break once window covers the required number of observations and uncensored points
132
+ if n_active >= min_required and n_uncen >= node.min_uncen:
133
+ break
134
+
135
+ # Abort expansion if disabled or reached maximum search limit
136
+ if not node.allow_expansion or k >= max_k:
137
+ break
138
+
139
+ current_windows = current_windows.expand()
140
+ k += 1
141
+
142
+ # Return NaN if window expansion failed to satisfy the required counts
143
+ if n_active < min_required or n_uncen < node.min_uncen:
144
+ return NodeResult(np.nan, np.nan, np.nan, current_windows)
145
+
146
+ w_active = total_weights[active_mask]
147
+
148
+ # Guard the case where all weights are zero or no active observations remain
149
+ sum_w = np.sum(w_active)
150
+ if sum_w <= 0.0 or n_active == 0:
151
+ return NodeResult(np.nan, np.nan, np.nan, current_windows)
152
+
153
+ w_active = w_active / (sum_w / n_active)
154
+
155
+ t_active = sample_data["time"][active_mask]
156
+ q_active = sample_data["logq"][active_mask]
157
+ y_active = sample_data["y"][active_mask]
158
+ uncen = sample_data["uncen"][active_mask]
159
+
160
+ # Prepare inputs as the design matrix X
161
+ X = np.column_stack((
162
+ np.ones(n_active), # x0
163
+ t_active - node.target_time, # x1
164
+ q_active - node.target_logq, # x2
165
+ np.sin(2 * np.pi * t_active), # x3
166
+ np.cos(2 * np.pi * t_active), # x4
167
+ ))
168
+
169
+ # Weighted least squares initialization for beta and sigma
170
+ W = np.diag(w_active)
171
+ try:
172
+ init_betas = np.linalg.inv(X.T @ W @ X) @ X.T @ W @ y_active
173
+ init_res = y_active - (X @ init_betas)
174
+ init_sigma = max(np.sqrt(np.average(init_res**2, weights=w_active)), 0.05)
175
+ except np.linalg.LinAlgError:
176
+ init_betas = np.zeros(5)
177
+ init_sigma = 1.0
178
+
179
+ # Pack the model data into a dict for the likelihood function
180
+ model_data = {"X": X, "y": y_active, "uncen": uncen, "weights": w_active}
181
+
182
+ result = minimize(
183
+ _tobit_neg_log_likelihood,
184
+ x0=np.append(init_betas, init_sigma),
185
+ args=(model_data,),
186
+ jac=True,
187
+ method="L-BFGS-B",
188
+ bounds=[(None, None)] * 5 + [(1e-5, None)],
189
+ )
190
+
191
+ if not result.success:
192
+ return NodeResult(np.nan, np.nan, np.nan, current_windows)
193
+
194
+ final_params = result.x
195
+ final_betas, final_sigma = final_params[:-1], final_params[-1]
196
+
197
+ # Use the fitted parameters to predict the log-concentration at the target node
198
+ # Here we only use the intercept and the seasonal terms, since the other terms are zero at the target node
199
+ y_hat = (
200
+ final_betas[0]
201
+ + final_betas[3] * np.sin(2 * np.pi * node.target_time)
202
+ + final_betas[4] * np.cos(2 * np.pi * node.target_time)
203
+ )
204
+
205
+ # Convert log-concentration to concentration using the expected value of a log-normal distribution
206
+ # This accounts for the bias introduced by the log transformation
207
+ log_arg = y_hat + (final_sigma**2) / 2.0
208
+ if not np.isfinite(log_arg) or log_arg > 20.0:
209
+ conc_hat = np.nan
210
+ else:
211
+ conc_hat = np.exp(log_arg)
212
+
213
+ return NodeResult(y_hat, final_sigma, conc_hat, current_windows)
@@ -0,0 +1,15 @@
1
+ import numpy as np
2
+
3
+ _CMS_TO_KG_PER_DAY = 86.4
4
+ _CFS_TO_KG_PER_DAY = 2.44657555
5
+
6
+ def calc_flux(conc: np.ndarray, q: np.ndarray, flow_unit: str = 'cms') -> np.ndarray:
7
+ match flow_unit:
8
+ case 'cms':
9
+ factor = _CMS_TO_KG_PER_DAY
10
+ case 'cfs':
11
+ factor = _CFS_TO_KG_PER_DAY
12
+ case _:
13
+ raise ValueError("flow_unit must be either 'cms' or 'cfs'.")
14
+
15
+ return conc * q * factor
File without changes
@@ -0,0 +1,32 @@
1
+ import numpy as np
2
+
3
+ from wrtds_py.data import prepare_data
4
+
5
+ class BaseWRTDS:
6
+ def __init__(
7
+ self,
8
+ window_time: float = 7.0,
9
+ window_discharge: float = 2.0,
10
+ window_season: float = 0.5,
11
+ min_num_obs: int = 50,
12
+ min_num_uncen: int = 30,
13
+ adjust_edges: bool = True,
14
+ allow_expansion: bool = True,
15
+ ) -> None:
16
+
17
+ self.window_time = window_time
18
+ self.window_discharge = window_discharge
19
+ self.window_season = window_season
20
+ self.min_num_obs = min_num_obs
21
+ self.min_num_uncen = min_num_uncen
22
+ self.adjust_edges = adjust_edges
23
+ self.allow_expansion = allow_expansion
24
+
25
+ self.surface_: np.ndarray | None = None
26
+ self.grid_logq_: np.ndarray | None = None
27
+ self.grid_time_: np.ndarray | None = None
28
+ self.effective_windows_: np.ndarray | None = None
29
+ self._is_fitted: bool = False
30
+
31
+ def _prepare_data(self, df_wq = None, df_q = None):
32
+ return prepare_data(df_wq, df_q)
@@ -0,0 +1,130 @@
1
+ import warnings
2
+ import numpy as np
3
+ import pandas as pd
4
+ from typing import Self
5
+ from scipy.interpolate import RegularGridInterpolator
6
+ from tqdm import tqdm
7
+
8
+ from wrtds_py.models.base import BaseWRTDS
9
+ from wrtds_py.estimation import estimate_surface_node, NodeConfig, WindowParams
10
+
11
+ class WRTDS(BaseWRTDS):
12
+
13
+ def fit(
14
+ self,
15
+ df_wq: pd.DataFrame,
16
+ df_q: pd.DataFrame | None = None,
17
+ q_min: float | None = None,
18
+ q_max: float | None = None,
19
+ verbose: bool = True
20
+ ) -> Self:
21
+
22
+ # Validate the input DataFrames
23
+ df_wq_clean, df_q_clean = self._prepare_data(df_wq, df_q)
24
+
25
+ if df_q_clean is not None:
26
+ min_logq = df_q_clean['LogQ'].min() - 0.01 if q_min is None else q_min
27
+ max_logq = df_q_clean['LogQ'].max() + 0.01 if q_max is None else q_max
28
+ grid_min_time, grid_max_time = df_q_clean['DecYear'].min(), df_q_clean['DecYear'].max()
29
+ else:
30
+ if q_min is None or q_max is None:
31
+ raise ValueError("Must provide `q_min` and `q_max` if `df_q` is None.")
32
+ min_logq, max_logq = np.log(q_min), np.log(q_max)
33
+ grid_min_time, grid_max_time = df_wq_clean['DecYear'].min(), df_wq_clean['DecYear'].max()
34
+
35
+ num_q_nodes = 14
36
+ grid_logq = np.linspace(min_logq, max_logq, num_q_nodes)
37
+
38
+ step_time = 1.0 / 16.0
39
+ num_time_nodes = int(np.ceil((grid_max_time - grid_min_time) / step_time)) + 1
40
+ grid_time = np.linspace(grid_min_time, grid_max_time, num_time_nodes)
41
+
42
+ self.surface_ = np.zeros((num_q_nodes, num_time_nodes, 3))
43
+ self.effective_windows_ = np.zeros((num_q_nodes, num_time_nodes, 3))
44
+
45
+ # Collect 'wq' data into a dict to pass to the node estimation function
46
+ sample_data = {
47
+ 'time': df_wq_clean['DecYear'].values,
48
+ 'logq': df_wq_clean['LogQ'].values,
49
+ 'y': df_wq_clean['LogConc'].values,
50
+ 'uncen': df_wq_clean['Uncen'].values
51
+ }
52
+
53
+ # Set the initial window to search
54
+ initial_windows = WindowParams(
55
+ time=self.window_time,
56
+ discharge=self.window_discharge,
57
+ season=self.window_season
58
+ )
59
+
60
+ total_nodes = num_q_nodes * num_time_nodes
61
+ expansion_warnings = 0
62
+
63
+ # Create a list of nodes to fit
64
+ nodes_to_fit = [
65
+ (i, j, target_logq, target_time)
66
+ for i, target_logq in enumerate(grid_logq)
67
+ for j, target_time in enumerate(grid_time)
68
+ ]
69
+
70
+ # Fit each node one by one
71
+ with tqdm(total=total_nodes, disable=not verbose, desc="Fitting WRTDS", ascii=True) as pbar:
72
+ for i, j, target_logq, target_time in nodes_to_fit:
73
+
74
+ node_config = NodeConfig(
75
+ target_logq=target_logq,
76
+ target_time=target_time,
77
+ min_obs=self.min_num_obs,
78
+ min_uncen=self.min_num_uncen,
79
+ adjust_edges=self.adjust_edges,
80
+ allow_expansion=self.allow_expansion
81
+ )
82
+
83
+ out = estimate_surface_node(node_config, sample_data, initial_windows)
84
+
85
+ self.surface_[i, j, :] = [out.y_hat, out.sigma, out.conc_hat]
86
+ self.effective_windows_[i, j, :] = out.final_windows.as_tuple()
87
+
88
+ # Check if the effective window was expanded beyond the initial window
89
+ if (out.final_windows.time > initial_windows.time) or \
90
+ (out.final_windows.discharge > initial_windows.discharge):
91
+ expansion_warnings += 1
92
+
93
+ pbar.update(1)
94
+
95
+ if expansion_warnings > 0:
96
+ warnings.warn(f"Adaptive window expansion triggered for {expansion_warnings} nodes.")
97
+
98
+ self.grid_logq_ = grid_logq
99
+ self.grid_time_ = grid_time
100
+ self._is_fitted = True
101
+
102
+ return self
103
+
104
+ def predict(self, df: pd.DataFrame) -> pd.DataFrame:
105
+ if not self._is_fitted:
106
+ raise RuntimeError("The model is not fitted yet. Call .fit() first.")
107
+
108
+ # Clean df as if it were 'df_q'. Cleaning sorts the rows by date, so each row is
109
+ # tagged with its original position to write the predictions back in place
110
+ _, df_clean = self._prepare_data(df_wq=None, df_q=df.assign(_row=np.arange(len(df))))
111
+ rows = df_clean['_row'].values
112
+
113
+ # Clip the target values to the grid range to prevent extrapolation
114
+ target_time = np.clip(df_clean['DecYear'].values, self.grid_time_.min(), self.grid_time_.max())
115
+ target_logq = np.clip(df_clean['LogQ'].values, self.grid_logq_.min(), self.grid_logq_.max())
116
+ points = np.column_stack((target_logq, target_time))
117
+
118
+ # Interpolate the fitted surface to get predictions
119
+ interp_yhat = RegularGridInterpolator((self.grid_logq_, self.grid_time_), self.surface_[:, :, 0], method='linear')
120
+ interp_se = RegularGridInterpolator((self.grid_logq_, self.grid_time_), self.surface_[:, :, 1], method='linear')
121
+ interp_conc = RegularGridInterpolator((self.grid_logq_, self.grid_time_), self.surface_[:, :, 2], method='linear')
122
+
123
+ df_out = df.copy()
124
+ for col, interp in (('yHat', interp_yhat), ('SE', interp_se), ('ConcHat', interp_conc)):
125
+ values = np.empty(len(df))
126
+ values[rows] = interp(points)
127
+ df_out[col] = values
128
+
129
+ return df_out
130
+
@@ -0,0 +1,138 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from tqdm import tqdm
4
+ from scipy.stats import truncnorm
5
+
6
+ from wrtds_py.models.classic import WRTDS
7
+
8
+
9
+ def _ar1_gap_residuals(z_left: float, z_right: float, gap_days: int, rho: float,
10
+ rng: np.random.Generator) -> np.ndarray:
11
+ """Draw the standardized residuals on the days strictly between two samples.
12
+
13
+ `gap_days` is the number of days from the left sample to the right one. The draw is an
14
+ expected residual, set by the distance to each sample, plus a random AR(1) deviation.
15
+ """
16
+ k = np.arange(1, gap_days) # days since the left sample
17
+
18
+ # Expected residual: weights of the left and right samples. Each weight decays with the
19
+ # distance to its sample, and both vanish in the middle of long gaps (plain WRTDS)
20
+ denom = 1.0 - rho ** (2 * gap_days)
21
+ w_left = (rho ** k - rho ** (2 * gap_days - k)) / denom
22
+ w_right = (rho ** (gap_days - k) - rho ** (gap_days + k)) / denom
23
+ expected = w_left * z_left + w_right * z_right
24
+
25
+ # Random deviation: simulate a free AR(1) path across the gap and remove the part that
26
+ # its own end points explain, leaving noise that is zero at both samples
27
+ path = np.empty(gap_days + 1)
28
+ path[0] = rng.standard_normal()
29
+ innovations = rng.standard_normal(gap_days) * np.sqrt(1.0 - rho ** 2)
30
+ for t in range(1, gap_days + 1):
31
+ path[t] = rho * path[t - 1] + innovations[t - 1]
32
+ deviation = path[1:gap_days] - (w_left * path[0] + w_right * path[gap_days])
33
+
34
+ return expected + deviation
35
+
36
+ class WRTDSK:
37
+ def __init__(self, base_model: WRTDS, rho: float = 0.9, niter: int = 200,
38
+ seed: int | np.random.Generator | None = None):
39
+ if not getattr(base_model, '_is_fitted', False):
40
+ raise ValueError("The base WRTDS model must be fitted before running the Kalman filter.")
41
+ if not 0 <= rho < 1:
42
+ raise ValueError("`rho` must be in [0, 1).")
43
+
44
+ self.base_model = base_model
45
+ self.rho = rho
46
+ self.niter = niter
47
+ self.seed = seed
48
+ self._is_fitted = False
49
+
50
+ def filter(self, df_wq: pd.DataFrame, df_q: pd.DataFrame, verbose: bool = True) -> pd.DataFrame:
51
+ # Local generator: the global NumPy random state is left untouched
52
+ rng = np.random.default_rng(self.seed)
53
+
54
+ df_wq_clean, df_q_clean = self.base_model._prepare_data(df_wq, df_q)
55
+
56
+ # Get predictions from the base WRTDS model
57
+ df_wq_pred = self.base_model.predict(df_wq_clean)
58
+ df_q_pred = self.base_model.predict(df_q_clean)
59
+
60
+ # Prepare arrays for the AR(1) model
61
+ y_obs = df_wq_pred['LogConc'].values # log-observations
62
+ y_hat = df_wq_pred['yHat'].values # log-predictions
63
+ se = df_wq_pred['SE'].values # standard errors
64
+ uncen = df_wq_pred['Uncen'].values # 1 if uncensored, 0 if left-censored
65
+
66
+ n_wq = len(df_wq_pred)
67
+ n_q = len(df_q_pred)
68
+
69
+ conc = np.zeros(n_q) # array to store samples
70
+
71
+ # Ensure standard errors are strictly positive and finite
72
+ se_safe = np.where(np.isfinite(se) & (se > 1e-4), se, 1e-4)
73
+
74
+ # Standardized residuals for the AR(1) model, as in EGRET's WRTDSKalman:
75
+ # z = (ln c - yHat) / SE, rescaled later by each day's own SE
76
+ residuals = (y_obs - y_hat) / se_safe
77
+
78
+ censored_mask = (uncen == 0)
79
+ num_censored = np.sum(censored_mask)
80
+
81
+ if num_censored > 0:
82
+ # Truncation bounds for the truncated normal distribution for censored data
83
+ a_vec = np.full(num_censored, -np.inf) # Smallest possible value for left-censor data
84
+ b_vec = residuals[censored_mask] # Standardized difference between 'detection limit' and predicted value
85
+
86
+ # Guard against NaN/inf values in the residuals themselves
87
+ b_vec = np.nan_to_num(b_vec, nan=0.0, posinf=10.0, neginf=-10.0)
88
+
89
+ # Whole-day counts since the start of the daily record
90
+ origin = df_q_pred.index.min().normalize()
91
+ day_q = (df_q_pred.index.normalize() - origin).days.to_numpy()
92
+ day_wq = (df_wq_pred.index.normalize() - origin).days.to_numpy()
93
+
94
+ # Days with at least one sample; `sample_of` maps each sample to its day in `sample_days`
95
+ sample_days, sample_of = np.unique(day_wq, return_inverse=True)
96
+ n_sampled = len(sample_days)
97
+
98
+ yhat_q = df_q_pred['yHat'].values
99
+ se_q = df_q_pred['SE'].values
100
+ n_record = day_q.max() + 1 # days from the first to the last day of the record
101
+
102
+ # Sampling residuals
103
+ with tqdm(total=self.niter, disable=not verbose, desc="Running WRTDS-K", ascii=True) as pbar:
104
+ for _ in range(self.niter):
105
+ residuals_iter = residuals.copy() # base residuals
106
+ if num_censored > 0: # censored data
107
+ samples = truncnorm.rvs(a_vec, b_vec, size=num_censored, random_state=rng) # samples for censored data
108
+ residuals_iter[censored_mask] = samples # already standardized
109
+
110
+ # One sample per sampled day, chosen at random when a day has several
111
+ order = rng.permutation(n_wq)
112
+ _, first = np.unique(sample_of[order], return_index=True)
113
+ z_days = residuals_iter[order[first]]
114
+
115
+ # Standardized residual for every day of the record. Before the first and after
116
+ # the last sample there is no information, so they stay N(0, 1): plain WRTDS
117
+ z = rng.standard_normal(n_record)
118
+ z[sample_days] = z_days
119
+
120
+ # Each gap between two consecutive samples is informed by both of them
121
+ for i in range(n_sampled - 1):
122
+ left, right = sample_days[i], sample_days[i + 1]
123
+ z[left + 1 : right] = _ar1_gap_residuals(z_days[i], z_days[i + 1], right - left, self.rho, rng)
124
+
125
+ # Rescale the standardized residuals by each day's SE and transform back to concentration.
126
+ # The Monte Carlo average provides the bias correction, so no exp(sigma^2 / 2) is applied.
127
+ conc += np.exp(yhat_q + z[day_q] * se_q)
128
+
129
+ pbar.update(1)
130
+
131
+ # Average the niter samples to get the final estimates
132
+ mean_conc = conc / self.niter
133
+
134
+ df_out = df_q_pred.copy()
135
+ df_out['ConcKalman'] = mean_conc
136
+
137
+ self._is_fitted = True
138
+ return df_out
File without changes
@@ -0,0 +1,12 @@
1
+ import numpy as np
2
+
3
+ def tricube_weight(distance: float | np.ndarray, half_window: float) -> np.ndarray:
4
+ d = np.abs(distance)
5
+ ratio = d / half_window
6
+ return np.where(ratio <= 1.0, (1.0 - ratio**3)**3, 0.0)
7
+
8
+ def cyclic_distance(time_target: float | np.ndarray, time_sample: np.ndarray) -> np.ndarray:
9
+ frac_target = time_target % 1.0
10
+ frac_sample = time_sample % 1.0
11
+ diff = np.abs(frac_target - frac_sample)
12
+ return np.where(diff > 0.5, 1.0 - diff, diff)