xairon commited on
Commit
81a8f21
·
verified ·
1 Parent(s): 24f3787

Upload notebooks/01_data_exploration.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. notebooks/01_data_exploration.ipynb +817 -0
notebooks/01_data_exploration.ipynb ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Benchmark Dataset Exploration\n",
8
+ "\n",
9
+ "This notebook explores the piezometric time-series dataset used in the embedding benchmark.\n",
10
+ "The dataset contains daily groundwater level measurements from the French national monitoring network (BRGM),\n",
11
+ "augmented with ERA5 climate reanalysis covariates.\n",
12
+ "\n",
13
+ "**Files:**\n",
14
+ "- `station_metadata.parquet` -- 4,210 stations with hydrogeological labels\n",
15
+ "- `piezo_daily_uni.parquet` -- univariate daily groundwater levels (2,000 stations)\n",
16
+ "- `piezo_daily_multi.parquet` -- multivariate daily series: groundwater + 3 ERA5 covariates\n",
17
+ "\n",
18
+ "**Goal:** Understand data characteristics (class balance, coverage, quality) before designing the embedding evaluation protocol."
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "import warnings\n",
28
+ "warnings.filterwarnings(\"ignore\")\n",
29
+ "\n",
30
+ "import numpy as np\n",
31
+ "import pandas as pd\n",
32
+ "import plotly.express as px\n",
33
+ "import plotly.graph_objects as go\n",
34
+ "from plotly.subplots import make_subplots\n",
35
+ "\n",
36
+ "# Consistent color palette for milieu_eh classes\n",
37
+ "MILIEU_COLORS = {\n",
38
+ " \"Poreux\": \"#636EFA\",\n",
39
+ " \"Fissure\": \"#EF553B\",\n",
40
+ " \"Karstique\": \"#00CC96\",\n",
41
+ " \"Double porosite F+P\": \"#AB63FA\",\n",
42
+ " \"Double porosite K+P\": \"#FFA15A\",\n",
43
+ " \"Composite\": \"#19D3F3\",\n",
44
+ " \"Non applicable\": \"#B6E880\",\n",
45
+ " \"Indetermine\": \"#FF6692\",\n",
46
+ "}\n",
47
+ "\n",
48
+ "# Short readable labels for milieu_eh codes\n",
49
+ "MILIEU_LABELS = {\n",
50
+ " \"1\": \"Poreux\",\n",
51
+ " \"2\": \"Fissure\",\n",
52
+ " \"3\": \"Karstique\",\n",
53
+ " \"4\": \"Double porosite F+P\",\n",
54
+ " \"5\": \"Double porosite K+P\",\n",
55
+ " \"6\": \"Double porosite K+F\",\n",
56
+ " \"8\": \"Composite\",\n",
57
+ " \"9\": \"Non applicable\",\n",
58
+ " \"X\": \"Indetermine\",\n",
59
+ "}\n",
60
+ "\n",
61
+ "DATA_DIR = \"../data\"\n",
62
+ "\n",
63
+ "# Plotly template for publication-quality figures\n",
64
+ "TEMPLATE = \"plotly_white\"\n",
65
+ "FONT = dict(family=\"Arial\", size=13)\n",
66
+ "\n",
67
+ "print(\"Libraries loaded.\")"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "markdown",
72
+ "metadata": {},
73
+ "source": [
74
+ "---\n",
75
+ "## 1. Dataset Overview\n",
76
+ "\n",
77
+ "Load the station metadata and inspect its structure, types, and basic statistics."
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "execution_count": null,
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "meta = pd.read_parquet(f\"{DATA_DIR}/station_metadata.parquet\")\n",
87
+ "print(f\"Shape: {meta.shape[0]} stations x {meta.shape[1]} columns\")\n",
88
+ "print(f\"\\nColumn types:\\n{meta.dtypes.to_string()}\")\n",
89
+ "meta.head()"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "execution_count": null,
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "# Add a readable milieu label column\n",
99
+ "meta[\"milieu_label\"] = meta[\"milieu_eh\"].map(MILIEU_LABELS)\n",
100
+ "\n",
101
+ "# Summary statistics for numeric columns\n",
102
+ "numeric_cols = [\n",
103
+ " \"latitude\", \"longitude\", \"altitude_station\",\n",
104
+ " \"profondeur_moyenne_globale\", \"niveau_stddev_global\",\n",
105
+ " \"amplitude_totale\", \"nb_mois_total\",\n",
106
+ "]\n",
107
+ "meta[numeric_cols].describe().round(2)"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "metadata": {},
113
+ "source": [
114
+ "---\n",
115
+ "## 2. Label Distribution\n",
116
+ "\n",
117
+ "The classification target is `milieu_eh`, encoding the hydrogeological environment of each station.\n",
118
+ "This section quantifies the class imbalance, which is critical for choosing evaluation metrics\n",
119
+ "(balanced accuracy, macro-F1) and designing stratified cross-validation splits."
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": null,
125
+ "metadata": {},
126
+ "outputs": [],
127
+ "source": [
128
+ "# Filter stations with a valid milieu_eh label\n",
129
+ "meta_labeled = meta.dropna(subset=[\"milieu_eh\"]).copy()\n",
130
+ "print(f\"Stations with milieu_eh label: {len(meta_labeled)} / {len(meta)} \"\n",
131
+ " f\"({len(meta) - len(meta_labeled)} missing)\")\n",
132
+ "\n",
133
+ "# Value counts\n",
134
+ "vc = meta_labeled[\"milieu_label\"].value_counts()\n",
135
+ "vc_pct = meta_labeled[\"milieu_label\"].value_counts(normalize=True) * 100\n",
136
+ "\n",
137
+ "dist_df = pd.DataFrame({\"count\": vc, \"pct\": vc_pct.round(1)}).reset_index()\n",
138
+ "dist_df.columns = [\"milieu_eh\", \"count\", \"pct\"]\n",
139
+ "dist_df[\"label\"] = dist_df.apply(lambda r: f\"{r['count']} ({r['pct']}%)\", axis=1)\n",
140
+ "dist_df"
141
+ ]
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "execution_count": null,
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "fig = px.bar(\n",
150
+ " dist_df,\n",
151
+ " x=\"milieu_eh\",\n",
152
+ " y=\"count\",\n",
153
+ " color=\"milieu_eh\",\n",
154
+ " color_discrete_map=MILIEU_COLORS,\n",
155
+ " text=\"label\",\n",
156
+ " template=TEMPLATE,\n",
157
+ " title=\"Distribution of hydrogeological environment classes (milieu_eh)\",\n",
158
+ " labels={\"milieu_eh\": \"Hydrogeological class\", \"count\": \"Number of stations\"},\n",
159
+ ")\n",
160
+ "fig.update_traces(textposition=\"outside\")\n",
161
+ "fig.update_layout(\n",
162
+ " font=FONT,\n",
163
+ " showlegend=False,\n",
164
+ " yaxis_range=[0, dist_df[\"count\"].max() * 1.15],\n",
165
+ " height=450,\n",
166
+ " width=800,\n",
167
+ ")\n",
168
+ "fig.show()"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "markdown",
173
+ "metadata": {},
174
+ "source": [
175
+ "**Key observation:** The dataset is heavily imbalanced. *Poreux* (porous) alone represents ~48% of labeled stations,\n",
176
+ "while minority classes (*Indetermine*, *Karstique*) have fewer than 200 samples each.\n",
177
+ "This motivates the use of balanced accuracy and macro-averaged F1 as primary evaluation metrics,\n",
178
+ "along with stratified cross-validation and class-weighted classifiers."
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "markdown",
183
+ "metadata": {},
184
+ "source": [
185
+ "---\n",
186
+ "## 3. Geographic Distribution\n",
187
+ "\n",
188
+ "Station locations across metropolitan France, colored by hydrogeological environment.\n",
189
+ "Geographic clustering of classes would indicate spatial autocorrelation, which must be\n",
190
+ "handled in the evaluation protocol (e.g., spatial cross-validation by departement)."
191
+ ]
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "execution_count": null,
196
+ "metadata": {},
197
+ "outputs": [],
198
+ "source": [
199
+ "fig = px.scatter_mapbox(\n",
200
+ " meta_labeled,\n",
201
+ " lat=\"latitude\",\n",
202
+ " lon=\"longitude\",\n",
203
+ " color=\"milieu_label\",\n",
204
+ " color_discrete_map=MILIEU_COLORS,\n",
205
+ " hover_name=\"code_bss\",\n",
206
+ " hover_data=[\"altitude_station\", \"nb_mois_total\", \"milieu_label\"],\n",
207
+ " zoom=4.5,\n",
208
+ " center={\"lat\": 46.5, \"lon\": 2.5},\n",
209
+ " mapbox_style=\"carto-positron\",\n",
210
+ " title=\"Geographic distribution of monitoring stations by hydrogeological class\",\n",
211
+ " labels={\"milieu_label\": \"Hydrogeological class\"},\n",
212
+ " opacity=0.7,\n",
213
+ " height=650,\n",
214
+ " width=850,\n",
215
+ ")\n",
216
+ "fig.update_layout(font=FONT, template=TEMPLATE, margin=dict(l=0, r=0, t=40, b=0))\n",
217
+ "fig.show()"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "# Fallback: simple scatter plot (lat vs lon) in case mapbox is unavailable\n",
227
+ "fig_scatter = px.scatter(\n",
228
+ " meta_labeled,\n",
229
+ " x=\"longitude\",\n",
230
+ " y=\"latitude\",\n",
231
+ " color=\"milieu_label\",\n",
232
+ " color_discrete_map=MILIEU_COLORS,\n",
233
+ " hover_name=\"code_bss\",\n",
234
+ " title=\"Station locations (latitude vs. longitude) by hydrogeological class\",\n",
235
+ " labels={\"longitude\": \"Longitude\", \"latitude\": \"Latitude\", \"milieu_label\": \"Class\"},\n",
236
+ " template=TEMPLATE,\n",
237
+ " opacity=0.6,\n",
238
+ " height=550,\n",
239
+ " width=750,\n",
240
+ ")\n",
241
+ "fig_scatter.update_traces(marker=dict(size=4))\n",
242
+ "fig_scatter.update_layout(font=FONT)\n",
243
+ "fig_scatter.show()"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "metadata": {},
249
+ "source": [
250
+ "**Observation:** Classes exhibit clear spatial clustering (e.g., porous aquifers dominate\n",
251
+ "sedimentary basins such as the Paris Basin and Aquitaine, while karst stations cluster in\n",
252
+ "limestone regions). This confirms that geographic cross-validation (split by departement)\n",
253
+ "is necessary to avoid spatial leakage."
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "---\n",
261
+ "## 4. Altitude Distribution\n",
262
+ "\n",
263
+ "Station altitude varies widely across France and correlates with hydrogeological environment.\n",
264
+ "Karst systems tend to occur at higher altitudes (limestone plateaus, mountain foothills),\n",
265
+ "while porous aquifers dominate low-altitude sedimentary plains."
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "execution_count": null,
271
+ "metadata": {},
272
+ "outputs": [],
273
+ "source": [
274
+ "# Histogram of altitude, colored by class\n",
275
+ "fig = px.histogram(\n",
276
+ " meta_labeled,\n",
277
+ " x=\"altitude_station\",\n",
278
+ " color=\"milieu_label\",\n",
279
+ " color_discrete_map=MILIEU_COLORS,\n",
280
+ " nbins=60,\n",
281
+ " barmode=\"stack\",\n",
282
+ " title=\"Altitude distribution of stations by hydrogeological class\",\n",
283
+ " labels={\"altitude_station\": \"Altitude (m a.s.l.)\", \"milieu_label\": \"Class\"},\n",
284
+ " template=TEMPLATE,\n",
285
+ " height=400,\n",
286
+ " width=800,\n",
287
+ ")\n",
288
+ "fig.update_layout(font=FONT)\n",
289
+ "fig.show()"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "execution_count": null,
295
+ "metadata": {},
296
+ "outputs": [],
297
+ "source": [
298
+ "# Box plot: altitude per class\n",
299
+ "fig = px.box(\n",
300
+ " meta_labeled,\n",
301
+ " x=\"milieu_label\",\n",
302
+ " y=\"altitude_station\",\n",
303
+ " color=\"milieu_label\",\n",
304
+ " color_discrete_map=MILIEU_COLORS,\n",
305
+ " title=\"Altitude distribution per hydrogeological class\",\n",
306
+ " labels={\"altitude_station\": \"Altitude (m a.s.l.)\", \"milieu_label\": \"Class\"},\n",
307
+ " template=TEMPLATE,\n",
308
+ " height=450,\n",
309
+ " width=800,\n",
310
+ ")\n",
311
+ "fig.update_layout(font=FONT, showlegend=False, xaxis_tickangle=-30)\n",
312
+ "fig.show()"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "markdown",
317
+ "metadata": {},
318
+ "source": [
319
+ "---\n",
320
+ "## 5. Time Series Examples\n",
321
+ "\n",
322
+ "We select one representative station per major hydrogeological class to illustrate the\n",
323
+ "diversity of groundwater dynamics. Different aquifer types exhibit fundamentally different\n",
324
+ "temporal behaviors (smooth vs. flashy responses, seasonal vs. multi-year trends),\n",
325
+ "which is precisely what we expect embeddings to capture."
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": null,
331
+ "metadata": {},
332
+ "outputs": [],
333
+ "source": [
334
+ "# Load univariate time series\n",
335
+ "uni = pd.read_parquet(f\"{DATA_DIR}/piezo_daily_uni.parquet\")\n",
336
+ "uni[\"date\"] = pd.to_datetime(uni[\"date\"])\n",
337
+ "print(f\"Univariate dataset: {uni.shape[0]:,} rows, {uni['code_bss'].nunique()} stations\")\n",
338
+ "uni.head()"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "execution_count": null,
344
+ "metadata": {},
345
+ "outputs": [],
346
+ "source": [
347
+ "# Select one representative station per major class\n",
348
+ "# We pick stations with good data coverage (high nb_mois_total)\n",
349
+ "TARGET_CLASSES = [\"Poreux\", \"Fissure\", \"Karstique\", \"Double porosite F+P\",\n",
350
+ " \"Double porosite K+P\", \"Composite\"]\n",
351
+ "\n",
352
+ "example_stations = []\n",
353
+ "for cls in TARGET_CLASSES:\n",
354
+ " candidates = meta_labeled[\n",
355
+ " (meta_labeled[\"milieu_label\"] == cls) &\n",
356
+ " (meta_labeled[\"nb_mois_total\"] > meta_labeled[\"nb_mois_total\"].quantile(0.7))\n",
357
+ " ].sort_values(\"nb_mois_total\", ascending=False)\n",
358
+ " if len(candidates) > 0:\n",
359
+ " # Pick the station closest to the median coverage in top 30%\n",
360
+ " mid = len(candidates) // 2\n",
361
+ " example_stations.append(candidates.iloc[mid])\n",
362
+ "\n",
363
+ "example_ids = [s[\"code_bss\"] for s in example_stations]\n",
364
+ "print(f\"Selected {len(example_ids)} stations:\")\n",
365
+ "for s in example_stations:\n",
366
+ " print(f\" {s['code_bss']:20s} {s['milieu_label']:30s} ({s['nb_mois_total']} months)\")"
367
+ ]
368
+ },
369
+ {
370
+ "cell_type": "code",
371
+ "execution_count": null,
372
+ "metadata": {},
373
+ "outputs": [],
374
+ "source": [
375
+ "# Plot time series for each selected station\n",
376
+ "uni_examples = uni[uni[\"code_bss\"].isin(example_ids)].copy()\n",
377
+ "uni_examples = uni_examples.merge(\n",
378
+ " meta[[\"code_bss\", \"milieu_label\"]], on=\"code_bss\", how=\"left\"\n",
379
+ ")\n",
380
+ "\n",
381
+ "n_stations = len(example_ids)\n",
382
+ "fig = make_subplots(\n",
383
+ " rows=n_stations, cols=1,\n",
384
+ " shared_xaxes=True,\n",
385
+ " vertical_spacing=0.03,\n",
386
+ " subplot_titles=[\n",
387
+ " f\"{s['milieu_label']} -- {s['code_bss']}\"\n",
388
+ " for s in example_stations\n",
389
+ " ],\n",
390
+ ")\n",
391
+ "\n",
392
+ "for i, station in enumerate(example_stations):\n",
393
+ " bss = station[\"code_bss\"]\n",
394
+ " cls = station[\"milieu_label\"]\n",
395
+ " ts = uni_examples[uni_examples[\"code_bss\"] == bss].sort_values(\"date\")\n",
396
+ " color = MILIEU_COLORS.get(cls, \"#636EFA\")\n",
397
+ " fig.add_trace(\n",
398
+ " go.Scatter(\n",
399
+ " x=ts[\"date\"], y=ts[\"niveau_nappe_eau\"],\n",
400
+ " mode=\"lines\", name=cls,\n",
401
+ " line=dict(color=color, width=1),\n",
402
+ " showlegend=(i == 0),\n",
403
+ " ),\n",
404
+ " row=i + 1, col=1,\n",
405
+ " )\n",
406
+ " fig.update_yaxes(title_text=\"Level (m NGF)\", row=i + 1, col=1)\n",
407
+ "\n",
408
+ "fig.update_layout(\n",
409
+ " height=250 * n_stations,\n",
410
+ " width=900,\n",
411
+ " title_text=\"Representative groundwater level time series by hydrogeological class\",\n",
412
+ " template=TEMPLATE,\n",
413
+ " font=FONT,\n",
414
+ " showlegend=False,\n",
415
+ ")\n",
416
+ "fig.update_xaxes(title_text=\"Date\", row=n_stations, col=1)\n",
417
+ "fig.show()"
418
+ ]
419
+ },
420
+ {
421
+ "cell_type": "markdown",
422
+ "metadata": {},
423
+ "source": [
424
+ "**Observation:** The six classes display markedly different temporal dynamics:\n",
425
+ "- **Poreux** (porous): smooth, slow inertia with long-period seasonal cycles.\n",
426
+ "- **Fissure** (fractured): more reactive, with sharper peaks and recession curves.\n",
427
+ "- **Karstique** (karst): flashy, spiky responses to precipitation events.\n",
428
+ "- **Double porosity** classes: intermediate behaviors reflecting mixed aquifer properties.\n",
429
+ "- **Composite**: complex, irregular patterns.\n",
430
+ "\n",
431
+ "These differences in temporal shape are exactly what time-series embeddings should encode."
432
+ ]
433
+ },
434
+ {
435
+ "cell_type": "markdown",
436
+ "metadata": {},
437
+ "source": [
438
+ "---\n",
439
+ "## 6. Multivariate View\n",
440
+ "\n",
441
+ "For one station, we visualize all four variables from the multivariate dataset:\n",
442
+ "groundwater level + three ERA5 climate covariates (temperature, precipitation, evapotranspiration).\n",
443
+ "This illustrates why multivariate embeddings may capture additional signal: climatic forcing\n",
444
+ "drives aquifer recharge, and different hydrogeological environments respond differently to\n",
445
+ "the same climate inputs."
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": null,
451
+ "metadata": {},
452
+ "outputs": [],
453
+ "source": [
454
+ "# Load multivariate data for one station\n",
455
+ "multi = pd.read_parquet(f\"{DATA_DIR}/piezo_daily_multi.parquet\")\n",
456
+ "multi[\"date\"] = pd.to_datetime(multi[\"date\"])\n",
457
+ "print(f\"Multivariate dataset: {multi.shape[0]:,} rows, {multi['code_bss'].nunique()} stations\")\n",
458
+ "print(f\"Variables: {list(multi.columns)}\")"
459
+ ]
460
+ },
461
+ {
462
+ "cell_type": "code",
463
+ "execution_count": null,
464
+ "metadata": {},
465
+ "outputs": [],
466
+ "source": [
467
+ "# Pick the first example station\n",
468
+ "demo_bss = example_ids[0]\n",
469
+ "demo_cls = example_stations[0][\"milieu_label\"]\n",
470
+ "ts_multi = multi[multi[\"code_bss\"] == demo_bss].sort_values(\"date\").copy()\n",
471
+ "\n",
472
+ "# Limit to a 5-year window for readability\n",
473
+ "ts_multi_window = ts_multi[\n",
474
+ " (ts_multi[\"date\"] >= ts_multi[\"date\"].min() + pd.Timedelta(days=365))\n",
475
+ " & (ts_multi[\"date\"] < ts_multi[\"date\"].min() + pd.Timedelta(days=365 * 6))\n",
476
+ "]\n",
477
+ "\n",
478
+ "variables = [\n",
479
+ " (\"niveau_nappe_eau\", \"Groundwater level (m NGF)\", \"#636EFA\"),\n",
480
+ " (\"temperature_2m\", \"Temperature 2m (K)\", \"#EF553B\"),\n",
481
+ " (\"total_precipitation\", \"Precipitation (m/day)\", \"#00CC96\"),\n",
482
+ " (\"potential_evaporation\", \"Pot. evapotranspiration (m/day)\", \"#FFA15A\"),\n",
483
+ "]\n",
484
+ "\n",
485
+ "fig = make_subplots(\n",
486
+ " rows=4, cols=1,\n",
487
+ " shared_xaxes=True,\n",
488
+ " vertical_spacing=0.05,\n",
489
+ " subplot_titles=[v[1] for v in variables],\n",
490
+ ")\n",
491
+ "\n",
492
+ "for i, (col, label, color) in enumerate(variables):\n",
493
+ " fig.add_trace(\n",
494
+ " go.Scatter(\n",
495
+ " x=ts_multi_window[\"date\"], y=ts_multi_window[col],\n",
496
+ " mode=\"lines\", name=label,\n",
497
+ " line=dict(color=color, width=1),\n",
498
+ " ),\n",
499
+ " row=i + 1, col=1,\n",
500
+ " )\n",
501
+ " fig.update_yaxes(title_text=label.split(\"(\")[0].strip(), row=i + 1, col=1)\n",
502
+ "\n",
503
+ "fig.update_layout(\n",
504
+ " height=800,\n",
505
+ " width=900,\n",
506
+ " title_text=f\"Multivariate view: {demo_bss} ({demo_cls})\",\n",
507
+ " template=TEMPLATE,\n",
508
+ " font=FONT,\n",
509
+ " showlegend=False,\n",
510
+ ")\n",
511
+ "fig.update_xaxes(title_text=\"Date\", row=4, col=1)\n",
512
+ "fig.show()"
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "markdown",
517
+ "metadata": {},
518
+ "source": [
519
+ "**Key insight:** Groundwater level responds to seasonal precipitation and evapotranspiration cycles\n",
520
+ "with a characteristic lag and damping that depends on the aquifer type.\n",
521
+ "Multivariate embeddings can encode this transfer function (climate input to water level response),\n",
522
+ "providing richer features for classification than the water level alone."
523
+ ]
524
+ },
525
+ {
526
+ "cell_type": "markdown",
527
+ "metadata": {},
528
+ "source": [
529
+ "---\n",
530
+ "## 7. Data Quality\n",
531
+ "\n",
532
+ "Assess data completeness: missing values, temporal coverage, and gaps.\n",
533
+ "This matters because short or heavily gapped series may produce unreliable embeddings\n",
534
+ "and need to be filtered or handled carefully."
535
+ ]
536
+ },
537
+ {
538
+ "cell_type": "code",
539
+ "execution_count": null,
540
+ "metadata": {},
541
+ "outputs": [],
542
+ "source": [
543
+ "# Missing values in metadata\n",
544
+ "print(\"Missing values in station_metadata:\")\n",
545
+ "missing = meta.isnull().sum()\n",
546
+ "missing = missing[missing > 0].sort_values(ascending=False)\n",
547
+ "print(missing.to_string())\n",
548
+ "print(f\"\\nStations without milieu_eh label: {meta['milieu_eh'].isnull().sum()} / {len(meta)}\")"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": null,
554
+ "metadata": {},
555
+ "outputs": [],
556
+ "source": [
557
+ "# Temporal coverage: histogram of nb_mois_total\n",
558
+ "fig = px.histogram(\n",
559
+ " meta,\n",
560
+ " x=\"nb_mois_total\",\n",
561
+ " nbins=50,\n",
562
+ " title=\"Temporal coverage per station (total months of data)\",\n",
563
+ " labels={\"nb_mois_total\": \"Total months of data\", \"count\": \"Number of stations\"},\n",
564
+ " template=TEMPLATE,\n",
565
+ " color_discrete_sequence=[\"#636EFA\"],\n",
566
+ " height=400,\n",
567
+ " width=800,\n",
568
+ ")\n",
569
+ "fig.add_vline(\n",
570
+ " x=meta[\"nb_mois_total\"].median(),\n",
571
+ " line_dash=\"dash\", line_color=\"red\",\n",
572
+ " annotation_text=f\"Median: {meta['nb_mois_total'].median():.0f} months\",\n",
573
+ " annotation_position=\"top right\",\n",
574
+ ")\n",
575
+ "fig.update_layout(font=FONT)\n",
576
+ "fig.show()"
577
+ ]
578
+ },
579
+ {
580
+ "cell_type": "code",
581
+ "execution_count": null,
582
+ "metadata": {},
583
+ "outputs": [],
584
+ "source": [
585
+ "# Missing values in univariate time series\n",
586
+ "uni_missing = uni.groupby(\"code_bss\").agg(\n",
587
+ " n_rows=(\"niveau_nappe_eau\", \"count\"),\n",
588
+ " n_missing=(\"niveau_nappe_eau\", lambda x: x.isnull().sum()),\n",
589
+ " date_min=(\"date\", \"min\"),\n",
590
+ " date_max=(\"date\", \"max\"),\n",
591
+ ")\n",
592
+ "uni_missing[\"span_days\"] = (uni_missing[\"date_max\"] - uni_missing[\"date_min\"]).dt.days\n",
593
+ "uni_missing[\"coverage_pct\"] = (\n",
594
+ " (uni_missing[\"n_rows\"] - uni_missing[\"n_missing\"]) / uni_missing[\"span_days\"] * 100\n",
595
+ ").clip(0, 100)\n",
596
+ "\n",
597
+ "print(f\"Stations in univariate dataset: {len(uni_missing)}\")\n",
598
+ "print(f\"\\nMissing value statistics (niveau_nappe_eau):\")\n",
599
+ "print(f\" Stations with no missing: {(uni_missing['n_missing'] == 0).sum()}\")\n",
600
+ "print(f\" Stations with >10% missing: {(uni_missing['n_missing'] / uni_missing['n_rows'] > 0.10).sum()}\")\n",
601
+ "print(f\"\\nCoverage (valid days / span):\")\n",
602
+ "print(uni_missing[\"coverage_pct\"].describe().round(1).to_string())"
603
+ ]
604
+ },
605
+ {
606
+ "cell_type": "code",
607
+ "execution_count": null,
608
+ "metadata": {},
609
+ "outputs": [],
610
+ "source": [
611
+ "# Coverage histogram\n",
612
+ "fig = px.histogram(\n",
613
+ " uni_missing,\n",
614
+ " x=\"coverage_pct\",\n",
615
+ " nbins=50,\n",
616
+ " title=\"Data coverage per station (valid observations / total span)\",\n",
617
+ " labels={\"coverage_pct\": \"Coverage (%)\", \"count\": \"Number of stations\"},\n",
618
+ " template=TEMPLATE,\n",
619
+ " color_discrete_sequence=[\"#00CC96\"],\n",
620
+ " height=400,\n",
621
+ " width=800,\n",
622
+ ")\n",
623
+ "fig.update_layout(font=FONT)\n",
624
+ "fig.show()"
625
+ ]
626
+ },
627
+ {
628
+ "cell_type": "code",
629
+ "execution_count": null,
630
+ "metadata": {},
631
+ "outputs": [],
632
+ "source": [
633
+ "# Time span distribution\n",
634
+ "fig = px.histogram(\n",
635
+ " uni_missing,\n",
636
+ " x=\"span_days\",\n",
637
+ " nbins=50,\n",
638
+ " title=\"Time span per station (days between first and last observation)\",\n",
639
+ " labels={\"span_days\": \"Span (days)\", \"count\": \"Number of stations\"},\n",
640
+ " template=TEMPLATE,\n",
641
+ " color_discrete_sequence=[\"#AB63FA\"],\n",
642
+ " height=400,\n",
643
+ " width=800,\n",
644
+ ")\n",
645
+ "fig.add_vline(\n",
646
+ " x=365,\n",
647
+ " line_dash=\"dash\", line_color=\"red\",\n",
648
+ " annotation_text=\"1 year (min for 365-day window)\",\n",
649
+ " annotation_position=\"top right\",\n",
650
+ ")\n",
651
+ "fig.update_layout(font=FONT)\n",
652
+ "fig.show()"
653
+ ]
654
+ },
655
+ {
656
+ "cell_type": "markdown",
657
+ "metadata": {},
658
+ "source": [
659
+ "**Findings:**\n",
660
+ "- Most stations have long records (median coverage >> 12 months), ensuring sufficient data for windowing.\n",
661
+ "- Missing values in the water level column exist but are generally sparse, confirming\n",
662
+ " that the dataset was pre-filtered for quality.\n",
663
+ "- A few stations have short spans; the windowing step (Section 8) will naturally exclude\n",
664
+ " stations with fewer than 365 consecutive valid days."
665
+ ]
666
+ },
667
+ {
668
+ "cell_type": "markdown",
669
+ "metadata": {},
670
+ "source": [
671
+ "---\n",
672
+ "## 8. Windowing Illustration\n",
673
+ "\n",
674
+ "The embedding pipeline extracts fixed-length windows from each station's time series.\n",
675
+ "We use a **365-day window** with a **90-day stride** (overlap of 275 days).\n",
676
+ "This section visualizes how overlapping windows are extracted from a single station,\n",
677
+ "producing multiple embedding vectors per station that are later aggregated (mean-pooled)\n",
678
+ "into a single station-level representation."
679
+ ]
680
+ },
681
+ {
682
+ "cell_type": "code",
683
+ "execution_count": null,
684
+ "metadata": {},
685
+ "outputs": [],
686
+ "source": [
687
+ "WINDOW_SIZE = 365 # days\n",
688
+ "STRIDE = 90 # days\n",
689
+ "\n",
690
+ "# Use the first example station\n",
691
+ "demo_ts = uni[uni[\"code_bss\"] == demo_bss].sort_values(\"date\").copy()\n",
692
+ "demo_ts = demo_ts.dropna(subset=[\"niveau_nappe_eau\"]).reset_index(drop=True)\n",
693
+ "\n",
694
+ "# Pick a 3-year segment for clarity\n",
695
+ "start_date = demo_ts[\"date\"].min() + pd.Timedelta(days=365)\n",
696
+ "end_date = start_date + pd.Timedelta(days=365 * 3)\n",
697
+ "segment = demo_ts[(demo_ts[\"date\"] >= start_date) & (demo_ts[\"date\"] < end_date)].copy()\n",
698
+ "\n",
699
+ "# Extract windows\n",
700
+ "windows = []\n",
701
+ "for i in range(0, len(segment) - WINDOW_SIZE + 1, STRIDE):\n",
702
+ " w = segment.iloc[i:i + WINDOW_SIZE]\n",
703
+ " if len(w) == WINDOW_SIZE:\n",
704
+ " windows.append(w)\n",
705
+ "\n",
706
+ "# Show only the first 4 windows for visual clarity\n",
707
+ "n_show = min(4, len(windows))\n",
708
+ "print(f\"Station: {demo_bss} ({demo_cls})\")\n",
709
+ "print(f\"Segment: {segment['date'].min().date()} to {segment['date'].max().date()}\")\n",
710
+ "print(f\"Total windows extracted: {len(windows)} (showing first {n_show})\")\n",
711
+ "print(f\"Window size: {WINDOW_SIZE} days, stride: {STRIDE} days\")"
712
+ ]
713
+ },
714
+ {
715
+ "cell_type": "code",
716
+ "execution_count": null,
717
+ "metadata": {},
718
+ "outputs": [],
719
+ "source": [
720
+ "# Visualize overlapping windows\n",
721
+ "window_colors = [\"#636EFA\", \"#EF553B\", \"#00CC96\", \"#FFA15A\", \"#AB63FA\"]\n",
722
+ "\n",
723
+ "fig = go.Figure()\n",
724
+ "\n",
725
+ "# Background: full segment in light gray\n",
726
+ "fig.add_trace(go.Scatter(\n",
727
+ " x=segment[\"date\"], y=segment[\"niveau_nappe_eau\"],\n",
728
+ " mode=\"lines\",\n",
729
+ " line=dict(color=\"lightgray\", width=1),\n",
730
+ " name=\"Full segment\",\n",
731
+ " showlegend=True,\n",
732
+ "))\n",
733
+ "\n",
734
+ "# Overlay each window with a distinct color\n",
735
+ "for j in range(n_show):\n",
736
+ " w = windows[j]\n",
737
+ " fig.add_trace(go.Scatter(\n",
738
+ " x=w[\"date\"], y=w[\"niveau_nappe_eau\"],\n",
739
+ " mode=\"lines\",\n",
740
+ " line=dict(color=window_colors[j % len(window_colors)], width=2),\n",
741
+ " name=f\"Window {j + 1} ({w['date'].iloc[0].strftime('%Y-%m-%d')} to {w['date'].iloc[-1].strftime('%Y-%m-%d')})\",\n",
742
+ " ))\n",
743
+ " # Add vertical markers for window boundaries\n",
744
+ " for dt in [w[\"date\"].iloc[0], w[\"date\"].iloc[-1]]:\n",
745
+ " fig.add_vline(\n",
746
+ " x=dt, line_dash=\"dot\",\n",
747
+ " line_color=window_colors[j % len(window_colors)],\n",
748
+ " opacity=0.4,\n",
749
+ " )\n",
750
+ "\n",
751
+ "fig.update_layout(\n",
752
+ " title=f\"Windowing illustration: {WINDOW_SIZE}-day windows, {STRIDE}-day stride -- {demo_bss}\",\n",
753
+ " xaxis_title=\"Date\",\n",
754
+ " yaxis_title=\"Groundwater level (m NGF)\",\n",
755
+ " template=TEMPLATE,\n",
756
+ " font=FONT,\n",
757
+ " height=450,\n",
758
+ " width=900,\n",
759
+ " legend=dict(yanchor=\"top\", y=0.99, xanchor=\"left\", x=0.01, bgcolor=\"rgba(255,255,255,0.8)\"),\n",
760
+ ")\n",
761
+ "fig.show()"
762
+ ]
763
+ },
764
+ {
765
+ "cell_type": "markdown",
766
+ "metadata": {},
767
+ "source": [
768
+ "**Summary:**\n",
769
+ "Each colored segment represents one 365-day input window fed to the encoder.\n",
770
+ "Consecutive windows overlap by 275 days (stride = 90 days), ensuring dense temporal coverage.\n",
771
+ "The encoder maps each window to a fixed-dimensional embedding vector.\n",
772
+ "All window embeddings for a station are then mean-pooled into a single station-level representation\n",
773
+ "used for downstream evaluation (classification, clustering, geographic coherence)."
774
+ ]
775
+ },
776
+ {
777
+ "cell_type": "markdown",
778
+ "metadata": {},
779
+ "source": [
780
+ "---\n",
781
+ "## Summary\n",
782
+ "\n",
783
+ "| Property | Value |\n",
784
+ "|----------|-------|\n",
785
+ "| Total stations (metadata) | 4,210 |\n",
786
+ "| Stations with time series | 2,000 |\n",
787
+ "| Stations with milieu_eh label | ~3,623 |\n",
788
+ "| Number of classes | 8 (+ missing) |\n",
789
+ "| Majority class (Poreux) | ~48% |\n",
790
+ "| Smallest class (Indetermine) | <1% |\n",
791
+ "| Variables (multivariate) | groundwater level, temperature, precipitation, evapotranspiration |\n",
792
+ "| Window size | 365 days |\n",
793
+ "| Stride | 90 days |\n",
794
+ "\n",
795
+ "**Implications for benchmark design:**\n",
796
+ "1. **Class imbalance** -- use balanced accuracy and macro-F1; apply class weights.\n",
797
+ "2. **Spatial autocorrelation** -- use department-level group cross-validation.\n",
798
+ "3. **Diverse temporal dynamics** -- good discriminative signal exists for embeddings to capture.\n",
799
+ "4. **Multivariate covariates** -- climate forcing adds information beyond the water level alone.\n",
800
+ "5. **Windowing** -- 365-day windows with 90-day stride provide dense coverage and multiple samples per station."
801
+ ]
802
+ }
803
+ ],
804
+ "metadata": {
805
+ "kernelspec": {
806
+ "display_name": "Python 3",
807
+ "language": "python",
808
+ "name": "python3"
809
+ },
810
+ "language_info": {
811
+ "name": "python",
812
+ "version": "3.12.0"
813
+ }
814
+ },
815
+ "nbformat": 4,
816
+ "nbformat_minor": 4
817
+ }