-
Notifications
You must be signed in to change notification settings - Fork 0
/
XGB_Model_v3_uncertainty.py
2170 lines (1545 loc) · 99.8 KB
/
XGB_Model_v3_uncertainty.py
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Script developed by Ryan C. Johnson, University of Alabama for the
#Salt Lake City Climate Vulnerability Project.
#Date: 3/4/2022
# coding: utf-8
import xgboost as xgb
from xgboost.sklearn import XGBRegressor
from xgboost import cv
import time
import pickle
import joblib
from pickle import dump
import numpy as np
import copy
from collinearity import SelectNonCollinear
from sklearn.feature_selection import f_regression
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
import hydroeval as he
import pandas as pd
import seaborn as sns
from sklearn.feature_selection import RFE
import xgboost as xgb
from xgboost.sklearn import XGBRegressor
from xgboost import cv
from sklearn.pipeline import Pipeline
from sklearn.model_selection import RepeatedKFold
from sklearn.model_selection import cross_val_score
from numpy import mean
from numpy import std
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from progressbar import ProgressBar
from collections import defaultdict
import jenkspy
from matplotlib.dates import MonthLocator, DateFormatter
class XGB_model():
def __init__(self, Target):
self = self
self.Target = Target
self.Prediction = self.Target+'_Pred'
self.Prediction_Rolling = self.Prediction+'_Rolling'
self.T_initial = self.Target+'_Initial'
def fit(self,param, X,y, M_save_filepath):
self.param=param
self.num_round=param['num_boost_round']
start_time = time.time()
print('Model Training')
y = y[self.Target]
feature_names = list(X.columns)
dtrain = xgb.DMatrix(np.array(X), label=np.array(y),feature_names=feature_names)
model = xgb.Booster(self.param, [dtrain])
model = xgb.train(self.param,dtrain,num_boost_round=self.num_round, xgb_model=model)
c_time = round(time.time() - start_time,2)
print('Calibration time', round(c_time), 's')
print('Saving Model')
#adjust this to match changing models
pickle.dump(model, open(M_save_filepath, "wb"))
self.model_=model
def predict(self,X, model):
self.model_=model
dtest=xgb.DMatrix(X)
return self.model_.predict(dtest)
def XGB_Predict(self,cwd, test_feat, test_targ):
#Make predictions with the model
model = pickle.load(open(cwd+'/BoostModels/XGBoost_'+self.Target+".dat", "rb"))
start_time = time.time()
#since the previous timestep is being used, we need to predict this value
predict = []
featcol = test_feat.columns
for i in range(0,(len(test_feat)-1),1):
t_feat = np.array(test_feat.iloc[i])
t_feat = t_feat.reshape(1,len(t_feat))
t_feat = pd.DataFrame(t_feat, columns = featcol)
p = self.predict(t_feat, model)
if self.T_initial in featcol:
test_feat[self.T_initial].iloc[(i+1)] = p
predict.append(p[0])
#need to manually add one more prediction
predict.append(predict[-1])
#add physical limitations to predictions
if self.Target =='SLCDPU_GW':
predict = np.array(predict)
predict[predict > 89.49] = 89.49
#Use this line for PCA
#predict = Targ_scaler.inverse_transform(predict.reshape(len(predict),1))
c_time = round(time.time() - start_time,8)
print('prediction time', round(c_time), 's')
#Analyze model performance
#use this line for PCA
#Targ_scaler.inverse_transform(test_targ)
Analysis = pd.DataFrame(test_targ, columns = [self.Target])
Analysis[self.Prediction] = predict
Analysis[self.Prediction_Rolling] = Analysis[self.Prediction].rolling(5).mean()
Analysis[self.Prediction_Rolling] = Analysis[self.Prediction_Rolling].interpolate(method='linear',
limit_direction='backward',
limit=5)
RMSEpred = mean_squared_error(Analysis[self.Target],Analysis[self.Prediction], squared=False)
RMSErolling = mean_squared_error(Analysis[self.Target],Analysis[self.Prediction_Rolling], squared=False)
# print('RMSE for predictions: ', RMSEpred, 'af/d. RMSE for rolling prediction mean: ', RMSErolling, 'af/d')
self.Analysis = Analysis
#Make a plot of predictions
def PredictionPerformancePlot(self):
#predicted and observed
labelsize = 14
# better control over ax
fig, ax = plt.subplots(2, 1)
fig.set_size_inches(9,8)
maxGW = max(max(self.Analysis[self.Target]), max(self.Analysis[self.Prediction]))*1.2
self.Analysis.plot( y = self.Target, ax=ax[0], color = 'blue', label = self.Target)
self.Analysis.plot(y = self.Prediction , ax=ax[0], color = 'orange', label = self.Prediction)
self.Analysis.plot(y = self.Prediction_Rolling , ax=ax[0], color = 'green', label = self.Prediction_Rolling)
ax[0].set_xlabel('Time ', size = labelsize)
ax[0].set_ylabel(self.Target +' (af/d)', size = labelsize)
#plt.xlim(0,370)
ax[0].set_ylim(0,maxGW*1.4)
ax[0].legend(loc="upper left",title = 'Prediction/Target')
self.Analysis.plot.scatter(x = self.Target, y = self.Prediction_Rolling , ax=ax[1], color = 'green', label = self.Prediction_Rolling)
self.Analysis.plot.scatter(x = self.Target, y = self.Prediction , ax=ax[1], color = 'orange', label = self.Prediction)
ax[1].plot((0,maxGW),(0,maxGW), linestyle = '--', color = 'red')
#plt.title('Production Simulations', size = labelsize+2)
#fig.savefig(O_path + 'Figures/MLP/MLP_Prod.png', dpi = 300)
plt.show()
RMSEpred = mean_squared_error(self.Analysis[self.Target],self.Analysis[self.Prediction], squared=False)
RMSErolling = mean_squared_error(self.Analysis[self.Target],self.Analysis[self.Prediction_Rolling], squared=False)
print('RMSE for predictions: ', RMSEpred, '. RMSE for rolling prediction mean: ', RMSErolling)
#Developing the XGBoost_Tuning package
class XGB_Tuning():
def __init__(self):
self = self
def ProcessData(self, df, sim, feat, targ, test_yr, scaling, allData):
print('Processing data to tune XGBoost model for ', targ[0])
print('This may take a few moments depending on computational power and data size')
self.targ = targ[0]
data = copy.deepcopy(df)
#get month, day, year, from df
dflen = len(data[sim])
months = []
days = []
years = []
data[sim]['DOY'] = 0
for t in range(0,dflen,1):
y = data[sim]['Time'][t].year
m = data[sim]['Time'][t].month
d = data[sim]['Time'][t].day
months.append(m)
days.append(d)
years.append(y)
data[sim]['DOY'].iloc[t] = data[sim]['Time'].iloc[t].day_of_year
years = list( dict.fromkeys(years) )
#remove yr 2000 and 2022 as it is not a complete year
#test by removing 2008, 2015, and 2017 too as these are the test years
years = years[1:-1]
data[sim]['Month'] = months
data[sim]['Day'] = days
data[sim].index = data[sim]['Time']
#input each year's initial reservoir conditions./ previous timestep conditions.
data[sim]['Mtn_Dell_Percent_Full_Initial'] = 0
data[sim]['LittleDell_Percent_Full_Initial'] = 0
data[sim]['SLCDPU_GW_Initial'] = 0
data[sim]['SLCDPU_DC_Water_Use_Initial'] = 0
timelen = len(data[sim])
for t in range(0,timelen, 1):
data[sim]['Mtn_Dell_Percent_Full_Initial'].iloc[t] = data[sim]['Mtn_Dell_Percent_Full'].iloc[(t-1)]
data[sim]['LittleDell_Percent_Full_Initial'].iloc[t] = data[sim]['LittleDell_Percent_Full'].iloc[(t-1)]
data[sim]['SLCDPU_GW_Initial'].iloc[t] = data[sim]['SLCDPU_GW'].iloc[(t-1)]
data[sim]['SLCDPU_DC_Water_Use_Initial'].iloc[t] = data[sim]['SLCDPU_DC_Water_Use'].iloc[(t-1)]
#make an aggregated streamflow metric
data[sim]['SLCDPU_Surface_Supplies'] = data[sim]['BCC_Streamflow']+data[sim]['LCC_Streamflow']+data[sim]['CC_Streamflow']+data[sim]['Dell_Streamflow']+data[sim]['Lambs_Streamflow']
features = data[sim][feat]
targets = data[sim][targ]
f_col = list(features.columns)
t_col = list(targets.columns)
if scaling ==True:
del data[sim]['Time']
Feat_scaler = MinMaxScaler()
Targ_scaler = MinMaxScaler()
Feat_scaler.fit(features)
Targ_scaler.fit(targets)
features = Feat_scaler.transform(features)
targets = Targ_scaler.transform(targets)
f = pd.DataFrame(features, columns = f_col)
t = pd.DataFrame(targets, columns = t_col)
f.index = data[sim].index
t.index = data[sim].index
else:
f = features
t = targets
#looks like adding more data can help train models, extending period to include march and april
train_feat = f.loc['2000-10-1':str(test_yr)+'-3-31']
train_targ = t.loc['2000-10-1':str(test_yr)+'-3-31']
test_feat = f.loc[str(test_yr)+'-4-1':str(test_yr)+'-10-31']
test_targs =t.loc[str(test_yr)+'-4-1':str(test_yr)+'-10-31']
if allData == True:
#need to remove years 2008,2015,2017 as these are testing streamflow conditions.
testyrs = [2008,2015,2017]
trainyrs = list(np.arange(2001, 2021, 1))
for t in testyrs:
trainyrs.remove(t)
train_feat.drop(train_feat.loc[str(t)+'-4-1':str(t)+'-10-31'].index, inplace=True)
train_targ.drop(train_targ.loc[str(t)+'-4-1':str(t)+'-10-31'].index, inplace=True)
if allData ==False:
#need to remove years 2008,2015,2017 as these are testing streamflow conditions.
testyrs = [2008,2015,2017]
trainyrs = list(np.arange(2001, 2021, 1))
for t in testyrs:
trainyrs.remove(t)
train_feat.drop(train_feat.loc[str(t-1)+'-11-1':str(t)+'-10-31'].index, inplace=True)
train_targ.drop(train_targ.loc[str(t-1)+'-11-1':str(t)+'-10-31'].index, inplace=True)
# Model is focused on April to October water use, remove dates out of this timeframe
for t in trainyrs:
train_feat.drop(train_feat.loc[str(t-1)+'-12-1':str(t)+'-1-31'].index, inplace=True)
train_targ.drop(train_targ.loc[str(t-1)+'-12-1':str(t)+'-1-31'].index, inplace=True)
#Drop WY2000
train_feat.drop(train_feat.loc['2000-1-1':'2001-3-30'].index, inplace=True)
train_targ.drop(test_targ.loc['2000-1-1':'2001-3-30'].index, inplace=True)
#Shuffle training data to help model training
if scaling ==True:
return train_feat, train_targ, test_feat, test_targs, Targ_scaler
else:
self.train_feat, self.train_targ, self.test_feat,self.test_targs = train_feat, train_targ, test_feat, test_targs
def CollinearityRemoval(self, col_threshold):
print('Calculating collinearity matrix and removing features > ', str(col_threshold))
start_time = time.time()
#look at correlations among features
features = self.train_feat.columns
X = np.array(self.train_feat)
y = np.array(self.train_targ)
selector = SelectNonCollinear(correlation_threshold=col_threshold,scoring=f_regression)
selector.fit(X,y)
mask = selector.get_support()
Col_Check_feat = pd.DataFrame(X[:,mask],columns = np.array(features)[mask])
Col_Check_features = Col_Check_feat.columns
sns.heatmap(Col_Check_feat.corr().abs(),annot=True)
self.Col_Check_feat, self.Col_Check_features =Col_Check_feat, Col_Check_features
c_time = round(time.time() - start_time,8)
print('Feature development time', round(c_time), 's')
# get a list of models to evaluate
def get_models(self):
models = dict()
for i in range(2, len(self.X.columns)):
rfe = RFE(estimator=XGBRegressor(), n_features_to_select=i)
model = XGBRegressor()
models[str(i)] = Pipeline(steps=[('s',rfe),('m',model)])
self.models = models
# evaluate a given model using cross-validation
def evaluate_model(self, model):
#pipeline = Pipeline(steps=[('s',rfe),('m',model)])
pipeline = model
# evaluate model
cv = RepeatedKFold(n_splits=3, n_repeats=3, random_state=1)
n_scores = cross_val_score(pipeline, self.X, self.y, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1, error_score='raise')
self.scores = n_scores
def FeatureSelection(self):
start_time = time.time()
# define dataset
X = self.Col_Check_feat
self.X =X
y = self.train_targ# get the models to evaluate
self.y = y
self.get_models()
# evaluate the models and store results
results, names = list(), list()
print('Using RFE to determine optimial features, scoring is:')
for name, model in self.models.items():
self.evaluate_model(model)
results.append(self.scores)
names.append(name)
print('>%s %.3f (%.3f)' % (name, mean(self.scores), std(self.scores)))
score_cols = ['n_feat' , 'mean_MAE', 'std_MAE']
Feat_Eval = pd.DataFrame(columns = score_cols)
for i in range(0,len(results)):
feats = i+2
meanMAE = mean(results[i])
stdMAE = std(results[i])
s = [feats, abs(meanMAE), stdMAE]
Feat_Eval.loc[len(Feat_Eval)] = s
#mean and std MAE both are applicable. std works well when feweer features are used
Feat_Eval=Feat_Eval.sort_values(by=['std_MAE', 'n_feat'])
Feat_Eval = Feat_Eval.reset_index()
print(Feat_Eval)
n_feat = int(Feat_Eval['n_feat'][0])
# create pipeline
rfe = RFE(estimator=XGBRegressor(), n_features_to_select=n_feat)
rfe = rfe.fit(X, y)
# summarize the selection of the attributes
print(rfe.support_)
print(rfe.ranking_)
RFE_Feat = pd.DataFrame(self.Col_Check_features, columns = ['Features'])
RFE_Feat['Selected']= rfe.support_
RFE_Feat = RFE_Feat[RFE_Feat['Selected']==True]
RFE_Feat = RFE_Feat['Features']
RFE_Features = self.Col_Check_feat[RFE_Feat]
print('The Recursive Feature Elimination identified features are: ')
print(list(RFE_Feat))
self.Final_FeaturesDF, self.Final_Features = RFE_Features, list(RFE_Feat)
c_time = round(time.time() - start_time,8)
print('Feature selection time: ', round(c_time), 's')
#These are the top features for XBoost
#RFE feature selection is a good starting point, but these features optimize predictive performance
def Feature_Optimization(self):
print(' ')
print('Features optimization identifies the following features best fit for the XGB-WSM')
if self.targ =='LittleDell_Percent_Full':
self.Final_Features = ['Month', 'Dell_Streamflow', 'Mtn_Dell_Percent_Full_Initial', 'LittleDell_Percent_Full_Initial']
self.Final_FeaturesDF = self.Col_Check_feat[self.Final_Features]
if self.targ =='Mtn_Dell_Percent_Full':
self.Final_Features= ['SLCDPU_Surface_Supplies', 'Dell_Streamflow', 'Lambs_Streamflow',
'SLCDPU_GW_Initial', 'Mtn_Dell_Percent_Full_Initial']
self.Final_FeaturesDF = self.Col_Check_feat[self.Final_Features]
if self.targ=='SLCDPU_GW':
self.Final_FeaturesDF = self.Col_Check_feat[self.Final_Features]
if self.targ =='SLCDPU_DC_Water_Use':
self.Final_Features = ['BCC_Streamflow', 'SLCDPU_Prod_Demands', 'SLCDPU_DC_Water_Use_Initial',
'Mtn_Dell_Percent_Full_Initial', 'LittleDell_Percent_Full_Initial']
self.Final_FeaturesDF = self.Col_Check_feat[self.Final_Features]
#save features list
pickle.dump(self.Final_Features, open("Models/V2/"+self.targ+"_features.pkl", "wb"))
print('The final features for ', self.targ, 'are: ')
print(self.Final_FeaturesDF.columns)
#gridsearch hyper parameter function
def GridSearch(self, parameters):
start_time = time.time()
print('Performing a Grid Search to identify the optimial model hyper-parameters')
xgb1 = XGBRegressor()
xgb_grid = GridSearchCV(xgb1,
parameters,
cv = 3,
n_jobs = -1,
verbose=3)
xgb_grid.fit(self.Final_FeaturesDF, self.train_targ[self.targ])
print('The best hyperparameter three-fold cross validation score is: ')
print(xgb_grid.best_score_)
print(' ')
print('The optimal hyper-parameters are: ')
print(xgb_grid.best_params_)
print(' ')
c_time = round(time.time() - start_time,8)
print('Hyper-parameter Optimization time', round(c_time), 's')
self.xgb_grid = xgb_grid
#Model Training Function
def Train(self, M_save_filepath):
#get the optimial hyperparams
params = {"objective":"reg:squarederror",
'booster' : "gbtree" ,
'eta': self.xgb_grid.best_params_['learning_rate'],
"max_depth":self.xgb_grid.best_params_['max_depth'],
"subsample":self.xgb_grid.best_params_['subsample'],
"colsample_bytree":self.xgb_grid.best_params_['colsample_bytree'],
"reg_lambda":self.xgb_grid.best_params_['reg_lambda'],
'reg_alpha':self.xgb_grid.best_params_['reg_alpha'],
"min_child_weight":self.xgb_grid.best_params_['min_child_weight'],
'num_boost_round':self.xgb_grid.best_params_['n_estimators'],
'verbosity':0,
'nthread':-1
}
#Train the model
model = XGB_model(self.targ)
model.fit(params,self.Final_FeaturesDF, self.train_targ, M_save_filepath)
xgb.plot_importance(model.model_, max_num_features=20)
#XGB Prediction Engine
class XGB_Prediction():
def __init__(self, MDell_Thresh, LDell_Thresh, units, Sim, condition, test_yr, cwd, figsave):
self = self
#set reservoir level thresholds as global vars
self.MDell_Thresh = MDell_Thresh
self.LDell_Thresh = LDell_Thresh
self.units = units
#define global variables
self.condition = condition
self.observations = 'Obs_'+self.condition
self.scenario = 'Mod_'+self.condition
self.scenario_Low = self.scenario+'_Low'
self.scenario_Hig = self.scenario+'_Hig'
self.Sim = Sim
self.test_yr = test_yr
self.cwd = cwd
self.figsave = figsave
#set up unit conversion from acre feet
if self.units == 'MG':
self.conversion = 271328
if self.units == 'AcreFeet':
self.conversion = 1
if self.units == 'x10^4m3':
self.conversion = 0.123348
#Data Processing needed to make a prediction, This processes the variable demand inputs to create high and
#low predictions
def ProcessData(self, observations):
self.obs = observations
print('Processing data into features/targets for ', self.condition, ' scenario')
#Input optimial features from XGBoost_WSM_Tuning.
LittleDell_Percent_Full = pickle.load(open(self.cwd+"/BoostModels/LittleDell_Percent_Full_features.pkl", "rb"))
Mtn_Dell_Percent_Full = pickle.load(open(self.cwd+"/BoostModels/Mtn_Dell_Percent_Full_features.pkl", "rb"))
SLCDPU_GW = pickle.load(open(self.cwd+"/BoostModels/SLCDPU_GW_features.pkl", "rb"))
SLCDPU_DC_Water_Use = pickle.load(open(self.cwd+"/BoostModels/SLCDPU_DC_Water_Use_features.pkl", "rb"))
feat = {
'LittleDell_Percent_Full':LittleDell_Percent_Full,
'Mtn_Dell_Percent_Full':Mtn_Dell_Percent_Full,
'SLCDPU_GW': SLCDPU_GW,
'SLCDPU_DC_Water_Use': SLCDPU_DC_Water_Use
}
self.features = {}
self.targets= {}
self.Hist_targs = {}
if self.obs == True:
self.Scenarios = [self.scenario, self.scenario_Low, self.scenario_Hig, self.observations]
else:
self.Scenarios = [self.scenario_Low, self.scenario_Hig, self.scenario]
for i in self.Scenarios:
print('Processing ', i, ' conditions')
#make a DF with some additional features (from GS)
data = copy.deepcopy(self.Sim)
dflen = len(data[i])
months = []
days = []
years = []
data[i]['DOY'] = 0
for t in range(0,dflen,1):
y = data[i]['Time'][t].year
m = data[i]['Time'][t].month
d = data[i]['Time'][t].day
months.append(m)
days.append(d)
years.append(y)
data[i]['DOY'].iloc[t] = data[i]['Time'].iloc[t].day_of_year
years = list( dict.fromkeys(years) )
#remove yr 2000 and 2022 as it is not a complete year
years = years[1:-1]
data[i]['Month'] = months
data[i]['Day'] = days
data[i].index = data[i]['Time']
#input each year's initial reservoir conditions./ previous timestep conditions.
data[i]['Mtn_Dell_Percent_Full_Initial'] = 0
data[i]['LittleDell_Percent_Full_Initial'] = 0
data[i]['SLCDPU_GW_Initial'] = 0
data[i]['SLCDPU_DC_Water_Use_Initial'] = 0
timelen = len(data[i])
for t in range(0,timelen, 1):
data[i]['Mtn_Dell_Percent_Full_Initial'].iloc[t] = data[i]['Mtn_Dell_Percent_Full'].iloc[(t-1)]
data[i]['LittleDell_Percent_Full_Initial'].iloc[t] = data[i]['LittleDell_Percent_Full'].iloc[(t-1)]
data[i]['SLCDPU_GW_Initial'].iloc[t] = data[i]['SLCDPU_GW'].iloc[(t-1)]
data[i]['SLCDPU_DC_Water_Use_Initial'].iloc[t] = data[i]['SLCDPU_DC_Water_Use'].iloc[(t-1)]
#make an aggregated streamflow metric
data[i]['SLCDPU_Surface_Supplies'] = data[i]['BCC_Streamflow']+data[i]['LCC_Streamflow']+data[i]['CC_Streamflow']+data[i]['Dell_Streamflow']+data[self.scenario]['Lambs_Streamflow']
#Make dictionary of acutal features
features = { 'LittleDell_Percent_Full':data[i][feat['LittleDell_Percent_Full']],
'Mtn_Dell_Percent_Full':data[i][feat['Mtn_Dell_Percent_Full']],
'SLCDPU_GW': data[i][feat['SLCDPU_GW']],
'SLCDPU_DC_Water_Use': data[i][feat['SLCDPU_DC_Water_Use']]
}
#set up Targets
targ = ['SLCDPU_GW', 'Mtn_Dell_Percent_Full', 'LittleDell_Percent_Full','SLCDPU_DC_Water_Use']
targets = data[i][targ]
for f in features:
features[f] = features[f].loc[str(self.test_yr)+'-4-1':str(self.test_yr)+'-10-30']
Hist_targs = targets.loc[:str(self.test_yr)+'-3-31'].copy()
targets = targets.loc[str(self.test_yr)+'-4-1':str(self.test_yr)+'-10-30']
self.features[i] = features
self.targets = targets
self.Hist_targs = Hist_targs
def get_col_n_list(self, MDell_feat, LDell_feat, GW_feat, DC_feat):
#Mtn dell
MDell_predict= []
MDell_col = MDell_feat.columns
#lil Dell
LDell_predict = []
LDell_col = LDell_feat.columns
#GW
GW_predict = []
GW_col = GW_feat.columns
#GW
DC_predict = []
DC_col = DC_feat.columns
return MDell_predict, MDell_col, LDell_predict, LDell_col, GW_predict, GW_col, DC_predict, DC_col
def Prediction(self,i, MDell_feat, MDell_col, LDell_feat, LDell_col, GW_feat, GW_col, DC_feat, DC_col):
#MOuntain Dell
MDell_t_feat = self.dataprocess(MDell_feat, MDell_col, i)
M = XGB_model.predict(self.MDell_model, MDell_t_feat, self.MDell_model)
#Little Dell
LDell_t_feat = self.dataprocess(LDell_feat, LDell_col, i)
L = XGB_model.predict(self.LDell_model, LDell_t_feat, self.LDell_model)
#GW
GW_t_feat = self.dataprocess(GW_feat, GW_col, i)
G = XGB_model.predict(self.GW_model, GW_t_feat, self.GW_model)
#add physical limitations to predictions
G = np.array(G)
#DC
DC_t_feat = self.dataprocess(DC_feat, DC_col, i)
D = XGB_model.predict(self.DC_model, DC_t_feat, self.DC_model)
return M, L, G, D
def dataprocess(self,feat, featcol, i):
feat_t = np.array(feat.iloc[i])
feat_t = feat_t.reshape(1,len(feat_t))
feat_t = pd.DataFrame(feat_t, columns = featcol)
return feat_t
def feat_update(self,i, feat, featcol, LDell_Initial, MDell_Initial, GW_Initial, DC_Initial, L, M, G, D):
#This updates each DF with the predictions
#Mountain Dell Features
if LDell_Initial in featcol:
feat[LDell_Initial].iloc[(i+1)] = L
if MDell_Initial in featcol:
feat[MDell_Initial].iloc[(i+1)] = M
if GW_Initial in featcol:
feat[GW_Initial].iloc[(i+1)] = G
if DC_Initial in featcol:
feat[DC_Initial].iloc[(i+1)] = D
return feat
def Analysis_DF(self,Analysis, targ,comp_targ, component,predict_Low, predict_Ave,predict_Hig, conversion):
comp_Low = component +'_Low'
comp_Hig = component + '_Hig'
Analysis[targ] = comp_targ* conversion
Analysis[comp_Low] = np.float32(predict_Low)*conversion
Analysis[component] = np.float32(predict_Ave)*conversion
Analysis[comp_Hig] = np.float32(predict_Hig)*conversion
#non-zero values cannot occur
Analysis[comp_Low][Analysis[comp_Low]<0] = 0
Analysis[component][Analysis[component]<0] = 0
Analysis[comp_Hig][Analysis[comp_Hig]<0] = 0
return Analysis
#This uses the XGB model to make predictions for each water system component at a daily time step.
def WSM_Predict(self):
#Set up the target labels
#Mountain Dell
self.MDell = 'Mtn_Dell_Percent_Full'
self.MDell_Pred = self.MDell+'_Pred'
self.MDell_Pred_Low = self.MDell_Pred+'_Low'
self.MDell_Pred_Hig = self.MDell_Pred+'_Hig'
self.MDell_Initial = self.MDell+'_Initial'
self.MDell_Initial_Low = self.MDell_Initial+'_Low'
self.MDell_Initial_Hig = self.MDell_Initial+'_Hig'
#Little Dell
self.LDell = 'LittleDell_Percent_Full'
self.LDell_Pred = self.LDell+'_Pred'
self.LDell_Pred_Low = self.LDell_Pred+'_Low'
self.LDell_Pred_Hig = self.LDell_Pred+'_Hig'
self.LDell_Initial = self.LDell+'_Initial'
self.LDell_Initial_Low = self.LDell_Initial+'_Low'
self.LDell_Initial_Hig = self.LDell_Initial+'_Hig'
#GW
self.GW = 'SLCDPU_GW'
self.GW_Pred = self.GW+'_Pred'
self.GW_Pred_Low = self.GW_Pred+'_Low'
self.GW_Pred_Hig = self.GW_Pred+'_Hig'
self.GW_Initial = self.GW+'_Initial'
self.GW_Initial_Low = self.GW_Initial+'_Low'
self.GW_Initial_Hig = self.GW_Initial+'_Hig'
#GW
self.DC = 'SLCDPU_DC_Water_Use'
self.DC_Pred = self.DC+'_Pred'
self.DC_Pred_Low = self.DC_Pred+'_Low'
self.DC_Pred_Hig = self.DC_Pred+'_Hig'
self.DC_Initial = self.DC+'_Initial'
self.DC_Initial_Low = self.DC_Initial+'_Low'
self.DC_Initial_Hig = self.DC_Initial+'_Hig'
#Grab features/targets for the respective target
#Low---adjust features above to include climate scenario
MDell_feat_Low = copy.deepcopy(self.features[self.scenario_Low][self.MDell])
LDell_feat_Low = copy.deepcopy(self.features[self.scenario_Low][self.LDell])
GW_feat_Low = copy.deepcopy(self.features[self.scenario_Low][self.GW])
DC_feat_Low = copy.deepcopy(self.features[self.scenario_Low][self.DC])
#Average
MDell_feat_Ave = copy.deepcopy(self.features[self.scenario][self.MDell])
MDell_targ = copy.deepcopy(self.targets[self.MDell])
LDell_feat_Ave = copy.deepcopy(self.features[self.scenario][self.LDell])
LDell_targ = copy.deepcopy(self.targets[self.LDell])
GW_feat_Ave = copy.deepcopy(self.features[self.scenario][self.GW])
GW_targ = copy.deepcopy(self.targets[self.GW])
DC_feat_Ave = copy.deepcopy(self.features[self.scenario][self.DC])
DC_targ = copy.deepcopy(self.targets[self.DC])
#High
MDell_feat_Hig = copy.deepcopy(self.features[self.scenario_Hig][self.MDell])
LDell_feat_Hig = copy.deepcopy(self.features[self.scenario_Hig][self.LDell])
GW_feat_Hig = copy.deepcopy(self.features[self.scenario_Hig][self.GW])
DC_feat_Hig = copy.deepcopy(self.features[self.scenario_Hig][self.DC])
#Make predictions with the model, load model from XGBoost_WSM_Tuning
self.MDell_model = pickle.load(open("BoostModels/XGBoost_"+self.MDell+".dat", "rb"))
self.LDell_model = pickle.load(open("BoostModels/XGBoost_"+self.LDell+".dat", "rb"))
self.GW_model = pickle.load(open("BoostModels/XGBoost_"+self.GW+".dat", "rb"))
self.DC_model = pickle.load(open("BoostModels/XGBoost_"+self.DC+".dat", "rb"))
start_time = time.time()
#since the previous timestep is being used, we need to predict this value
#Low
MDell_predict_Low, MDell_col_Low, LDell_predict_Low, LDell_col_Low, GW_predict_Low, GW_col_Low, DC_predict_Low, DC_col_Low = self.get_col_n_list(MDell_feat_Low,LDell_feat_Low, GW_feat_Low, DC_feat_Low)
#Average
MDell_predict_Ave, MDell_col_Ave, LDell_predict_Ave, LDell_col_Ave, GW_predict_Ave, GW_col_Ave, DC_predict_Ave, DC_col_Ave = self.get_col_n_list(MDell_feat_Ave,LDell_feat_Ave, GW_feat_Ave, DC_feat_Ave)
#High
MDell_predict_Hig, MDell_col_Hig, LDell_predict_Hig, LDell_col_Hig, GW_predict_Hig, GW_col_Hig, DC_predict_Hig, DC_col_Hig = self.get_col_n_list(MDell_feat_Hig, LDell_feat_Hig, GW_feat_Hig, DC_feat_Hig)
#Make Predictions by row, update DF intitials to make new row prediction based on the current
for i in range(0,(len(LDell_feat_Ave)-1),1):
#Low
M_Low, L_Low, G_Low, D_Low = self.Prediction(i, MDell_feat_Low ,MDell_col_Low, LDell_feat_Low, LDell_col_Low, GW_feat_Low, GW_col_Low, DC_feat_Low, DC_col_Low)
#update the feature DFs
MDell_feat_Low = self.feat_update(i, MDell_feat_Low, MDell_col_Low, self.LDell_Initial_Low, self.MDell_Initial_Low, self.GW_Initial_Low, self.DC_Initial_Low, L_Low, M_Low, G_Low, D_Low)
LDell_feat_Low = self.feat_update(i, LDell_feat_Low, LDell_col_Low, self.LDell_Initial_Low, self.MDell_Initial_Low, self.GW_Initial_Low,self.DC_Initial_Low, L_Low, M_Low, G_Low, D_Low)
GW_feat_Low = self.feat_update(i, GW_feat_Low, GW_col_Low, self.LDell_Initial_Low, self.MDell_Initial_Low, self.GW_Initial_Low, self.DC_Initial_Low,L_Low, M_Low, G_Low, D_Low)
DC_feat_Low = self.feat_update(i, DC_feat_Low, DC_col_Low, self.LDell_Initial_Low, self.MDell_Initial_Low, self.GW_Initial_Low, self.DC_Initial_Low,L_Low, M_Low, G_Low, D_Low)
#Append predictions
MDell_predict_Low.append(M_Low[0])
LDell_predict_Low.append(L_Low[0])
GW_predict_Low.append(G_Low[0])
DC_predict_Low.append(D_Low[0])
#Ave
M_Ave, L_Ave, G_Ave, D_Ave = self.Prediction(i, MDell_feat_Ave, MDell_col_Ave, LDell_feat_Ave, LDell_col_Ave, GW_feat_Ave, GW_col_Ave, DC_feat_Ave, DC_col_Ave)
#update the feature DFs
MDell_feat_Ave = self.feat_update(i, MDell_feat_Ave, MDell_col_Ave, self.LDell_Initial, self.MDell_Initial, self.GW_Initial, self.DC_Initial, L_Ave, M_Ave, G_Ave, D_Ave)
LDell_feat_Ave = self.feat_update(i, LDell_feat_Ave, LDell_col_Ave, self.LDell_Initial, self.MDell_Initial, self.GW_Initial, self.DC_Initial, L_Ave, M_Ave, G_Ave, D_Ave)
GW_feat_Ave = self.feat_update(i, GW_feat_Ave, GW_col_Ave, self.LDell_Initial, self.MDell_Initial, self.GW_Initial, self.DC_Initial, L_Ave, M_Ave, G_Ave, D_Ave)
DC_feat_Ave = self.feat_update(i, DC_feat_Ave, DC_col_Ave, self.LDell_Initial, self.MDell_Initial, self.GW_Initial, self.DC_Initial,L_Ave, M_Ave, G_Ave, D_Ave)
#Append predictions
MDell_predict_Ave.append(M_Ave[0])
LDell_predict_Ave.append(L_Ave[0])
GW_predict_Ave.append(G_Ave[0])
DC_predict_Ave.append(D_Ave[0])
#High
M_Hig, L_Hig, G_Hig, D_Hig = self.Prediction(i, MDell_feat_Hig ,MDell_col_Hig, LDell_feat_Hig, LDell_col_Hig, GW_feat_Hig, GW_col_Hig, DC_feat_Hig, DC_col_Hig)
#update the feature DFs
MDell_feat_Hig = self.feat_update(i, MDell_feat_Hig, MDell_col_Hig, self.LDell_Initial_Hig, self.MDell_Initial_Hig, self.GW_Initial_Hig, self.DC_Initial_Hig, L_Hig, M_Hig, G_Hig, D_Hig)
LDell_feat_Hig = self.feat_update(i, LDell_feat_Hig, LDell_col_Hig, self.LDell_Initial_Hig, self.MDell_Initial_Hig, self.GW_Initial_Hig, self.DC_Initial_Hig, L_Hig, M_Hig, G_Hig, D_Hig)
GW_feat_Hig = self.feat_update(i, GW_feat_Hig, GW_col_Hig, self.LDell_Initial_Hig, self.MDell_Initial_Hig, self.GW_Initial_Hig, self.DC_Initial_Hig, L_Hig, M_Hig, G_Hig, D_Hig)
DC_feat_Hig = self.feat_update(i, DC_feat_Hig, DC_col_Hig, self.LDell_Initial_Hig, self.MDell_Initial_Hig, self.GW_Initial_Hig, self.DC_Initial_Hig, L_Hig, M_Hig, G_Hig, D_Hig)
#Append predictions
MDell_predict_Hig.append(M_Hig[0])
LDell_predict_Hig.append(L_Hig[0])
GW_predict_Hig.append(G_Hig[0])
DC_predict_Hig.append(D_Hig[0])
#need to manually add one more prediction
MDell_predict_Low.append(MDell_predict_Low[-1])
LDell_predict_Low.append(LDell_predict_Low[-1])
GW_predict_Low.append(GW_predict_Low[-1])
DC_predict_Low.append(DC_predict_Low[-1])
MDell_predict_Ave.append(MDell_predict_Ave[-1])
LDell_predict_Ave.append(LDell_predict_Ave[-1])
GW_predict_Ave.append(GW_predict_Ave[-1])
DC_predict_Ave.append(DC_predict_Ave[-1])
MDell_predict_Hig.append(MDell_predict_Hig[-1])
LDell_predict_Hig.append(LDell_predict_Hig[-1])
GW_predict_Hig.append(GW_predict_Hig[-1])
DC_predict_Hig.append(DC_predict_Hig[-1])
#Use this line for PCA
c_time = round(time.time() - start_time,8)
print('prediction time', round(c_time), 's')
#Analyze model performance
Analysis = pd.DataFrame(LDell_targ, columns = [self.LDell])
Analysis = self.Analysis_DF(Analysis,self.LDell, LDell_targ, self.LDell_Pred, LDell_predict_Low, LDell_predict_Ave, LDell_predict_Hig, 1)
Analysis = self.Analysis_DF(Analysis,self.MDell, MDell_targ, self.MDell_Pred, MDell_predict_Low, MDell_predict_Ave, MDell_predict_Hig, 1)
Analysis = self.Analysis_DF(Analysis,self.GW, GW_targ, self.GW_Pred, GW_predict_Low, GW_predict_Ave, GW_predict_Hig, 1)
Analysis = self.Analysis_DF(Analysis,self.DC, DC_targ, self.DC_Pred, DC_predict_Low, DC_predict_Ave,DC_predict_Hig, 1)
print('Predictions Complete')
#input physical limitations to components. the 0.000810714 is a conversion from m3 to af
#Changes 0 values to 1 to avoid inf
Analysis[self.GW].loc[Analysis[self.GW]<.05] =0.05
Analysis[self.DC].loc[Analysis[self.DC]<.5] =.05
#input physical limitations to components
#GW
Analysis[self.GW_Pred_Low].loc[Analysis[self.GW_Pred_Low]>89.49] = 89.49
Analysis[self.GW_Pred].loc[Analysis[self.GW_Pred]>89.49] = 89.49
Analysis[self.GW_Pred_Hig].loc[Analysis[self.GW_Pred_Hig]>89.49] = 89.49
Analysis[self.GW_Pred_Low].loc['2021-7-10':'2021-9-15'][Analysis[self.GW_Pred_Low]<89.49]=89.49
Analysis[self.GW_Pred].loc['2021-7-10':'2021-9-15'][Analysis[self.GW_Pred]<89.49]=89.49
Analysis[self.GW_Pred_Hig].loc['2021-7-10':'2021-9-15'][Analysis[self.GW_Pred_Hig]<89.49]=89.49
#Deer Creek
Analysis[self.DC_Pred_Low].loc[Analysis[self.DC_Pred_Low]<0.405357] =0.405357
Analysis[self.DC_Pred].loc[Analysis[self.DC_Pred]<0.405357] =0.405357
Analysis[self.DC_Pred_Hig].loc[Analysis[self.DC_Pred_Hig]<0.405357] =0.405357
#Mountain Dell
Analysis[self.MDell_Pred_Low].loc[Analysis[self.MDell_Pred_Low]<25] =25
Analysis[self.MDell_Pred].loc[Analysis[self.MDell_Pred]<25] =25
Analysis[self.MDell_Pred_Hig].loc[Analysis[self.MDell_Pred_Hig]<25] =25
#Little Dell
Analysis[self.LDell_Pred_Low].loc[Analysis[self.LDell_Pred_Low]<10] =10
Analysis[self.LDell_Pred].loc[Analysis[self.LDell_Pred]<10] =10
Analysis[self.LDell_Pred_Hig].loc[Analysis[self.LDell_Pred_Hig]<10] =10
self.Analysis = Analysis
self.HistoricalAnalysis()
self.RRV_Assessment()
print('Plotting results for visual analysis:')
self.WSM_Pred_RRV_Plot()
#A function to calculate the daily mean values for each water system component
def DailyMean(self,component, month, yrs, days, monthnumber, inputyr):
Daylist = defaultdict(list)
DayFrame= defaultdict(list)
timecol = ['Year', 'Month' , 'Day']
for i in days:
Daylist[month+ str(i)]= []
DayFrame[month + str(i)] = pd.DataFrame(yrs, columns=['Year'])
for i in yrs:
for j in days:
Daylist[month+str(j)].append(self.Histyrs.loc[str(i)+'-'+ monthnumber +'-'+str(j)][component])
DayFrame[month+str(j)]['Day']=j
DayFrame[month+str(j)]['Month'] = int(monthnumber)
for i in DayFrame:
DayFrame[i][component] = Daylist[i]
histcomponent = 'Hist_Mean_' + component
for i in DayFrame:
DayFrame[i][histcomponent]= np.mean(DayFrame[i][component])
del DayFrame[i][component]
##put into year of choice