{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "37dd2fbb",
   "metadata": {},
   "source": "# Forecast tomorrow's regional consumption: production notebook\n\nThis notebook is the production job, and only the production job: it retrains one model per region on the most recent 730 days\nand writes the forecast of every hour of tomorrow (Paris time) to `regional_forecasts`.\nThe exploration and the choice of the model live in `eco2mix_regional_exploration.ipynb`.\n\nRun it once from top to bottom to check it, then export it as a **Custom PySpark** action with the Data Platform extension.\nEvery code cell becomes part of the job: keep checks and explorations out of it.\n\n`holidays` and `scikit-learn` come from the **Dependencies** of the notebook server.\n\nKernel: **Python 3 (ipykernel)**."
  },
  {
   "cell_type": "markdown",
   "id": "ef13e6bc",
   "metadata": {},
   "source": "## 1. Set up\n\nMessages go through `logging`: they show below each cell in the notebook, and in Logs Explorer once the notebook runs as an action."
  },
  {
   "cell_type": "code",
   "id": "10ba86eb",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import logging\nfrom datetime import datetime, time, timedelta, timezone\nfrom zoneinfo import ZoneInfo\n\nimport holidays\nfrom forepaas.dwh import connect\nfrom forepaas.dwh.lineage import lineage_run\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\n\nlogger = logging.getLogger(__name__)\n\nPARIS = ZoneInfo(\"Europe/Paris\")\nFMT = \"%Y-%m-%d %H:%M:%S\"\nTRAIN_DAYS = 730\n\nFEATURE_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\""
  },
  {
   "cell_type": "code",
   "id": "9523f5fa",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "logging.basicConfig(level=logging.INFO)\n\n# connect() first: in the notebook it creates the Spark session with the lakehouse settings,\n# which views need; in the action the session already exists. getOrCreate returns it\nsource = connect(\"dwh/default_dataset/\")\nspark = SparkSession.builder.getOrCreate()\nsc = spark.sparkContext\n\nspark.sql(f\"USE {source.catalog}.{source.schema}\")\nspark.conf.set(\"spark.sql.session.timeZone\", \"UTC\")\n# 12 regions: a few shuffle partitions are enough, instead of the default 200\nspark.conf.set(\"spark.sql.shuffle.partitions\", \"12\")\nlogger.info(f\"Spark {spark.version}, catalog {source.catalog}\")"
  },
  {
   "cell_type": "markdown",
   "id": "970e70e0",
   "metadata": {},
   "source": "## 2. Features\n\nCalendar in Paris time, public holidays counted as Sundays, and the consumption 48 and 168 hours earlier.\nOn the day clocks go back, one UTC hour is missing: it takes the consumption of the hour before."
  },
  {
   "cell_type": "code",
   "id": "2033b49b",
   "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\n\ndef holiday_table(spark):\n    return spark.createDataFrame(\n        [(day, name) for day, name in sorted(holidays.France(years=range(2012, 2030)).items())],\n        [\"date_paris\", \"holiday\"],\n    )\n\n\ndef with_calendar(df, holiday_dates):\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\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": "3f246aec",
   "metadata": {},
   "source": "## 3. One model per region\n\n`applyInPandas` runs this function once per region, on a pandas DataFrame holding all the rows of that region."
  },
  {
   "cell_type": "code",
   "id": "a83d07dc",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def fit_and_forecast(rows):\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"
  },
  {
   "cell_type": "markdown",
   "id": "fc02ef9d",
   "metadata": {},
   "source": "## 4. Forecast tomorrow and write it\n\nThe job raises an error if the lags of tomorrow are missing: run the collection workflow first if the data is not fresh.\nIt replaces the forecasts of the target day, so a second run on the same day does not duplicate rows."
  },
  {
   "cell_type": "code",
   "id": "270494b3",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def target_window(run_date):\n    \"\"\"First and last-plus-one UTC hours of the day after run_date, in Paris time.\"\"\"\n    day = run_date + timedelta(days=1)\n    start = datetime.combine(day, time(0), PARIS).astimezone(timezone.utc)\n    end = datetime.combine(day + timedelta(days=1), time(0), PARIS).astimezone(timezone.utc)\n    return start.strftime(FMT), end.strftime(FMT)\n\n\ndef forecast_tomorrow(spark, run_date=None, train_days=TRAIN_DAYS):\n    \"\"\"Retrain each region on its most recent hours and forecast every hour of the next day.\"\"\"\n    if run_date is None:\n        run_date = datetime.now(PARIS).date()\n    start, end = target_window(run_date)\n    run_at = datetime.now(timezone.utc).strftime(FMT)\n\n    holiday_dates = holiday_table(spark)\n    view = spark.table(\"regional_consumption_hourly\")\n\n    # Latest measured hour, read from the small real time table: reading it from the view\n    # would aggregate the whole history first\n    latest_quarter = (\n        spark.table(\"eco2mix_regional_realtime\")\n        .where(F.col(\"consommation\").isNotNull())\n        .agg(F.max(\"date_heure\"))\n        .first()[0]\n    )\n    last_measured = latest_quarter.replace(minute=0, second=0, microsecond=0)\n\n    # Keep only the hours the job needs: the training window, plus 8 days so that the oldest rows still get their 168 h lag\n    hourly = view.where(\n        F.col(\"hour_utc\") > F.lit(last_measured) - F.expr(f\"INTERVAL {train_days + 8} DAYS\")\n    ).cache()\n\n    history = (\n        with_lags(with_calendar(hourly, holiday_dates), hourly)\n        .where(F.col(\"consumption_mw\").isNotNull())\n        .dropna(subset=[\"lag_48h\", \"lag_168h\"])\n    )\n    train = history.where(F.col(\"hour_utc\") > F.lit(last_measured) - F.expr(f\"INTERVAL {train_days} DAYS\"))\n\n    regions = hourly.select(\"region_code\", \"region_name\").distinct()\n    target_hours = spark.range(1).select(\n        F.explode(F.sequence(\n            F.lit(start).cast(\"timestamp_ntz\"),\n            F.lit(end).cast(\"timestamp_ntz\") - F.expr(\"INTERVAL 1 HOUR\"),\n            F.expr(\"INTERVAL 1 HOUR\"),\n        )).alias(\"hour_utc\")\n    )\n    target = with_lags(with_calendar(regions.crossJoin(target_hours), holiday_dates), hourly).withColumn(\n        \"consumption_mw\", F.lit(None).cast(\"double\")\n    )\n\n    missing = target.where(F.col(\"lag_48h\").isNull() | F.col(\"lag_168h\").isNull()).count()\n    if missing:\n        raise ValueError(\n            f\"{missing} region-hours of {run_date + timedelta(days=1)} have no lag: \"\n            f\"the latest measured hour is {last_measured}, collect eco2mix_regional_realtime first\"\n        )\n\n    forecast = (\n        prepare(train, \"train\").unionByName(prepare(target, \"target\"))\n        .groupBy(\"region_code\")\n        .applyInPandas(fit_and_forecast, schema=PREDICTION_SCHEMA)\n        .join(regions, \"region_code\")\n        .select(\n            F.col(\"hour_utc\").alias(\"forecast_hour\"),\n            \"region_code\",\n            \"region_name\",\n            \"predicted_mw\",\n            F.lit(run_at).cast(\"timestamp_ntz\").alias(\"run_at\"),\n            \"train_hours\",\n        )\n    )\n    return forecast, start, end, last_measured\n\n\ndef write_forecast(spark, source, forecast, start, end):\n    \"\"\"Replace the forecasts of the target day, then append the new ones.\"\"\"\n    spark.sql(\n        f\"DELETE FROM regional_forecasts \"\n        f\"WHERE forecast_hour >= TIMESTAMP_NTZ '{start}' AND forecast_hour < TIMESTAMP_NTZ '{end}'\"\n    )\n    source.insert_dataframe(table=\"regional_forecasts\", df=forecast.drop(\"train_hours\"), mode=\"append\")"
  },
  {
   "cell_type": "markdown",
   "id": "0e64f06a",
   "metadata": {},
   "source": "## 5. Run\n\n`lineage_run` declares what the job reads and writes, `setJobDescription` names its Spark jobs in the Spark History Server."
  },
  {
   "cell_type": "code",
   "id": "aed39494",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# Lineage is opt-in for Custom actions: declare what the job reads and writes\nwith lineage_run(\n    \"regional_forecast\",\n    inputs=[\n        \"default_dataset/eco2mix_regional_history\",\n        \"default_dataset/eco2mix_regional_realtime\",\n    ],\n    outputs=[\"default_dataset/regional_forecasts\"],\n    connector=source,\n):\n    sc.setJobDescription(\"Train one model per region and forecast tomorrow\")\n    forecast, start, end, last_measured = forecast_tomorrow(spark)\n    forecast = forecast.cache()\n\n    rows = forecast.count()\n    logger.info(f\"Latest measured hour: {last_measured}\")\n    logger.info(f\"Forecast {start} to {end} (UTC): {rows} region-hours\")\n    for r in forecast.groupBy(\"region_name\").agg(F.first(\"train_hours\").alias(\"train_hours\")).orderBy(\"region_name\").collect():\n        logger.info(f\"{r['region_name']}: trained on {r['train_hours']} hours\")\n\n    sc.setJobDescription(\"Write regional_forecasts\")\n    write_forecast(spark, source, forecast, start, end)\n    logger.info(\"regional_forecasts written\")"
  },
  {
   "cell_type": "markdown",
   "id": "d180a503",
   "metadata": {},
   "source": "To check the result, run in the Lakehouse Manager Explorer:\n\n```sql\nSELECT run_at, count(*) AS forecasts\nFROM regional_forecasts\nGROUP BY run_at\nORDER BY run_at\n```\n\nRun the notebook a second time: `regional_forecasts` must still hold 288 forecasts for tomorrow, with a newer `run_at`."
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}