Update fmda_rnn_spatial.ipynb
[notebooks.git] / fmda / fmda_rnn_spatial.ipynb
blob9317417cf86d92233c048d691b89c1796f2f8716
2  "cells": [
3   {
4    "cell_type": "markdown",
5    "id": "83b774b3-ef55-480a-b999-506676e49145",
6    "metadata": {},
7    "source": [
8     "# v2.1 run RNN with Spatial Training\n",
9     "\n",
10     "This notebook is intended to set up a test where the RNN is run serial by location and compared to the spatial training scheme. Additionally, the ODE model with the augmented KF will be run as a comparison, but note that the RNN models will be predicting entirely without knowledge of the heldout locations, while the augmented KF will be run directly on the test locations.\n"
11    ]
12   },
13   {
14    "cell_type": "markdown",
15    "id": "bbd84d61-a9cd-47b4-b538-4986fb10b98d",
16    "metadata": {},
17    "source": [
18     "## Environment Setup"
19    ]
20   },
21   {
22    "cell_type": "code",
23    "execution_count": null,
24    "id": "83cc1dc4-3dcb-4325-9263-58101a3dc378",
25    "metadata": {},
26    "outputs": [],
27    "source": [
28     "import numpy as np\n",
29     "from utils import print_dict_summary, print_first, str2time, logging_setup\n",
30     "import pickle\n",
31     "import logging\n",
32     "import os.path as osp\n",
33     "from moisture_rnn_pkl import pkl2train\n",
34     "from moisture_rnn import RNNParams, RNNData, RNN \n",
35     "from utils import hash2, read_yml, read_pkl, retrieve_url, Dict\n",
36     "from moisture_rnn import RNN\n",
37     "import reproducibility\n",
38     "from data_funcs import rmse, to_json, combine_nested, build_train_dict\n",
39     "from moisture_models import run_augmented_kf\n",
40     "import copy\n",
41     "import pandas as pd\n",
42     "import matplotlib.pyplot as plt\n",
43     "import yaml\n",
44     "import time"
45    ]
46   },
47   {
48    "cell_type": "code",
49    "execution_count": null,
50    "id": "17db9b90-a931-4674-a447-5b8ffbcdc86a",
51    "metadata": {},
52    "outputs": [],
53    "source": [
54     "logging_setup()"
55    ]
56   },
57   {
58    "cell_type": "code",
59    "execution_count": null,
60    "id": "35319c1c-7849-4b8c-8262-f5aa6656e0c7",
61    "metadata": {},
62    "outputs": [],
63    "source": [
64     "retrieve_url(\n",
65     "    url = \"https://demo.openwfm.org/web/data/fmda/dicts/fmda_nw_202401-05_f05.pkl\", \n",
66     "    dest_path = \"data/fmda_nw_202401-05_f05.pkl\")"
67    ]
68   },
69   {
70    "cell_type": "code",
71    "execution_count": null,
72    "id": "eabdbd9c-07d9-4bae-9851-cca79f321895",
73    "metadata": {},
74    "outputs": [],
75    "source": [
76     "file_paths = ['data/fmda_nw_202401-05_f05.pkl']"
77    ]
78   },
79   {
80    "cell_type": "code",
81    "execution_count": null,
82    "id": "dcca6185-e799-4dd1-8acb-87ad33c411d7",
83    "metadata": {},
84    "outputs": [],
85    "source": [
86     "# read/write control\n",
87     "train_file='data/train.pkl'\n",
88     "train_create=True   # if false, read\n",
89     "train_write=False\n",
90     "train_read=False"
91    ]
92   },
93   {
94    "cell_type": "code",
95    "execution_count": null,
96    "id": "604388de-11ab-45c3-9f0d-80bdff0cca60",
97    "metadata": {},
98    "outputs": [],
99    "source": [
100     "# Params used for data filtering\n",
101     "params_data = read_yml(\"params_data.yaml\") \n",
102     "params_data"
103    ]
104   },
105   {
106    "cell_type": "code",
107    "execution_count": null,
108    "id": "211a1c2f-ba8d-40b8-b29c-daa38af97a26",
109    "metadata": {},
110    "outputs": [],
111    "source": [
112     "# Params used for setting up RNN\n",
113     "params = read_yml(\"params.yaml\", subkey='rnn') \n",
114     "params"
115    ]
116   },
117   {
118    "cell_type": "code",
119    "execution_count": null,
120    "id": "be81d76c-3123-4467-982b-d2da5b1c08bd",
121    "metadata": {
122     "scrolled": true
123    },
124    "outputs": [],
125    "source": [
126     "train = build_train_dict(file_paths, atm_source=\"HRRR\", params_data = params_data, spatial=False, verbose=True)"
127    ]
128   },
129   {
130    "cell_type": "code",
131    "execution_count": null,
132    "id": "bc0a775b-b587-42ef-8576-e36dc0be3a75",
133    "metadata": {
134     "scrolled": true
135    },
136    "outputs": [],
137    "source": [
138     "# if train_create:\n",
139     "#     logging.info('creating the training cases from files %s',file_paths)\n",
140     "#     # osp.join works on windows too, joins paths using \\ or /\n",
141     "#     train = process_train_dict(file_paths, atm_dict=\"HRRR\", params_data = params_data, verbose=True)\n",
142     "# if train_write:\n",
143     "#     with open(train_file, 'wb') as file:\n",
144     "#         logging.info('Writing the rain cases into file %s',train_file)\n",
145     "#         pickle.dump(train, file)\n",
146     "# if train_read:\n",
147     "#     logging.info('Reading the train cases from file %s',train_file)\n",
148     "#     train = read_pkl(train_file)"
149    ]
150   },
151   {
152    "cell_type": "code",
153    "execution_count": null,
154    "id": "23cd60c0-9865-4314-9a96-948c3d400c08",
155    "metadata": {},
156    "outputs": [],
157    "source": [
158     "from itertools import islice\n",
159     "train = {k: train[k] for k in islice(train, 250)}"
160    ]
161   },
162   {
163    "cell_type": "markdown",
164    "id": "efc10cdc-f18b-4781-84da-b8e2eef39981",
165    "metadata": {},
166    "source": [
167     "## Setup Validation Runs"
168    ]
169   },
170   {
171    "cell_type": "markdown",
172    "id": "2d9cd5c5-87ed-41f9-b36c-e0c18d58c841",
173    "metadata": {},
174    "source": [
175     "The following parameters will be used for both serial and spatial models."
176    ]
177   },
178   {
179    "cell_type": "code",
180    "execution_count": null,
181    "id": "66f40c9f-c1c2-4b12-bf14-2ada8c26113d",
182    "metadata": {},
183    "outputs": [],
184    "source": [
185     "params = RNNParams(params)\n",
186     "params.update({'epochs': 200, \n",
187     "               'learning_rate': 0.001,\n",
188     "               'activation': ['tanh', 'tanh'], # Activation for RNN Layers, Dense layers respectively.\n",
189     "               'rnn_layers': 2, 'recurrent_units': 30, \n",
190     "               'dense_layers': 2, 'dense_units': 30,\n",
191     "               'early_stopping_patience': 30, # how many epochs of no validation accuracy gain to wait before stopping\n",
192     "               'batch_schedule_type': 'exp', # Hidden state batch reset schedule\n",
193     "               'bmin': 20, # Lower bound of hidden state batch reset, \n",
194     "               'bmax': params_data['hours'], # Upper bound of hidden state batch reset, using max hours\n",
195     "               'features_list': ['Ed', 'Ew', 'rain', 'elev', 'lon', 'lat', 'solar', 'wind'],\n",
196     "               'timesteps': 12\n",
197     "              })"
198    ]
199   },
200   {
201    "cell_type": "code",
202    "execution_count": null,
203    "id": "36823193-b93c-421e-b699-8c1ae5719309",
204    "metadata": {},
205    "outputs": [],
206    "source": [
207     "reproducibility.set_seed(123)"
208    ]
209   },
210   {
211    "cell_type": "markdown",
212    "id": "a24d76fc-6c25-43e7-99df-3cd5dbf84fc3",
213    "metadata": {},
214    "source": [
215     "## Spatial Data Training\n",
216     "\n",
217     "This method combines the training timeseries data into a single 3-d array, with timeseries at the same location arranged appropriately in the right order for a given `batch_size` hyperparameter. The hidden state of the recurrent layers are set up reset when the location changes. "
218    ]
219   },
220   {
221    "cell_type": "code",
222    "execution_count": null,
223    "id": "3b5371a9-c1e8-4df5-b360-210746f7cd52",
224    "metadata": {},
225    "outputs": [],
226    "source": [
227     "# Start timer for code \n",
228     "start_time = time.time()"
229    ]
230   },
231   {
232    "cell_type": "code",
233    "execution_count": null,
234    "id": "faf93470-b55f-4770-9fa9-3288a2f13fcc",
235    "metadata": {},
236    "outputs": [],
237    "source": [
238     "# Combine Nested Dictionary into Spatial Data\n",
239     "train_sp = Dict(combine_nested(train))"
240    ]
241   },
242   {
243    "cell_type": "code",
244    "execution_count": null,
245    "id": "c0c7f5fb-4c33-45f8-9a2e-38c9ab1cd4e3",
246    "metadata": {},
247    "outputs": [],
248    "source": [
249     "rnn_dat_sp = RNNData(\n",
250     "    train_sp, # input dictionary\n",
251     "    scaler=\"standard\",  # data scaling type\n",
252     "    features_list = params['features_list'] # features for predicting outcome\n",
253     ")\n",
254     "\n",
255     "\n",
256     "rnn_dat_sp.train_test_split(   \n",
257     "    time_fracs = [.8, .1, .1], # Percent of total time steps used for train/val/test\n",
258     "    space_fracs = [.8, .1, .1] # Percent of total timeseries used for train/val/test\n",
259     ")\n",
260     "rnn_dat_sp.scale_data()\n",
261     "\n",
262     "rnn_dat_sp.batch_reshape(\n",
263     "    timesteps = params['timesteps'], # Timesteps aka sequence length for RNN input data. \n",
264     "    batch_size = params['batch_size'] # Number of samples of length timesteps for a single round of grad. descent\n",
265     ")"
266    ]
267   },
268   {
269    "cell_type": "code",
270    "execution_count": null,
271    "id": "7431bc95-d384-40fd-a622-bbc0ee68e5cd",
272    "metadata": {},
273    "outputs": [],
274    "source": [
275     "# Update Params specific to spatial training\n",
276     "params.update({\n",
277     "    'loc_batch_reset': rnn_dat_sp.n_seqs # Used to reset hidden state when location changes for a given batch\n",
278     "})"
279    ]
280   },
281   {
282    "cell_type": "code",
283    "execution_count": null,
284    "id": "4bc11474-fed8-47f2-b9cf-dfdda0d3d3b2",
285    "metadata": {},
286    "outputs": [],
287    "source": [
288     "rnn_sp = RNN(params)\n",
289     "m_sp, errs = rnn_sp.run_model(rnn_dat_sp)"
290    ]
291   },
292   {
293    "cell_type": "code",
294    "execution_count": null,
295    "id": "704ad662-d81a-488d-be3d-e90bf775a5b8",
296    "metadata": {},
297    "outputs": [],
298    "source": [
299     "errs.mean()"
300    ]
301   },
302   {
303    "cell_type": "code",
304    "execution_count": null,
305    "id": "d53571e3-b6cf-49aa-9848-e3c77053283d",
306    "metadata": {},
307    "outputs": [],
308    "source": [
309     "# End Timer\n",
310     "end_time = time.time()\n",
311     "\n",
312     "# Calculate Code Runtime\n",
313     "elapsed_time_sp = end_time - start_time\n",
314     "print(f\"Spatial Training Elapsed time: {elapsed_time_sp:.4f} seconds\")"
315    ]
316   },
317   {
318    "cell_type": "markdown",
319    "id": "7d8292a2-418c-48ed-aff7-ccbe98b046d3",
320    "metadata": {},
321    "source": [
322     "## Run ODE + KF "
323    ]
324   },
325   {
326    "cell_type": "code",
327    "execution_count": null,
328    "id": "cca12d8c-c0e1-4df4-b2ca-20440485f2f3",
329    "metadata": {},
330    "outputs": [],
331    "source": [
332     "# Get timeseries IDs from previous RNNData object\n",
333     "test_cases = rnn_dat_sp.loc['test_locs']\n",
334     "print(len(test_cases))"
335    ]
336   },
337   {
338    "cell_type": "code",
339    "execution_count": null,
340    "id": "997f2534-7e77-45b3-93bf-d988837dfc0b",
341    "metadata": {},
342    "outputs": [],
343    "source": [
344     "test_ind = rnn_dat_sp.test_ind # Time index for test period start\n",
345     "print(test_ind)"
346    ]
347   },
348   {
349    "cell_type": "code",
350    "execution_count": null,
351    "id": "1e4ffc68-c775-41c6-ac42-f49c76824b43",
352    "metadata": {
353     "scrolled": true
354    },
355    "outputs": [],
356    "source": [
357     "outputs_kf = {}\n",
358     "for case in test_cases:\n",
359     "    print(\"~\"*50)\n",
360     "    print(case)\n",
361     "    # Run Augmented KF\n",
362     "    print('Running Augmented KF')\n",
363     "    train[case]['h2'] = test_ind\n",
364     "    train[case]['scale_fm'] = 1\n",
365     "    m, Ec = run_augmented_kf(train[case])\n",
366     "    y = train[case]['y']        \n",
367     "    train[case]['m_kf'] = m\n",
368     "    print(f\"KF RMSE: {rmse(m[test_ind:],y[test_ind:])}\")\n",
369     "    outputs_kf[case] = {'case':case, 'errs': rmse(m[test_ind:],y[test_ind:])}"
370    ]
371   },
372   {
373    "cell_type": "code",
374    "execution_count": null,
375    "id": "57b19ec5-23f6-44ec-9f71-16d4d69aec68",
376    "metadata": {},
377    "outputs": [],
378    "source": [
379     "df_kf = pd.DataFrame.from_dict(outputs_kf).transpose()\n",
380     "df_kf.head()"
381    ]
382   },
383   {
384    "cell_type": "code",
385    "execution_count": null,
386    "id": "25a9d2fe-83f7-4ef3-a04b-14c970b6e2ba",
387    "metadata": {},
388    "outputs": [],
389    "source": [
390     "df_kf.errs.mean()"
391    ]
392   },
393   {
394    "cell_type": "markdown",
395    "id": "86795281-f8ea-4141-81ea-c53fae830e80",
396    "metadata": {},
397    "source": [
398     "## Compare"
399    ]
400   },
401   {
402    "cell_type": "code",
403    "execution_count": null,
404    "id": "508a6392-49bc-4471-ad8e-814f60119283",
405    "metadata": {},
406    "outputs": [],
407    "source": [
408     "print(f\"Total Test Cases: {len(test_cases)}\")\n",
409     "print(f\"Total Test Hours: {rnn_dat_temp.y_test.shape[0]}\")"
410    ]
411   },
412   {
413    "cell_type": "code",
414    "execution_count": null,
415    "id": "73e8ca05-d17b-4e72-8def-fa77664e7bb0",
416    "metadata": {},
417    "outputs": [],
418    "source": [
419     "print(f\"Spatial Training RMSE: {errs.mean()}\")\n",
420     "print(f\"Augmented KF RMSE: {df_kf.errs.mean()}\")"
421    ]
422   },
423   {
424    "cell_type": "code",
425    "execution_count": null,
426    "id": "a73d22ee-707b-44a3-80ab-ad6e671731cf",
427    "metadata": {},
428    "outputs": [],
429    "source": []
430   },
431   {
432    "cell_type": "code",
433    "execution_count": null,
434    "id": "272bfb32-e8e2-49dd-8f90-4b5b09c3a2a2",
435    "metadata": {},
436    "outputs": [],
437    "source": [
438     "print(f\"Spatial Training Elapsed time: {elapsed_time_sp:.4f} seconds\")"
439    ]
440   },
441   {
442    "cell_type": "code",
443    "execution_count": null,
444    "id": "38ab08fb-ac97-45be-8907-6f9cd124243b",
445    "metadata": {},
446    "outputs": [],
447    "source": []
448   }
449  ],
450  "metadata": {
451   "kernelspec": {
452    "display_name": "Python 3 (ipykernel)",
453    "language": "python",
454    "name": "python3"
455   },
456   "language_info": {
457    "codemirror_mode": {
458     "name": "ipython",
459     "version": 3
460    },
461    "file_extension": ".py",
462    "mimetype": "text/x-python",
463    "name": "python",
464    "nbconvert_exporter": "python",
465    "pygments_lexer": "ipython3",
466    "version": "3.12.5"
467   }
468  },
469  "nbformat": 4,
470  "nbformat_minor": 5