{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Benchmark Dataset Exploration\n", "\n", "This notebook explores the piezometric time-series dataset used in the embedding benchmark.\n", "The dataset contains daily groundwater level measurements from the French national monitoring network (BRGM),\n", "augmented with ERA5 climate reanalysis covariates.\n", "\n", "**Files:**\n", "- `station_metadata.parquet` -- 4,210 stations with hydrogeological labels\n", "- `piezo_daily_uni.parquet` -- univariate daily groundwater levels (2,000 stations)\n", "- `piezo_daily_multi.parquet` -- multivariate daily series: groundwater + 3 ERA5 covariates\n", "\n", "**Goal:** Understand data characteristics (class balance, coverage, quality) before designing the embedding evaluation protocol." ] }, { "cell_type": "code", "source": "# === Setup: auto-download data from HuggingFace if not available locally ===\nimport os\nfrom pathlib import Path\n\n# Detect environment\nDATA_DIR = Path(\"../data\")\nREPORTS_DIR = Path(\"../reports\")\nHF_REPO = \"xairon/piezo-embedding-benchmark\"\n\nDATA_FILES = [\n \"station_metadata.parquet\",\n \"piezo_daily_uni.parquet\",\n \"piezo_daily_multi.parquet\",\n]\n\nif not (DATA_DIR / DATA_FILES[0]).exists():\n print(\"Local data not found. Downloading from HuggingFace...\")\n try:\n from huggingface_hub import hf_hub_download\n except ImportError:\n os.system(\"pip install -q huggingface_hub\")\n from huggingface_hub import hf_hub_download\n\n DATA_DIR.mkdir(parents=True, exist_ok=True)\n for fname in DATA_FILES:\n print(f\" Downloading {fname}...\")\n path = hf_hub_download(HF_REPO, f\"data/{fname}\", repo_type=\"dataset\")\n # Symlink or copy to expected location\n target = DATA_DIR / fname\n if not target.exists():\n os.symlink(path, str(target))\n print(\"Done. All data files available.\")\nelse:\n print(f\"Using local data from {DATA_DIR.resolve()}\")\n\nDATA_DIR = str(DATA_DIR)", "metadata": {}, "execution_count": null, "outputs": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings(\"ignore\")\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import plotly.express as px\n", "import plotly.graph_objects as go\n", "from plotly.subplots import make_subplots\n", "\n", "# Consistent color palette for milieu_eh classes\n", "MILIEU_COLORS = {\n", " \"Poreux\": \"#636EFA\",\n", " \"Fissure\": \"#EF553B\",\n", " \"Karstique\": \"#00CC96\",\n", " \"Double porosite F+P\": \"#AB63FA\",\n", " \"Double porosite K+P\": \"#FFA15A\",\n", " \"Composite\": \"#19D3F3\",\n", " \"Non applicable\": \"#B6E880\",\n", " \"Indetermine\": \"#FF6692\",\n", "}\n", "\n", "# Short readable labels for milieu_eh codes\n", "MILIEU_LABELS = {\n", " \"1\": \"Poreux\",\n", " \"2\": \"Fissure\",\n", " \"3\": \"Karstique\",\n", " \"4\": \"Double porosite F+P\",\n", " \"5\": \"Double porosite K+P\",\n", " \"6\": \"Double porosite K+F\",\n", " \"8\": \"Composite\",\n", " \"9\": \"Non applicable\",\n", " \"X\": \"Indetermine\",\n", "}\n", "\n", "DATA_DIR = \"../data\"\n", "\n", "# Plotly template for publication-quality figures\n", "TEMPLATE = \"plotly_white\"\n", "FONT = dict(family=\"Arial\", size=13)\n", "\n", "print(\"Libraries loaded.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 1. Dataset Overview\n", "\n", "Load the station metadata and inspect its structure, types, and basic statistics." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "meta = pd.read_parquet(f\"{DATA_DIR}/station_metadata.parquet\")\n", "print(f\"Shape: {meta.shape[0]} stations x {meta.shape[1]} columns\")\n", "print(f\"\\nColumn types:\\n{meta.dtypes.to_string()}\")\n", "meta.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add a readable milieu label column\n", "meta[\"milieu_label\"] = meta[\"milieu_eh\"].map(MILIEU_LABELS)\n", "\n", "# Summary statistics for numeric columns\n", "numeric_cols = [\n", " \"latitude\", \"longitude\", \"altitude_station\",\n", " \"profondeur_moyenne_globale\", \"niveau_stddev_global\",\n", " \"amplitude_totale\", \"nb_mois_total\",\n", "]\n", "meta[numeric_cols].describe().round(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 2. Label Distribution\n", "\n", "The classification target is `milieu_eh`, encoding the hydrogeological environment of each station.\n", "This section quantifies the class imbalance, which is critical for choosing evaluation metrics\n", "(balanced accuracy, macro-F1) and designing stratified cross-validation splits." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Filter stations with a valid milieu_eh label\n", "meta_labeled = meta.dropna(subset=[\"milieu_eh\"]).copy()\n", "print(f\"Stations with milieu_eh label: {len(meta_labeled)} / {len(meta)} \"\n", " f\"({len(meta) - len(meta_labeled)} missing)\")\n", "\n", "# Value counts\n", "vc = meta_labeled[\"milieu_label\"].value_counts()\n", "vc_pct = meta_labeled[\"milieu_label\"].value_counts(normalize=True) * 100\n", "\n", "dist_df = pd.DataFrame({\"count\": vc, \"pct\": vc_pct.round(1)}).reset_index()\n", "dist_df.columns = [\"milieu_eh\", \"count\", \"pct\"]\n", "dist_df[\"label\"] = dist_df.apply(lambda r: f\"{r['count']} ({r['pct']}%)\", axis=1)\n", "dist_df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = px.bar(\n", " dist_df,\n", " x=\"milieu_eh\",\n", " y=\"count\",\n", " color=\"milieu_eh\",\n", " color_discrete_map=MILIEU_COLORS,\n", " text=\"label\",\n", " template=TEMPLATE,\n", " title=\"Distribution of hydrogeological environment classes (milieu_eh)\",\n", " labels={\"milieu_eh\": \"Hydrogeological class\", \"count\": \"Number of stations\"},\n", ")\n", "fig.update_traces(textposition=\"outside\")\n", "fig.update_layout(\n", " font=FONT,\n", " showlegend=False,\n", " yaxis_range=[0, dist_df[\"count\"].max() * 1.15],\n", " height=450,\n", " width=800,\n", ")\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Key observation:** The dataset is heavily imbalanced. *Poreux* (porous) alone represents ~48% of labeled stations,\n", "while minority classes (*Indetermine*, *Karstique*) have fewer than 200 samples each.\n", "This motivates the use of balanced accuracy and macro-averaged F1 as primary evaluation metrics,\n", "along with stratified cross-validation and class-weighted classifiers." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 3. Geographic Distribution\n", "\n", "Station locations across metropolitan France, colored by hydrogeological environment.\n", "Geographic clustering of classes would indicate spatial autocorrelation, which must be\n", "handled in the evaluation protocol (e.g., spatial cross-validation by departement)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = px.scatter_mapbox(\n", " meta_labeled,\n", " lat=\"latitude\",\n", " lon=\"longitude\",\n", " color=\"milieu_label\",\n", " color_discrete_map=MILIEU_COLORS,\n", " hover_name=\"code_bss\",\n", " hover_data=[\"altitude_station\", \"nb_mois_total\", \"milieu_label\"],\n", " zoom=4.5,\n", " center={\"lat\": 46.5, \"lon\": 2.5},\n", " mapbox_style=\"carto-positron\",\n", " title=\"Geographic distribution of monitoring stations by hydrogeological class\",\n", " labels={\"milieu_label\": \"Hydrogeological class\"},\n", " opacity=0.7,\n", " height=650,\n", " width=850,\n", ")\n", "fig.update_layout(font=FONT, template=TEMPLATE, margin=dict(l=0, r=0, t=40, b=0))\n", "fig.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Fallback: simple scatter plot (lat vs lon) in case mapbox is unavailable\n", "fig_scatter = px.scatter(\n", " meta_labeled,\n", " x=\"longitude\",\n", " y=\"latitude\",\n", " color=\"milieu_label\",\n", " color_discrete_map=MILIEU_COLORS,\n", " hover_name=\"code_bss\",\n", " title=\"Station locations (latitude vs. longitude) by hydrogeological class\",\n", " labels={\"longitude\": \"Longitude\", \"latitude\": \"Latitude\", \"milieu_label\": \"Class\"},\n", " template=TEMPLATE,\n", " opacity=0.6,\n", " height=550,\n", " width=750,\n", ")\n", "fig_scatter.update_traces(marker=dict(size=4))\n", "fig_scatter.update_layout(font=FONT)\n", "fig_scatter.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Observation:** Classes exhibit clear spatial clustering (e.g., porous aquifers dominate\n", "sedimentary basins such as the Paris Basin and Aquitaine, while karst stations cluster in\n", "limestone regions). This confirms that geographic cross-validation (split by departement)\n", "is necessary to avoid spatial leakage." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 4. Altitude Distribution\n", "\n", "Station altitude varies widely across France and correlates with hydrogeological environment.\n", "Karst systems tend to occur at higher altitudes (limestone plateaus, mountain foothills),\n", "while porous aquifers dominate low-altitude sedimentary plains." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Histogram of altitude, colored by class\n", "fig = px.histogram(\n", " meta_labeled,\n", " x=\"altitude_station\",\n", " color=\"milieu_label\",\n", " color_discrete_map=MILIEU_COLORS,\n", " nbins=60,\n", " barmode=\"stack\",\n", " title=\"Altitude distribution of stations by hydrogeological class\",\n", " labels={\"altitude_station\": \"Altitude (m a.s.l.)\", \"milieu_label\": \"Class\"},\n", " template=TEMPLATE,\n", " height=400,\n", " width=800,\n", ")\n", "fig.update_layout(font=FONT)\n", "fig.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Box plot: altitude per class\n", "fig = px.box(\n", " meta_labeled,\n", " x=\"milieu_label\",\n", " y=\"altitude_station\",\n", " color=\"milieu_label\",\n", " color_discrete_map=MILIEU_COLORS,\n", " title=\"Altitude distribution per hydrogeological class\",\n", " labels={\"altitude_station\": \"Altitude (m a.s.l.)\", \"milieu_label\": \"Class\"},\n", " template=TEMPLATE,\n", " height=450,\n", " width=800,\n", ")\n", "fig.update_layout(font=FONT, showlegend=False, xaxis_tickangle=-30)\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 5. Time Series Examples\n", "\n", "We select one representative station per major hydrogeological class to illustrate the\n", "diversity of groundwater dynamics. Different aquifer types exhibit fundamentally different\n", "temporal behaviors (smooth vs. flashy responses, seasonal vs. multi-year trends),\n", "which is precisely what we expect embeddings to capture." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load univariate time series\n", "uni = pd.read_parquet(f\"{DATA_DIR}/piezo_daily_uni.parquet\")\n", "uni[\"date\"] = pd.to_datetime(uni[\"date\"])\n", "print(f\"Univariate dataset: {uni.shape[0]:,} rows, {uni['code_bss'].nunique()} stations\")\n", "uni.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# Select one representative station per major class\n# We pick stations with good data coverage (high nb_mois_total)\n# AND that exist in the time-series datasets with sufficient daily coverage\n# (metadata has ~4200 stations, but uni/multi only ~2000, some with sparse data)\nTARGET_CLASSES = [\"Poreux\", \"Fissure\", \"Karstique\", \"Double porosite F+P\",\n \"Double porosite K+P\", \"Composite\"]\n\n# Compute daily coverage per station to ensure windowing works downstream\n_station_stats = uni.dropna(subset=[\"niveau_nappe_eau\"]).groupby(\"code_bss\").agg(\n _n_valid=(\"date\", \"count\"),\n _date_min=(\"date\", \"min\"),\n _date_max=(\"date\", \"max\"),\n)\n_station_stats[\"_span_days\"] = (_station_stats[\"_date_max\"] - _station_stats[\"_date_min\"]).dt.days\n_station_stats[\"_coverage\"] = _station_stats[\"_n_valid\"] / _station_stats[\"_span_days\"].clip(lower=1)\n\n# Require 4+ years of data and >80% daily coverage\n_good_stations = set(_station_stats[\n (_station_stats[\"_span_days\"] >= 365 * 4) &\n (_station_stats[\"_coverage\"] > 0.8)\n].index)\n\nexample_stations = []\nfor cls in TARGET_CLASSES:\n candidates = meta_labeled[\n (meta_labeled[\"milieu_label\"] == cls) &\n (meta_labeled[\"code_bss\"].isin(_good_stations)) &\n (meta_labeled[\"nb_mois_total\"] > meta_labeled[\"nb_mois_total\"].quantile(0.7))\n ].sort_values(\"nb_mois_total\", ascending=False)\n if len(candidates) > 0:\n # Pick the station closest to the median coverage in top 30%\n mid = len(candidates) // 2\n example_stations.append(candidates.iloc[mid])\n\nexample_ids = [s[\"code_bss\"] for s in example_stations]\nprint(f\"Selected {len(example_ids)} stations:\")\nfor s in example_stations:\n print(f\" {s['code_bss']:20s} {s['milieu_label']:30s} ({s['nb_mois_total']} months)\")" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot time series for each selected station\n", "uni_examples = uni[uni[\"code_bss\"].isin(example_ids)].copy()\n", "uni_examples = uni_examples.merge(\n", " meta[[\"code_bss\", \"milieu_label\"]], on=\"code_bss\", how=\"left\"\n", ")\n", "\n", "n_stations = len(example_ids)\n", "fig = make_subplots(\n", " rows=n_stations, cols=1,\n", " shared_xaxes=True,\n", " vertical_spacing=0.03,\n", " subplot_titles=[\n", " f\"{s['milieu_label']} -- {s['code_bss']}\"\n", " for s in example_stations\n", " ],\n", ")\n", "\n", "for i, station in enumerate(example_stations):\n", " bss = station[\"code_bss\"]\n", " cls = station[\"milieu_label\"]\n", " ts = uni_examples[uni_examples[\"code_bss\"] == bss].sort_values(\"date\")\n", " color = MILIEU_COLORS.get(cls, \"#636EFA\")\n", " fig.add_trace(\n", " go.Scatter(\n", " x=ts[\"date\"], y=ts[\"niveau_nappe_eau\"],\n", " mode=\"lines\", name=cls,\n", " line=dict(color=color, width=1),\n", " showlegend=(i == 0),\n", " ),\n", " row=i + 1, col=1,\n", " )\n", " fig.update_yaxes(title_text=\"Level (m NGF)\", row=i + 1, col=1)\n", "\n", "fig.update_layout(\n", " height=250 * n_stations,\n", " width=900,\n", " title_text=\"Representative groundwater level time series by hydrogeological class\",\n", " template=TEMPLATE,\n", " font=FONT,\n", " showlegend=False,\n", ")\n", "fig.update_xaxes(title_text=\"Date\", row=n_stations, col=1)\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Observation:** The six classes display markedly different temporal dynamics:\n", "- **Poreux** (porous): smooth, slow inertia with long-period seasonal cycles.\n", "- **Fissure** (fractured): more reactive, with sharper peaks and recession curves.\n", "- **Karstique** (karst): flashy, spiky responses to precipitation events.\n", "- **Double porosity** classes: intermediate behaviors reflecting mixed aquifer properties.\n", "- **Composite**: complex, irregular patterns.\n", "\n", "These differences in temporal shape are exactly what time-series embeddings should encode." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 6. Multivariate View\n", "\n", "For one station, we visualize all four variables from the multivariate dataset:\n", "groundwater level + three ERA5 climate covariates (temperature, precipitation, evapotranspiration).\n", "This illustrates why multivariate embeddings may capture additional signal: climatic forcing\n", "drives aquifer recharge, and different hydrogeological environments respond differently to\n", "the same climate inputs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load multivariate data for one station\n", "multi = pd.read_parquet(f\"{DATA_DIR}/piezo_daily_multi.parquet\")\n", "multi[\"date\"] = pd.to_datetime(multi[\"date\"])\n", "print(f\"Multivariate dataset: {multi.shape[0]:,} rows, {multi['code_bss'].nunique()} stations\")\n", "print(f\"Variables: {list(multi.columns)}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pick the first example station\n", "demo_bss = example_ids[0]\n", "demo_cls = example_stations[0][\"milieu_label\"]\n", "ts_multi = multi[multi[\"code_bss\"] == demo_bss].sort_values(\"date\").copy()\n", "\n", "# Limit to a 5-year window for readability\n", "ts_multi_window = ts_multi[\n", " (ts_multi[\"date\"] >= ts_multi[\"date\"].min() + pd.Timedelta(days=365))\n", " & (ts_multi[\"date\"] < ts_multi[\"date\"].min() + pd.Timedelta(days=365 * 6))\n", "]\n", "\n", "variables = [\n", " (\"niveau_nappe_eau\", \"Groundwater level (m NGF)\", \"#636EFA\"),\n", " (\"temperature_2m\", \"Temperature 2m (K)\", \"#EF553B\"),\n", " (\"total_precipitation\", \"Precipitation (m/day)\", \"#00CC96\"),\n", " (\"potential_evaporation\", \"Pot. evapotranspiration (m/day)\", \"#FFA15A\"),\n", "]\n", "\n", "fig = make_subplots(\n", " rows=4, cols=1,\n", " shared_xaxes=True,\n", " vertical_spacing=0.05,\n", " subplot_titles=[v[1] for v in variables],\n", ")\n", "\n", "for i, (col, label, color) in enumerate(variables):\n", " fig.add_trace(\n", " go.Scatter(\n", " x=ts_multi_window[\"date\"], y=ts_multi_window[col],\n", " mode=\"lines\", name=label,\n", " line=dict(color=color, width=1),\n", " ),\n", " row=i + 1, col=1,\n", " )\n", " fig.update_yaxes(title_text=label.split(\"(\")[0].strip(), row=i + 1, col=1)\n", "\n", "fig.update_layout(\n", " height=800,\n", " width=900,\n", " title_text=f\"Multivariate view: {demo_bss} ({demo_cls})\",\n", " template=TEMPLATE,\n", " font=FONT,\n", " showlegend=False,\n", ")\n", "fig.update_xaxes(title_text=\"Date\", row=4, col=1)\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Key insight:** Groundwater level responds to seasonal precipitation and evapotranspiration cycles\n", "with a characteristic lag and damping that depends on the aquifer type.\n", "Multivariate embeddings can encode this transfer function (climate input to water level response),\n", "providing richer features for classification than the water level alone." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 7. Data Quality\n", "\n", "Assess data completeness: missing values, temporal coverage, and gaps.\n", "This matters because short or heavily gapped series may produce unreliable embeddings\n", "and need to be filtered or handled carefully." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Missing values in metadata\n", "print(\"Missing values in station_metadata:\")\n", "missing = meta.isnull().sum()\n", "missing = missing[missing > 0].sort_values(ascending=False)\n", "print(missing.to_string())\n", "print(f\"\\nStations without milieu_eh label: {meta['milieu_eh'].isnull().sum()} / {len(meta)}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Temporal coverage: histogram of nb_mois_total\n", "fig = px.histogram(\n", " meta,\n", " x=\"nb_mois_total\",\n", " nbins=50,\n", " title=\"Temporal coverage per station (total months of data)\",\n", " labels={\"nb_mois_total\": \"Total months of data\", \"count\": \"Number of stations\"},\n", " template=TEMPLATE,\n", " color_discrete_sequence=[\"#636EFA\"],\n", " height=400,\n", " width=800,\n", ")\n", "fig.add_vline(\n", " x=meta[\"nb_mois_total\"].median(),\n", " line_dash=\"dash\", line_color=\"red\",\n", " annotation_text=f\"Median: {meta['nb_mois_total'].median():.0f} months\",\n", " annotation_position=\"top right\",\n", ")\n", "fig.update_layout(font=FONT)\n", "fig.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Missing values in univariate time series\n", "uni_missing = uni.groupby(\"code_bss\").agg(\n", " n_rows=(\"niveau_nappe_eau\", \"count\"),\n", " n_missing=(\"niveau_nappe_eau\", lambda x: x.isnull().sum()),\n", " date_min=(\"date\", \"min\"),\n", " date_max=(\"date\", \"max\"),\n", ")\n", "uni_missing[\"span_days\"] = (uni_missing[\"date_max\"] - uni_missing[\"date_min\"]).dt.days\n", "uni_missing[\"coverage_pct\"] = (\n", " (uni_missing[\"n_rows\"] - uni_missing[\"n_missing\"]) / uni_missing[\"span_days\"] * 100\n", ").clip(0, 100)\n", "\n", "print(f\"Stations in univariate dataset: {len(uni_missing)}\")\n", "print(f\"\\nMissing value statistics (niveau_nappe_eau):\")\n", "print(f\" Stations with no missing: {(uni_missing['n_missing'] == 0).sum()}\")\n", "print(f\" Stations with >10% missing: {(uni_missing['n_missing'] / uni_missing['n_rows'] > 0.10).sum()}\")\n", "print(f\"\\nCoverage (valid days / span):\")\n", "print(uni_missing[\"coverage_pct\"].describe().round(1).to_string())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Coverage histogram\n", "fig = px.histogram(\n", " uni_missing,\n", " x=\"coverage_pct\",\n", " nbins=50,\n", " title=\"Data coverage per station (valid observations / total span)\",\n", " labels={\"coverage_pct\": \"Coverage (%)\", \"count\": \"Number of stations\"},\n", " template=TEMPLATE,\n", " color_discrete_sequence=[\"#00CC96\"],\n", " height=400,\n", " width=800,\n", ")\n", "fig.update_layout(font=FONT)\n", "fig.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Time span distribution\n", "fig = px.histogram(\n", " uni_missing,\n", " x=\"span_days\",\n", " nbins=50,\n", " title=\"Time span per station (days between first and last observation)\",\n", " labels={\"span_days\": \"Span (days)\", \"count\": \"Number of stations\"},\n", " template=TEMPLATE,\n", " color_discrete_sequence=[\"#AB63FA\"],\n", " height=400,\n", " width=800,\n", ")\n", "fig.add_vline(\n", " x=365,\n", " line_dash=\"dash\", line_color=\"red\",\n", " annotation_text=\"1 year (min for 365-day window)\",\n", " annotation_position=\"top right\",\n", ")\n", "fig.update_layout(font=FONT)\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Findings:**\n", "- Most stations have long records (median coverage >> 12 months), ensuring sufficient data for windowing.\n", "- Missing values in the water level column exist but are generally sparse, confirming\n", " that the dataset was pre-filtered for quality.\n", "- A few stations have short spans; the windowing step (Section 8) will naturally exclude\n", " stations with fewer than 365 consecutive valid days." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 8. Windowing Illustration\n", "\n", "The embedding pipeline extracts fixed-length windows from each station's time series.\n", "We use a **365-day window** with a **90-day stride** (overlap of 275 days).\n", "This section visualizes how overlapping windows are extracted from a single station,\n", "producing multiple embedding vectors per station that are later aggregated (mean-pooled)\n", "into a single station-level representation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "WINDOW_SIZE = 365 # days\n", "STRIDE = 90 # days\n", "\n", "# Use the first example station\n", "demo_ts = uni[uni[\"code_bss\"] == demo_bss].sort_values(\"date\").copy()\n", "demo_ts = demo_ts.dropna(subset=[\"niveau_nappe_eau\"]).reset_index(drop=True)\n", "\n", "# Pick a 3-year segment for clarity\n", "start_date = demo_ts[\"date\"].min() + pd.Timedelta(days=365)\n", "end_date = start_date + pd.Timedelta(days=365 * 3)\n", "segment = demo_ts[(demo_ts[\"date\"] >= start_date) & (demo_ts[\"date\"] < end_date)].copy()\n", "\n", "# Extract windows\n", "windows = []\n", "for i in range(0, len(segment) - WINDOW_SIZE + 1, STRIDE):\n", " w = segment.iloc[i:i + WINDOW_SIZE]\n", " if len(w) == WINDOW_SIZE:\n", " windows.append(w)\n", "\n", "# Show only the first 4 windows for visual clarity\n", "n_show = min(4, len(windows))\n", "print(f\"Station: {demo_bss} ({demo_cls})\")\n", "print(f\"Segment: {segment['date'].min().date()} to {segment['date'].max().date()}\")\n", "print(f\"Total windows extracted: {len(windows)} (showing first {n_show})\")\n", "print(f\"Window size: {WINDOW_SIZE} days, stride: {STRIDE} days\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Visualize overlapping windows\n", "window_colors = [\"#636EFA\", \"#EF553B\", \"#00CC96\", \"#FFA15A\", \"#AB63FA\"]\n", "\n", "fig = go.Figure()\n", "\n", "# Background: full segment in light gray\n", "fig.add_trace(go.Scatter(\n", " x=segment[\"date\"], y=segment[\"niveau_nappe_eau\"],\n", " mode=\"lines\",\n", " line=dict(color=\"lightgray\", width=1),\n", " name=\"Full segment\",\n", " showlegend=True,\n", "))\n", "\n", "# Overlay each window with a distinct color\n", "for j in range(n_show):\n", " w = windows[j]\n", " fig.add_trace(go.Scatter(\n", " x=w[\"date\"], y=w[\"niveau_nappe_eau\"],\n", " mode=\"lines\",\n", " line=dict(color=window_colors[j % len(window_colors)], width=2),\n", " name=f\"Window {j + 1} ({w['date'].iloc[0].strftime('%Y-%m-%d')} to {w['date'].iloc[-1].strftime('%Y-%m-%d')})\",\n", " ))\n", " # Add vertical markers for window boundaries\n", " for dt in [w[\"date\"].iloc[0], w[\"date\"].iloc[-1]]:\n", " fig.add_vline(\n", " x=dt, line_dash=\"dot\",\n", " line_color=window_colors[j % len(window_colors)],\n", " opacity=0.4,\n", " )\n", "\n", "fig.update_layout(\n", " title=f\"Windowing illustration: {WINDOW_SIZE}-day windows, {STRIDE}-day stride -- {demo_bss}\",\n", " xaxis_title=\"Date\",\n", " yaxis_title=\"Groundwater level (m NGF)\",\n", " template=TEMPLATE,\n", " font=FONT,\n", " height=450,\n", " width=900,\n", " legend=dict(yanchor=\"top\", y=0.99, xanchor=\"left\", x=0.01, bgcolor=\"rgba(255,255,255,0.8)\"),\n", ")\n", "fig.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Summary:**\n", "Each colored segment represents one 365-day input window fed to the encoder.\n", "Consecutive windows overlap by 275 days (stride = 90 days), ensuring dense temporal coverage.\n", "The encoder maps each window to a fixed-dimensional embedding vector.\n", "All window embeddings for a station are then mean-pooled into a single station-level representation\n", "used for downstream evaluation (classification, clustering, geographic coherence)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Summary\n", "\n", "| Property | Value |\n", "|----------|-------|\n", "| Total stations (metadata) | 4,210 |\n", "| Stations with time series | 2,000 |\n", "| Stations with milieu_eh label | ~3,623 |\n", "| Number of classes | 8 (+ missing) |\n", "| Majority class (Poreux) | ~48% |\n", "| Smallest class (Indetermine) | <1% |\n", "| Variables (multivariate) | groundwater level, temperature, precipitation, evapotranspiration |\n", "| Window size | 365 days |\n", "| Stride | 90 days |\n", "\n", "**Implications for benchmark design:**\n", "1. **Class imbalance** -- use balanced accuracy and macro-F1; apply class weights.\n", "2. **Spatial autocorrelation** -- use department-level group cross-validation.\n", "3. **Diverse temporal dynamics** -- good discriminative signal exists for embeddings to capture.\n", "4. **Multivariate covariates** -- climate forcing adds information beyond the water level alone.\n", "5. **Windowing** -- 365-day windows with 90-day stride provide dense coverage and multiple samples per station." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.12.0" } }, "nbformat": 4, "nbformat_minor": 4 }