-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuant_Final.Rmd
1141 lines (923 loc) · 40.1 KB
/
Quant_Final.Rmd
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
---
title: "Quantative Methods Final Project"
subtitle: "Forest Fire Time Series Data"
author: Nathan Korinek, Claire Simpson
output:
html_document:
css: "lab.css"
---
```{r setup, include=FALSE}
# Setup the environment
library(knitr)
knitr::opts_chunk$set(fig.align='center',fig.width=10, fig.height=6, fig.path='Figs/', warning=FALSE, echo=TRUE, eval=TRUE, message=FALSE)
r = getOption("repos")
r["CRAN"] = "http://cran.us.r-project.org"
options(repos = r)
```
```{r, echo=T, eval=T, results='hide'}
library(maptools)
library(maps)
library(raster)
library(spatstat)
library(spdep)
library(ggmap)
library(ggsn)
library(randomForest)
library(factoextra)
library(tidyr)
library(sf)
library(dplyr)
library(ggcorrplot)
library(doParallel)
library(caret)
library(gridExtra)
library(GWmodel)
library(imputeTS)
library(lubridate)
# Load shape file
fire_data<-st_read("Quant_Fire_Data/Quant_Fire_Data.shp")
# Set the right projection information
fire_data<-st_set_crs(fire_data, 4326)
# Reproject the fire data to EPSG:26913, which represents UTM projection
projLocs<-st_transform(fire_data, CRS("+init=epsg:26913"))
# Load shape file
simple_fire_data<-st_read("Simplified_Quant_Fire_Data/Simplified_Quant_Fire_Data.shp")
# Set the right projection information
simple_fire_data<-st_set_crs(simple_fire_data, 4326)
# Reproject the fire data to EPSG:26913, which represents UTM projection
simple_projLocs<-st_transform(simple_fire_data, CRS("+init=epsg:26913"))
# Load shape file
fire_boundaries<-st_read("ForestFires_MLFinal/ForestFires_MLFinal.shp")
# Set the right projection information
fire_boundaries<-st_set_crs(fire_boundaries, 4326)
# Reproject the fire data to EPSG:26913, which represents UTM projection
fire_boundaries<-st_transform(fire_boundaries, CRS("+init=epsg:26913"))
```
Add Columns for Training vs. Test vs Validation data;
Drop Geometry
Reformat fire_date column as R date object
```{r, echo=T, eval=T, results='hide'}
# Create lists of ID's for different fire categories
Test_Ids = c("CO3741010757920121016","NM3700010423620110526","CO3894510543620120617","NM3692010445620110612","CO3747210346920110607","NM3696310515520100523")
Val_Ids = c('CO3726810830320120622', 'CO3935510767920100507', 'CO4005110538520100906', 'CO3943610521720120326')
# Add these IDs to every fire dataset we are using
fire_data['isTest'] <-'Train'
fire_data$isTest[fire_data$Event_ID %in% Test_Ids]<-'Test'
fire_data$isTest[fire_data$Event_ID %in% Val_Ids]<-'Validation'
simple_fire_data['isTest'] <-'Train'
simple_fire_data$isTest[simple_fire_data$Event_ID %in% Test_Ids]<-'Test'
simple_fire_data$isTest[simple_fire_data$Event_ID %in% Val_Ids]<-'Validation'
fire_boundaries['isTest'] <-'Train'
fire_boundaries$isTest[fire_boundaries$Event_ID %in% Test_Ids]<-'Test'
fire_boundaries$isTest[fire_boundaries$Event_ID %in% Val_Ids]<-'Validation'
fire_boundaries['isTest'] <- factor(fire_boundaries$isTest)
# Convert fire_date to a Date object
fire_data$fire_date <- as.Date(paste(fire_data$Year, fire_data$Month, fire_data$Day, sep = "-"))
# Drop geometry of fire data
my_df <- fire_data %>% st_drop_geometry()
```
Apply Seasonal Differencing to control periodicity!
```{r, echo=T, eval=T, results='hide'}
applySeasonalDif=FALSE
if (applySeasonalDif){
# Identify columns with "N" values for each month using regular expressions
n_cols <- grep("^N[A-Za-z]{3}\\d{4}$", names(my_df),value=TRUE)
# Create a new data frame with the yearly differences between the current month and the same month in the previous year for each row
yearly_diffs <- data.frame(t(apply(my_df[n_cols], 1, function(x) {
# x <- as.numeric(x)
len_sel<-length(x[grepl("^NJan\\d{4}$", names(x))])
cbind(x[grepl("^NJan\\d{4}$", names(x))][2:len_sel] - x[grepl("^NJan\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NFeb\\d{4}$", names(x))][2:len_sel] - x[grepl("^NFeb\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NMar\\d{4}$", names(x))][2:len_sel] - x[grepl("^NMar\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NApr\\d{4}$", names(x))][2:len_sel] - x[grepl("^NApr\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NMay\\d{4}$", names(x))][2:len_sel] - x[grepl("^NMay\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NJun\\d{4}$", names(x))][2:len_sel] - x[grepl("^NJun\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NJul\\d{4}$", names(x))][2:len_sel] - x[grepl("^NJul\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NAug\\d{4}$", names(x))][2:len_sel] - x[grepl("^NAug\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NSep\\d{4}$", names(x))][2:len_sel] - x[grepl("^NSep\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NOct\\d{4}$", names(x))][2:len_sel] - x[grepl("^NOct\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^NNov\\d{4}$", names(x))][2:len_sel] - x[grepl("^NNov\\d{4}$", names(x))[1:(len_sel-1)]],
x[grepl("^NDec\\d{4}$", names(x))][2:len_sel] - x[grepl("^NDec\\d{4}$", names(x))[1:(len_sel-1)]]
)
})))
# Rename columns so that now each column is equal to its original value minus
# the value from the previous year's equivalent month
#e.g., now NJan2020 column is equal to NJan2020-NJan2019
#(NOTE values from 2000 remain the same as there is not a prior year to difference)
colnames(yearly_diffs) <-n_cols[13:length(n_cols)] #REN
#reassign values in main dataframe to be the new monthly differenced values
my_df[names(yearly_diffs)] <- yearly_diffs
##############################
#this is basically what the col name should ACTUALLY be
# # Extract the last two digits of the years being differenced
# year_suffix <- substring(n_cols, 7, 9)[13:length(n_cols)]
#
# # Subtract 1 from the year suffix to get the previous year's suffix
# prev_year_suffix<-substring(n_cols, 7, 9)[1:(length(n_cols)-13)]
#
# # Create the new column names using the modified format
# new_names <- paste0("N", month.abb, year_suffix, "_", prev_year_suffix)
#
# # Rename the columns of the yearly_diffs dataframe
# colnames(yearly_diffs) <- new_names
######
# Identify columns with "N" values for each month using regular expressions
n_cols <- grep("^T[A-Za-z]{3}\\d{4}$", names(my_df),value=TRUE)
# Create a new data frame with the yearly differences between the current month and the same month in the previous year for each row
yearly_diffs <- data.frame(t(apply(my_df[n_cols], 1, function(x) {
# x <- as.numeric(x)
len_sel<-length(x[grepl("^TJan\\d{4}$", names(x))])
cbind(x[grepl("^TJan\\d{4}$", names(x))][2:len_sel] - x[grepl("^TJan\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TFeb\\d{4}$", names(x))][2:len_sel] - x[grepl("^TFeb\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TMar\\d{4}$", names(x))][2:len_sel] - x[grepl("^TMar\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TApr\\d{4}$", names(x))][2:len_sel] - x[grepl("^TApr\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TMay\\d{4}$", names(x))][2:len_sel] - x[grepl("^TMay\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TJun\\d{4}$", names(x))][2:len_sel] - x[grepl("^TJun\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TJul\\d{4}$", names(x))][2:len_sel] - x[grepl("^TJul\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TAug\\d{4}$", names(x))][2:len_sel] - x[grepl("^TAug\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TSep\\d{4}$", names(x))][2:len_sel] - x[grepl("^TSep\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TOct\\d{4}$", names(x))][2:len_sel] - x[grepl("^TOct\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^TNov\\d{4}$", names(x))][2:len_sel] - x[grepl("^TNov\\d{4}$", names(x))[1:(len_sel-1)]],
x[grepl("^TDec\\d{4}$", names(x))][2:len_sel] - x[grepl("^TDec\\d{4}$", names(x))[1:(len_sel-1)]]
)
})))
# Rename columns so that now each column is equal to its original value minus
# the value from the previous year's equivalent month
#e.g., now NJan2020 column is equal to NJan2020-NJan2019
#(NOTE values from 2000 remain the same as there is not a prior year to difference)
colnames(yearly_diffs) <-n_cols[13:length(n_cols)] #REN
#reassign values in main dataframe to be the new monthly differenced values
my_df[names(yearly_diffs)] <- yearly_diffs
### PRECIP
# Identify columns with "N" values for each month using regular expressions
n_cols <- grep("^P[A-Za-z]{3}\\d{4}$", names(my_df),value=TRUE)
# Create a new data frame with the yearly differences between the current month and the same month in the previous year for each row
yearly_diffs <- data.frame(t(apply(my_df[n_cols], 1, function(x) {
# x <- as.numeric(x)
len_sel<-length(x[grepl("^PJan\\d{4}$", names(x))])
cbind(x[grepl("^PJan\\d{4}$", names(x))][2:len_sel] - x[grepl("^PJan\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PFeb\\d{4}$", names(x))][2:len_sel] - x[grepl("^PFeb\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PMar\\d{4}$", names(x))][2:len_sel] - x[grepl("^PMar\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PApr\\d{4}$", names(x))][2:len_sel] - x[grepl("^PApr\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PMay\\d{4}$", names(x))][2:len_sel] - x[grepl("^PMay\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PJun\\d{4}$", names(x))][2:len_sel] - x[grepl("^PJun\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PJul\\d{4}$", names(x))][2:len_sel] - x[grepl("^PJul\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PAug\\d{4}$", names(x))][2:len_sel] - x[grepl("^PAug\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PSep\\d{4}$", names(x))][2:len_sel] - x[grepl("^PSep\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^POct\\d{4}$", names(x))][2:len_sel] - x[grepl("^POct\\d{4}$", names(x))][1:(len_sel-1)],
x[grepl("^PNov\\d{4}$", names(x))][2:len_sel] - x[grepl("^PNov\\d{4}$", names(x))[1:(len_sel-1)]],
x[grepl("^PDec\\d{4}$", names(x))][2:len_sel] - x[grepl("^PDec\\d{4}$", names(x))[1:(len_sel-1)]]
)
})))
# Rename columns so that now each column is equal to its original value minus
# the value from the previous year's equivalent month
#e.g., now NJan2020 column is equal to NJan2020-NJan2019
#(NOTE values from 2000 remain the same as there is not a prior year to difference)
colnames(yearly_diffs) <-n_cols[13:length(n_cols)] #REN
#reassign values in main dataframe to be the new monthly differenced values
my_df[names(yearly_diffs)] <- yearly_diffs
###############
### old code to subtract mean from dif cols
# all_month_cols <- c(Ncols,Pcols,Tcols)
# for (month_col in all_month_cols) { #iterate through all variable mean monthly columns (36)
# my_exp <- paste0("^",substr(month_col, 1, 1), substr(month_col, 2, 4), "\\d{4}$")
# my_df[, grepl(my_exp, names(my_df))] <-
# my_df[, grepl(my_exp, names(my_df))] - my_df[, month_col]
# }
}
```
Normalize Data
```{r, echo=T, eval=T, results='hide'}
# Select columns to normalize
my_df['id'] <- seq(1:nrow(my_df))
dont_scale <- c("id","Event_ID", "Month","Day","Year","fire_date","isTest")
cols_to_normalize <- dplyr::setdiff(names(my_df), dont_scale)
# Normalize selected columns
df_scaled <- my_df %>%
dplyr::select(cols_to_normalize) %>%
dplyr::mutate_if(is.numeric, scale) %>%
cbind(my_df[dont_scale])#, my_df[dont_scale])
my_df <-df_scaled
```
# Temporal Interpolation for NA values in NDVI data
```{r}
# Copy dataframe
interpolate_data <- df_scaled
# Filter the data to only include monthly NVDI values
interpolate_data_before <- interpolate_data %>%
select(starts_with("N")) %>%
select(!contains(c("before", "after")))
```
```{r}
interpolate_time_series <- function(ts_df) {
# Convert date columns to Date class
date_cols <- colnames(ts_df)
date_cols <- as.Date(paste0("01", substr(date_cols, 2, nchar(date_cols))), format = "%d%b%Y")
# Transpose data frame
transposed_df <- as.data.frame(t(as.matrix(ts_df)))
# Convert data frame to time series object
ts_data <- ts(transposed_df, start = c(year(date_cols[1]), month(date_cols[1])), frequency = 12)
# Interpolate missing values
ts_data_interp <- na_interpolation(ts_data, option = "spline")
# Convert interpolated time series back to data frame
df_interp <- as.data.frame(t(ts_data_interp))
colnames(df_interp) <- colnames(ts_df)
return(df_interp)
}
# Run interpolation function on NDVI data
interpolated_ndvi <- interpolate_time_series(interpolate_data_before)
```
```{r}
# Create a comparison between the interpolated and not interpolated data
ndvi_ts_plot <- replace(interpolate_data_before, is.na(interpolate_data_before), 0)
row1_df1 <- as.data.frame(t(as.matrix(ndvi_ts_plot[1, ])))
row1_df2 <- as.data.frame(t(as.matrix(interpolated_ndvi[1, ])))
# Convert data frame to time series object
ts_data1 <- ts(row1_df1, start = c(2000, 1), frequency = 12)
ts_data2 <- ts(row1_df2, start = c(2000, 1), frequency = 12)
# Plot time series against each other
par(mfrow = c(1, 2))
plot(ts_data1, col = "blue", main = "Time Series Where NA is Set to 0")
plot(ts_data2, col = "purple", main = "Time Series Where NA is Interpolated")
```
```{r}
# Insert interpolated data into original dataframe for future analysis
recalc_cols <- colnames(interpolated_ndvi)
my_df[, recalc_cols] <- interpolated_ndvi[, recalc_cols]
```
Get attributes before and after fire to Split data into pre fire and post fire data
```{r, echo=T, eval=T, results='hide'}
# selected_names <- names(my_df)[8:799] #all names with var-month-year
# Vector of month names
month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
#get new column names
attr_list <- list()
precip_list <- list()
temp_list <- list()
precip_list_post <- list()
temp_list_post <- list()
ndvi_list_post <- list()
# Loop through the desired number of attributes
for (i in 1:24) {
#NOTE: 1 mo before fire = month in which fire occurred
# Create the attribute name using paste0
# Add the attribute name to the list
attr_list[i] <- paste0("N", i, "before")
precip_list[i] <- paste0("P", i, "before")
temp_list[i] <- paste0("T", i, "before")
#columns for after fire
precip_list_post[i] <- paste0("P", i, "after")
temp_list_post[i] <- paste0("T", i, "after")
ndvi_list_post[i] <- paste0("N", i, "after")
}
# Print the attribute names list
print(attr_list)
attr_list =unlist(attr_list)
precip_list = unlist(precip_list)
temp_list = unlist(temp_list)
precip_list_post = unlist(precip_list_post)
temp_list_post = unlist(temp_list_post)
ndvi_list_post = unlist(ndvi_list_post)
#iterate through rows and then cols to parse NDVI, preicp, temp for N months before/after fire
for (r in 1:nrow(my_df)){
#get fire date
this_fire_date = my_df$fire_date[r]
fire_month <- as.numeric(format(this_fire_date, "%m"))
fire_mo_name <- month_names[fire_month]
fire_year <- format(this_fire_date, "%Y")
#get index of column that represents month of fire
match_idx <- grep(paste('N',fire_mo_name, fire_year,sep=''), colnames(my_df))
#get NDVI 24 months before the fire
col_indices <- seq(match_idx, match_idx - 24*3, by = -3)[1:24]
for (i in seq_along(col_indices)){
attr_name = attr_list[i]
col_idx = col_indices[i]
# print(c(colnames(my_df)[col_idx],attr_name))
my_df[r, attr_name] <- my_df[r,col_idx]
}
#get NDVI 24 months AFTER the fire
col_indices <- seq(match_idx+3, match_idx + 24*3, by = 3)#[1:24]
for (i in seq_along(col_indices)){
attr_name = ndvi_list_post[i]
col_idx = col_indices[i]
my_df[r, attr_name] <- my_df[r,col_idx]
}
match_idx = match_idx-1
col_indices <- seq(match_idx, match_idx - 24*3, by = -3)[1:24]
#get temp 24 months before fire
for (i in seq_along(col_indices)){
attr_name = temp_list[i]
col_idx = col_indices[i]
my_df[r, attr_name] <- my_df[r,col_idx]
}
#get temp 24 months AFTER the fire
col_indices <- seq(match_idx+3, match_idx + 24*3, by = 3)
for (i in seq_along(col_indices)){
attr_name = temp_list_post[i]
col_idx = col_indices[i]
my_df[r, attr_name] <- my_df[r,col_idx]
}
#get precip 24 months before the fire
match_idx = match_idx-1
col_indices <- seq(match_idx, match_idx - 24*3, by = -3)[1:24]
for (i in seq_along(col_indices)){
attr_name = precip_list[i]
col_idx = col_indices[i]
my_df[r, attr_name] <- my_df[r,col_idx]
}
#get precip 24 months AFTER the fire
col_indices <- seq(match_idx+3, match_idx + 24*3, by = 3)
for (i in seq_along(col_indices)){
attr_name = precip_list_post[i]
col_idx = col_indices[i]
my_df[r, attr_name] <- my_df[r,col_idx]
}
}
```
Here: ACTUALLY split data into training and test :)
```{r, echo=T, eval=T, results='hide'}
#split into train/test sets (val is part of train right now)
train_Xy <- my_df %>% dplyr::filter(my_df$isTest != 'Test') #currently this keeps validation rows in training set
test_Xy <- my_df %>% dplyr::filter(my_df$isTest == 'Test')
# Create input and output data frames
static_list <- c('slope','chili','elevation','aspect','mtpi')#colnames(my_df)[1:6]
predictor_cols <- c(attr_list,precip_list, temp_list, static_list) #X (predictor) column names
target_cols <- c(ndvi_list_post, temp_list_post, ndvi_list_post) #y (target) col names
```
Random Forests Analysis
We will fire run recursive feature elimination to get a sense of which predictor
variables are the most important. We have already prepared the data for input,
including transforming the data to remove the seasonal fluctuations (making it
stationary),
Here: remove NAs
```{r, echo=T, eval=T, results='hide'}
#random forests
# if installing caret doesnt work try:
# library(devtools)
# devtools::install_url("https://cran.r-project.org/src/contrib/caret_6.0-78.tar.gz")
#subset out columns from dataset (remove non-predictors/targets)
# names <- names(fire_data)
# to_remove <- c("Event_ID", "geometry", "index_righ")
# keep_names <- names[! names %in% to_remove]
# keep_names
# fire_data_4_model <- fire_data[keep_names]
# fire_data_4_model <- fire_data_4_model %>% st_drop_geometry()
#check for complete cases (will remove everything bc some columns are blank...)
# fire_data_4_model <- fire_data_4_model[complete.cases(fire_data_4_model), ]
#drop row where column 'elevation' is NA
train_Xy<- train_Xy %>% tidyr::drop_na(elevation)
test_Xy<- test_Xy %>% tidyr::drop_na(elevation)
#drop any column where there is an NA value
# train_X<-train_X[ , apply(train_X, 2, function(x) !any(is.na(x)))]
#TEMPORARY until we do interpolation to fill missing values
train_Xy[is.na(train_Xy)] <- 0
test_Xy[is.na(test_Xy)] <- 0
#Run Recursive Feature Elimination
#RFE parameters
# subsets <- seq(20, 700, by=20)#c(1:(length(fire_data_4_model)-1))
# # seeds <- vector(mode = "list", length = 51)
# seeds <- vector(mode = "list", length = 35)
# for(i in 1:75) seeds[[i]] <- sample.int(1000, length(subsets) + 1)
# seeds[[76]] <- sample.int(1000, 1)
#
# ctrl.RFE <- caret::rfeControl(functions = rfFuncs,
# method = "repeatedcv",
# number = 15,
# repeats = 5,
# seeds = seeds,
# verbose = FALSE)
#
# #this code makes it run in parallel
# c1 <- makeCluster(detectCores()-1)
# registerDoParallel(c1)
# set.seed(9)
# target <- c('NApr2021')
# rf.RFE <- rfe(x = fire_data_4_model[! fire_data_4_model %in% target],
# y = fire_data_4_model$NApr2021,
# sizes = subsets,
# # na.rm=TRUE,
# rfeControl = ctrl.RFE,
# allowParallel = TRUE
# )
# stopCluster(c1)
#
# gc()
#
# # Look at the results
# rf.RFE
#
# rf.RFE$fit
#
# rf.RFE$results
#
# plot(rf.RFE) # default plot is for Accuracy, but it can also be changed to Kappa
# plot(rf.RFE, metric="Kappa", main='RFE Kappa')
# plot(rf.RFE, metric="Accuracy", main='RFE Accuracy')
```
SANITY CHECK
```{r, echo=T, eval=T, results='hide'}
temp <- my_df[2,] #select row (2)
temp$fire_date
temp$N1after==temp$NJul2012
temp$N1before == temp$NJun2012
compare <-fire_data[2,]
compare$fire_date
compare$NJun2012 #wont be the same bc my_df has been seasonally differenced + scaled
```
We now can run the Random Forests model.
Options for RF strategies:
1.) create n RF models, one for each timestep we want to predict. Say, 12 different RF models,
1 for each of the 12 months in the second year after the fire. We fire need to create
12 training and test sets, where the training data consists of the 12 months immediately
preeceeding the fire
2.) Create 1 RF model where there is an input predictor variable (feature) that
tells the model which timestep after the fire the model is supposed to predict
```{r, echo=T, eval=T, results='hide'}
#Run Option 1:
#define R2
r_squared <- function(pred, target) {
ss_residual <- sum((target - pred) ^ 2)
ss_total <- sum((target - mean(target)) ^ 2)
return(1 - ss_residual / ss_total)
}
#store RMSE of test set in this dataframe:
rmse_df <- data.frame()
r2_df <- data.frame()
for (i in 1:24){
print(i)
#create training set with t timesteps pre-prediction
#e.g. first want to predict NDVI for month after fire, using 24-months pre-fire
#get list of attributes to keep as predictors:
end <- length(attr_list)
#want include attributes from 1 mo before through
range_i <- seq_len(25 - i)
keep_attr_pre <- c(attr_list[range_i], precip_list[range_i], temp_list[range_i])
len <- length(attr_list) - length(attr_list[i:end])
#^ how many timesteps do we need in order to ensure that we have 24 pre-prediction inputs?
if (len>0){
keep_attr_post <- c(ndvi_list_post[1:len], precip_list_post[1:len], temp_list_post[1:len])
}else{
keep_attr_post <- c()#ndvi_list_post[1:1])#, precip_list_post[1:1], temp_list_post[1:1])
}
#get attribute to keep as target
target_col <- ndvi_list_post[i]
print(c("target:", target_col))
#concat attribute lists to keep as predictors/targets
keep <- c(keep_attr_pre, keep_attr_post, static_list,target_col)
#split data into train and test
current <- train_Xy[keep]
current_test <- test_Xy[keep]
#run RF!!
#subsets max number should be the same or equal to the number of covariates being used
# determine number of covariates
subsets <- length(keep)
# set seeds to get reproducable results when running the process in parallel
set.seed(12)
seeds <- vector(mode = "list", length=76)
for(j in 1:75) seeds[[j]] <- sample.int(1000, length(1:subsets) + 1)
seeds[[76]] <- sample.int(1000, 1)
# Create the formula for randomForest
formula <- as.formula(paste(target_col, paste(names(current)[!names(current) %in% target_col], collapse = "+"), sep = "~"))
set.seed(12)
# Fit the random forest model
rf_model <- randomForest(formula=formula, data = current, importance = TRUE, ntree=500,mtry=50,type='regression')
#get training r2 to ensure model training correctly..
train_pred <- rf_model$predicted
print(c("training R2",r_squared(train_pred, current$N1after)))
# Make predictions on the test set
rf_pred <- predict(rf_model, newdata = current_test)
# Check the accuracy of the model
#r2 on test set
actual <- current_test[[target_col]]
test_r2 <- r_squared(rf_pred, actual)
print(c("test R2:",test_r2))
r2_df[1, target_col] <- test_r2
# varImpPlot(rf_model)
test_rmse <- sqrt(mean((actual - rf_pred)^2))
print(c("RMSE on test set:", test_rmse))
rmse_df[1, target_col] <- test_rmse
# plot(current_test$T1after,rf_pred, xlim=c(40,160), ylim=c(40,160),asp=1)
#store predictions in dataframe to plot
test_Xy[paste("pred_",target_col,sep='')] = rf_pred
}
```
Visualize the results
** want to add variable importance
```{r, echo=T, eval=T, results='hide'}
print(t(r2_df))
print(rmse_df)
# par(mar = c(4, 4, 2, 2)) # set margins to be 4 lines on bottom, left, and right, and 2 lines on top
# png(file = "/Users/clairesimpson/Downloads/r2_by_month_seasonally_differenced.png",res = 300,width = 1600, height = 1200)#_seasonally_differenced #width = 1200, height = 800,
#plot relationship between post-fire timesteps and accuracy metrics
plot(t(r2_df), main= "R^2 by Timestep", xlab="Months After Fire", ylab="R^2") #transposed
# Copy plot to a file
dev.copy(png)
dev.off()
gc()
# png(file = "/Users/clairesimpson/Downloads/rmse_by_month_seasonally_differenced.png",res = 300,width = 1600, height = 1200)#seasonally_differenced
plot(t(rmse_df), main="RMSE by Timestep", xlab="Months After Fire", ylab="RMSE")
# Copy plot to a file
dev.copy(png)
dev.off()
gc()
#want to plot an example sample
# Create some sample data
rand_num=6
x <- 1:24
truth_cols <- grep("^N\\d{1,2}after$", names(test_Xy),value=TRUE)
truth <- t(test_Xy[rand_num,truth_cols])
pred_cols <- grep("^pred_N\\d{1,2}after$", names(test_Xy),value=TRUE)
pred_cols
pred <- t(test_Xy[rand_num,pred_cols])
# png(file = "/Users/clairesimpson/Downloads/pred_and_true_ts_for_testsample_seas_dif.png",res=300,width = 1600, height = 1200)
plot(x, truth,
type="b",
col='blue',
main=paste0("Predicted and True NDVI for Test Sample ", as.character(rand_num)),
xlab = "Months After Fire",
ylab = "NDVI")
# Add the second list to the plot
points(x, pred, type='b',col = "red")
legend("topright", legend = c("True", "Predicted"), col = c("blue", "red"), lty = 1)
# Copy plot to a file
dev.copy(png)
dev.off()
gc()
```
Clustering Analysis:
Run Kmeans to group the points and determine which points are most similar to one another
This will help reveal which fires are most similar
```{r, echo=T, eval=T, results='hide'}
#kmeans
set.seed(12)
# output_df <- my_df[, !(names(my_df) %in% c("fire_date", after_fire_date_cols))]
#use simple_fire_data
#remove NAs - TEMPORARY?
non_na_cluster<- simple_fire_data %>% tidyr::drop_na(elevation)
non_na_cluster[is.na(non_na_cluster)] <- 0
cluster_data <- non_na_cluster[, !names(non_na_cluster) %in% c("Event_ID", "geometry", "Year","Month","Day","severity")]
cluster_data <- cluster_data %>% st_drop_geometry()
names(cluster_data)
## Elbow Plot
library(factoextra)
# Create elbow plot
elbow_plot <- fviz_nbclust(cluster_data, kmeans, method = "wss")
print(elbow_plot)
# Copy plot to a file
png(file = "/Users/clairesimpson/Downloads/elbow_plot.png")
dev.copy(png)
dev.off()
gc()
# Run kmeans with 3 clusters
k <- kmeans(cluster_data, centers = 6)
# View the cluster assignments
# k$cluster
#add clusters back to original dataframe
non_na_cluster['kmeans'] <- k$cluster
#plot clusters on map
#add lat and long
non_na_cluster$Longitude <- st_coordinates(non_na_cluster$geometry)[, 1]
non_na_cluster$Latitude <- st_coordinates(non_na_cluster$geometry)[, 2]
ggplot() +
geom_sf(data = non_na_cluster) +
geom_point(aes(x = Longitude, y = Latitude, color = factor(kmeans)), data=non_na_cluster, size = 2) +
scale_color_discrete(name = "Kmeans")
# save the plot to my downloads folder as a PNG file
filename <- file.path(Sys.getenv("HOME"), "Downloads", "kmeans_map.png")
ggsave(filename, device = "png", width = 6, height = 6, dpi = 300)
```
# Means comparison between test/train/validation fires
First getting checking the normality of each variable in each group of the fires
```{r}
# Get the columns we are interested in testing
columns <- colnames(simple_fire_data)
variables <- c(columns[1:9], columns[11:12])
shapiro_dict <- list()
# Split the fire by type, whether it is test, validation, or training
fires_list <- split(simple_fire_data, simple_fire_data$isTest)
# Loop through each dataframe and test each variable we will compare to check for normality
for (i in seq_along(fires_list)) {
fire_name <- names(fires_list)[i]
fires <- fires_list[[i]]
for (var in variables) {
shapiro_test <- shapiro.test(fires[[var]])
p_value <- shapiro_test$p.value
name_var = paste0(fire_name, "_", var)
shapiro_dict[[name_var]] <- p_value
}
}
# Print out p-values over 0.05 to look at columns that are normally distributed
for (i in seq_along(shapiro_dict)) {
value <- shapiro_dict[[i]]
name <- names(shapiro_dict)[i]
if (value > 0.05) {
print(paste0("Value of ", name, " is ", value))
}
}
```
Most of our columns are not normally distributed, so we will use the Mann Whitney test to compare each column between both the test and validation fires, and the test and training fires. We will compare the training and validation fires seperately against the test fires.
```{r}
# Get different fire groups from list of dataframes
test_fires <- fires_list[[1]]
train_fires <- fires_list[[2]]
validation_fires <- fires_list[[3]]
# Function that takes in the 3 dataframes we're interested in and returns the metrics of the wilcox tests ran on the datasets
get_wilcox_output <- function(test_fires, train_fires, validation_fires, variables) {
train_val_dict <- list()
train_test_dict <- list()
for (var in variables){
train_val_comp = wilcox.test(train_fires[[var]], validation_fires[[var]])$p.value
train_test_comp = wilcox.test(train_fires[[var]], test_fires[[var]])$p.value
train_val_dict[[var]] <- train_val_comp
train_test_dict[[var]] <- train_test_comp
}
return(list(train_val_dict, train_test_dict))
}
# Function that takes output of get_wilcox_output and returns total variables that were significantly different
get_wilcox_list_num_sig <- function(wilcox_pvalues) {
return(sum(unlist(wilcox_pvalues) < 0.05))
}
# Function that takes output of get_wilcox_output and returns the mean p-value for all wilcox tests
get_wilcox_list_median_val <- function(wilcox_pvalues) {
return(median(unlist(wilcox_pvalues)))
}
wilcox_out = get_wilcox_output(test_fires, train_fires, validation_fires, variables)
train_val_dict = wilcox_out[[1]]
train_test_dict = wilcox_out[[2]]
print(get_wilcox_list_median_val(train_val_dict))
print(get_wilcox_list_median_val(train_test_dict))
print(get_wilcox_list_num_sig(train_val_dict))
print(get_wilcox_list_num_sig(train_test_dict))
```
Here we will print out all values below 0.05, which are the variables between the testing and validation data that were significantly different.
```{r}
# Print out variables that had a p value we care about
for (i in seq_along(train_val_dict)) {
value <- train_val_dict[[i]]
name <- names(train_val_dict)[i]
if (value < 0.05) {
print(paste0("Value of ", name, " is ", value))
}
}
```
We will print these values out again but for the comparisons between the testing and training data.
```{r}
# Print out variables that had a p value we care about
for (i in seq_along(train_test_dict)) {
value <- train_test_dict[[i]]
name <- names(train_test_dict)[i]
if (value < 0.05) {
print(paste0("Value of ", name, " is ", value))
}
}
```
Here we will resample the fires list and see which resamples match our criteria to see if we can create a split that
has less differences between variables.
```{r}
# Create list of fire ids
eventids <- fire_boundaries$Event_ID
train_fires_list <- list(train_fires)
test_fires_list <- list(test_fires)
val_fires_list <- list(validation_fires)
set.seed(123)
i <- 2
# Create 25 random resamples
while (length(train_fires_list) < 26) {
samp <- sample(eventids)
train_events <- list()
test_events <- list()
val_events <- list()
for (event in samp){
# Checks to see if our resample was successful
if (length(train_events) == 0){
train_events <- append(train_events, event)
}
else if (sum(simple_fire_data$Event_ID %in% train_events) < nrow(simple_fire_data) * .65){
train_events <- append(train_events, event)
}
else if (length(test_events) == 0){
test_events <- append(test_events, event)
}
else if (sum(simple_fire_data$Event_ID %in% test_events) < nrow(simple_fire_data) * .17){
test_events <- append(test_events, event)
}
else{
val_events <- append(val_events, event)
}
}
if ((sum(simple_fire_data$Event_ID %in% val_events)) > 100){
# If resample was successful, add the new dataframes to a list
train_fire <- simple_fire_data %>%
filter(Event_ID %in% train_events)
test_fire <- simple_fire_data %>%
filter(Event_ID %in% test_events)
val_fire <- simple_fire_data %>%
filter(Event_ID %in% val_events)
valid = TRUE
for (var in variables){
if (all(is.na(train_fire[[var]])) || all(is.na(test_fire[[var]])) || all(is.na(val_fire[[var]]))){
valid = FALSE
}
}
if (valid){
train_fires_list[[i]] <- train_fire
test_fires_list[[i]] <- test_fire
val_fires_list[[i]] <- val_fire
i <- i + 1
}
}
}
```
Compare all resampled fire distributions to see which ones have the least differnces
between variables.
```{r}
# For resamples in list, find the one that scores the best on our metrics
best_combo <- 100
best_val <- 0
best_test <- 0
best_val_med <- 0
best_test_med <- 0
best_combo_ix <- 0
for (i in 1:26){
# Run the wilcox comparisons between fire types
wilcox = get_wilcox_output(test_fires_list[[i]], train_fires_list[[i]], val_fires_list[[i]], variables)
train_val = wilcox[[1]]
train_test = wilcox[[2]]
# Get output of wilcox tests
val_sig <- get_wilcox_list_num_sig(train_val)
test_sig <- get_wilcox_list_num_sig(train_test)
combo_sig <- val_sig + test_sig
# Store the combination if the fires score better then any previous combination
if (combo_sig < best_combo){
best_combo <- combo_sig
best_val <- val_sig
best_test <- test_sig
best_val_med <- get_wilcox_list_median_val(train_val)
best_test_med <- get_wilcox_list_median_val(train_test)
best_combo_ix <- i
}
}
```
Display best fire combination results
```{r}
orig_train_val_p <- get_wilcox_list_median_val(train_val_dict)
orig_train_test_p <- get_wilcox_list_median_val(train_test_dict)
cat(paste0("The sampling of fires with the lowest difference in variables was combination ", best_combo_ix))
cat(paste0("\nThis combination of fires had ", best_combo, " variables that were significantly different between the training/validation and the training/testing combinations.\n"))
cat(paste0(best_val, " of these variables were from the validation fires, and ", best_test, " of these were from the testing fires.\n"))
cat(paste0("The median P-Value for the validation fire comparison was ", best_val_med, ", while it was ", best_test_med, " for the testing fires.\n"))
cat(paste0("The original median P-Value for the validation fire comparison was ", orig_train_val_p, ", while it was ", orig_train_test_p, " for the testing fires."))
```
Here we assign the best combination to a new column in the dataframe so we can display
the differences between the two splits
```{r}
Test_Ids2 <- unique(test_fires_list[[best_combo_ix]]$Event_ID)
Val_Ids2 <- unique(val_fires_list[[best_combo_ix]]$Event_ID)
fire_boundaries['isTest2'] <-'Train'
fire_boundaries$isTest2[fire_boundaries$Event_ID %in% Test_Ids2]<-'Test'
fire_boundaries$isTest2[fire_boundaries$Event_ID %in% Val_Ids2]<-'Validation'
fire_boundaries['isTest2'] <- factor(fire_boundaries$isTest2)
```
Plot the differences
```{r}
plot1 <- ggplot() +
geom_sf(data=fire_boundaries, aes(color=isTest)) +
ggtitle("Original Distribution of Training, Testing\nand Validation Fires") +
theme(plot.title = element_text(hjust = 0.5))
plot2 <- ggplot() +
geom_sf(data=fire_boundaries, aes(color=isTest2)) +
ggtitle("Updated Distribution of Training, Testing\nand Validation Fires") +
theme(plot.title = element_text(hjust = 0.5))
grid.arrange(plot1, plot2, ncol = 2)
```
# Checking for Covariance
Here we make a simple linear model
```{r}
# Create a scaled simple dataset
simple_fire_data.sp <- simple_fire_data %>%
dplyr::select(variables) %>%
dplyr::mutate_if(is.numeric, scale) %>%
cbind(simple_fire_data['Event_ID'])
simple_fire_data_scaled <- simple_fire_data.sp
# Create a linear model and run a stepwise function to see which variables are dropped
fire_lm <- lm(post_ndvi2 ~ slope + chili + elevation + aspect + mtpi + precip + temp + pre_ndvi, data = simple_fire_data_scaled)
fire_step_lm <- step(fire_lm, direction = "backward")
summary(fire_step_lm)
```