File size: 21,734 Bytes
83ce993
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f9728f51",
   "metadata": {},
   "source": [
    "# Protostar Challenge: example entry (\"Ocarina of Ten\" on the leaderboard)\n",
    "\n",
    "*The 10-year mean.* A complete, simple entry for the *Climate Risk Intelligence* challenge. Its forecasts are on the leaderboard as **Ocarina of Ten**¹ (tagged *reference*): run it, then try to beat it.\n",
    "\n",
    "1. Load the yearly data (up to 2018).\n",
    "2. Try the model on a **practice run**: train up to 2010, predict 2011–2018, and score it like the challenge does.\n",
    "3. Refit on all data up to 2018 and write `submission.csv` for 2019–2025 (5,880 rows).\n",
    "\n",
    "## The model: the 10-year average\n",
    "\n",
    "For each city and metric, every forecast year (2019–2025) gets the same number: **the average of the city's last 10 valid years** (up to 2018).\n",
    "\n",
    "- **Why recent years?** The climate is warming, so the last decade is closer to the next few years than a 30-year average is. NOAA's Climate Prediction Center has long used such short \"optimal climate normals\" for this reason (Huang, van den Dool & Barnston, 1996, *Journal of Climate* 9:809, doi:10.1175/1520-0442(1996)009<0809:LLSTPU>2.0.CO;2).\n",
    "- **Why 10 years?** A trade-off: fewer years follow the warming better but are noisier (one hot summer weighs more); more years are smoother but lag behind the trend.\n",
    "- **What it ignores:** the trend *within* the 10 years, year-to-year cycles (e.g., El Niño), and other cities. Each of those is a way to improve on it.\n",
    "- **Where it should help:** average temperature and CDD (steady warming). Hottest day and precipitation are noisy: no simple model beats the 30-year average there by much.\n",
    "\n",
    "No data after 2018 is used, so the notebook follows the data rule.\n",
    "\n",
    "¹ *Ocarina of Ten is not to be confused with* Ocarina of Time, *whose Switch 2 remake comes out on November 5. Save the princess after the deadline: in Hyrule, pulling the Master Sword jumps you 7 years ahead; here, you have to forecast them.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "196b9c2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:48.885998Z",
     "iopub.status.busy": "2026-11-05T14:00:48.885488Z",
     "iopub.status.idle": "2026-11-05T14:00:50.034585Z",
     "shell.execute_reply": "2026-11-05T14:00:50.033293Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/claude-1000/-home-alfredo-Datasets-NVIDIA-Hackhathon/03276e96-5a28-48c5-a971-d3be837fcaea/scratchpad/nbvenv/lib64/python3.14/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(28052, 24) 1851 2018 210 cities\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "LOCAL = Path(\"protostar-climate-train-to-2018\")\n",
    "SOURCE = LOCAL if LOCAL.exists() else \"hf://datasets/CMU-OSPO/protostar-climate-train-to-2018\"\n",
    "annual = pd.read_parquet(f\"{SOURCE}/annual_indices\")\n",
    "# with the datasets library: load_dataset(\"CMU-OSPO/protostar-climate-train-to-2018\", \"annual_indices\", split=\"train\")\n",
    "\n",
    "print(annual.shape, annual[\"Year\"].min(), annual[\"Year\"].max(), annual[\"ID\"].nunique(), \"cities\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bee0cc3f",
   "metadata": {},
   "source": [
    "## Long format and the 355-day rule\n",
    "\n",
    "One row per city × year × metric. A year counts only if the station missed **10 days or fewer** (Tmax and Tmin for the temperature metrics and CDD, precipitation for `total_precip_in`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d848f6b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.037480Z",
     "iopub.status.busy": "2026-11-05T14:00:50.037039Z",
     "iopub.status.idle": "2026-11-05T14:00:50.061945Z",
     "shell.execute_reply": "2026-11-05T14:00:50.061559Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city_id</th>\n",
       "      <th>year</th>\n",
       "      <th>value</th>\n",
       "      <th>metric</th>\n",
       "      <th>valid</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>USW00014929</td>\n",
       "      <td>1893</td>\n",
       "      <td>41.09</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>USW00014929</td>\n",
       "      <td>1894</td>\n",
       "      <td>49.05</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>USW00014929</td>\n",
       "      <td>1895</td>\n",
       "      <td>41.94</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>USW00014929</td>\n",
       "      <td>1896</td>\n",
       "      <td>41.16</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>USW00014929</td>\n",
       "      <td>1897</td>\n",
       "      <td>40.89</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       city_id  year  value           metric  valid\n",
       "0  USW00014929  1893  41.09  annual_avg_temp  False\n",
       "1  USW00014929  1894  49.05  annual_avg_temp  False\n",
       "2  USW00014929  1895  41.94  annual_avg_temp  False\n",
       "3  USW00014929  1896  41.16  annual_avg_temp   True\n",
       "4  USW00014929  1897  40.89  annual_avg_temp  False"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "METRICS = {  # metric code: (column, missing-day columns)\n",
    "    \"annual_avg_temp\": (\"Avg Temp\", [\"Miss Tmax\", \"Miss Tmin\"]),\n",
    "    \"total_precip_in\": (\"ToT Prcp\", [\"Miss Prcp\"]),\n",
    "    \"hottest_day_temp\": (\"Max Tmax\", [\"Miss Tmax\", \"Miss Tmin\"]),\n",
    "    \"cdd\": (\"cdd\", [\"Miss Tmax\", \"Miss Tmin\"]),\n",
    "}\n",
    "\n",
    "rows = []\n",
    "for metric, (col, miss) in METRICS.items():\n",
    "    part = annual[[\"ID\", \"Year\", col]].rename(columns={\"ID\": \"city_id\", \"Year\": \"year\", col: \"value\"})\n",
    "    part[\"metric\"] = metric\n",
    "    part[\"valid\"] = (annual[miss] <= 10).all(axis=1) & part[\"value\"].notna()\n",
    "    rows.append(part)\n",
    "long = pd.concat(rows, ignore_index=True)\n",
    "long.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e461f81d",
   "metadata": {},
   "source": [
    "## The model and the 30-year-average baseline\n",
    "\n",
    "`recent_average` is the whole model. `thirty_year_average` is the challenge's reference: the Score compares every forecast with it (0 = no better, 100 = perfect). `forecast` repeats a single value for every year, since both are flat lines."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2afc0bea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.062779Z",
     "iopub.status.busy": "2026-11-05T14:00:50.062675Z",
     "iopub.status.idle": "2026-11-05T14:00:50.065409Z",
     "shell.execute_reply": "2026-11-05T14:00:50.065077Z"
    }
   },
   "outputs": [],
   "source": [
    "def recent_average(history, n_years=10):\n",
    "    \"\"\"Our model: mean of each city-metric's last n valid years.\n",
    "\n",
    "    \"Valid\" years follow the 355-day rule; skipping invalid years means a city\n",
    "    with a gap still averages 10 real years, just reaching further back.\n",
    "    \"\"\"\n",
    "    v = history[history[\"valid\"]].sort_values(\"year\")\n",
    "    return v.groupby([\"city_id\", \"metric\"])[\"value\"].apply(lambda s: s.tail(n_years).mean())\n",
    "\n",
    "\n",
    "def thirty_year_average(history, last_year):\n",
    "    \"\"\"Baseline: mean of the valid years in the 30 years up to last_year.\"\"\"\n",
    "    v = history[history[\"valid\"] & history[\"year\"].between(last_year - 29, last_year)]\n",
    "    return v.groupby([\"city_id\", \"metric\"])[\"value\"].mean()\n",
    "\n",
    "\n",
    "def forecast(point, years):\n",
    "    \"\"\"Repeat one value per city-metric for every forecast year.\"\"\"\n",
    "    out = point.rename(\"predicted_value\").reset_index()\n",
    "    return out.merge(pd.DataFrame({\"year\": years}), how=\"cross\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82315d4c",
   "metadata": {},
   "source": [
    "## Practice run: train up to 2010, predict 2011–2018\n",
    "\n",
    "Before forecasting the unknown years, test the idea on years we know: pretend it is the end of 2010, forecast 2011–2018, and compare with what happened. This is how to check any model without using data after 2018.\n",
    "\n",
    "Scored like the challenge: MAE per metric, skill $S_m = 1 - \\mathrm{MAE}_{\\text{model}} / \\mathrm{MAE}_{\\text{30-year average}}$, and Score $= 100 \\times \\max(0, \\text{mean of the four } S_m)$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "fd771b9d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.066876Z",
     "iopub.status.busy": "2026-11-05T14:00:50.066623Z",
     "iopub.status.idle": "2026-11-05T14:00:50.126495Z",
     "shell.execute_reply": "2026-11-05T14:00:50.126039Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MAE 30-year average</th>\n",
       "      <th>MAE our model</th>\n",
       "      <th>skill S_m</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>metric</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>annual_avg_temp</th>\n",
       "      <td>1.657</td>\n",
       "      <td>1.513</td>\n",
       "      <td>0.087</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>cdd</th>\n",
       "      <td>212.636</td>\n",
       "      <td>184.059</td>\n",
       "      <td>0.134</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>hottest_day_temp</th>\n",
       "      <td>2.563</td>\n",
       "      <td>2.568</td>\n",
       "      <td>-0.002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>total_precip_in</th>\n",
       "      <td>6.198</td>\n",
       "      <td>6.207</td>\n",
       "      <td>-0.001</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                  MAE 30-year average  MAE our model  skill S_m\n",
       "metric                                                         \n",
       "annual_avg_temp                 1.657          1.513      0.087\n",
       "cdd                           212.636        184.059      0.134\n",
       "hottest_day_temp                2.563          2.568     -0.002\n",
       "total_precip_in                 6.198          6.207     -0.001"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train = long[long[\"year\"] <= 2010]\n",
    "test = long[long[\"year\"].between(2011, 2018) & long[\"valid\"]]\n",
    "years = list(range(2011, 2019))\n",
    "\n",
    "def mae_per_metric(pred):\n",
    "    m = test.merge(pred, on=[\"city_id\", \"metric\", \"year\"])\n",
    "    return (m[\"predicted_value\"] - m[\"value\"]).abs().groupby(m[\"metric\"]).mean()\n",
    "\n",
    "mae_ref = mae_per_metric(forecast(thirty_year_average(train, 2010), years))\n",
    "mae_model = mae_per_metric(forecast(recent_average(train), years))\n",
    "\n",
    "skill = 1 - mae_model / mae_ref\n",
    "score = 100 * max(0, skill.mean())\n",
    "pd.DataFrame({\"MAE 30-year average\": mae_ref, \"MAE our model\": mae_model, \"skill S_m\": skill}).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "42cf8379",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.127368Z",
     "iopub.status.busy": "2026-11-05T14:00:50.127254Z",
     "iopub.status.idle": "2026-11-05T14:00:50.129206Z",
     "shell.execute_reply": "2026-11-05T14:00:50.128839Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Practice-run Score: 5.5  (0 = no better than the 30-year average, 100 = perfect)\n"
     ]
    }
   ],
   "source": [
    "print(f\"Practice-run Score: {score:.1f}  (0 = no better than the 30-year average, 100 = perfect)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a546bdf5",
   "metadata": {},
   "source": [
    "Read the table per metric: a positive skill means the 10-year average beat the 30-year average on that metric. Expect most of the gain on temperature and CDD, little or none on precipitation and hottest day. The practice run is one 8-year window; the real test years (2019–2025) can behave differently."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b59df177",
   "metadata": {},
   "source": [
    "## Refit on everything up to 2018 and write `submission.csv`\n",
    "\n",
    "Same model, now using every year up to 2018. A few cities have no valid recent years for a metric; they fall back to their long-term average, so all 5,880 rows get a number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a581cd97",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.130301Z",
     "iopub.status.busy": "2026-11-05T14:00:50.130151Z",
     "iopub.status.idle": "2026-11-05T14:00:50.189571Z",
     "shell.execute_reply": "2026-11-05T14:00:50.189078Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city_id</th>\n",
       "      <th>year</th>\n",
       "      <th>metric</th>\n",
       "      <th>predicted_value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2019</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>66.40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2019</td>\n",
       "      <td>total_precip_in</td>\n",
       "      <td>11.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2019</td>\n",
       "      <td>hottest_day_temp</td>\n",
       "      <td>103.89</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2019</td>\n",
       "      <td>cdd</td>\n",
       "      <td>1571.40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2020</td>\n",
       "      <td>annual_avg_temp</td>\n",
       "      <td>66.40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2020</td>\n",
       "      <td>total_precip_in</td>\n",
       "      <td>11.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2020</td>\n",
       "      <td>hottest_day_temp</td>\n",
       "      <td>103.89</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>USC00042863</td>\n",
       "      <td>2020</td>\n",
       "      <td>cdd</td>\n",
       "      <td>1571.40</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       city_id  year            metric  predicted_value\n",
       "0  USC00042863  2019   annual_avg_temp            66.40\n",
       "1  USC00042863  2019   total_precip_in            11.06\n",
       "2  USC00042863  2019  hottest_day_temp           103.89\n",
       "3  USC00042863  2019               cdd          1571.40\n",
       "4  USC00042863  2020   annual_avg_temp            66.40\n",
       "5  USC00042863  2020   total_precip_in            11.06\n",
       "6  USC00042863  2020  hottest_day_temp           103.89\n",
       "7  USC00042863  2020               cdd          1571.40"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cities = sorted(annual[\"ID\"].unique())\n",
    "grid = pd.MultiIndex.from_product([cities, range(2019, 2026), METRICS], names=[\"city_id\", \"year\", \"metric\"]).to_frame(index=False)\n",
    "\n",
    "point = recent_average(long)\n",
    "fallback = long.groupby([\"city_id\", \"metric\"])[\"value\"].mean()  # cities with no valid recent years\n",
    "point = point.reindex(fallback.index).fillna(fallback)\n",
    "\n",
    "submission = grid.merge(point.rename(\"predicted_value\").reset_index(), on=[\"city_id\", \"metric\"], how=\"left\")\n",
    "submission[\"predicted_value\"] = submission[\"predicted_value\"].round(2)\n",
    "\n",
    "# Run from the dataset's code/ folder: submission.csv goes to the dataset root\n",
    "out = Path(\"..\") if Path.cwd().name == \"code\" else Path(\"example_submission\")\n",
    "out.mkdir(exist_ok=True)\n",
    "submission.to_csv(out / \"submission.csv\", index=False)\n",
    "submission.head(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad9655ef",
   "metadata": {},
   "source": [
    "## Check the file before submitting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1a3e1909",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T14:00:50.190667Z",
     "iopub.status.busy": "2026-11-05T14:00:50.190545Z",
     "iopub.status.idle": "2026-11-05T14:00:50.198543Z",
     "shell.execute_reply": "2026-11-05T14:00:50.198229Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "submission.csv OK: 5880 rows. Copy it to your Hugging Face dataset, with your README.\n"
     ]
    }
   ],
   "source": [
    "s = pd.read_csv(out / \"submission.csv\")\n",
    "assert list(s.columns) == [\"city_id\", \"year\", \"metric\", \"predicted_value\"]\n",
    "assert len(s) == 210 * 7 * 4 == 5880\n",
    "assert not s.duplicated([\"city_id\", \"year\", \"metric\"]).any()\n",
    "assert set(s[\"metric\"]) == set(METRICS) and set(s[\"year\"]) == set(range(2019, 2026))\n",
    "assert s[\"predicted_value\"].notna().all()\n",
    "print(\"submission.csv OK:\", len(s), \"rows. Copy it to your Hugging Face dataset, with your README.\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}