{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "974ef3fe",
   "metadata": {},
   "source": "# Explore regional electricity consumption and choose a model\n\nExploration notebook: it describes the data, builds the features and tests one model per region on 2024.\nThe production job lives in `eco2mix_regional_production.ipynb`, which holds only what the job needs.\n\nData: éCO2mix regional consumption from RTE, published by Open Data Réseaux Énergies (ODRÉ) under the Licence Ouverte 2.0,\nread through the view `regional_consumption_hourly`: one row per region and per hour, in UTC, for the 12 regions of mainland France\n(Corsica is not part of the dataset).\n\nThe model is trained **once per region**: Spark distributes the 12 regions across its executors, which train them side by side.\n\nKernel: **Python 3 (ipykernel)**."
  },
  {
   "cell_type": "markdown",
   "id": "7f8e39bd",
   "metadata": {},
   "source": "## 1. Set up"
  },
  {
   "cell_type": "markdown",
   "id": "51714abd",
   "metadata": {},
   "source": "`holidays` provides the French public holidays, `scikit-learn` the regression trained in each region.\nThe notebook server installs both, from its **Dependencies**."
  },
  {
   "cell_type": "code",
   "id": "ce7d0acb",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "from forepaas.dwh import connect\nfrom pyspark.sql import functions as F\n\nsource = connect(\"dwh/default_dataset/\")\nspark = source.spark\nspark.sql(f\"USE {source.catalog}.{source.schema}\")\n\n# Store and compute in UTC; Paris time is derived explicitly where needed\nspark.conf.set(\"spark.sql.session.timeZone\", \"UTC\")\n\nprint(f\"Spark {spark.version}, catalog {source.catalog}\")"
  },
  {
   "cell_type": "markdown",
   "id": "3c05eb8f",
   "metadata": {},
   "source": "## 2. Load the regional consumption\n\n`regional_consumption_hourly` is written in SQL that both Trino and Spark understand.\nCalendar columns follow local life, so they are computed in Paris time here."
  },
  {
   "cell_type": "code",
   "id": "b7585403",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def with_paris_time(df):\n    return (\n        df.withColumn(\"hour_paris\", F.from_utc_timestamp(F.col(\"hour_utc\").cast(\"timestamp\"), \"Europe/Paris\"))\n        .withColumn(\"hour_of_day\", F.hour(\"hour_paris\"))\n        .withColumn(\"year\", F.year(\"hour_paris\"))\n        .withColumn(\"month\", F.month(\"hour_paris\"))\n    )\n\nregional = with_paris_time(spark.table(\"regional_consumption_hourly\")).cache()\n\nprint(f\"{regional.count()} region-hours\")\nregional.groupBy(\"region_code\", \"region_name\").agg(\n    F.count(\"*\").alias(\"hours\"),\n    F.count(\"consumption_mw\").alias(\"measured_hours\"),\n    F.min(\"hour_utc\").alias(\"first_hour\"),\n    F.max(\"hour_utc\").alias(\"last_hour\"),\n).orderBy(\"region_code\").show(truncate=False)"
  },
  {
   "cell_type": "markdown",
   "id": "8ffbd77e",
   "metadata": {},
   "source": "12 regions, from 1 January 2013, with the same number of hours each."
  },
  {
   "cell_type": "markdown",
   "id": "e3802253",
   "metadata": {},
   "source": "## 3. Explore\n\n### 3.1 Coverage, year by year"
  },
  {
   "cell_type": "code",
   "id": "25eaf468",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "coverage = (\n    regional.where(F.col(\"consumption_mw\").isNotNull())\n    .groupBy(\"region_name\")\n    .pivot(\"year\")\n    .count()\n    .orderBy(\"region_name\")\n    .toPandas()\n    .set_index(\"region_name\")\n)\ncoverage"
  },
  {
   "cell_type": "markdown",
   "id": "e2908072",
   "metadata": {},
   "source": "A full year shows 8,759 measured hours (8,783 in leap years): the hour that occurs twice in autumn appears only once in the data.\nFrom 2013 to 2025, every year is complete for the 12 regions."
  },
  {
   "cell_type": "markdown",
   "id": "5ebc19e3",
   "metadata": {},
   "source": "### 3.2 How big is each region?"
  },
  {
   "cell_type": "code",
   "id": "601646a9",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import matplotlib.pyplot as plt\n\nmeasured = regional.where(F.col(\"consumption_mw\").isNotNull())\n\nsize = (\n    measured.where(F.col(\"year\") == 2024)\n    .groupBy(\"region_name\")\n    .agg((F.avg(\"consumption_mw\") / 1000).alias(\"consumption_gw\"))\n    .orderBy(\"consumption_gw\")\n    .toPandas()\n)\nsize.plot(x=\"region_name\", y=\"consumption_gw\", kind=\"barh\", legend=False, figsize=(8, 5))\nplt.title(\"Average consumption in 2024\")\nplt.xlabel(\"GW\")\nplt.ylabel(\"\")\nplt.show()"
  },
  {
   "cell_type": "markdown",
   "id": "ee401791",
   "metadata": {},
   "source": "Regions differ by a factor of several: an error of 300 MW is small for Île-de-France and large for Centre-Val de Loire.\nErrors are therefore compared in percent (MAPE)."
  },
  {
   "cell_type": "markdown",
   "id": "9ae7dfec",
   "metadata": {},
   "source": "### 3.3 Same daily shape, different heating"
  },
  {
   "cell_type": "code",
   "id": "24b221b0",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "profile = (\n    measured.where((F.col(\"year\") == 2024) & (F.weekday(\"hour_paris\") < 5))\n    .groupBy(\"region_name\", \"hour_of_day\")\n    .agg(F.avg(\"consumption_mw\").alias(\"mw\"))\n    .toPandas()\n    .pivot(index=\"hour_of_day\", columns=\"region_name\", values=\"mw\")\n)\n(profile / profile.mean()).plot(figsize=(11, 5), legend=False, alpha=0.8)\nplt.title(\"Weekday profile by region, relative to its own average (2024)\")\nplt.xlabel(\"Hour of day (Paris time)\")\nplt.ylabel(\"Ratio to the regional average\")\nplt.xticks(range(24))\nplt.grid(True, alpha=0.3)\nplt.show()"
  },
  {
   "cell_type": "markdown",
   "id": "1c8dad5f",
   "metadata": {},
   "source": "All regions follow the same daily cycle, with a night low and two peaks."
  },
  {
   "cell_type": "code",
   "id": "c00b0601",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "heating = (\n    measured.where(F.col(\"year\") == 2024)\n    .groupBy(\"region_name\")\n    .agg(\n        (F.avg(F.when(F.col(\"month\") == 1, F.col(\"consumption_mw\")))\n         / F.avg(F.when(F.col(\"month\") == 7, F.col(\"consumption_mw\")))).alias(\"january_to_july\")\n    )\n    .orderBy(\"january_to_july\")\n    .toPandas()\n)\nheating.plot(x=\"region_name\", y=\"january_to_july\", kind=\"barh\", legend=False, figsize=(8, 5))\nplt.title(\"January consumption relative to July, 2024\")\nplt.xlabel(\"Ratio\")\nplt.ylabel(\"\")\nplt.show()"
  },
  {
   "cell_type": "markdown",
   "id": "1130381a",
   "metadata": {},
   "source": "The winter increase differs from one region to another: regions with more electric heating are more sensitive to cold.\nThis is why one model per region makes sense."
  },
  {
   "cell_type": "markdown",
   "id": "cc33c421",
   "metadata": {},
   "source": "## 4. Build the features\n\nEach hour gets:\n\n| Feature | Why |\n|---|---|\n| `hour_day` | Hour of day crossed with the type of day (Monday to Sunday, public holidays counted as Sundays): each type of day keeps its own shape |\n| `hour_lag_day` | The same for the day 48 hours before: a Tuesday forecast from a Sunday needs to know it |\n| `month` | The season |\n| `lag_48h` | Consumption of the region at the same hour two days before |\n| `lag_168h` | Consumption of the region at the same hour one week before |\n\n**Why 48 hours and not 24.** The job runs in the morning of day D to forecast day D+1: day D is not over, the latest complete day is D-1.\n**Lags by time, not by row**: each lag is a join on region and time, so missing hours never shift the data."
  },
  {
   "cell_type": "code",
   "id": "a615fdd5",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import holidays\n\nholiday_dates = spark.createDataFrame(\n    [(day, name) for day, name in sorted(holidays.France(years=range(2012, 2030)).items())],\n    [\"date_paris\", \"holiday\"],\n)\nprint(f\"{holiday_dates.count()} public holidays\")\n\n\ndef with_calendar(df):\n    \"\"\"Day types in Paris time, public holidays counted as Sundays (6).\"\"\"\n    hol = F.broadcast(holiday_dates.select(\"date_paris\", \"holiday\", F.lit(1).alias(\"is_holiday\")))\n    lag_hol = F.broadcast(holiday_dates.select(F.col(\"date_paris\").alias(\"lag_date\"), F.lit(1).alias(\"lag_is_holiday\")))\n    lag_time = F.col(\"hour_paris\") - F.expr(\"INTERVAL 48 HOURS\")\n    return (\n        with_paris_time(df)\n        .withColumn(\"date_paris\", F.to_date(\"hour_paris\"))\n        .withColumn(\"lag_date\", F.to_date(lag_time))\n        .join(hol, \"date_paris\", \"left\")\n        .join(lag_hol, \"lag_date\", \"left\")\n        .withColumn(\"day_type\", F.when(F.col(\"is_holiday\") == 1, 6).otherwise(F.weekday(\"hour_paris\")))\n        .withColumn(\"lag_day_type\", F.when(F.col(\"lag_is_holiday\") == 1, 6).otherwise(F.weekday(lag_time)))\n        .withColumn(\"hour_day\", F.concat_ws(\"_\", F.col(\"hour_of_day\").cast(\"string\"), F.col(\"day_type\").cast(\"string\")))\n        .withColumn(\"hour_lag_day\", F.concat_ws(\"_\", F.col(\"hour_of_day\").cast(\"string\"), F.col(\"lag_day_type\").cast(\"string\")))\n        .drop(\"is_holiday\", \"lag_is_holiday\", \"lag_date\")\n    )\n\n\ndef with_lags(df, hourly):\n    \"\"\"Join each region's consumption 48 and 168 hours earlier, on region and time.\n\n    The dataset follows Paris time: on the day clocks go back, one UTC hour is missing.\n    A missing hour takes the consumption of the hour before.\n    \"\"\"\n    for hours in (48, 168):\n        for shift in (0, 1):\n            lag = hourly.select(\n                \"region_code\",\n                (F.col(\"hour_utc\") + F.expr(f\"INTERVAL {hours + shift} HOURS\")).alias(\"hour_utc\"),\n                F.col(\"consumption_mw\").alias(f\"lag_{hours}h_{shift}\"),\n            )\n            df = df.join(lag, [\"region_code\", \"hour_utc\"], \"left\")\n        df = df.withColumn(\n            f\"lag_{hours}h\", F.coalesce(f\"lag_{hours}h_0\", f\"lag_{hours}h_1\")\n        ).drop(f\"lag_{hours}h_0\", f\"lag_{hours}h_1\")\n    return df\n\n\nhourly = spark.table(\"regional_consumption_hourly\")\ndataset = (\n    with_lags(with_calendar(hourly), hourly)\n    .where(F.col(\"consumption_mw\").isNotNull())\n    .dropna(subset=[\"lag_48h\", \"lag_168h\"])\n    .cache()\n)\nprint(f\"{dataset.count()} region-hours with both lags\")"
  },
  {
   "cell_type": "code",
   "id": "8d8acae6",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "(\n    dataset.where(\n        (F.col(\"region_code\") == 11)\n        & (F.col(\"hour_of_day\") == 8)\n        & F.col(\"hour_paris\").between(\"2024-12-23 00:00:00\", \"2024-12-28 00:00:00\")\n    )\n    .select(\"region_name\", \"hour_paris\", \"holiday\", \"day_type\", \"hour_day\", \"hour_lag_day\")\n    .orderBy(\"hour_paris\")\n    .show(truncate=False)\n)"
  },
  {
   "cell_type": "markdown",
   "id": "3bf6d7b4",
   "metadata": {},
   "source": "Île-de-France at 8 a.m., around Christmas 2024 (23 December is a Monday).\nOn 25 December, `day_type` is 6: the holiday is counted as a Sunday.\nOn 27 December, the day 48 hours before is Christmas, so `hour_lag_day` also ends with 6."
  },
  {
   "cell_type": "markdown",
   "id": "216eb199",
   "metadata": {},
   "source": "## 5. One model per region, in parallel\n\n`groupBy(\"region_code\").applyInPandas(...)` sends the rows of each region to one Python worker,\nwhich trains a scikit-learn regression and forecasts the target rows.\nRegions run side by side, as many at a time as there are executor cores: in a Custom PySpark action, this is set by the number and size of instances in the action's resources.\n\nThe same function serves the evaluation here and the production job in section 7: rows marked `train` fit the model,\nrows marked `target` receive a forecast."
  },
  {
   "cell_type": "code",
   "id": "e91904a7",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "FEATURE_CATEGORIES = [\"hour_day\", \"hour_lag_day\", \"month_name\"]\nFEATURE_NUMBERS = [\"lag_48h\", \"lag_168h\"]\nMODEL_COLUMNS = [\"region_code\", \"hour_utc\", \"split\", \"consumption_mw\"] + FEATURE_CATEGORIES + FEATURE_NUMBERS\nPREDICTION_SCHEMA = \"region_code long, hour_utc timestamp_ntz, predicted_mw double, train_hours long\"\n\n\ndef fit_and_forecast(rows):\n    \"\"\"Runs once per region, on a pandas DataFrame holding all the rows of that region.\"\"\"\n    import pandas as pd\n    from sklearn.compose import ColumnTransformer\n    from sklearn.linear_model import LinearRegression\n    from sklearn.pipeline import Pipeline\n    from sklearn.preprocessing import OneHotEncoder\n\n    train = rows[rows[\"split\"] == \"train\"]\n    target = rows[rows[\"split\"] == \"target\"]\n    if train.empty or target.empty:\n        return pd.DataFrame(columns=[\"region_code\", \"hour_utc\", \"predicted_mw\", \"train_hours\"])\n\n    model = Pipeline([\n        (\"encode\", ColumnTransformer(\n            [(\"calendar\", OneHotEncoder(handle_unknown=\"ignore\"), FEATURE_CATEGORIES)],\n            remainder=\"passthrough\",\n        )),\n        (\"regress\", LinearRegression()),\n    ])\n    model.fit(train[FEATURE_CATEGORIES + FEATURE_NUMBERS], train[\"consumption_mw\"])\n\n    forecast = target[[\"region_code\", \"hour_utc\"]].copy()\n    forecast[\"predicted_mw\"] = model.predict(target[FEATURE_CATEGORIES + FEATURE_NUMBERS])\n    forecast[\"train_hours\"] = len(train)\n    return forecast\n\n\ndef prepare(df, split):\n    return df.withColumn(\"split\", F.lit(split)).withColumn(\"month_name\", F.col(\"month\").cast(\"string\")).select(MODEL_COLUMNS)"
  },
  {
   "cell_type": "markdown",
   "id": "ab028f11",
   "metadata": {},
   "source": "### Train on 2022-2023, test on 2024"
  },
  {
   "cell_type": "code",
   "id": "402fbb80",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "evaluation_rows = prepare(dataset.where(F.col(\"year\").between(2022, 2023)), \"train\").unionByName(\n    prepare(dataset.where(F.col(\"year\") == 2024), \"target\")\n)\n\npredictions = (\n    evaluation_rows.groupBy(\"region_code\")\n    .applyInPandas(fit_and_forecast, schema=PREDICTION_SCHEMA)\n    .join(dataset.select(\"region_code\", \"region_name\", \"hour_utc\", \"hour_paris\", \"consumption_mw\", \"lag_168h\"),\n          [\"region_code\", \"hour_utc\"])\n    .cache()\n)\nprint(f\"{predictions.count()} forecasts for 2024\")"
  },
  {
   "cell_type": "markdown",
   "id": "2745bee8",
   "metadata": {},
   "source": "Notebook sessions do not appear in the Spark History Server, which only lists the runs of actions and workflows.\nThe parallel training is observed on the production job, in the Custom PySpark action."
  },
  {
   "cell_type": "code",
   "id": "e48f0783",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def mape(prediction_col, actual_col=\"consumption_mw\"):\n    return F.round(100 * F.avg(F.abs(F.col(prediction_col) - F.col(actual_col)) / F.col(actual_col)), 2)\n\nby_region = (\n    predictions.groupBy(\"region_code\", \"region_name\")\n    .agg(\n        F.first(\"train_hours\").alias(\"train_hours\"),\n        mape(\"predicted_mw\").alias(\"model_mape_pct\"),\n        mape(\"lag_168h\").alias(\"one_week_before_mape_pct\"),\n    )\n    .orderBy(\"model_mape_pct\")\n    .toPandas()\n)\nby_region"
  },
  {
   "cell_type": "markdown",
   "id": "f9e23327",
   "metadata": {},
   "source": "The model beats \"same hour one week before\" in every region, by about a third.\nThe error ranges from under 4 % (Provence-Alpes-Côte d'Azur, Hauts-de-France) to about 6.5 % (Centre-Val de Loire), with no simple link to the size of the region."
  },
  {
   "cell_type": "markdown",
   "id": "11f2e2cc",
   "metadata": {},
   "source": "## 6. Add up the regions\n\nThe 12 regional forecasts are added hour by hour, on the hours where all 12 regions have a forecast,\nand compared with the sum of the actual regional consumption."
  },
  {
   "cell_type": "code",
   "id": "f8fa4fab",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "regions_sum = (\n    predictions.groupBy(\"hour_utc\")\n    .agg(\n        F.count(\"*\").alias(\"regions\"),\n        F.sum(\"predicted_mw\").alias(\"predicted_mw\"),\n        F.sum(\"consumption_mw\").alias(\"consumption_mw\"),\n        F.sum(\"lag_168h\").alias(\"lag_168h\"),\n    )\n    .where(F.col(\"regions\") == 12)\n)\n\nprint(regions_sum.select(\n    F.count(\"*\").alias(\"hours\"),\n    mape(\"predicted_mw\").alias(\"regional_models_mape_pct\"),\n    mape(\"lag_168h\").alias(\"one_week_before_mape_pct\"),\n).first())"
  },
  {
   "cell_type": "markdown",
   "id": "88717d02",
   "metadata": {},
   "source": "Added up, the regional errors partly cancel out: in 2024, the sum of the regional models reaches about 3.5 %,\nagainst about 6 % for the forecast \"same hour one week before\".\nMost of the remaining error is the weather, which this model does not use."
  },
  {
   "cell_type": "code",
   "id": "d0649385",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "week = (\n    regions_sum\n    .withColumn(\"hour_paris\", F.from_utc_timestamp(F.col(\"hour_utc\").cast(\"timestamp\"), \"Europe/Paris\"))\n    .where(F.col(\"hour_paris\").between(\"2024-01-08 00:00:00\", \"2024-01-14 23:00:00\"))\n    .select(\"hour_paris\", \"consumption_mw\", \"predicted_mw\")\n    .orderBy(\"hour_paris\")\n    .toPandas()\n    .set_index(\"hour_paris\")\n    / 1000\n)\nweek.rename(columns={\"consumption_mw\": \"Actual (sum of regions)\", \"predicted_mw\": \"Sum of regional forecasts\"}).plot(figsize=(12, 4))\nplt.title(\"Week of 8 January 2024 (Paris time)\")\nplt.ylabel(\"GW\")\nplt.grid(True, alpha=0.3)\nplt.show()"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}