Project

General

Profile

« Previous | Next » 

Revision 92ef8501

Added by Benoit Parmentier almost 11 years ago

multi timescale draft adding functions, Moran's I and std dev for grain contents

View differences:

climate/research/oregon/interpolation/multi_timescale_paper_interpolation.R
5 5
#Figures, tables and data for the  paper are also produced in the script.
6 6
#AUTHOR: Benoit Parmentier 
7 7
#CREATED ON: 10/31/2013  
8
#MODIFIED ON: 12/14/2013            
8
#MODIFIED ON: 12/18/2013            
9 9
#Version: 1
10 10
#PROJECT: Environmental Layers project                                     
11 11
#################################################################################################
......
39 39
#### FUNCTION USED IN SCRIPT
40 40

  
41 41
function_analyses_paper1 <-"contribution_of_covariates_paper_interpolation_functions_10222013.R"
42
function_analyses_paper2 <-"multi_timescales_paper_interpolation_functions_12122013.R"
42
function_analyses_paper2 <-"multi_timescales_paper_interpolation_functions_12182013.R"
43 43

  
44 44
##############################
45 45
#### Parameters and constants  
......
198 198
####################################
199 199
####### Now create figures #############
200 200

  
201
#figure 1: study area
202
#figure 2: methodological worklfow: outside R
203
#figure 3: LST climatology production: daily mean compared to monthly mean: 
204
#Figure 4. RMSE and MAE, monthly hold out for FSS and GAM methods
205
#Figure 5. Overtraining tendency, monhtly hold out
201
#figure 1: Study area OR
202
#Figure 2: LST climatology production: daily mean compared to monthly mean
203
#figure 3: Prediction procedures: direct, CAI and FSS (figure created outside R)
204
#Figure 4. Accuracy and monthly hold out for FSS and CAI procedures and GWR, Kriging and GAM methods.
205
#Figure 5. Overtraining tendency, difference between training and testing
206 206
#Figure 6: Spatial pattern of prediction for one day (3 maps)
207
#Figure 7: Spatial transects for one day (transect map + transect profiles)
208
#Figure 8: Image differencing and land cover: spatial patterns     
209
#Figure 9: Spatial lag profiles and stations data  
207
#Figure 7: Transect location (transect map)
208
#Figure 8: Transect profiles for one day 
209
#Figure 9: Image differencing and land cover: spatial patterns   
210
#Figure 10: LST and Tmax at stations, elevation and land cover.
211
#Figure 11: Spatial lag profiles and stations data  
212
#Figure 12: Daily deviation
213
#Figure 13: Spatial correlogram at stations, LST and elevation every 5 lags
210 214

  
211 215
################################################
212 216
######### Figure 1: Oregon study area, add labeling names to  Willamette Valley an Mountain Ranges?
......
403 407

  
404 408
dev.off()
405 409

  
406
#bwplot(cyl.f~mpg|gear.f,
407
#        ylab="Cylinders", xlab="Miles per Gallon", 
408
#        main="Mileage by Cylinders and Gears", 
409
#        layout=(c(1,3)))
410
     
410

  
411 411
################################################
412 412
######### Figure 6: Spatial pattern of prediction for one day (maps)
413 413

  
......
417 417
lf_list<-lapply(list_raster_obj_files[c("gam_daily","gam_CAI","gam_fss")],
418 418
                               FUN=function(x){x<-load_obj(x);x$method_mod_obj[[index]][[y_var_name]]})                           
419 419

  
420
#lf1 <- raster_prediction_obj_1$method_mod_obj[[index]][[y_var_name]] #select relevant raster images for the given dates
421
#lf4 <- raster_prediction_obj_4$method_mod_obj[[index]][[y_var_name]]
422
#lf7 <- raster_prediction_obj_7$method_mod_obj[[index]][[y_var_name]]
423

  
424 420
date_selected <- "20109101"
425 421
#methods_names <-c("gam","kriging","gwr")
426 422
methods_names <-c("gam_daily","gam_CAI","gam_FSS")
......
561 557
methods_name <-c("gam_daily","gam_CAI","gam_fss")
562 558
index<-244 #index corresponding to Sept 1
563 559
y_var_name <-"dailyTmax"
564
ref_mod <- 3 #mod1
565
alt_mod <- 6
560
ref_mod <- 3 #mod3
561
alt_mod <- 6 #mod6
566 562
file_format <- ".rst"
567 563
NA_flag_val <- -9999
568 564

  
......
587 583

  
588 584
LC_subset <- c("LC1","LC5","LC6","LC7","LC9","LC11")  
589 585
LC_names <- c("LC1_forest", "LC5_shrub", "LC6_grass", "LC7_crop", "LC9_urban","LC11_barren")
590
plot()
586
LC_s <- subset(s_raster,LC_subset)
587
names(LC_s) <- LC_names
588
plot(LC_s)
589

  
591 590
avl<-c(0,10,1,10,20,2,20,30,3,30,40,4,40,50,5,50,60,6,60,70,7,70,80,8,80,90,9,90,100,10)#Note that category 1 does not include 0!!
592 591

  
593 592
stat_list <- extract_diff_by_landcover(r_stack_diff,s_raster,LC_subset,LC_names,avl)
594 593

  
595
#stat_list <- extract_diff_by_landcover(s_raster,LC_subset,LC_names,avl)
594
#r_subset_name <- "elev_s"
595
#r_names <- c("elev_s")
596
#stat_list_elev <- extract_diff_by_landcover(r_stack_diff,s_raster,LC_subset,LC_names,avl)
596 597

  
597 598
#write_out_raster_fun(s_raster,out_suffix=out_prefix,out_dir=out_dir,NA_flag_val=-9999,file_format=".rst")
598 599

  
......
685 686
#dev.off()
686 687

  
687 688
################################################
688
#Figure 9: Spatial lag profiles and stations data  
689
#Figure 9: Tmax and LST averagees
690

  
691
names_tmp<-c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12")
692
LST_s<-subset(s_raster,names_tmp)
693
names_tmp<-c("nobs_01","nobs_02","nobs_03","nobs_04","nobs_05","nobs_06","nobs_07","nobs_08",
694
             "nobs_09","nobs_10","nobs_11","nobs_12")
695
LST_nobs<-subset(s_raster,names_tmp)
696

  
697
#LST_nobs<-mask(LST_nobs,LC_mask,filename="test2.tif")
698
#LST_s<-mask(LST_s,LC_mask,filename="test3.tif")
699
#c("Jan","Feb")
700
plot(LST_s)
701
plot(LST_nobs)
702

  
703
#Map 5: LST and TMax
704

  
705
#note differnces in patternin agricultural areas and 
706
min_values<-cellStats(LST_s,"min")
707
max_values<-cellStats(LST_s,"max")
708
mean_values<-cellStats(LST_s,"mean")
709
sd_values<-cellStats(LST_s,"sd")
710
#median_values<-cellStats(molst,"median") Does not extist
711
statistics_LST_s<-cbind(min_values,max_values,mean_values,sd_values) #This shows that some values are extremes...especially in October
712
LST_stat_data<-as.data.frame(statistics_LST_s)
713
rownames(LST_stat_data) <- month.abb
714
names(LST_stat_data)<-c("min","max","mean","sd")
715
# Statistics for number of valid observation stack
716
min_values<-cellStats(LST_nobs,"min")
717
max_values<-cellStats(LST_nobs,"max")
718
mean_values<-cellStats(LST_nobs,"mean")
719
sd_values<-cellStats(LST_nobs,"sd")
720
LST_nobs_stat_data<-cbind(min_values,max_values,mean_values,sd_values) #This shows that some values are extremes...especially in October
721
LST_nobs_stat_data <- as.data.frame(LST_nobs_stat_data)
722
rownames(LST_nobs_stat_data) <- month.abb
723

  
724
#X11(width=12,height=12)
725
#Plot statiscs (mean,min,max) for monthly LST images
726
plot(1:12,LST_stat_data$mean,type="b",ylim=c(-15,60),col="black",xlab="month",ylab="tmax (degree C)")
727
lines(1:12,LST_stat_data$min,type="b",col="blue")
728
lines(1:12,LST_stat_data$max,type="b",col="red")
729
text(1:12,LST_stat_data$mean,rownames(LST_stat_data),cex=1,pos=2)
730

  
731
legend("topleft",legend=c("min","mean","max"), cex=1.5, col=c("blue","black","red"),
732
       lty=1)
733
title(paste("LST statistics for Oregon", "2010",sep=" "))
734
#savePlot("lst_statistics_OR.png",type="png")
735

  
736
#Plot number of valid observations for LST
737
plot(1:12,LST_nobs_stat_data$mean,type="b",ylim=c(0,365),col="black",xlab="month",ylab="tmax (degree C)")
738
lines(1:12,LST_nobs_stat_data$min,type="b",col="blue")
739
lines(1:12,LST_nobs_stat_data$max,type="b",col="red")
740
text(1:12,LST_nobs_stat_data$mean,rownames(LST_stat_data),cex=1,pos=2)
741

  
742
legend("topleft",legend=c("min","mean","max"), cex=1.5, col=c("blue","black","red"),
743
       lty=1)
744
title(paste("LST number of valid observations for Oregon", "2010",sep=" "))
745
#savePlot("lst_nobs_OR.png",type="png")
746

  
747
#met_stations_obj <- load_obj(file.path(in_dir1,met_obj_file_1))
748
#met_stations_obj$monthly_query_ghcn_data
749
#
750

  
751
raster_obj <- load_obj(list_raster_obj_files$gam_CAI)
752
data_month <- (raster_obj$method_mod_obj[[1]]$data_month_s)
753
dates<-unique(raster_obj$tb_diagnostic_v$date)
754

  
755

  
756
#########################
757
#Figure
758
#LST for area with FOrest 50> and grass >50
759

  
760
########################
761
#Figure 
762

  
763
#get the  list of all prediction for a specific method
764
#list_lf <-extract_list_from_list_obj(load_obj(list_raster_obj_files$gam_CAI)$method_mod_obj,"dailyTmax") #getting objet
765
list_lf_gam_CAI <-extract_list_from_list_obj(load_obj(list_raster_obj_files[["gam_CAI"]])$method_mod_obj,"dailyTmax") #getting objet
766
list_lf_gam_fss <-extract_list_from_list_obj(load_obj(list_raster_obj_files[["gam_fss"]])$method_mod_obj,"dailyTmax") #getting objet
767

  
768

  
769

  
770
#nb_lag <- 10
771
list_filters<-lapply(1:nb_lag,FUN=autocor_filter_fun,f_type="queen") #generate lag 10 filters
772
list_param_stat_moran <- list(filter=list_filters[[10]],lf_list=list_lf_gam_CAI)
773
tt <- stat_moran_std_raster_fun(1,list_param=list_param_stat_moran)
774
tt <- mclapply(1:11, list_param=list_param_stat_moran, FUN=stat_moran_std_raster_fun,mc.preschedule=FALSE,mc.cores = 11) #This is the end bracket from mclapply(...) statement
775
list_param_stat_moran <- list(filter=list_filters[[10]],lf_list=list_lf_gam_fss)
776
tt_fss <- mclapply(1:365, list_param=list_param_stat_moran, FUN=stat_moran_std_raster_fun,mc.preschedule=FALSE,mc.cores = 11) #This is the end bracket from mclapply(...) statement
777
save(tt_fss,file=file.path(out_dir,"moran_std_tt_fss.RData"))
778

  
779
tx<- do.call(rbind,tt_fss)
780

  
781
mo<-as.integer(strftime(dates, "%m"))          # current month of the date being processed
782

  
783
tt_fss2 <- load_obj("moran_std_tt_fss2.RData")
784
tx<- do.call(rbind,tt_fss2)
785
dates_proc<-strptime(dates, "%Y%m%d")   # interpolation date being processed
786

  
787
dates_proc <- as.data.frame(dates_proc)
788
dates_proc$index <- 1:365
789
tx2 <- merge(tx,dates_proc,by="index")
790
tx2$month <- as.integer(strftime(tx2$dates_proc, "%m"))          # current month of the date being processed
791
names(tx2) <- c("index","moranI","std","pred_mod","date","month")
792
t<-melt(tx2,
793
          #measure=mod_var, 
794
          id=c("pred_mod","month"),
795
          na.rm=F)
796
#t$value<-as.numeric(t$value) #problem with char!!!
797
tb_mod_m_avg <-cast(t,pred_mod+month~variable,mean) #monthly mean for every model
798

  
799
#mo<-as.integer(strftime(date_proc, "%m"))          # current month of the date being processed
800
#day<-as.integer(strftime(date_proc, "%d"))
801
#year<-as.integer(strftime(date_proc, "%Y"))
802
# end of pasted
803
x<-subset(tb_mod_m_avg,pred_mod=="mod7")
804

  
805
plot(x$month,x$moranI,type="b",col="blue")
806
par(new=TRUE)              # key: ask for new plot without erasing old
807
plot(x$month,x$std,type="b",col="red",axes=F)
808
  #axis(4,xlab="",ylab="elevation(m)")  
809
axis(4,cex=1.2)
810
#now summarize by month...
811

  
812
#plot(data_month$TMax,add=TRUE)
813
#list_data_s <-extract_list_from_list_obj(load_obj(list_raster_obj_files$gam_CAI)$validation_mod_obj,"data_s")
814
#list_data_v <-extract_list_from_list_obj(load_obj(list_raster_obj_files$gam_CAI)$validation_mod_obj,"data_v")
815

  
816
#data_s <- list_data_s[[1]]
817
#res_m <- data_s$dailyTmax - data_s$mod3
818
#SSRES_m <- sum((res_m)^2,na.rm=T)
819
#res_dev <- data_s$dailyTmax - data_s$mod3_del
820
#SSRES_dev <- sum((res_dev)^2,na.rm=T)
821
#SST <- sum((data_s$dailyTmax - mean(data_s$dailyTmax))^2,na.rm=T)
822

  
823
#1- (SSRES_m/SST)
824
#1- (SSRES_dev/SST)
825

  
826
##############
827

  
828
lf_delta_gam_fss <-extract_list_from_list_obj(load_obj(list_raster_obj_files[["gam_fss"]])$method_mod_obj,"delta") #getting objet
829

  
830
test01 <-stack(lf_delta_gam_fss[[287]]) #Ot.14
831

  
832
test0 <-stack(lf_delta_gam_fss[[288]]) #Ot.15
833
test1 <-stack(lf_delta_gam_fss[[289]]) #Ot.16
834
test2<-stack(lf_delta_gam_fss[[290]]) #Ot.17
835

  
836
plot(test01)
837

  
838
plot(test0)
839
plot(test1)
840
plot(test2)
689 841

  
690
index<-244 #index corresponding to Sept 1 #For now create Moran's I for only one date...
842
################################################
843
#Figure 10: Spatial lag profiles and stations data  
691 844

  
845
index<-244 #index corresponding to Sept 1 #For now create Moran's I for only one date...
846
index<-1
692 847
lf_moran_list<-lapply(list_raster_obj_files[c("gam_daily","gam_CAI","gam_fss")],
693 848
                               FUN=function(x){x<-load_obj(x);x$method_mod_obj[[index]][[y_var_name]]})                           
694 849
#lf1 <- raster_prediction_obj_1$method_mod_obj[[index]][[y_var_name]] #select relevant raster images for the given dates
695 850

  
696
date_selected <- "20109101"
851
date_selected <- "20100901"
852
date_selected <- "20100101"
697 853
#methods_names <-c("gam","kriging","gwr")
698 854
methods_names <-c("gam_daily","gam_CAI","gam_FSS")
699 855

  
......
703 859

  
704 860
names_layers <-c("mod1 = lat*long","mod2 = lat*long + LST","mod3 = lat*long + elev","mod4 = lat*long + N_w*E_w",
705 861
                 "mod5 = lat*long + elev + DISTOC","mod6 = lat*long + elev + LST","mod7 = lat*long + elev + LST*FOREST")
862

  
863

  
706 864
nb_lag <-10
707
list_filters<-lapply(1:nb_lag,FUN=autocor_filter_fun,f_type="queen") #generate lag 10 filters
708
#moran_list <- lapply(list_filters,FUN=Moran,x=r)
709
list_moran_df <- vector("list",length=length(lf))
710
for (j in 1:length(lf)){
711
  r_stack <- stack(lf[[j]])
712
  list_param_moran <- list(list_filters=list_filters,r_stack=r_stack) #prepare parameters list for function
713
  #moran_r <-moran_multiple_fun(1,list_param=list_param_moran)
714
  nlayers(r_stack) 
715
  moran_I_df <-mclapply(1:nlayers(r_stack), list_param=list_param_moran, FUN=moran_multiple_fun,mc.preschedule=FALSE,mc.cores = 10) #This is the end bracket from mclapply(...) statement
716

  
717
  moran_df <- do.call(cbind,moran_I_df) #bind Moran's I value 10*nlayers data.frame
718
  moran_df$lag <-1:nrow(moran_df)
865
#lf
866

  
867
calculate_moranI_profile <- function(nb_lag,lf){
868
  list_filters<-lapply(1:nb_lag,FUN=autocor_filter_fun,f_type="queen") #generate lag 10 filters
869
  #moran_list <- lapply(list_filters,FUN=Moran,x=r)
870
  list_moran_df <- vector("list",length=length(lf))
871
  for (j in 1:length(lf)){
872
    r_stack <- stack(lf[[j]])
873
    list_param_moran <- list(list_filters=list_filters,r_stack=r_stack) #prepare parameters list for function
874
    #moran_r <-moran_multiple_fun(1,list_param=list_param_moran)
875
    nlayers(r_stack) 
876
    moran_I_df <-mclapply(1:nlayers(r_stack), list_param=list_param_moran, FUN=moran_multiple_fun,mc.preschedule=FALSE,mc.cores = 10) #This is the end bracket from mclapply(...) statement
877

  
878
    moran_df <- do.call(cbind,moran_I_df) #bind Moran's I value 10*nlayers data.frame
879
    moran_df$lag <-1:nrow(moran_df)
719 880
  
720
  list_moran_df[[j]] <- moran_df
721

  
881
    list_moran_df[[j]] <- moran_df
882
  }
722 883
}
723 884

  
724 885
names(list_moran_df)<-c("gam_daily","gam_CAI","gam_fss")
......
735 896

  
736 897
dd_combined<- do.call(rbind,list_dd)
737 898

  
738
layout_m<-c(4,3) #one row two columns
899
layout_m<-c(2,4) #one row two columns
739 900

  
740 901
png(paste("Figure_9_spatial_correlogram_tmax_prediction_models_gam_levelplot_",date_selected,out_prefix,".png", sep=""),
741 902
    height=480*layout_m[1],width=480*layout_m[2])
742

  
903
par(mfrow=layout_m)
743 904
p<-xyplot(data ~ lag | which , data=dd_combined,group=method_v,type="b", as.table=TRUE,
744 905
          pch=1:3,auto.key=list(columns=3,cex=1.5,font=2),
745 906
          par.settings = list(
......
765 926

  
766 927
dev.off()
767 928

  
929
LST_s <- subset(s_raster,c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12"))
930
LST1 <- subset(LST_s,1)
931
test<-stack(LST_s,elev)
932
names(test) <- c("mm_01","mm_02","mm_03","mm_04","mm_05","mm_06","mm_07","mm_08","mm_09","mm_10","mm_11","mm_12","elev")
933
x_cor <-layerStats(test,stat="pearson",na.rm=T)
934
corr(values(LST1),values(elev))
935
plot(1:12,x_cor[[1]][1:12,13],type="b",ylab="corelation",xlab="month",main="correlation between elevation and LST")
936

  
768 937
###################### END OF SCRIPT #######################
769 938

  
770 939
# #LAND COVER INFORMATION
climate/research/oregon/interpolation/multi_timescales_paper_interpolation_functions.R
5 5
#Functions used in the production of figures and data for the multi timescale paper are recorded.
6 6
#AUTHOR: Benoit Parmentier                                                                      #
7 7
#DATE CREATED: 11/25/2013            
8
#DATE MODIFIED: 12/12/2013            
8
#DATE MODIFIED: 12/16/2013            
9 9
#Version: 1
10 10
#PROJECT: Environmental Layers project                                       #
11 11
#################################################################################################
......
184 184
  return(moran_v)
185 185
}
186 186

  
187
#Modfiy...temporal plot for 1,10,20
188
stat_moran_std_raster_fun<-function(i){
189
  list_var_stat<-vector("list",ncol(lf_list))
187
#Modfiy...to allow any stat: min, max, mean,sd etc.
188
stat_moran_std_raster_fun<-function(i,list_param){
189
  f <-list_param$filter
190
  lf_list <- list_param$lf_list[[i]]
191
  list_var_stat<-vector("list",length(lf_list))
190 192
  for (k in 1:length(lf_list)){
191 193
    
192
    raster_pred<-raster(lf_list[i,k]) 
193
    tmp_rast<-mask(raster_pred,mask_rast)
194
    raster_pred<-raster(unlist(lf_list[k])) 
195
    #tmp_rast<-mask(raster_pred,mask_rast)
194 196
    #tmp_rast<-raster_pred
195
    raster_pred2<-tmp_rast
197
    #raster_pred2<-tmp_rast
198
    
199
    t1<-cellStats(raster_pred,na.rm=TRUE,stat=sd)    #Calculating the standard deviation for the     
200
    m1 <- Moran(x=raster_pred,w=f) #Calculating Moran's I with window of 3 an default Queen's case
201
    #m1 <- Moran(raster_pred,w=3) #Calculating Moran's I with window of 3 an default Queen's case
196 202
    
197
    t1<-cellStats(raster_pred,na.rm=TRUE,stat=sd)    #Calculating the standard deviation for the 
198
    m1<-Moran(raster_pred,w=3) #Calculating Moran's I with window of 3 an default Queen's case
199 203
    stat<-as.data.frame(t(c(m1,t1)))
200 204
    names(stat)<-c("moranI","std")
201 205
    list_var_stat[[k]]<-stat
202 206
  }
203 207
  dat_var_stat<-do.call(rbind,list_var_stat)
204 208
  dat_var_stat$lf_names<-names(lf_list)
205
  dat_var_stat$dates<-dates[i]
209
  dat_var_stat$index<- i
206 210
  return(dat_var_stat)
207 211
}
208 212

  
......
316 320
  return(list_zones)
317 321
}
318 322
   
319
## Utilit function to quickly write out a stack or brick of rasterlayer to disk using names of layers
323
## Utility function to quickly write out a stack or brick of rasterlayer to disk using names of layers
320 324
# Note that each layers are written individually, default NA value and format is provided
321 325
write_out_raster_fun <-function(r_stack,out_suffix,out_dir,NA_flag_val=-9999,file_format=".rst"){
322 326
  for(i in 1:nlayers(r_stack)){

Also available in: Unified diff