heat-cold-spell 0.1.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.
- heat_cold_spell-0.1.0/LICENSE +9 -0
- heat_cold_spell-0.1.0/PKG-INFO +267 -0
- heat_cold_spell-0.1.0/README.md +249 -0
- heat_cold_spell-0.1.0/pyproject.toml +29 -0
- heat_cold_spell-0.1.0/setup.cfg +4 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/01_prepare_data.py +69 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/02_historical_analysis.py +598 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/03_train_and_compare.py +340 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/04_train_best_model.py +487 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/05_predict_future.py +399 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/06_pastspells.py +336 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/__init__.py +19 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/config.py +4 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/heat_cold_spell.py +346 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/pipeline/__init__.py +1 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/pipeline/data.py +42 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/pipeline/historical.py +519 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell/pipeline/modeling.py +435 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell.egg-info/PKG-INFO +267 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell.egg-info/SOURCES.txt +22 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell.egg-info/dependency_links.txt +1 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell.egg-info/requires.txt +8 -0
- heat_cold_spell-0.1.0/src/heat_cold_spell.egg-info/top_level.txt +1 -0
- heat_cold_spell-0.1.0/tests/test_import.py +17 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shagun Tyagi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: heat-cold-spell
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Heat and cold spell analysis and forecasting library
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: numpy
|
|
10
|
+
Requires-Dist: pandas
|
|
11
|
+
Requires-Dist: scikit-learn
|
|
12
|
+
Requires-Dist: tensorflow
|
|
13
|
+
Requires-Dist: joblib
|
|
14
|
+
Requires-Dist: openpyxl
|
|
15
|
+
Requires-Dist: matplotlib
|
|
16
|
+
Requires-Dist: scipy
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# Heat & Cold Spell Analysis and Forecasting Library
|
|
20
|
+
|
|
21
|
+
A Python library and workflow pipeline for analyzing historical daily extreme temperatures (maximum and minimum), training predictive machine learning models, and identifying heat waves and cold waves under standardized meteorological criteria.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Technical Overview & Architecture
|
|
26
|
+
|
|
27
|
+
The pipeline processes daily maximum ($T_{\max}$) and minimum ($T_{\min}$) temperatures through a six-stage workflow:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
+-----------------------------------------------------------------------------------+
|
|
31
|
+
| 1. Data Preparation & Validation |
|
|
32
|
+
| Inputs raw daily MAX/MIN data -> Cleans, standardizes dates, and validates schema |
|
|
33
|
+
+-----------------------------------------------------------------------------------+
|
|
34
|
+
|
|
|
35
|
+
+-------------------------------+-------------------------------+
|
|
36
|
+
| |
|
|
37
|
+
v v
|
|
38
|
+
+------------------------------------+ +------------------------------------+
|
|
39
|
+
| 2. Retrospective Historical | | 3. Model Training & Comparison |
|
|
40
|
+
| Analysis & Spell Detection | | Evaluates candidate forecasters|
|
|
41
|
+
| - Computes 15-year normals | | on chronological holdout split |
|
|
42
|
+
| - Identifies heat/cold spells | +------------------------------------+
|
|
43
|
+
| - Generates annual summaries | |
|
|
44
|
+
+------------------------------------+ v
|
|
45
|
+
+------------------------------------+
|
|
46
|
+
| 4. Model Refitting & Manifest |
|
|
47
|
+
| Refits winning candidate models|
|
|
48
|
+
| on all available data |
|
|
49
|
+
+------------------------------------+
|
|
50
|
+
|
|
|
51
|
+
v
|
|
52
|
+
+------------------------------------+
|
|
53
|
+
| 5. Multi-Year Future Prediction |
|
|
54
|
+
| Generates forward predictions |
|
|
55
|
+
| (e.g., 5-year horizon) |
|
|
56
|
+
+------------------------------------+
|
|
57
|
+
|
|
|
58
|
+
v
|
|
59
|
+
+------------------------------------+
|
|
60
|
+
| 6. Forecast Spell Detection |
|
|
61
|
+
| Applies spell rules to future |
|
|
62
|
+
| forecasts using prior normals |
|
|
63
|
+
+------------------------------------+
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Theoretical & Methodological Foundations
|
|
69
|
+
|
|
70
|
+
### 1. Climatological Normals & Departures
|
|
71
|
+
Daily temperature anomalies are measured relative to **calendar-day climatological normals** calculated across a 15-year baseline window:
|
|
72
|
+
|
|
73
|
+
* **Historical Analysis**: Uses a 15-year centered moving window ($\pm 7$ years around the given year) to account for multi-decadal trends. A trailing 15-year window is applied to the final 7 historical years.
|
|
74
|
+
* **Forecast Spell Detection**: Uses a trailing 15-year window of observed data immediately preceding the forecast period to avoid future data leakage.
|
|
75
|
+
|
|
76
|
+
Temperature departures (anomalies) are defined as:
|
|
77
|
+
|
|
78
|
+
$$\Delta T_{\max} = T_{\max} - N_{\max, d}, \quad \Delta T_{\min} = T_{\min} - N_{\min, d}$$
|
|
79
|
+
|
|
80
|
+
where $N_{\max, d}$ and $N_{\min, d}$ represent the 15-year mean normal temperatures for calendar day $d \in [1, 365]$.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
### 2. Meteorological Wave & Spell Criteria
|
|
85
|
+
|
|
86
|
+
#### Daily Classifications
|
|
87
|
+
|
|
88
|
+
* **Heat Wave Day**: Triggered if either:
|
|
89
|
+
1. **Regional Threshold + Departure**: $T_{\max} \ge T_{\text{regional}}$ **AND** $\Delta T_{\max} \ge +4.5^\circ\text{C}$
|
|
90
|
+
* *Plains*: $T_{\text{regional}} = 40.0^\circ\text{C}$
|
|
91
|
+
* *Coastal*: $T_{\text{regional}} = 37.0^\circ\text{C}$
|
|
92
|
+
* *Hilly*: $T_{\text{regional}} = 30.0^\circ\text{C}$
|
|
93
|
+
2. **Absolute Extreme Threshold**: $T_{\max} \ge 45.0^\circ\text{C}$ (regardless of departure).
|
|
94
|
+
* **Cold Wave Day**: Triggered if:
|
|
95
|
+
* $T_{\min} < 10.0^\circ\text{C}$ **AND** $\Delta T_{\min} \le -3.0^\circ\text{C}$
|
|
96
|
+
|
|
97
|
+
#### Spell Event Aggregation
|
|
98
|
+
Consecutive qualifying extreme days are grouped into formal spell events based on duration triggers:
|
|
99
|
+
|
|
100
|
+
* **Heat Wave Event**: $\ge 5$ consecutive Heat Wave Days **OR** $\ge 2$ consecutive days with $T_{\max} \ge 45.0^\circ\text{C}$.
|
|
101
|
+
* **Cold Wave Event**: $\ge 5$ consecutive Cold Wave Days.
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
### 3. Machine Learning Forecasting Pipeline
|
|
106
|
+
|
|
107
|
+
#### Candidate Model Families
|
|
108
|
+
The pipeline evaluates six model architectures separately for $T_{\max}$ and $T_{\min}$:
|
|
109
|
+
|
|
110
|
+
1. **Seasonal Baseline**: Non-parametric daily climatology mean benchmark.
|
|
111
|
+
2. **Trend + Fourier**: Linear trend combined with 6 harmonic sine/cosine annual cycles.
|
|
112
|
+
3. **Random Forest**: Non-linear ensemble trees on calendar and rolling lag features.
|
|
113
|
+
4. **DNN**: Deep Feed-Forward Neural Network on engineered temporal features.
|
|
114
|
+
5. **LSTM**: Long Short-Term Memory recurrent neural network over 60-day sequence lookbacks.
|
|
115
|
+
6. **GRU**: Gated Recurrent Unit neural network over 60-day sequence lookbacks.
|
|
116
|
+
|
|
117
|
+
#### Chronological Holdout Evaluation
|
|
118
|
+
Models are evaluated on a chronological test period (`2022-06-01` to `2024-05-31`) to prevent temporal data leakage. Selection prioritizes models using the following metric hierarchy:
|
|
119
|
+
|
|
120
|
+
$$\text{Rank Criteria: } \text{RMSE} \longrightarrow \text{MAE} \longrightarrow R^2 \longrightarrow |\text{Bias}|$$
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Installation & Setup
|
|
125
|
+
|
|
126
|
+
### Requirements
|
|
127
|
+
* Python 3.9+
|
|
128
|
+
* Required packages: `numpy`, `pandas`, `scikit-learn`, `tensorflow`, `joblib`, `openpyxl`, `matplotlib`
|
|
129
|
+
|
|
130
|
+
### Directory Structure Requirements
|
|
131
|
+
```text
|
|
132
|
+
.
|
|
133
|
+
├── src/
|
|
134
|
+
│ └── heat_cold_spell/
|
|
135
|
+
│ ├── __init__.py
|
|
136
|
+
│ ├── heat_cold_spell.py # Primary high-level API wrapper
|
|
137
|
+
│ ├── config.py
|
|
138
|
+
│ ├── 01_prepare_data.py # CLI Stage 1: Data preparation
|
|
139
|
+
│ ├── 02_historical_analysis.py # CLI Stage 2: Historical analysis
|
|
140
|
+
│ ├── 03_train_and_compare.py # CLI Stage 3: Model comparison
|
|
141
|
+
│ ├── 04_train_best_model.py # CLI Stage 4: Model refitting
|
|
142
|
+
│ ├── 05_predict_future.py # CLI Stage 5: Future prediction
|
|
143
|
+
│ ├── 06_pastspells.py # CLI Stage 6: Spell detection
|
|
144
|
+
│ └── pipeline/ # Internal processing modules
|
|
145
|
+
│ ├── __init__.py
|
|
146
|
+
│ ├── data.py
|
|
147
|
+
│ ├── historical.py
|
|
148
|
+
│ └── modeling.py
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The examples below assume that the `src` directory is available on `PYTHONPATH`.
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Python API Usage
|
|
156
|
+
|
|
157
|
+
The library provides a high-level Functional API via the `heat_cold_spell` package:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
import heat_cold_spell as hcs
|
|
161
|
+
|
|
162
|
+
# 1. Prepare and validate raw observations
|
|
163
|
+
data_info = hcs.prepare_data(
|
|
164
|
+
input_path="raw_daily_data.csv",
|
|
165
|
+
output_path="processed_data.csv"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
# 2. Analyze historical records & generate spell reports + heatmaps
|
|
169
|
+
hist_results = hcs.analyze_history(
|
|
170
|
+
input_path="processed_data.csv",
|
|
171
|
+
output_dir="./outputs/historical",
|
|
172
|
+
location="plains" # Options: 'plains', 'coastal', 'hilly'
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# 3. Train and compare model candidates on chronological holdout
|
|
176
|
+
comparison = hcs.compare_models(
|
|
177
|
+
input_path="processed_data.csv",
|
|
178
|
+
output_dir="./outputs/comparison"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# 4. Refit the winning candidate models on all data
|
|
182
|
+
models = hcs.train_models(
|
|
183
|
+
input_path="processed_data.csv",
|
|
184
|
+
comparison_dir="./outputs/comparison",
|
|
185
|
+
model_dir="./saved_models"
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
# 5. Forecast future daily MAX/MIN temperatures (e.g., 5 years / 1825 days)
|
|
189
|
+
forecasts = hcs.predict_future(
|
|
190
|
+
input_path="processed_data.csv",
|
|
191
|
+
model_dir="./saved_models",
|
|
192
|
+
output_dir="./outputs/forecasts",
|
|
193
|
+
days=1825
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# 6. Detect heat and cold spells in future forecasts
|
|
197
|
+
forecast_spells = hcs.predict_spells(
|
|
198
|
+
input_path="./outputs/forecasts/future_max_min_predictions.csv",
|
|
199
|
+
output_dir="./outputs/forecast_spells",
|
|
200
|
+
location="plains",
|
|
201
|
+
historical_path="processed_data.csv"
|
|
202
|
+
)
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## Command-Line Interface (CLI)
|
|
208
|
+
|
|
209
|
+
Each pipeline stage can also be executed as a module from the repository root.
|
|
210
|
+
First make the `src` directory importable.
|
|
211
|
+
|
|
212
|
+
### PowerShell
|
|
213
|
+
|
|
214
|
+
```powershell
|
|
215
|
+
$env:PYTHONPATH = "src"
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Linux/macOS
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
export PYTHONPATH=src
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Then run the pipeline stages:
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
# Stage 1: Validate and prepare daily CSV/Excel data
|
|
228
|
+
python -m heat_cold_spell.01_prepare_data
|
|
229
|
+
|
|
230
|
+
# Stage 2: Analyze historical trends, heatmaps, and spell events
|
|
231
|
+
python -m heat_cold_spell.02_historical_analysis
|
|
232
|
+
|
|
233
|
+
# Stage 3: Train and evaluate candidate forecasters
|
|
234
|
+
python -m heat_cold_spell.03_train_and_compare \
|
|
235
|
+
--input data/processed/processed_daily_data.csv \
|
|
236
|
+
--output-dir outputs/comparison
|
|
237
|
+
|
|
238
|
+
# Stage 4: Refit the top-ranked models on the full dataset
|
|
239
|
+
python -m heat_cold_spell.04_train_best_model \
|
|
240
|
+
--input data/processed/processed_daily_data.csv \
|
|
241
|
+
--comparison-dir outputs/comparison \
|
|
242
|
+
--model-dir saved_models
|
|
243
|
+
|
|
244
|
+
# Stage 5: Generate multi-year future predictions
|
|
245
|
+
python -m heat_cold_spell.05_predict_future \
|
|
246
|
+
--input data/processed/processed_daily_data.csv \
|
|
247
|
+
--model-dir saved_models \
|
|
248
|
+
--output-dir outputs/forecasts \
|
|
249
|
+
--forecast-days 1825
|
|
250
|
+
|
|
251
|
+
# Stage 6: Detect heat and cold spells
|
|
252
|
+
python -m heat_cold_spell.06_pastspells
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## Output Artefacts
|
|
258
|
+
|
|
259
|
+
| Module / Script | Generated Artefacts |
|
|
260
|
+
| :--- | :--- |
|
|
261
|
+
| `01_prepare_data.py` | `processed_daily_data.csv`, `validation_report.json` |
|
|
262
|
+
| `02_historical_analysis.py` | `daily_classifications.csv`, `spell_events.csv`, `annual_summaries.csv`, `monthly_*_heatmap.png`, `yearly_spell_occurrences.png` |
|
|
263
|
+
| `03_train_and_compare.py` | `{max,min}_model_comparison.xlsx`, `{max,min}_model_predictions.xlsx` |
|
|
264
|
+
| `04_train_best_model.py` | `{max,min}/model_manifest.json`, serialized model weights (`model.keras` or `model.joblib`), `model_selection_explanation.md` |
|
|
265
|
+
| `05_predict_future.py` | `future_max_min_predictions.csv`, `future_monthly_summary.csv`, `future_annual_summary.csv`, `forecast_verification.json`, `future_max_min_forecast.png` |
|
|
266
|
+
| `06_pastspells.py` | Daily spell classification and spell-event output files |
|
|
267
|
+
| `predict_spells` | `daily_spell_classification.csv`, `spell_events.csv` |
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Heat & Cold Spell Analysis and Forecasting Library
|
|
2
|
+
|
|
3
|
+
A Python library and workflow pipeline for analyzing historical daily extreme temperatures (maximum and minimum), training predictive machine learning models, and identifying heat waves and cold waves under standardized meteorological criteria.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Technical Overview & Architecture
|
|
8
|
+
|
|
9
|
+
The pipeline processes daily maximum ($T_{\max}$) and minimum ($T_{\min}$) temperatures through a six-stage workflow:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
+-----------------------------------------------------------------------------------+
|
|
13
|
+
| 1. Data Preparation & Validation |
|
|
14
|
+
| Inputs raw daily MAX/MIN data -> Cleans, standardizes dates, and validates schema |
|
|
15
|
+
+-----------------------------------------------------------------------------------+
|
|
16
|
+
|
|
|
17
|
+
+-------------------------------+-------------------------------+
|
|
18
|
+
| |
|
|
19
|
+
v v
|
|
20
|
+
+------------------------------------+ +------------------------------------+
|
|
21
|
+
| 2. Retrospective Historical | | 3. Model Training & Comparison |
|
|
22
|
+
| Analysis & Spell Detection | | Evaluates candidate forecasters|
|
|
23
|
+
| - Computes 15-year normals | | on chronological holdout split |
|
|
24
|
+
| - Identifies heat/cold spells | +------------------------------------+
|
|
25
|
+
| - Generates annual summaries | |
|
|
26
|
+
+------------------------------------+ v
|
|
27
|
+
+------------------------------------+
|
|
28
|
+
| 4. Model Refitting & Manifest |
|
|
29
|
+
| Refits winning candidate models|
|
|
30
|
+
| on all available data |
|
|
31
|
+
+------------------------------------+
|
|
32
|
+
|
|
|
33
|
+
v
|
|
34
|
+
+------------------------------------+
|
|
35
|
+
| 5. Multi-Year Future Prediction |
|
|
36
|
+
| Generates forward predictions |
|
|
37
|
+
| (e.g., 5-year horizon) |
|
|
38
|
+
+------------------------------------+
|
|
39
|
+
|
|
|
40
|
+
v
|
|
41
|
+
+------------------------------------+
|
|
42
|
+
| 6. Forecast Spell Detection |
|
|
43
|
+
| Applies spell rules to future |
|
|
44
|
+
| forecasts using prior normals |
|
|
45
|
+
+------------------------------------+
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Theoretical & Methodological Foundations
|
|
51
|
+
|
|
52
|
+
### 1. Climatological Normals & Departures
|
|
53
|
+
Daily temperature anomalies are measured relative to **calendar-day climatological normals** calculated across a 15-year baseline window:
|
|
54
|
+
|
|
55
|
+
* **Historical Analysis**: Uses a 15-year centered moving window ($\pm 7$ years around the given year) to account for multi-decadal trends. A trailing 15-year window is applied to the final 7 historical years.
|
|
56
|
+
* **Forecast Spell Detection**: Uses a trailing 15-year window of observed data immediately preceding the forecast period to avoid future data leakage.
|
|
57
|
+
|
|
58
|
+
Temperature departures (anomalies) are defined as:
|
|
59
|
+
|
|
60
|
+
$$\Delta T_{\max} = T_{\max} - N_{\max, d}, \quad \Delta T_{\min} = T_{\min} - N_{\min, d}$$
|
|
61
|
+
|
|
62
|
+
where $N_{\max, d}$ and $N_{\min, d}$ represent the 15-year mean normal temperatures for calendar day $d \in [1, 365]$.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
### 2. Meteorological Wave & Spell Criteria
|
|
67
|
+
|
|
68
|
+
#### Daily Classifications
|
|
69
|
+
|
|
70
|
+
* **Heat Wave Day**: Triggered if either:
|
|
71
|
+
1. **Regional Threshold + Departure**: $T_{\max} \ge T_{\text{regional}}$ **AND** $\Delta T_{\max} \ge +4.5^\circ\text{C}$
|
|
72
|
+
* *Plains*: $T_{\text{regional}} = 40.0^\circ\text{C}$
|
|
73
|
+
* *Coastal*: $T_{\text{regional}} = 37.0^\circ\text{C}$
|
|
74
|
+
* *Hilly*: $T_{\text{regional}} = 30.0^\circ\text{C}$
|
|
75
|
+
2. **Absolute Extreme Threshold**: $T_{\max} \ge 45.0^\circ\text{C}$ (regardless of departure).
|
|
76
|
+
* **Cold Wave Day**: Triggered if:
|
|
77
|
+
* $T_{\min} < 10.0^\circ\text{C}$ **AND** $\Delta T_{\min} \le -3.0^\circ\text{C}$
|
|
78
|
+
|
|
79
|
+
#### Spell Event Aggregation
|
|
80
|
+
Consecutive qualifying extreme days are grouped into formal spell events based on duration triggers:
|
|
81
|
+
|
|
82
|
+
* **Heat Wave Event**: $\ge 5$ consecutive Heat Wave Days **OR** $\ge 2$ consecutive days with $T_{\max} \ge 45.0^\circ\text{C}$.
|
|
83
|
+
* **Cold Wave Event**: $\ge 5$ consecutive Cold Wave Days.
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
### 3. Machine Learning Forecasting Pipeline
|
|
88
|
+
|
|
89
|
+
#### Candidate Model Families
|
|
90
|
+
The pipeline evaluates six model architectures separately for $T_{\max}$ and $T_{\min}$:
|
|
91
|
+
|
|
92
|
+
1. **Seasonal Baseline**: Non-parametric daily climatology mean benchmark.
|
|
93
|
+
2. **Trend + Fourier**: Linear trend combined with 6 harmonic sine/cosine annual cycles.
|
|
94
|
+
3. **Random Forest**: Non-linear ensemble trees on calendar and rolling lag features.
|
|
95
|
+
4. **DNN**: Deep Feed-Forward Neural Network on engineered temporal features.
|
|
96
|
+
5. **LSTM**: Long Short-Term Memory recurrent neural network over 60-day sequence lookbacks.
|
|
97
|
+
6. **GRU**: Gated Recurrent Unit neural network over 60-day sequence lookbacks.
|
|
98
|
+
|
|
99
|
+
#### Chronological Holdout Evaluation
|
|
100
|
+
Models are evaluated on a chronological test period (`2022-06-01` to `2024-05-31`) to prevent temporal data leakage. Selection prioritizes models using the following metric hierarchy:
|
|
101
|
+
|
|
102
|
+
$$\text{Rank Criteria: } \text{RMSE} \longrightarrow \text{MAE} \longrightarrow R^2 \longrightarrow |\text{Bias}|$$
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Installation & Setup
|
|
107
|
+
|
|
108
|
+
### Requirements
|
|
109
|
+
* Python 3.9+
|
|
110
|
+
* Required packages: `numpy`, `pandas`, `scikit-learn`, `tensorflow`, `joblib`, `openpyxl`, `matplotlib`
|
|
111
|
+
|
|
112
|
+
### Directory Structure Requirements
|
|
113
|
+
```text
|
|
114
|
+
.
|
|
115
|
+
├── src/
|
|
116
|
+
│ └── heat_cold_spell/
|
|
117
|
+
│ ├── __init__.py
|
|
118
|
+
│ ├── heat_cold_spell.py # Primary high-level API wrapper
|
|
119
|
+
│ ├── config.py
|
|
120
|
+
│ ├── 01_prepare_data.py # CLI Stage 1: Data preparation
|
|
121
|
+
│ ├── 02_historical_analysis.py # CLI Stage 2: Historical analysis
|
|
122
|
+
│ ├── 03_train_and_compare.py # CLI Stage 3: Model comparison
|
|
123
|
+
│ ├── 04_train_best_model.py # CLI Stage 4: Model refitting
|
|
124
|
+
│ ├── 05_predict_future.py # CLI Stage 5: Future prediction
|
|
125
|
+
│ ├── 06_pastspells.py # CLI Stage 6: Spell detection
|
|
126
|
+
│ └── pipeline/ # Internal processing modules
|
|
127
|
+
│ ├── __init__.py
|
|
128
|
+
│ ├── data.py
|
|
129
|
+
│ ├── historical.py
|
|
130
|
+
│ └── modeling.py
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The examples below assume that the `src` directory is available on `PYTHONPATH`.
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Python API Usage
|
|
138
|
+
|
|
139
|
+
The library provides a high-level Functional API via the `heat_cold_spell` package:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
import heat_cold_spell as hcs
|
|
143
|
+
|
|
144
|
+
# 1. Prepare and validate raw observations
|
|
145
|
+
data_info = hcs.prepare_data(
|
|
146
|
+
input_path="raw_daily_data.csv",
|
|
147
|
+
output_path="processed_data.csv"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# 2. Analyze historical records & generate spell reports + heatmaps
|
|
151
|
+
hist_results = hcs.analyze_history(
|
|
152
|
+
input_path="processed_data.csv",
|
|
153
|
+
output_dir="./outputs/historical",
|
|
154
|
+
location="plains" # Options: 'plains', 'coastal', 'hilly'
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# 3. Train and compare model candidates on chronological holdout
|
|
158
|
+
comparison = hcs.compare_models(
|
|
159
|
+
input_path="processed_data.csv",
|
|
160
|
+
output_dir="./outputs/comparison"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# 4. Refit the winning candidate models on all data
|
|
164
|
+
models = hcs.train_models(
|
|
165
|
+
input_path="processed_data.csv",
|
|
166
|
+
comparison_dir="./outputs/comparison",
|
|
167
|
+
model_dir="./saved_models"
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# 5. Forecast future daily MAX/MIN temperatures (e.g., 5 years / 1825 days)
|
|
171
|
+
forecasts = hcs.predict_future(
|
|
172
|
+
input_path="processed_data.csv",
|
|
173
|
+
model_dir="./saved_models",
|
|
174
|
+
output_dir="./outputs/forecasts",
|
|
175
|
+
days=1825
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# 6. Detect heat and cold spells in future forecasts
|
|
179
|
+
forecast_spells = hcs.predict_spells(
|
|
180
|
+
input_path="./outputs/forecasts/future_max_min_predictions.csv",
|
|
181
|
+
output_dir="./outputs/forecast_spells",
|
|
182
|
+
location="plains",
|
|
183
|
+
historical_path="processed_data.csv"
|
|
184
|
+
)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
## Command-Line Interface (CLI)
|
|
190
|
+
|
|
191
|
+
Each pipeline stage can also be executed as a module from the repository root.
|
|
192
|
+
First make the `src` directory importable.
|
|
193
|
+
|
|
194
|
+
### PowerShell
|
|
195
|
+
|
|
196
|
+
```powershell
|
|
197
|
+
$env:PYTHONPATH = "src"
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Linux/macOS
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
export PYTHONPATH=src
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Then run the pipeline stages:
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
# Stage 1: Validate and prepare daily CSV/Excel data
|
|
210
|
+
python -m heat_cold_spell.01_prepare_data
|
|
211
|
+
|
|
212
|
+
# Stage 2: Analyze historical trends, heatmaps, and spell events
|
|
213
|
+
python -m heat_cold_spell.02_historical_analysis
|
|
214
|
+
|
|
215
|
+
# Stage 3: Train and evaluate candidate forecasters
|
|
216
|
+
python -m heat_cold_spell.03_train_and_compare \
|
|
217
|
+
--input data/processed/processed_daily_data.csv \
|
|
218
|
+
--output-dir outputs/comparison
|
|
219
|
+
|
|
220
|
+
# Stage 4: Refit the top-ranked models on the full dataset
|
|
221
|
+
python -m heat_cold_spell.04_train_best_model \
|
|
222
|
+
--input data/processed/processed_daily_data.csv \
|
|
223
|
+
--comparison-dir outputs/comparison \
|
|
224
|
+
--model-dir saved_models
|
|
225
|
+
|
|
226
|
+
# Stage 5: Generate multi-year future predictions
|
|
227
|
+
python -m heat_cold_spell.05_predict_future \
|
|
228
|
+
--input data/processed/processed_daily_data.csv \
|
|
229
|
+
--model-dir saved_models \
|
|
230
|
+
--output-dir outputs/forecasts \
|
|
231
|
+
--forecast-days 1825
|
|
232
|
+
|
|
233
|
+
# Stage 6: Detect heat and cold spells
|
|
234
|
+
python -m heat_cold_spell.06_pastspells
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## Output Artefacts
|
|
240
|
+
|
|
241
|
+
| Module / Script | Generated Artefacts |
|
|
242
|
+
| :--- | :--- |
|
|
243
|
+
| `01_prepare_data.py` | `processed_daily_data.csv`, `validation_report.json` |
|
|
244
|
+
| `02_historical_analysis.py` | `daily_classifications.csv`, `spell_events.csv`, `annual_summaries.csv`, `monthly_*_heatmap.png`, `yearly_spell_occurrences.png` |
|
|
245
|
+
| `03_train_and_compare.py` | `{max,min}_model_comparison.xlsx`, `{max,min}_model_predictions.xlsx` |
|
|
246
|
+
| `04_train_best_model.py` | `{max,min}/model_manifest.json`, serialized model weights (`model.keras` or `model.joblib`), `model_selection_explanation.md` |
|
|
247
|
+
| `05_predict_future.py` | `future_max_min_predictions.csv`, `future_monthly_summary.csv`, `future_annual_summary.csv`, `forecast_verification.json`, `future_max_min_forecast.png` |
|
|
248
|
+
| `06_pastspells.py` | Daily spell classification and spell-event output files |
|
|
249
|
+
| `predict_spells` | `daily_spell_classification.csv`, `spell_events.csv` |
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "heat-cold-spell"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Heat and cold spell analysis and forecasting library"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
|
|
13
|
+
dependencies = [
|
|
14
|
+
"numpy",
|
|
15
|
+
"pandas",
|
|
16
|
+
"scikit-learn",
|
|
17
|
+
"tensorflow",
|
|
18
|
+
"joblib",
|
|
19
|
+
"openpyxl",
|
|
20
|
+
"matplotlib",
|
|
21
|
+
"scipy"
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
testpaths = ["tests"]
|
|
29
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Stage 1: validate raw observations and save a processed copy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from heat_cold_spell.config import (
|
|
10
|
+
REQUIRED_COLUMNS,
|
|
11
|
+
)
|
|
12
|
+
from heat_cold_spell.pipeline.data import load_and_validate_daily_data
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_arguments() -> argparse.Namespace:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
description="Validate raw observations and save a processed copy."
|
|
18
|
+
)
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--input",
|
|
21
|
+
type=Path,
|
|
22
|
+
required=True,
|
|
23
|
+
help="Input CSV file containing the raw daily observations.",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--output",
|
|
27
|
+
type=Path,
|
|
28
|
+
required=True,
|
|
29
|
+
help="Output path for the processed CSV file.",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--report",
|
|
33
|
+
type=Path,
|
|
34
|
+
required=True,
|
|
35
|
+
help="Output path for the validation JSON report.",
|
|
36
|
+
)
|
|
37
|
+
return parser.parse_args()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main() -> None:
|
|
41
|
+
args = parse_arguments()
|
|
42
|
+
input_path = args.input.expanduser()
|
|
43
|
+
output_path = args.output.expanduser()
|
|
44
|
+
report_path = args.report.expanduser()
|
|
45
|
+
|
|
46
|
+
if not input_path.is_file():
|
|
47
|
+
raise FileNotFoundError(f"Input CSV file not found: {input_path}")
|
|
48
|
+
|
|
49
|
+
data, report = load_and_validate_daily_data(input_path, REQUIRED_COLUMNS)
|
|
50
|
+
|
|
51
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
report_path.parent.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
|
|
54
|
+
data.to_csv(output_path, index=False, date_format="%Y-%m-%d")
|
|
55
|
+
report_path.write_text(
|
|
56
|
+
json.dumps(report, indent=2),
|
|
57
|
+
encoding="utf-8",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
print("Data validation completed successfully.")
|
|
61
|
+
print(f"Rows processed: {report.get('row_count', len(data))}")
|
|
62
|
+
if "start_date" in report and "end_date" in report:
|
|
63
|
+
print(f"Date range: {report['start_date']} to {report['end_date']}")
|
|
64
|
+
print(f"Processed data saved to: {output_path}")
|
|
65
|
+
print(f"Validation report saved to: {report_path}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
main()
|