├── LICENSE ├── Model ├── README.md └── model.py ├── Notebook ├── ADCP.ipynb └── README ├── README.md ├── deep_learning_experiments ├── functions.py ├── prediction │ ├── ADCP_sensor_2_CNN_prediction.csv │ ├── ADCP_sensor_2_LSTM_prediction.csv │ ├── ADCP_sensor_2_SPATIAL_prediction.csv │ ├── ADCP_sensor_4_CNN_prediction.csv │ ├── ADCP_sensor_4_LSTM_prediction.csv │ └── ADCP_sensor_4_SPATIAL_prediction.csv └── run_deep_learning_experiments.ipynb ├── figs ├── ADCP_Error_heatmap.pdf ├── ADCP_Exact_heatmap.pdf ├── ADCP_Predicted_heatmap.pdf ├── ADCP_sensor_plot_Time_series_sensor_No1.pdf ├── ADCP_sensor_plot_Time_series_sensor_No2.pdf ├── ADCP_sensor_plot_Time_series_sensor_No3.pdf ├── ADCP_sensor_plot_Time_series_sensor_No4.pdf └── README.md ├── machine_learning_experiments ├── amlp │ └── results │ │ └── adcp │ │ ├── ADC.perf │ │ ├── ADCP_Sensor_1.csv │ │ ├── ADCP_Sensor_1.csv.autoai │ │ ├── ADCP_Sensor_1.prediction │ │ ├── ADCP_Sensor_1.test │ │ ├── ADCP_Sensor_1.train │ │ ├── ADCP_Sensor_2.csv │ │ ├── ADCP_Sensor_2.csv.autoai │ │ ├── ADCP_Sensor_2.prediction │ │ ├── ADCP_Sensor_2.test │ │ ├── ADCP_Sensor_2.train │ │ ├── ADCP_Sensor_3.csv │ │ ├── ADCP_Sensor_3.csv.autoai │ │ ├── ADCP_Sensor_3.prediction │ │ ├── ADCP_Sensor_3.test │ │ ├── ADCP_Sensor_3.train │ │ ├── ADCP_Sensor_4.csv │ │ ├── ADCP_Sensor_4.csv.autoai │ │ ├── ADCP_Sensor_4.prediction │ │ ├── ADCP_Sensor_4.test │ │ └── ADCP_Sensor_4.train └── autoAI_experiments │ ├── results │ ├── ErrorMetrics_Lale.csv │ └── adcp │ │ ├── ADCP_Sensor_1_pred.csv │ │ ├── ADCP_Sensor_2_pred.csv │ │ ├── ADCP_Sensor_3_pred.csv │ │ └── ADCP_Sensor_4_pred.csv │ └── run_autoai_experiments.py ├── plots ├── ExploreStatisticalSignificance.R ├── figures │ └── pwc_res2.csv ├── plot_results_timeseries.R └── util_fncs.R └── sensor_data ├── interpolated_data ├── ADCP_Sensor_1.csv ├── ADCP_Sensor_2.csv ├── ADCP_Sensor_3.csv └── ADCP_Sensor_4.csv └── timelagged_data └── adcp ├── ADCP_Sensor_1.csv.autoai ├── ADCP_Sensor_2.csv.autoai ├── ADCP_Sensor_3.csv.autoai └── ADCP_Sensor_4.csv.autoai /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Model/README.md: -------------------------------------------------------------------------------- 1 | ## Model for SPATIAL and data cleaning 2 | -------------------------------------------------------------------------------- /Model/model.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import seaborn as sns 4 | import matplotlib.pyplot as plt 5 | import time 6 | from keras.models import Sequential 7 | from keras.layers import Dense, LSTM, Bidirectional 8 | from keras.layers import Masking 9 | from scipy.interpolate import UnivariateSpline,CubicSpline 10 | output = 'C:/Users/yihao/Dropbox/Research/ADCP/figs/' 11 | #---------------------------data analysis------------------------------------- 12 | # flattern the batch time series data into a m by n matrix 13 | # m= p.shape[1]: number of sensors, n=p.shape[0]*p.shape[2]: time steps 14 | def flattern(p): 15 | pred_y_matrix = [[]for _ in range(len(p[0])) ] 16 | for pp in p: 17 | a = pp.tolist() 18 | for m in range(len(a)): 19 | pred_y_matrix[m] += a[m] 20 | return pred_y_matrix 21 | 22 | 23 | # interpolate the missing values with mask value 24 | def interpolate(data, mask): 25 | temp = [list(dd) for dd in data] 26 | d = [] 27 | for i in range(len(temp)): 28 | for j in range(len(temp[i])): 29 | if temp[i][j] == mask: temp[i][j]= float("NaN") 30 | df = pd.Series(temp[i]).interpolate(method='linear') 31 | d.append(df.tolist()) 32 | return d 33 | 34 | #Continous data split for masked and unmasked data: 35 | def split_train(Int_dat, Norm_dat,T1,T2,T3,Stride, start, end,data_name): 36 | length = len(Int_dat[0]) 37 | s = int(length*start) 38 | e = int(length*end) 39 | Train = [ N[:s] + N[e:] for N in Norm_dat ] 40 | Test = [ M[s:e] for M in Int_dat ] 41 | print('Training Data Length: ', len(Train),'X',len(Train[0])) 42 | print('Test Data Length: ', len(Test), 'X',len(Test[0])) 43 | print('Testing percentage: ',len(Test[0])/(len(Test[0])+len(Train[0]))*100,'%' ) 44 | print('Total data size: ', len(Int_dat), 'X', len(Int_dat[0])) 45 | np.savetxt(data_name + '_train.txt', np.exp(np.array(Train))) 46 | np.savetxt(data_name + '_test.txt', np.exp(np.array(Test))) 47 | train_x, train_y = data_split(Train, T1, T2, T3,Stride) 48 | test_x, test_y = data_split(Test, T1, T2, T3,Stride) 49 | return train_x, train_y, test_x, test_y 50 | 51 | # split data for Multivairate time series (matrix of sensors) 52 | # the data is feed to Bidirectional LSTM model 53 | def data_split(dat, train_hour, test_hour, predict_position, stride): 54 | #train_hour: training data length 55 | #test_hour: testing data length 56 | #predict_position: gap between train_hour and test_hour 57 | x, y = [], [] 58 | period = train_hour + predict_position + test_hour 59 | i = 0 60 | while i + period <= len(dat[0]): 61 | x_temp = [] 62 | y_temp = [] 63 | for j in range(len(dat)): 64 | x_temp.append(dat[j][i:i + train_hour]) 65 | y_temp.append(dat[j][i+ train_hour+ predict_position:i+ train_hour+ predict_position +test_hour]) 66 | x.append(x_temp) 67 | y.append(y_temp) 68 | i += stride 69 | return np.array(x), np.array(y) 70 | 71 | # Data normalization: 72 | # using log function and skip the masked data with -1 73 | # 0 values are replaced by 1e-5 in order to avoid nan value in log 74 | def data_normalize(Dat): 75 | new_dat = [] 76 | for d in Dat: 77 | min, max = np.min(sorted(list(set(d)))[1]), np.max(d) 78 | a = max -min 79 | temp = [] 80 | for val in d: 81 | if val == -1: temp.append(val) 82 | else: 83 | norm =np.log(val) if val!=0 else 1e-5 84 | temp.append(norm ) #temp.append((val - min)/a ) 85 | new_dat.append(temp) 86 | return new_dat 87 | 88 | #---------------------------MAE STD------------------------------------- 89 | def log_mae(py,ty, t,plot_name): 90 | print('predict data size: ',len(py),len(py[0])) 91 | print('exact data size: ', len(ty), len(ty[0])) 92 | mae_lis = [] 93 | std = [] 94 | for i in range(len(py)): 95 | mae = np.exp(np.array(py[i])) - np.exp(np.array(ty[i])) 96 | print('Predicted Data Point size for sensor '+str(i+1)+' ', len(mae)) 97 | mae = np.abs(mae) 98 | mae_lis.append(np.mean(np.abs(mae))) 99 | std.append(np.std(mae)) 100 | return mae_lis, std 101 | 102 | #---------------------------Plot------------------------------------- 103 | def py_ty_plot(data_py, data_ty, s, p,data_name, idx): 104 | l = len(data_py[0]) 105 | x = range(len(data_py[0])) 106 | y = data_py[idx] 107 | xs = np.linspace(0, l, p) 108 | ss = UnivariateSpline(x, y) 109 | ys = ss(xs) 110 | plt.figure() 111 | plt.title('Sensor No: ' + str(idx + 1)) 112 | plt.scatter(range(l),y ,s = s) 113 | plt.plot(xs, ys,label = 'Sp') 114 | y = data_ty[idx] 115 | ss = UnivariateSpline(x, y) 116 | ys = ss(xs) 117 | plt.plot(xs, ys,label = 'Exact') 118 | plt.scatter(range(l),data_ty[idx],s = s) 119 | plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), 120 | ncol=3, fancybox=True, shadow=True) 121 | plt.savefig(output + data_name+'_Time_series_sensor_No'+str(idx)+'.pdf',bbox_inches='tight') 122 | plt.show() 123 | return 124 | 125 | # Heatmap of two matrix 126 | def multi_heatmap(Test_y, Pred_y, t,plot_name): 127 | Test_y = Test_y.reshape(Test_y.shape[0],Test_y.shape[1],Test_y.shape[2]) 128 | Pred_y = Pred_y.reshape(Pred_y.shape[0],Pred_y.shape[1],Pred_y.shape[2]) 129 | py = flattern(Pred_y) 130 | ty = flattern(Test_y) 131 | min, max = np.min(ty), np.max(ty) 132 | #Plot the new heatmap of predict data vs test data 133 | plt.figure() 134 | print(len(py),len(ty)) 135 | ax1 = sns.heatmap(np.array(ty).T,vmin = min, vmax = max) 136 | ax1.set_title('Exact Data') 137 | ax1.set(xlabel='Sensors', ylabel='Time Step') 138 | f1 = ax1.get_figure() 139 | f1.savefig(output + str(plot_name) + '_Exact_heatmap.pdf',bbox_inches='tight') 140 | plt.show() 141 | plt.figure() 142 | ax2 = sns.heatmap(np.array(py).T,vmin = min, vmax = max) 143 | ax2.set_title('Predicted Data') 144 | ax2.set(xlabel='Sensors', ylabel='Time Step') 145 | f2 = ax2.get_figure() 146 | f2.savefig(output + str(plot_name) + '_Predicted_heatmap.pdf',bbox_inches='tight') 147 | plt.show() 148 | plt.figure() 149 | error = np.array(py).T - np.array(ty).T 150 | print('error shape: ', error.shape) 151 | ax3 = sns.heatmap(error,vmin = min, vmax = max) 152 | ax3.set_title('Error Map') 153 | ax3.set(xlabel='Sensors', ylabel='Time Step') 154 | f3 = ax3.get_figure() 155 | f3.savefig(output + str(plot_name) + '_Error_heatmap.pdf',bbox_inches='tight') 156 | plt.show() 157 | #return the mae and std after plot 158 | MAE_lis, STD_lis = log_mae(py,ty, t,plot_name) 159 | return MAE_lis, STD_lis 160 | 161 | #---------------------------Model------------------------------------- 162 | # Bidirectional LSTM model 163 | def stacked_LSTM(X, Y): 164 | time_step = X.shape[1] 165 | input_dim = X.shape[2] 166 | out = Y.shape[2] 167 | #Bidirectional LSTM 168 | start = time.time() 169 | model = Sequential() 170 | model.add(Masking(mask_value=-1.,input_shape=(time_step, input_dim))) 171 | model.add(Bidirectional(LSTM(32,activation='elu', input_shape=(time_step, input_dim),return_sequences=True))) 172 | #model.add(Bidirectional(LSTM(64, activation='elu', input_shape=(time_step, input_dim), return_sequences=True))) 173 | #model.add(Masking(mask_value=-1.,input_shape=(time_step, input_dim))) 174 | model.add(Dense(out)) 175 | model.compile(loss='mean_absolute_error', optimizer='adam') 176 | hist = model.fit(X, Y,epochs=100, validation_split=.2, 177 | verbose=0, batch_size=10) 178 | model.summary() 179 | end = time.time() 180 | print("Total compile time: --------", end - start, 's') 181 | return model, hist 182 | 183 | def SP_Learner(data, train_time, predict_time, predict_position,Stride, start, end, data_name): 184 | print('########################Start##################################') 185 | norm_dat = data_normalize(data) #normalized data (used for training) 186 | norm_int_dat = interpolate(norm_dat,-1) #normalized interpolated data (used for prediction) 187 | #-----------------------------------plot------------------------------------------- 188 | f1 = sns.heatmap(norm_dat) 189 | f1.set_title(data_name + ' Masked Data') 190 | plt.figure() 191 | plt.show() 192 | f2 = sns.heatmap(norm_int_dat) 193 | f2.set_title(data_name + ' Interpolated Data') 194 | plt.figure() 195 | plt.show() 196 | # -----------------------------------end plot------------------------------------------- 197 | # split the data set 198 | train_x, train_y, test_x, test_y = split_train(norm_int_dat, norm_dat, train_time, predict_time,predict_position, Stride,start, end, data_name) 199 | print('Train data size(batch, row, column)','Train X: ', train_x.shape,' ,Train Y: ',train_y.shape) 200 | print('test data size(batch, row, column)','Test X: ',test_x.shape,' ,Test Y: ',test_y.shape) 201 | # model training 202 | model, hist = stacked_LSTM(train_x,train_y) 203 | pred_y = model.predict(test_x, verbose=1) 204 | error, std = multi_heatmap(test_y, pred_y,predict_time,data_name) 205 | py = flattern(pred_y) 206 | ty = flattern(test_y) 207 | plt.figure() 208 | for j in range(len(ty)): 209 | plt.scatter(range(len(ty[j])),[ty[j][i]-py[j][i] for i in range(len(ty[j]))]) 210 | plt.title(data_name + ' Test Errors') 211 | print('MAE: ', np.mean(error), 'STD: ',np.mean(std)) 212 | print('########################End##################################') 213 | return py, ty, error, std, model 214 | -------------------------------------------------------------------------------- /Notebook/README: -------------------------------------------------------------------------------- 1 | ## Jupyter Notebook for ADCP data predictiong using SPATIAL 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spatial-lstm 2 | Repo related to our Ecological Informatics paper [A spatio-temporal LSTM model to forecast across multiple temporal and spatial scales](https://www.sciencedirect.com/science/article/pii/S1574954122001376?casa_token=Sgd5WcZLtu8AAAAA:4h_h0x_vQhmVDccgCSlWDt6MSnqInCHLsliH4iesdLJczCrK5GqpXfO4u2I15gOTiPKerYQCNtc). 3 | Contact details: 4 | - Fearghal O'Donncha (feardonn@ie.ibm.com) 5 | - Yihao Hu () 6 | 7 | This repo includes three subdirectories 8 | - `sensor_data` sensor or observation data used in the study. For data ownership reasons we could only make ADCP data publicly available. Repo is structured to implement all experiments on that dataset. For those interested in a more detailed exploration of the work, please contact the authors to get access to temperature and oxygen data used in study 9 | - `machine_learning_experiments` - scripts to run two different machine learning experiments on the data. We use two popular AutoAI frameworks to generate the two implementations, namely [Lale](https://github.com/iBM/lale) and [AutoMLPipeline or AMLP](https://github.com/IBM/AutoMLPipeline.jl). 10 | - `deep_learning_experiments` scripts to run deep learning experinments used in the paper, namely CNN, LSTM, and bidirectional LSTM model that we term SPATIAL 11 | - `plots` R scripts to visualise and statistically analyse model results 12 | ======= 13 | -------------------------------------------------------------------------------- /deep_learning_experiments/functions.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import seaborn as sns 4 | import matplotlib.pyplot as plt 5 | import time 6 | from keras import callbacks 7 | from keras.models import Sequential 8 | from keras.layers import Dense, LSTM, Bidirectional, Conv1D, Conv2D, Flatten, MaxPooling1D, MaxPooling2D, Masking, AveragePooling2D 9 | import random 10 | from scipy.interpolate import UnivariateSpline,CubicSpline 11 | output = './figs/' 12 | #---------------------------data analysis------------------------------------- 13 | #convert minute data into hourly/daily data by mean 14 | def convert_time(s, period): 15 | p = 0 16 | if period == 'hour': p = 60 17 | elif period == 'day': p = 60*24 18 | impute_data = [] 19 | i = 0 20 | while i > ( XGB | RFR ) 96 | trainable_pipe = Hyperopt(estimator=planned_pipe, cv=3, max_evals=100, scoring='neg_mean_squared_error') 97 | trained = trainable_pipe.fit(X_train, y_train) 98 | print(trained.summary().loss.sort_values().head()) 99 | best_found = trained.get_pipeline() 100 | pred = trained.predict(X_test) 101 | print(f'The RMSE of trained pipeline on train set is: {np.sqrt(mse(trained.predict(X_train), y_train))}') 102 | print(f'The RMSE of trained pipeline on test set is: {np.sqrt(mse(pred, y_test))}') 103 | ### 104 | # 1) Save test and predict data to file 105 | # 2) Save Mae stats to single file 106 | df_result = pd.DataFrame({"year" : year_test_, 107 | "month": month_test_, 108 | "day": X_test['day'], 109 | "hour": X_test['hour'], 110 | "output_res": y_test, 111 | "output": test_data_raw_, 112 | "prediction": pred}) 113 | fname_split = f.split('/')[-1].split('.')[0] # drop the .csv.autoai 114 | fname_out = fname_split + '_pred.csv' 115 | fname_out = path_to_results / subd / fname_out 116 | df_result.to_csv(fname_out, index=False) 117 | f_results.write("{},{},{},{}\n".format(fname_split, 118 | mse(pred, y_test), 119 | mae(pred, y_test), 120 | np.sqrt(mse(pred, y_test)))) 121 | print(trained.get_pipeline().pretty_print(show_imports=True, ipython_display=False)) 122 | trained.get_pipeline().pretty_print(ipython_display=True, show_imports=True) 123 | 124 | f_results.close() 125 | -------------------------------------------------------------------------------- /plots/ExploreStatisticalSignificance.R: -------------------------------------------------------------------------------- 1 | ### Process the SPATIAL experiments into same format as Lale/AMLP 2 | library(here) 3 | library(tidyverse) 4 | library(ggpubr) 5 | library(rstatix) 6 | library("Hmisc") 7 | library(GGally) 8 | this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works. 9 | setwd(this.dir) 10 | print(getwd()) 11 | source('./util_fncs.R') 12 | 13 | init_pwc_write = TRUE 14 | create_grid_plot = FALSE 15 | 16 | results_dir = './figures/' 17 | 18 | ## List the pertinent directories that store data, spatial results, amlp results, lale results... 19 | # input data 20 | raw_data_dir = '../sensor_data/interpolated_data/' 21 | ## Spatial data dir 22 | dl_dir = '../deep_learning_experiments/prediction/' 23 | # Lale data dire 24 | lale_dir = '../machine_learning_experiments//autoAI_experiments//results/' 25 | # AMLP dir 26 | amlp_dir = '../machine_learning_experiments/amlp/results/' 27 | 28 | ## Load the raw and SPATIAL results. 29 | ### Files we use are (from Yihao) 30 | sensors_to_use <- list(c(9), c(9), c(4)) # for temperature, oxy, and adcp respectively 31 | sensor_stem_list <- c('Temp_Sensor_', 'Oxygen_Sensor_', 'ADCP_Sensor_') 32 | spat_stem_list <- c('Diff_Temp_aqme_proc-mcnuttsisland_cage-19-', 33 | 'Diff_dissolved_oxygen_aqme_proc-mcnuttsisland_cage-19-', 34 | 'Diff_ADCP_sensor') 35 | 36 | lale_sensor_dir = c('temperature/', 'oxygen/', 'adcp/') 37 | amlp_sensor_dir = c('temp/', 'oxygen/', 'adcp/') 38 | 39 | 40 | for (sens_type in seq(3, 3)){ # We just focus 41 | if (sens_type == 3){ 42 | ADCP = TRUE 43 | } else { 44 | ADCP = FALSE 45 | } 46 | sensor_stem <- sensor_stem_list[sens_type] 47 | sens_extract = unlist(sensors_to_use[sens_type]) 48 | # 1) raw data files 49 | raw_data_fname <- paste(paste(sensor_stem_list[sens_type], 50 | sens_extract, sep=''), '.csv', sep = '') 51 | # 2) spatial data files 52 | spatial_fname <- paste(paste(sensor_stem_list[sens_type], 53 | sens_extract, sep=''), '_SPATIAL_prediction.csv', sep = '') 54 | # 3) Lale data files 55 | lale_fname <- paste(paste(sensor_stem_list[sens_type], 56 | sens_extract, sep = ''), '_pred.csv', sep='') 57 | # 4) AMLP data files 58 | amlp_fname <- paste(paste(sensor_stem_list[sens_type], 59 | sens_extract, sep = ''), '.prediction', sep='') 60 | 61 | # 5) CNN data files 62 | cnn_fname <- paste(paste(sensor_stem_list[sens_type], 63 | sens_extract, sep=''), '_CNN_prediction.csv', sep = '') 64 | 65 | # 6) LSTM data files 66 | lstm_fname <- paste(paste(sensor_stem_list[sens_type], 67 | sens_extract, sep=''), '_LSTM_prediction.csv', sep = '') 68 | 69 | 70 | 71 | for (id_loop in seq(1, length(sens_extract))){ 72 | sens_id <- sens_extract[id_loop] 73 | sens_id <- sens_extract[id_loop] 74 | sensor_fname = here(getwd(), raw_data_dir, raw_data_fname[id_loop]) 75 | residual_fname = here(getwd(), lale_dir, lale_sensor_dir[sens_type], lale_fname[id_loop]) 76 | amlp_fname_ = here(getwd(), amlp_dir, amlp_sensor_dir[sens_type], amlp_fname[id_loop]) 77 | spat_fname_ = here(getwd(), dl_dir, spatial_fname[id_loop]) 78 | print(sensor_fname) 79 | print(residual_fname) 80 | if (sens_type == 3){ADCP_FLAG=TRUE} 81 | list_df = reconstruct_residual(sensor_fname, residual_fname, ADCP=ADCP_FLAG) 82 | list_df_amlp = reconstruct_residual_amlp(sensor_fname, amlp_fname_, ADCP=ADCP_FLAG) 83 | list_df_spat = reconstruct_residual_spat(sensor_fname, spat_fname_, ADCP=ADCP_FLAG) 84 | 85 | df_sensor = list_df[['df_sensor']] 86 | df_lale = list_df[['df_model']] 87 | df_amlp = list_df_amlp[['df_model']] 88 | df_spat = list_df_spat[['df_model']] 89 | if (sens_type == 1){ ## filter out crazy high value for temp 90 | df_lale$reconstruct_signal[df_lale$reconstruct_signal>8] = NA 91 | df_lale$output[df_lale$output>8] = NA 92 | df_amlp$reconstruct_signal[df_amlp$reconstruct_signal>8] = NA 93 | df_amlp$output[df_amlp$output>8] = NA 94 | df_spat$reconstruct_signal[df_spat$reconstruct_signal>8] = NA 95 | df_spat$output[df_spat$output>8] = NA 96 | } 97 | 98 | if (sens_type == 1){ ##and crazy low values 99 | lim_b <- 4.5 100 | date_beg_lale = as.POSIXct("2018-12-05","%Y-%m-%d", tz = "UTC") 101 | df_spat <- df_spat %>% filter((date < date_beg_lale & 102 | reconstruct_signal>lim_b) 103 | | date > date_beg_lale) 104 | 105 | } 106 | 107 | df <- combine_all_forecasts(df_lale, df_spat, df_amlp) 108 | df_model <- select(df, date, observation, AutoAI, SPATIAL, AMLP) 109 | gdf <- df_model %>% 110 | gather(key = "dataset", value = "value", observation, AutoAI, SPATIAL, AMLP) %>% 111 | convert_as_factor(date, dataset) 112 | 113 | bxp <- ggboxplot(gdf, x = "dataset", y = "value", xlab = FALSE, 114 | order = c("observation", "SPATIAL", "AutoAI", "AMLP"), 115 | color = "dataset", error.plot = "errorbar") + 116 | theme(panel.grid = element_blank(), 117 | panel.background = element_blank(), 118 | panel.border = element_rect(colour = "black", fill=NA, size=1), 119 | axis.ticks.x = element_blank(), 120 | axis.text.x = element_blank()) 121 | 122 | data_rcorr <-as.matrix(df_model[, 2:5]) 123 | 124 | ### Now let's save our figure objects for further formatting 125 | if (sens_type == 1){ 126 | bxp_temp <- bxp 127 | r_temp <- rcorr(data_rcorr) 128 | } 129 | 130 | if (sens_type == 2){ 131 | bxp_do <- bxp 132 | r_do <- rcorr(data_rcorr) 133 | 134 | } 135 | 136 | if (sens_type == 3){ 137 | bxp_adcp <- bxp + labs(y = 'Speed (cm/s)') + 138 | ylim(c(0,20)) 139 | r_adcp <- rcorr(data_rcorr) 140 | 141 | } 142 | 143 | 144 | # pairwise comparisons 145 | pwc <- gdf %>% 146 | t_test(value ~ dataset, paired = TRUE) %>% 147 | add_significance() 148 | pwc$sensor <-paste(sensor_stem, sens_id, sep = '') 149 | 150 | effect_size <- gdf %>% cohens_d(value ~ dataset, paired = TRUE) 151 | pwc$effsize = effect_size$effsize 152 | pwc$magnitude = effect_size$magnitude 153 | 154 | if (init_pwc_write){ 155 | init_pwc_write=FALSE 156 | write.table(pwc, here(getwd(), results_dir, 'pwc_res2.csv'), 157 | append = FALSE, 158 | sep = ",", 159 | col.names = TRUE, 160 | row.names = FALSE, 161 | quote = FALSE) 162 | } else { 163 | write.table(pwc, here(getwd(), results_dir, 'pwc_res2.csv'), 164 | append = TRUE, 165 | sep = ",", 166 | col.names = FALSE, 167 | row.names = FALSE, 168 | quote = FALSE) 169 | } 170 | } 171 | 172 | } 173 | 174 | if (create_grid_plot){ 175 | g = ggarrange(bxp_temp + labs(y= expression('Temperature ('*~degree*C*')')) , 176 | bxp_do + labs(y = 'DO (mg/L)'), 177 | bxp_adcp + labs(y = 'Speed (cm/s)') + 178 | ylim(c(0,20)), 179 | nrow = 1, ncol=3, common.legend = T) 180 | 181 | ggsave(here(getwd(), results_dir, 'boxplot_all.png') ,g, height=4.8, width=6.4) 182 | 183 | } 184 | 185 | 186 | 187 | 188 | ndays <- 7 # number of days to include for analysis 189 | df_model <- df_model[1:(48*ndays),] 190 | 191 | gdf <- df_model %>% 192 | gather(key = "variable", value = "value", observation, AutoAI, SPATIAL, AMLP) %>% 193 | convert_as_factor(date, variable) 194 | head(gdf, 3) 195 | 196 | gdf %>% 197 | group_by(date) %>% 198 | get_summary_stats(value, type = "mean_sd") 199 | 200 | 201 | gdf %>% 202 | group_by(variable) %>% 203 | identify_outliers(value) 204 | 205 | 206 | 207 | # pairwise comparisons 208 | pwc <- gdf %>% 209 | t_test(value ~ variable, paired = TRUE) %>% 210 | add_significance() 211 | 212 | 213 | #pwc_select <- pwc[pwc$group1=='observation' | pwc$group2=='observation',] 214 | pwc$sensor <-paste(sensor_stem, sens_id, sep = '') 215 | 216 | if (init_pwc_write){ 217 | init_pwc_write=FALSE 218 | write.table(pwc, here(getwd(), results_dir, 'pwc_res2.csv'), 219 | append = FALSE, 220 | sep = ",", 221 | col.names = TRUE, 222 | row.names = FALSE, 223 | quote = FALSE) 224 | } else { 225 | write.table(pwc, here(getwd(), results_dir, 'pwc_res2.csv'), 226 | append = TRUE, 227 | sep = ",", 228 | col.names = FALSE, 229 | row.names = FALSE, 230 | quote = FALSE) 231 | } 232 | 233 | 234 | -------------------------------------------------------------------------------- /plots/figures/pwc_res2.csv: -------------------------------------------------------------------------------- 1 | .y.,group1,group2,n1,n2,statistic,df,p,p.adj,p.adj.signif,sensor,effsize,magnitude 2 | value,AMLP,AutoAI,3346,3346,-8.79821549006776,3345,2.19e-18,4.38e-18,****,ADCP_Sensor_4,-0.152100844863758,negligible 3 | value,AMLP,observation,3346,3346,4.10740748688907,3345,4.1e-05,4.1e-05,****,ADCP_Sensor_4,0.0710075980363084,negligible 4 | value,AMLP,SPATIAL,3346,3346,-40.8749920196494,3345,1.31e-296,7.86e-296,****,ADCP_Sensor_4,-0.706634297262498,moderate 5 | value,AutoAI,observation,3346,3346,11.1866678752689,3345,1.51e-28,4.53e-28,****,ADCP_Sensor_4,0.193391675500501,negligible 6 | value,AutoAI,SPATIAL,3346,3346,-34.5660250803077,3345,3.86e-224,1.93e-223,****,ADCP_Sensor_4,-0.597566816160828,moderate 7 | value,observation,SPATIAL,3346,3346,-29.683149767159,3345,4.46e-172,1.78e-171,****,ADCP_Sensor_4,-0.51315316871917,moderate 8 | value,AMLP,AutoAI,336,336,0.609773086256435,335,0.542,0.542,ns,ADCP_Sensor_4 9 | value,AMLP,observation,336,336,4.87382216607871,335,1.69e-06,3.38e-06,****,ADCP_Sensor_4 10 | value,AMLP,SPATIAL,336,336,-12.5040255600923,335,1.05e-29,5.25e-29,****,ADCP_Sensor_4 11 | value,AutoAI,observation,336,336,6.41976896527158,335,4.67e-10,1.4e-09,****,ADCP_Sensor_4 12 | value,AutoAI,SPATIAL,336,336,-13.2533354480043,335,1.59e-32,9.54e-32,****,ADCP_Sensor_4 13 | value,observation,SPATIAL,336,336,-10.4130086327733,335,3.49e-22,1.4e-21,****,ADCP_Sensor_4 14 | -------------------------------------------------------------------------------- /plots/plot_results_timeseries.R: -------------------------------------------------------------------------------- 1 | ### Process the SPATIAL experiments into same format as Lale/AMLP 2 | library(here) 3 | library(tidyverse) 4 | library(ggpubr) 5 | library(rstatix) 6 | library(dplyr) 7 | library(gridExtra) 8 | library(scales) 9 | this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works. 10 | 11 | setwd(this.dir) 12 | print(getwd()) 13 | source('./util_fncs.R') 14 | mae_all = c() 15 | 16 | create_grid_plot = FALSE 17 | 18 | results_dir = './figures/' 19 | fout = paste(results_dir, 'MAE_all_models_normalised.csv', sep = "") 20 | fout_mae = paste(results_dir, 'MAE_each_station.csv', sep = "") 21 | fout_mape = paste(results_dir, 'MAPE_each_station.csv', sep = "") 22 | 23 | ## List the pertinent directories that store data, for SPATIAL 24 | ## results, amlp results, and lale results... 25 | # input data (observation data) 26 | raw_data_dir = '../sensor_data/interpolated_data/' 27 | ## Spatial data dir 28 | dl_dir = '../deep_learning_experiments/prediction/' 29 | # Lale data dire 30 | lale_dir = '../machine_learning_experiments//autoAI_experiments//results/' 31 | # AMLP dir 32 | amlp_dir = '../machine_learning_experiments/amlp/results/' 33 | 34 | ## Load the raw and SPATIAL results. 35 | ### Files we use for visualisation (for temperature and oxygen 1--9, for ADCP 1-4) 36 | sensors_to_use <- list(c(1,8,9), c(1,8,9), c(2,4)) # for temperature, oxy, and adcp respectively 37 | sensors_to_use <- list(c(9), c(9), c(4)) # for temperature, oxy, and adcp respectively 38 | 39 | write_stats = TRUE 40 | if (length(unlist(sensors_to_use[1])) == 1){ 41 | write_stats = FALSE # We use this just to make plots 42 | } 43 | # data file stem names for the 3 44 | sensor_stem_list <- c('Temp_Sensor_', 'Oxygen_Sensor_', 'ADCP_Sensor_') 45 | 46 | 47 | # Different subdirectory details 48 | lale_sensor_dir = c('temperature/', 'oxygen/', 'adcp/') 49 | amlp_sensor_dir = c('temp/', 'oxygen/', 'adcp/') 50 | 51 | # Some simple annotation details for plotting 52 | yax_labs <- c(expression('Temperature ('*~degree*C*')'), 'DO (mg/L)', 'Speed (cm/s)') 53 | annotate_xlox <- c('2018-12-15', '2018-12-15', '2019-11-01') 54 | annotate_yloc <- list(c(7.75, 7.25, 6.75), c(7.75, 7.25, 6.75), c(45, 40, 35)) 55 | 56 | lims_arr <- list(c("2018-11-27","2018-12-11"), 57 | c("2018-11-27","2018-12-11"), 58 | c("2019-10-22","2019-11-06")) 59 | 60 | lims_arr <- list(c("2018-11-27","2018-12-11"), 61 | c("2018-11-27","2018-12-11"), 62 | c("2019-12-10","2019-12-30")) 63 | 64 | ## We want to read both the Lale and raw data and recreate the true signal 65 | ## from residual forecast (Lale) 66 | ## Basic function is of form 67 | ## y_reconstruct = y_sens(t-48) + y_res(t) 68 | #1) Read the raw and Lale data 69 | 70 | for (sens_type in seq(3,3)){ #3) ){ # itereate across temperature, oxygen, and ADCP 71 | mae_lale = c(); mape_lale = c() 72 | mae_amlp = c(); mape_amlp = c() 73 | mae_spatial = c(); mape_spatial =c() 74 | mae_cnn = c(); mape_cnn =c() 75 | mae_lstm = c(); mape_lstm =c() 76 | 77 | id_loop <- 1 78 | sens_extract = unlist(sensors_to_use[sens_type]) # IDs of which sensors to use for each of temp, oxy, adcp 79 | sensor_stem = sensor_stem_list[sens_type] 80 | raw_data_fname <- paste(paste(sensor_stem_list[sens_type], 81 | sens_extract, sep=''), '.csv', sep = '') 82 | # 2) spatial data files 83 | spatial_fname <- paste(paste(sensor_stem_list[sens_type], 84 | sens_extract, sep=''), '_SPATIAL_prediction.csv', sep = '') 85 | # 3) Lale data files 86 | lale_fname <- paste(paste(sensor_stem_list[sens_type], 87 | sens_extract, sep = ''), '_pred.csv', sep='') 88 | # 4) AMLP data files 89 | amlp_fname <- paste(paste(sensor_stem_list[sens_type], 90 | sens_extract, sep = ''), '.prediction', sep='') 91 | amlp_fname_test <- paste(paste(sensor_stem_list[sens_type], 92 | sens_extract, sep = ''), '.test', sep='') 93 | 94 | # 5) CNN data files 95 | cnn_fname <- paste(paste(sensor_stem_list[sens_type], 96 | sens_extract, sep=''), '_CNN_prediction.csv', sep = '') 97 | 98 | # 6) LSTM data files 99 | lstm_fname <- paste(paste(sensor_stem_list[sens_type], 100 | sens_extract, sep=''), '_LSTM_prediction.csv', sep = '') 101 | 102 | 103 | ADCP_FLAG = FALSE # We need to treat ADCP slightly differently 104 | for (id_loop in seq(1, length(sens_extract))) # we generally select across 3 sensors for each dataset. 105 | { # The exact ID is defined above 106 | sensor_fname = here(getwd(), raw_data_dir, raw_data_fname[id_loop]) 107 | residual_fname = here(getwd(),lale_dir, lale_sensor_dir[sens_type], lale_fname[id_loop]) 108 | amlp_fname_ = here(getwd(),amlp_dir, amlp_sensor_dir[sens_type], amlp_fname[id_loop]) 109 | spat_fname_ = here(getwd(),dl_dir, spatial_fname[id_loop]) 110 | cnn_fname_ = here(getwd(),dl_dir, cnn_fname[id_loop]) 111 | lstm_fname_ = here(getwd(),dl_dir, lstm_fname[id_loop]) 112 | print(sensor_fname) 113 | print(residual_fname) 114 | if (sens_type == 3){ADCP_FLAG=TRUE} 115 | list_df = reconstruct_residual(sensor_fname, residual_fname, ADCP=ADCP_FLAG) 116 | list_df_amlp = reconstruct_residual_amlp(sensor_fname, amlp_fname_, ADCP=ADCP_FLAG) 117 | list_df_spat = reconstruct_residual_spat(sensor_fname, spat_fname_, ADCP=ADCP_FLAG) 118 | list_df_cnn = reconstruct_residual_spat(sensor_fname, cnn_fname_, ADCP=ADCP_FLAG) 119 | list_df_lstm = reconstruct_residual_spat(sensor_fname, lstm_fname_, ADCP=ADCP_FLAG) 120 | 121 | df_sensor = list_df[['df_sensor']] 122 | df_lale = list_df[['df_model']] 123 | df_amlp = list_df_amlp[['df_model']] 124 | df_spat = list_df_spat[['df_model']] 125 | df_cnn = list_df_cnn[['df_model']] 126 | df_lstm = list_df_lstm[['df_model']] 127 | if (sens_type == 1){ ## filter out crazy high value for temp 128 | df_lale$reconstruct_signal[df_lale$reconstruct_signal>8] = NA 129 | df_lale$output[df_lale$output>8] = NA 130 | df_amlp$reconstruct_signal[df_amlp$reconstruct_signal>8] = NA 131 | df_amlp$output[df_amlp$output>8] = NA 132 | df_spat$reconstruct_signal[df_spat$reconstruct_signal>8] = NA 133 | df_spat$output[df_spat$output>8] = NA 134 | df_cnn$reconstruct_signal[df_cnn$reconstruct_signal>8] = NA 135 | df_cnn$output[df_cnn$output>8] = NA 136 | df_lstm$reconstruct_signal[df_lstm$reconstruct_signal>8] = NA 137 | df_lstm$output[df_lstm$output>8] = NA 138 | } 139 | 140 | if (sens_type == 1){ ##and crazy low values 141 | lim_b <- 4.5 142 | date_beg_lale = as.POSIXct("2018-12-05","%Y-%m-%d", tz = "UTC") 143 | df_spat <- df_spat %>% filter((date < date_beg_lale & 144 | reconstruct_signal>lim_b) 145 | | date > date_beg_lale) 146 | df_cnn <- df_cnn %>% filter((date < date_beg_lale & 147 | reconstruct_signal>lim_b) 148 | | date > date_beg_lale) 149 | df_lstm <- df_lstm %>% filter((date < date_beg_lale & 150 | reconstruct_signal>lim_b) 151 | | date > date_beg_lale) 152 | 153 | } 154 | if (sens_type == 3){ ##and crazy low values 155 | lim_b <-23 156 | date_beg_lale = as.POSIXct("2019-12-10","%Y-%m-%d", tz = "UTC") 157 | df_spat <- df_spat %>% filter((date < date_beg_lale & 158 | reconstruct_signal>lim_b) 159 | | date > date_beg_lale) 160 | 161 | } 162 | ylab <- expression('Temperature ('*~degree*C*')') 163 | ylab <- yax_labs[sens_type] 164 | 165 | p_ts_total <- ggplot(data=df_lale,aes(x=as.POSIXct(date),y=output, color = 'sensor')) + 166 | geom_point(size = 0.5) + 167 | geom_line(data=df_lale, aes(x = as.POSIXct(date), y = reconstruct_signal ,color = 'AutoAI') ) + 168 | geom_line(data=df_amlp, aes(x = as.POSIXct(date), y = reconstruct_signal ,color = 'AMLP') ) + 169 | 170 | geom_line(data=df_cnn, aes(x = as.POSIXct(date), y = reconstruct_signal ,color = 'CNN') ) + 171 | geom_line(data=df_lstm, aes(x = as.POSIXct(date), y = reconstruct_signal ,color = 'LSTM') ) + 172 | geom_line(data=df_spat, aes(x = as.POSIXct(date), y = reconstruct_signal ,color = 'SPATIAL') ) + 173 | 174 | labs(x = "", 175 | y = ylab, 176 | 'colour' = "") 177 | # unify the color legend 178 | p_ts_total <- p_ts_total + scale_colour_manual(values=c(sensor = "black", 179 | AutoAI = "#ff6e54", 180 | AMLP="#ffa600", 181 | CNN="#444e86", 182 | LSTM="#955196", 183 | SPATIAL="#488f31")) 184 | 185 | 186 | lims <- as.POSIXct(strptime(unlist(lims_arr[sens_type]), format = "%Y-%m-%d")) 187 | # p_ts_total <- p_ts_total + scale_x_datetime(limits = lims, labels=date_format("%d-%m-%Y")) 188 | # p_ts_res <- p_ts_res + scale_x_datetime(limits = lims, labels=date_format("%d-%m-%Y")) 189 | 190 | sens_id <- sens_extract[id_loop] 191 | fname_ts_t = paste(paste(paste('TimeSeries_total', sensor_stem, sep = ''), sens_id, sep = ''), '.png', sep='') 192 | fname_ts_r = paste(paste(paste('TimeSeries_residual', sensor_stem, sep = ''), sens_id, sep = ''), '.png', sep='') 193 | fname_ts_res_scat = paste(paste(paste('Residual_scatter', sensor_stem, sep = ''), sens_id, sep = ''), '.png', sep='') 194 | 195 | # p_ts_total <- p_ts_total + annotate(geom="text",as.POSIXct(strptime(annotate_xlox[sens_type], "%Y-%m-%d" )), 196 | # y=unlist(annotate_yloc[sens_type])[1],label=paste("SPATIAL MAE = ",round(mae_spatial_, digits = 2)),fontface="bold") 197 | # p_ts_total <- p_ts_total + annotate(geom="text",as.POSIXct(strptime(annotate_xlox[sens_type], "%Y-%m-%d" )), 198 | # y=unlist(annotate_yloc[sens_type])[2],label=paste("LALE MAE = ",round(mae_lale_, digits = 2)),fontface="bold") 199 | # p_ts_total <- p_ts_total + annotate(geom="text",as.POSIXct(strptime(annotate_xlox[sens_type], "%Y-%m-%d" )), 200 | # y=unlist(annotate_yloc[sens_type])[3],label=paste("AMLP MAE = ",round(mae_amlp_, digits = 2)),fontface="bold") 201 | # 202 | 203 | mae_lale = c(mae_lale, mean(abs(df_lale$output - df_lale$reconstruct_signal),na.rm=TRUE)) 204 | mae_amlp = c(mae_amlp, mean(abs(df_lale$output - df_amlp$reconstruct_signal),na.rm=TRUE)) 205 | mae_spatial = c(mae_spatial, mean(abs(df_spat$output - df_spat$reconstruct_signal),na.rm=TRUE)) 206 | mae_cnn = c(mae_cnn, mean(abs(df_cnn$output - df_cnn$reconstruct_signal),na.rm=TRUE)) 207 | mae_lstm = c(mae_lstm, mean(abs(df_lale$output - df_lale$reconstruct_signal),na.rm=TRUE)) 208 | 209 | mape_lale = c(mape_lale, mean(abs( (df_lale$output - df_lale$reconstruct_signal)/df_lale$output*100), na.rm=TRUE)) 210 | mape_amlp = c(mape_amlp, mean(abs( (df_amlp$output - df_amlp$reconstruct_signal)/df_amlp$output*100), na.rm=TRUE)) 211 | mape_spatial = c(mape_spatial, mean(abs( (df_spat$output - df_spat$reconstruct_signal)/df_spat$output*100),na.rm=TRUE)) 212 | mape_cnn = c(mape_cnn, mean(abs( (df_cnn$output - df_cnn$reconstruct_signal)/df_cnn$output*100),na.rm=TRUE)) 213 | mape_lstm = c(mape_lstm, mean(abs( (df_lstm$output - df_lstm$reconstruct_signal)/df_lstm$output*100),na.rm=TRUE)) 214 | 215 | 216 | ggsave(here(getwd(),results_dir, fname_ts_t),p_ts_total) 217 | 218 | } # end the loop over similar sensors 219 | if (write_stats){ # check whether to write stats 220 | 221 | mae_all_lale <- cbind( mean(mae_lale,na.rm=TRUE), 222 | sd(mae_lale,na.rm=TRUE), 223 | mean(mape_lale,na.rm=TRUE)) 224 | mae_all_amlp <- cbind( mean(mae_amlp,na.rm=TRUE), 225 | sd(mae_amlp,na.rm=TRUE), 226 | mean(mape_amlp,na.rm=TRUE)) 227 | mae_all_spat <- cbind( mean(mae_spatial,na.rm=TRUE), 228 | sd(mae_spatial,na.rm=TRUE), 229 | mean(mape_spatial,na.rm=TRUE)) 230 | mae_all_cnn <- cbind( mean(mae_cnn,na.rm=TRUE), 231 | sd(mae_cnn,na.rm=TRUE), 232 | mean(mape_cnn,na.rm=TRUE)) 233 | mae_all_lstm <- cbind( mean(mae_lstm,na.rm=TRUE), 234 | sd(mae_lstm,na.rm=TRUE), 235 | mean(mape_lstm,na.rm=TRUE)) 236 | 237 | 238 | if (sens_type == 1){ 239 | col_names = c("sensor","AutoAI_MAE","AutoAI_SD","AutoAI_MAPE","AMLP_MAE", 240 | "AMLP_SD","AMLP_MAPE","CNN_MAE", "CNN_SD","CNN_MAPE", 241 | "LSTM_MAE", "LSTM_SD","LSTM_MAPE", 242 | "SPATIAL_MAE", "SPATIAL_SD","SPATIAL_MAPE") 243 | col_names_all = c("sensor","AutoAI","AMLP", 244 | "CNN", "LSTM", "SPATIAL") 245 | append_file = FALSE 246 | }else{ 247 | col_names = FALSE 248 | append_file = TRUE 249 | col_names_all = FALSE 250 | } 251 | 252 | write.table(cbind(lale_sensor_dir[sens_type], 253 | round(mae_all_lale,digits = 2), 254 | round(mae_all_amlp,digits = 2), 255 | round(mae_all_cnn,digits = 2), 256 | round(mae_all_lstm,digits = 2), 257 | round(mae_all_spat,digits = 2)), 258 | fout, append = append_file, 259 | row.names = FALSE, 260 | col.names = col_names, 261 | # col.names = c("sensor", "AutoAI", "AMLP", "CNN","LSTM", "SPATIAL"), 262 | sep = ',') 263 | 264 | write.table(cbind(lale_sensor_dir[sens_type], 265 | round(mae_lale, digits = 2), 266 | round(mae_amlp, digits = 2), 267 | round(mae_cnn, digits = 2), 268 | round(mae_lstm, digits = 2), 269 | round(mae_spatial, digits = 2)), 270 | fout_mae, append = append_file, 271 | col.names = col_names_all, row.names = FALSE, sep = ',') 272 | 273 | 274 | write.table(cbind(lale_sensor_dir[sens_type], 275 | round(mape_lale, digits = 2), 276 | round(mape_amlp, digits = 2), 277 | round(mape_cnn, digits = 2), 278 | round(mape_lstm, digits = 2), 279 | round(mape_spatial, digits = 2)), 280 | fout_mape, append = append_file, 281 | col.names = col_names_all, row.names = FALSE, sep = ',') 282 | } # end check on whether to write stats 283 | 284 | 285 | ### Finally let's look at the MAE reported for the pertinent sensors 286 | sensors_we_use = c(1,8,9) 287 | print(paste('The MAE at all Lale sensors is ', mean(mae_lale,na.rm=TRUE))) 288 | print(paste('The standard deviation of the Lale MAE is ', sd(mae_lale,na.rm=TRUE))) 289 | print(paste('The MAE at all AMLP sensors is ', mean(mae_amlp,na.rm=TRUE))) 290 | print(paste('The standard deviation of the AMLP MAE is ', sd(mae_amlp,na.rm=TRUE))) 291 | print(paste('The MAE at all SPATIAL sensors is ', mean(mae_spatial,na.rm=TRUE))) 292 | print(paste('The standard deviation of the AMLP MAE is ', sd(mae_spatial,na.rm=TRUE))) 293 | print(sens_type) 294 | 295 | lims_1 <- as.POSIXct(strptime(unlist(lims_arr[1]), format = "%Y-%m-%d")) 296 | lims_2 <- as.POSIXct(strptime(unlist(lims_arr[2]), format = "%Y-%m-%d")) 297 | lims_3 <- as.POSIXct(strptime(unlist(lims_arr[3]), format = "%Y-%m-%d")) 298 | 299 | ### Now let's save our figure objects for further formatting 300 | if (sens_type == 1){ 301 | p_ts_total_temp <- p_ts_total + rremove("xlab") + 302 | scale_x_datetime(limits = lims_1, labels=date_format("%d-%m")) + 303 | ylim(c(4,7)) 304 | } 305 | 306 | if (sens_type == 2){ 307 | p_ts_total_do <- p_ts_total + rremove("xlab") + 308 | scale_x_datetime(limits = lims_2, labels=date_format("%d-%m")) 309 | } 310 | 311 | if (sens_type == 3){ 312 | p_ts_total_adcp <- p_ts_total + rremove("xlab") + 313 | scale_x_datetime(limits = lims_3, labels=date_format("%d-%m"), 314 | breaks=date_breaks("4 day")) +ylim(c(0,30)) 315 | } 316 | 317 | } 318 | 319 | 320 | if (create_grid_plot){ 321 | g = ggarrange(p_ts_total_temp , 322 | p_ts_total_do , 323 | p_ts_total_adcp , 324 | p_ts_res_temp , 325 | p_ts_res_do , 326 | p_ts_res_adcp , 327 | nrow = 3, ncol=2, common.legend = T) 328 | 329 | g_review = ggarrange(p_ts_total_temp , 330 | p_ts_total_do , 331 | p_ts_total_adcp , 332 | nrow = 3, ncol=1, common.legend = T) 333 | 334 | ggsave(here(getwd(), results_dir, 'combined_images.png') ,g, height=4.8, width=6.4) 335 | ggsave(here(getwd(), results_dir, 'lstm_cnn_spatial.png') ,g_review, height=6.4, width=6.4) 336 | 337 | } 338 | 339 | 340 | 341 | 342 | 343 | -------------------------------------------------------------------------------- /plots/util_fncs.R: -------------------------------------------------------------------------------- 1 | ## This script contains utility functions used for the SPATIAL, 2 | ## Lale, and AMLP model results. 3 | 4 | combine_spatial_and_observation <- function(fname_raw, fname_spatial, ADCP){ 5 | ## Function to read the raw and Spatial results and join to dataframe 6 | df_raw = read.table(fname_raw, sep=',', header = TRUE) 7 | if (ADCP){ 8 | print('we;re doing ADCP') 9 | df_raw$observed_timestamp <- as.POSIXct(strptime(df_raw$observed_timestamp, "%Y-%m-%d %H:%M:%S", tz="UTC")) 10 | } else{ 11 | df_raw$observed_timestamp <- as.POSIXct(strptime(df_raw$observed_timestamp, "%Y-%m-%d %H:%M:%S+00:00", tz="UTC")) 12 | } 13 | print(head(df_raw,3)) 14 | df_spat = read.table(fname_spatial, sep=',', header = TRUE) 15 | if (ADCP){ 16 | print('were doing ADCP again') 17 | df_spat$date <- as.POSIXct(strptime(df_spat$date, "%Y-%m-%d %H:%M:%S", tz="UTC")) 18 | } else { 19 | df_spat$date <- as.POSIXct(strptime(df_spat$date, "%Y-%m-%d %H:%M:%S+00:00", tz="UTC")) 20 | } 21 | print(head(df_spat,3)) 22 | df_jn <- merge(df_spat,df_raw, by.x='date', by.y = 'observed_timestamp') 23 | names(df_jn)[names(df_jn) == "value.x"] <- "SPATIAL" 24 | names(df_jn)[names(df_jn) == "value.y"] <- "observation" 25 | # df_jn$diff_spatial = df_jn$observation - df_jn$SPATIAL 26 | df_jn 27 | } 28 | 29 | add_lale_and_amlp_to_df <- function(df_, df_lale, df_amlp){ 30 | df_lale <- add_minute(df_lale) 31 | df_lale$date <- ISOdate(df_lale$year, df_lale$month, df_lale$day, 32 | df_lale$hour, df_lale$minute, tz = 'UTC') 33 | df_lale$date <- df_lale$date + 86400 34 | df_lale$amlp <- df_amlp$pred 35 | df_jn <- merge(df_,df_lale, by.x='date', by.y = 'date') 36 | names(df_jn)[names(df_jn) == "prediction"] <- "Lale" 37 | # df_jn$diff_lale = df_jn$observation - df_jn$SPATIAL 38 | df_jn 39 | } 40 | 41 | add_minute <- function(df){ 42 | # The Lale and AMLP results don't include minutes so add manually 43 | df$minute <- 0 44 | for (i in seq(1, dim(df)[1])){ 45 | if (i %% 2 == 0){ 46 | df$minute[i] <- 30 47 | } 48 | } 49 | df 50 | } 51 | 52 | add_observed_to_residual <- function(df_sensor, df_res){ 53 | ### The residual is created by taking the difference, 54 | ### lagged by the forecast horizon. 55 | ### ie y_res = y_t - y_t-48 56 | ### reconstruction is the reverse 57 | 58 | # first find date of first index by matching timestamps 59 | ind_beg <- match(df_res$date[1], df_sensor$observed_timestamp) 60 | df_res$reconstruct_signal <- NULL 61 | df_res$test_reconstruct <- NULL 62 | for (i in seq(1, dim(df_res)[1])){ 63 | df_res$reconstruct_signal[i] <- df_res$prediction[i] + df_sensor$value[ind_beg + i -48] 64 | df_res$test_reconstruct[i] <- df_res$output_res[i] + df_sensor$value[ind_beg + i -48] 65 | } 66 | return(df_res) 67 | } 68 | 69 | add_observed_to_residual_spat <- function(df_sensor, df_res){ 70 | ### The residual is created by taking the difference, 71 | ### lagged by the forecast horizon. 72 | ### ie y_res = y_t - y_t-48 73 | ### reconstruction is the reverse 74 | 75 | # first find date of first index by matching timestamps 76 | ind_beg <- match(df_res$date[1], df_sensor$observed_timestamp) 77 | df_res$reconstruct_signal <- NULL 78 | df_res$test_reconstruct <- NULL 79 | df_res$output <- NULL 80 | df_res$output_res <- NULL 81 | for (i in seq(1, dim(df_res)[1])){ 82 | df_res$reconstruct_signal[i] <- df_res$value[i] + df_sensor$value[ind_beg + i -48] 83 | df_res$output[i] <- df_sensor$value[ind_beg + i] 84 | } 85 | return(df_res) 86 | } 87 | 88 | 89 | 90 | add_observed_to_residual_amlp <- function(df_sensor, df_res){ 91 | ### The residual is created by taking the difference, 92 | ### lagged by the forecast horizon. 93 | ### ie y_res = y_t - y_t-48 94 | ### y_t = y_res + y_t-48 95 | ### reconstruction is the reverse 96 | 97 | # first find date of first index by matching timestamps 98 | ind_beg <- match(df_res$date[1], df_sensor$observed_timestamp) 99 | diff_sens <- diff(df_sensor$value, lag=48) 100 | df_res$reconstruct_signal <- NULL 101 | df_res$output <- NULL 102 | df_res$output_res <- NULL 103 | 104 | for (i in seq(1, dim(df_res)[1])){ 105 | df_res$reconstruct_signal[i] <- df_res$pred[i] + df_sensor$value[ind_beg + i -48] 106 | df_res$output[i] <- df_sensor$value[ind_beg + i] 107 | df_res$output_res[i] <- diff_sens[ind_beg + i] 108 | } 109 | return(df_res) 110 | } 111 | 112 | 113 | 114 | reconstruct_residual <- function(sensor_fname, residual_fname, ADCP){ 115 | ## Function to read the raw and Spatial results and join to dataframe 116 | df_sensor = read.table(sensor_fname, sep=',', header = TRUE) 117 | if (ADCP){ 118 | print('we;re doing ADCP') 119 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S", tz="UTC")) 120 | } else{ 121 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S+00:00", tz="UTC")) 122 | } 123 | df_res = read.table(residual_fname, sep=',', header = TRUE) 124 | ## If Lale or AMLP, date is of form, year, month, day, etc. 125 | ## Also, minute is not included so need to add manually 126 | df_res <- add_minute(df_res) 127 | df_res$date <- ISOdate(df_res$year, df_res$month, df_res$day, 128 | df_res$hour, df_res$minute, tz = 'UTC') 129 | ## For Lale or AMLP, date refers to the forecast date while senor refers to 130 | ## date t_now, so need to step forward 24 hours 131 | df_res$date <- df_res$date + 86400 132 | ### 133 | ### 134 | df_res = add_observed_to_residual(df_sensor, df_res) 135 | 136 | return(list("df_sensor" = df_sensor, "df_model" = df_res)) 137 | } 138 | 139 | 140 | reconstruct_residual_spat <- function(sensor_fname, residual_fname, ADCP){ 141 | ## Function to read the raw and Spatial results and join to dataframe 142 | df_sensor = read.table(sensor_fname, sep=',', header = TRUE) 143 | if (ADCP){ 144 | print('we;re doing ADCP') 145 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S", tz="UTC")) 146 | } else{ 147 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S+00:00", tz="UTC")) 148 | } 149 | df_res = read.table(residual_fname, sep=',', header = TRUE) 150 | ## If Lale or AMLP, date is of form, year, month, day, etc. 151 | ## Also, minute is not included so need to add manually 152 | df_res$date <- as.POSIXct(strptime(df_res$date, "%Y-%m-%d %H:%M:%S", tz="UTC")) 153 | ## For Lale or AMLP, date refers to the forecast date while senor refers to 154 | ## date t_now, so need to step forward 24 hours 155 | ### 156 | ### 157 | # df_res$date <- df_res$date - 86400 158 | df_res = add_observed_to_residual_spat(df_sensor, df_res) 159 | 160 | return(list("df_sensor" = df_sensor, "df_model" = df_res)) 161 | } 162 | 163 | 164 | 165 | 166 | 167 | reconstruct_residual_amlp <- function(sensor_fname, residual_fname, ADCP){ 168 | ## Function to read the raw and AMLP results and join to dataframe 169 | df_sensor = read.table(sensor_fname, sep=',', header = TRUE) 170 | if (ADCP){ 171 | print('we;re doing ADCP') 172 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S", tz="UTC")) 173 | } else{ 174 | df_sensor$observed_timestamp <- as.POSIXct(strptime(df_sensor$observed_timestamp, "%Y-%m-%d %H:%M:%S+00:00", tz="UTC")) 175 | } 176 | df_res = read.table(residual_fname, sep=',', header = TRUE) 177 | ## AMLP has no date signal so need to reconstruct from test file 178 | df_res <- add_minute(df_res) 179 | df_res$date <- ISOdate(df_res$year, df_res$month, df_res$day, 180 | df_res$hour, df_res$minute, tz = 'UTC') 181 | ## For Lale or AMLP, date refers to the forecast date while senor refers to 182 | ## date t_now, so need to step forward 24 hours 183 | ## For AMLP it's a little complicated. 184 | ## We start with the the data processed by Paulito AutoML 185 | ## which time aligns data along 186 | ## timestamp_t, output_t+48 187 | ## Then we compute diff based on diff(data, nlag = 48) 188 | ## which computes of form 189 | ## ==> x[(1+lag):n] - x[1:(n-lag)] 190 | ## This steps data forward again so is of form 191 | ## timestamp_t, output_t+96. Hence, need to update this 192 | ## df_res$date <- df_res$date + (86400 * 2) 193 | ### 194 | ### 195 | df_res = add_observed_to_residual_amlp(df_sensor, df_res) 196 | 197 | return(list("df_sensor" = df_sensor, "df_model" = df_res)) 198 | } 199 | 200 | combine_all_forecasts <- function(df_lale, df_amlp, df_spat){ 201 | df_lale_ <- df_lale[c('date', 'reconstruct_signal', 'output')] 202 | df_amlp_ <- df_amlp[c('date', 'reconstruct_signal', 'output')] 203 | df_spat_ <- df_spat[c('date', 'reconstruct_signal', 'output')] 204 | df_lale_$date <- df_lale_$date - 1800 205 | names(df_lale_)[names(df_lale_) == "reconstruct_signal"] <- "AutoAI" 206 | names(df_amlp_)[names(df_amlp_) == "reconstruct_signal"] <- "AMLP" 207 | names(df_spat_)[names(df_spat_) == "reconstruct_signal"] <- "SPATIAL" 208 | 209 | df <- merge(df_lale_,df_amlp_, by.x='date', by.y = 'date') 210 | df <- merge(df,df_spat_, by.x='date', by.y = 'date') 211 | names(df)[names(df) == "output"] <- "observation" 212 | df 213 | } 214 | --------------------------------------------------------------------------------