5 "execution_count": null,
6 "id": "c7291842-a72d-4c4e-9312-6c0c31df18e0",
10 "# both can change\n",
12 "import numpy as np\n",
13 "import pandas as pd\n",
14 "from MesoPy import Meso\n",
15 "import matplotlib.pyplot as plt\n",
16 "from datetime import datetime, timedelta\n",
18 "import tensorflow as tf\n",
19 "from keras.models import Sequential\n",
20 "from keras.layers import Dense, SimpleRNN\n",
21 "from keras.utils.vis_utils import plot_model\n",
22 "from sklearn.preprocessing import MinMaxScaler\n",
23 "from sklearn.metrics import mean_squared_error\n",
25 "import matplotlib.pyplot as plt\n",
26 "import tensorflow as tf\n",
27 "import keras.backend as K\n",
28 "from keras.utils.vis_utils import plot_model\n",
29 "from scipy.interpolate import LinearNDInterpolator, interpn\n",
30 "from scipy.optimize import root\n",
32 "# Local modules for handling data and running moisture models\n",
33 "import data_funcs as datf\n",
34 "from data_funcs import format_raws, retrieve_raws, format_precip, fixnan\n",
35 "import moisture_models as mod\n",
36 "from moisture_rnn import create_RNN, create_RNN_2, staircase, seq2batches, create_rnn_data, train_rnn, rnn_predict\n",
38 "meso_token=\"4192c18707b848299783d59a9317c6e1\"\n",
44 "execution_count": null,
45 "id": "7d299dea-9c39-4410-a4a5-a7f72d23ba99",
49 "# Calculate mean squared error\n",
51 " return ((a - b)**2).mean()\n",
52 "# Calculate mean absolute error\n",
54 " return ((a - b).__abs__()).mean()"
59 "execution_count": null,
60 "id": "04d3b14a-20e8-4e4e-802f-88404d151991",
64 "def vprint(*args):\n",
66 " for s in args[:(len(args)-1)]:\n",
67 " print(s, end=' ')\n",
72 "cell_type": "markdown",
73 "id": "947f972c-9a02-4550-8d82-1b9cf69d7e9c",
81 "execution_count": null,
82 "id": "d6236755-11e7-4b31-bf50-ffedb6077795",
86 "time_start = \"201806010800\"\n",
87 "hours = 1200 # total simulation time\n",
88 "time_end = datetime.strptime(time_start, \"%Y%m%d%H%M\")+timedelta(hours = hours+1) # end time, plus a buffer to control for time shift\n",
89 "time_end = str(int(time_end.strftime(\"%Y%m%d%H%M\")))\n",
90 "h2 = 300 # training period\n",
91 "train_hrs = np.arange(0, h2) # training time\n",
92 "test_hrs = np.arange(h2, hours) # forecast time\n",
94 "print('Time Parameters:')\n",
96 "print('Time Start:', datetime.strptime(time_start, \"%Y%m%d%H%M\").strftime(\"%Y/%M/%d %H:%M\"))\n",
97 "print('Time End:', datetime.strptime(time_end, \"%Y%m%d%H%M\").strftime(\"%Y/%M/%d %H:%M\"))\n",
98 "print('Total Runtime:', hours, 'hours')\n",
99 "print('Training Time:', h2, 'hours')\n",
104 "cell_type": "markdown",
105 "id": "8320fb68-771e-4441-8849-e5bdec432bd1",
108 "## Retrieve RAWS Data"
113 "execution_count": null,
114 "id": "6dae1750-0656-4369-a114-2ccaa885ff55",
118 "raws_vars='air_temp,relative_humidity,precip_accum,fuel_moisture'"
123 "execution_count": null,
124 "id": "a5d8616e-3f4d-4f56-8e52-f065e8d3d5ae",
128 "station, raws_dat = retrieve_raws(m, \"BKCU1\", raws_vars, time_start, time_end)"
133 "execution_count": null,
134 "id": "0d751525-58c9-4668-9755-f1aaeb34aa40",
138 "def plot_dat(stn, dat, val):\n",
139 " plt.figure(figsize=(16,4))\n",
140 " plt.plot(dat[val],linestyle='-',c='k')\n",
141 " plt.title(stn['STID']+' '+ val)\n",
142 " plt.xlabel('Time (hours)') \n",
148 "execution_count": null,
149 "id": "013a6794-9c56-4a32-8699-15763465544f",
153 "%matplotlib inline\n",
154 "plot_dat(station, raws_dat, 'fm')"
159 "execution_count": null,
160 "id": "ce5e033c-5d16-44ec-9b58-4a55ff76d04d",
164 "print('Data Read:')\n",
166 "print('Station ID:', station['STID'])\n",
167 "print('Lat / Lon:', station['LATITUDE'],', ',station['LONGITUDE'])\n",
168 "if(station['QC_FLAGGED']): print('WARNING: station flagged for QC')\n",
173 "cell_type": "markdown",
174 "id": "b45fcc1f-8394-418f-89ab-0cfbaa04d65f",
177 "## Retrieve RTMA Function\n",
179 "<mark>Not needed?</mark>"
183 "cell_type": "markdown",
187 "% Jonathon changes above create each case as a dictionary, then dictionary of dictionaries, figure out how to store and load dictionaries as a file. json is possible but: cannot contain datetime objects\n",
188 "% look into pickle also compresses while json is plain text clone wrfxpy look how for idioms, pickle added jan/angel lager\n",
189 "% Jan will edit from here below. \n",
190 "% cases will be extracted from dictionary as global variables for now at least"
194 "cell_type": "markdown",
195 "id": "6c42a886-ecff-4379-8a12-db9a77d64045",
198 "## Fit Augmented KF"
203 "execution_count": null,
204 "id": "fda8aa6b-a241-47e3-881f-6e75373f1a2c",
208 "m,Ec = mod.run_augmented_kf(raws_dat['fm'],raws_dat['Ed'],raws_dat['Ew'],raws_dat['rain'],h2,hours) # extract from state"
213 "execution_count": null,
214 "id": "c531fad3-1d6f-4738-a019-f587a7ab7139",
218 "def plot_moisture(hmin,hmax):\n",
219 " print('training from 0 to',h2,'plot from',hmin,'to',hmax)\n",
220 " plt.figure(figsize=(16,4))\n",
221 " plt.plot(range(hmin,hmax),raws_dat['Ed'][hmin:hmax],linestyle='--',c='r',label='Drying Equilibrium (%)')\n",
222 " plt.plot(range(hmin,hmax),raws_dat['Ew'][hmin:hmax],linestyle='--',c='b',label='Wetting Equilibrium (%)')\n",
223 " plt.plot(range(hmin,hmax),Ec[hmin:hmax],linestyle='--',c='g',label='Equilibrium Correction (%)')\n",
224 " plt.plot(range(hmin,hmax),m[hmin:hmax],linestyle='-',c='k',label='filtered')\n",
225 " plt.plot(range(hmin,hmax),raws_dat['fm'][hmin:hmax],linestyle='-',c='b',label='RAWS data (%)')\n",
226 " plt.plot(range(hmin,hmax),raws_dat['rain'][hmin:hmax],linestyle='-',c='b',label='RTMA rain (mm/h)')\n",
228 " plt.plot(m[hmin:h2],linestyle='-',c='k',label='Filtered')\n",
229 " h1 = np.maximum(hmin,h2)\n",
230 " plt.plot(range(h1,hmax),m[h1:hmax],linestyle='-',c='r',label='Forecast (%)')\n",
231 " plt.title(station['STID'] +' Kalman filtering and forecast with augmented state, real data. Training 0:%i hmax' % h2)\n",
232 " plt.xlabel('Time (hours)') \n",
233 " plt.ylabel('Fuel moisture content (%)')\n",
239 "execution_count": null,
240 "id": "4d5388f2-1c21-4b4e-860f-a7ea7c7e2bbc",
244 "plot_moisture(0, hours)"
249 "execution_count": null,
250 "id": "ff9f0f20-b38f-4643-97cd-969914fca2dc",
254 "# Forecast Error\n",
255 "print('Forecast MSE: ' + str(np.round(mse(m[h2:hours], raws_dat['fm'][h2:hours]), 4)))"
259 "cell_type": "markdown",
260 "id": "f41a26c2-4a85-4c7e-b818-a1a2906dfb25",
268 "execution_count": null,
269 "id": "01143521-8222-4e69-9cde-7dc7c7c780e0",
273 "# Set seed for reproducibility\n",
274 "tf.random.set_seed(123)"
279 "execution_count": null,
280 "id": "cff5a394-c6f0-4af1-9890-37bf65ba0e68",
286 "rnn_dat = create_rnn_data(raws_dat, hours, h2, scale)"
291 "execution_count": null,
292 "id": "871821a9-bcd9-47db-9bd6-1933094ac137",
296 "model_predict = train_rnn(\n",
299 " activation=['linear','linear'],\n",
300 " hidden_units=3,\n",
302 " dense_layers=1,\n",
303 " verbose = verbose\n",
309 "execution_count": null,
310 "id": "5dc3ec60-292d-4526-a793-7d466f4ce9c7",
315 "m = rnn_predict(model_predict, rnn_dat, hours)"
320 "execution_count": null,
321 "id": "6ccc15fc-5d08-4df1-a4d5-4f0107171c15",
325 "hour=np.array(range(hours))\n",
326 "title=\"RNN forecast\"\n",
327 "plt.figure(figsize=(16,4))\n",
328 "plt.plot(hour,rnn_dat['Et'][:,0],linestyle='--',c='r',label='E=Equilibrium data')\n",
329 "# print(len(hour),len(m_f))\n",
330 "plt.scatter(hour,raws_dat['fm'],c='b',label='data=10-h fuel data')\n",
331 "if m is not None:\n",
332 " plt.plot(hour[:h2],m[:h2],linestyle='-',c='k',label='m=filtered')\n",
333 " plt.plot(hour[h2:hours],m[h2:hours],linestyle='-',c='r',label='m=forecast')\n",
334 "plt.title(title) \n",
340 "execution_count": null,
341 "id": "1d06f6ee-2c05-4473-956c-ba490cf773d2",
346 "print(mse(m, raws_dat['fm'][0:hours]))\n",
349 "print(mse(m[h2:hours], raws_dat['fm'][h2:hours]))"
354 "execution_count": null,
355 "id": "1e7253c4-0e4c-4076-8f2a-f661e057efd8",
363 "display_name": "Python 3 (ipykernel)",
364 "language": "python",
372 "file_extension": ".py",
373 "mimetype": "text/x-python",
375 "nbconvert_exporter": "python",
376 "pygments_lexer": "ipython3",