source: src/htune_EOF.R @ 158

Last change on this file since 158 was 71, checked in by htune, 8 years ago

New htune_EOF.R + update for ARPCLIMAT (benchmark: modify default; serie: bugfix for multiwaves and add option of cleaning MUSC simulations) + update of ExeterUQ/Demonstrations/RomainExample.R (Romain Roehrig)

  • Property svn:executable set to *
File size: 10.5 KB
Line 
1#Step 1 Source files and load data
2source('BuildEmulator/BuildEmulator.R')
3source("BuildEmulator/DannyDevelopment.R")
4source("BuildEmulator/Rotation.R")
5source("HistoryMatching/HistoryMatchingFast.R")
6library("ncdf4") # to manipulate ncdf
7
8#########################
9# First settings
10
11case_name="AYOTTE"
12subcase_name="24SC"
13variable="theta" # qv ou rneb # Don't use "var" which is un R function !!!
14
15WAVEN=1
16
17source('htune_case_setup.R')
18file = paste("WAVE",WAVEN,"/Wave",WAVEN,".RData",sep="")
19load(file)
20
21casesu <-case_setup(case_name)
22NLES=casesu[1]
23TimeLES=casesu[2]
24TimeSCM=casesu[3]
25
26NRUNS=dim(wave_param_US)[1]
27nparam=dim(wave_param_US)[2]-1
28
29#########################
30# Get vertical grid to project everything
31print("Get vertical grid")
32
33file=paste("WAVE",WAVEN,"/",case_name,"/",subcase_name,"/SCM_",WAVEN,"-001.nc",sep="")
34print(file)
35nc =  nc_open(file)
36zf = ncvar_get(nc,"zf")
37zfSCM = zf[,1]
38nlev = length(zfSCM)
39nc_close(nc)
40
41# Get vertical grid of LES
42file = paste("LES/",case_name,"/",subcase_name,"/LES",0,".nc",sep="")
43nc =  nc_open(file)
44zfLES = ncvar_get(nc,"zf")
45nc_close(nc)
46
47# Extract the SCM vertical below the top of the LES
48zgrid = rep(0,nlev)
49ii = 1
50maxzLES = max(zfLES)
51minzLES = min(zfLES)
52for (k in 1:nlev) {
53  if ( zfSCM[k] <= maxzLES & zfSCM[k] >= minzLES ) {
54    zgrid[ii] = zfSCM[k]
55    ii = ii +1
56  }
57}
58zgrid=zgrid[1:ii-1]
59nlevout = length(zgrid)[1]
60
61print("Chosen vertical grid:")
62print(zgrid)
63
64#########################
65# Interpolate LES data on the chosen vertical grid
66print("Interpolate LES data on the chosen vertical grid")
67
68dataLES = matrix(0,ncol=NLES+2,nrow=nlevout)
69dataLES[,1] = zgrid
70
71for ( k in 0:(NLES-1) ) {
72  file = paste("LES/",case_name,"/",subcase_name,"/LES",k,".nc",sep="")
73  nc =  nc_open(file)
74  zf = ncvar_get(nc,"zf")
75  data = ncvar_get(nc,variable)
76  nc_close(nc)
77
78  tempFun <- approxfun(zf,data[,TimeLES],yleft=data[1,TimeLES])
79  dataLES[,k+2] <- tempFun(zgrid) 
80 
81#  if ( k == 0 ) {
82#    # Check the interpolation
83#    plot(x=dataLES[,k+2],y=dataLES[,1],type='l')
84#    lines(x=data[,TimeLES],y=zf,col="red")
85#  }
86}
87
88# Compute observation uncertainty
89for ( k in 1:nlevout ) {
90  dataLES[k,NLES+2] = sd(dataLES[k,2:NLES+1])^2
91}
92
93#save(dataLES,file="dataLES.RData")
94#load("dataLES.RData")
95
96#########################
97# Interpolate SCM data on the chosen vertical grid
98print("Interpolate SCM data on the chosen vertical grid")
99
100dataSCM = matrix(0,ncol=NRUNS+1,nrow=nlevout)
101dataSCM[,1] = zgrid
102
103for ( k in 1:NRUNS ) {
104  i = sprintf("%03i",k)
105  file=paste("WAVE",WAVEN,"/",case_name,"/",subcase_name,"/SCM_",WAVEN,"-",i,".nc",sep="")
106  nc =  nc_open(file)
107  zf = ncvar_get(nc,"zf")
108  data = ncvar_get(nc,variable)
109  nc_close(nc)
110  nlev = dim(zf)[1]
111 
112  # yright, yleft to constrain what happen at the edge. Not clear yet how to do it properly
113  tempFun <- approxfun(zf[,TimeSCM],data[,TimeSCM],yright=data[1,TimeSCM],yleft=data[nlev,TimeSCM])
114  dataSCM[,k+1] <- tempFun(zgrid) 
115 
116#  if ( k == 0 ) {
117#    # Check the interpolation
118#    plot(x=dataSCM[,k+2],y=dataSCM[,1],type='l')
119#    lines(x=data[,TimeSCM],y=zf,col="red")
120#  }
121 
122}
123
124# Compute SCM ensemble mean
125SCMmean = rep(0,nlevout)
126for ( k in 1:nlevout ) {
127  SCMmean[k] = mean(dataSCM[k,2:NRUNS+1])
128}
129
130#save(dataSCM,file="dataSCM.RData")
131#load("dataSCM.RData")
132
133# Plotting the ensemble profiles
134pdf(file=paste("WAVE",WAVEN,"/EOFs_InputProfiles.pdf",sep=""))
135plot(x=dataLES[,2],y=dataLES[,1],type='l',lwd=2,col=2,xlab=variable,ylab="Altitude",xlim=c(min(dataSCM[,2:NRUNS+1]),max(dataSCM[,2:NRUNS+1])))
136title(main=paste("WAVE #",WAVEN,"- Profiles",sep=""))
137depths <- dataLES[,1]
138for(j in 2:NRUNS+1){
139  lines(x=dataSCM[,j],y=depths,col=8,lwd=0.5)
140}
141lines(x=dataLES[,2],y=dataLES[,1],lwd=2,col=2)
142dev.off() # Closing the pdf file
143
144# Plotting the ensemble profile errors
145pdf(file=paste("WAVE",WAVEN,"/EOFs_InputProfiles_errors.pdf",sep=""))
146plot(x=dataLES[,2]-dataLES[,2],y=dataLES[,1],type='l',lwd=2,col=2,xlab=variable,ylab="Altitude",xlim=c(min(dataSCM[,2:NRUNS+1]-dataLES[,2]),max(dataSCM[,2:NRUNS+1]-dataLES[,2])))
147title(main=paste("WAVE #",WAVEN,"- Profile errors",sep=""))
148depths <- dataLES[,1]
149for(j in 2:NRUNS+1){
150  lines(x=dataSCM[,j]-dataLES[,2],y=depths,col=8,lwd=0.5)
151}
152dev.off() # Closing the pdf file
153
154# Plotting the ensemble profile anomalies
155pdf(file=paste("WAVE",WAVEN,"/EOFs_InputProfiles_anomalies.pdf",sep=""))
156plot(x=SCMmean-SCMmean,y=dataLES[,1],type='l',lwd=2,col=1,xlab=variable,ylab="Altitude",xlim=c(min(dataSCM[,2:NRUNS+1]-SCMmean),max(dataSCM[,2:NRUNS+1]-SCMmean)))
157title(main=paste("WAVE #",WAVEN,"- Profile anomalies",sep=""))
158depths <- dataLES[,1]
159for(j in 2:NRUNS+1){
160  lines(x=dataSCM[,j]-SCMmean,y=depths,col=8,lwd=0.5)
161}
162dev.off() # Closing the pdf file
163
164#Step 2 Extract the fields you want, ie remove the first column which contains the altitude vector
165SCMdata <- dataSCM[,-1]
166
167#Step 3: Centre the data and find the Singular vectors (EOFs)
168SCMsvd <- CentreAndBasis(SCMdata)
169pdf(file=paste("WAVE",WAVEN,"/EOFs.pdf",sep=""))
170par(mfrow=c(3,3))
171for ( i in 1:9 ) {
172  plot(x=SCMsvd$tBasis[,i],y=dataSCM[,1],type='l',xlab=paste("EOF #",i,sep=""),ylab="Altitude")
173}
174title(main=paste("WAVE #",WAVEN,"- 9 first EOFs",sep=""),outer=TRUE)
175dev.off() # Closing the pdf file
176
177#Step 4: Set a discrepancy variance and check the performance of basis reconstructions
178Disc <- diag(0.01,nlevout) # To be thought about
179DiscInv <- GetInverse(Disc)
180attributes(DiscInv)
181ObsDat <- dataLES[,2] - SCMsvd$EnsembleMean
182SCMsvd <- CentreAndBasis(SCMdata)
183pdf(file=paste("WAVE",WAVEN,"/EOF_ExplainedVariance.pdf",sep=""))
184par(mfrow=c(1,2), mar = c(4,4,2,4))
185vSVD <- VarMSEplot(SCMsvd, ObsDat, weightinv = DiscInv, ylim = c(0,80), qmax = NULL)
186title(main=paste("WAVE #",WAVEN,"- Cumulated explained variance",sep=""),outer=TRUE)
187abline(v = which(vSVD[,2] > 0.95)[1])
188
189#Step 5: Rotate the basis for optimal calibration
190rotSCM <- RotateBasis(SCMsvd, ObsDat, kmax = 4, weightinv = DiscInv, v = c(0.35,0.15,0.1,0.1,0.1), vtot = 0.95, MaxTime = 10)
191
192#save(rotSCM,file="rotSCM.RData")
193#load("rotSCM.RData")
194
195vROT <- VarMSEplot(rotSCM, ObsDat, weightinv = DiscInv, ylim = c(0,80), qmax = NULL)
196abline(v = which(vROT[,2] > 0.95)[1])
197dev.off() # Closing the pdf file
198qROT <- which(vROT[,2] > 0.95)[1]
199print(paste("Number of rotated EOFs that are retained: ",qROT,sep=""))
200
201# Plotting rotated EOFs
202pdf(file=paste("WAVE",WAVEN,"/rotEOFs.pdf",sep=""))
203par(mfrow=c(3,3), mar=c(4,4,1,1))
204for (i in 1:9) {
205  plot(x=rotSCM$tBasis[,i],y=dataSCM[,1],type='l',xlab=paste("EOF #",sprintf("%i",i),sep=""),ylab="Altitude")
206}
207title(main=paste("WAVE #",WAVEN,"- 9 first rotated EOFs",sep=""),outer=TRUE)
208dev.off() # Closing the pdf file
209
210#Step 6: Emulate the basis coefficients and tune emulators!
211tDataSCM <- GetEmulatableDataWeighted(Design = wave_param_US[,-1], EnsembleData = rotSCM, HowManyBasisVectors = qROT, weightinv = DiscInv)
212StanEmsSCM <- InitialBasisEmulators(tDataSCM, HowManyEmulators=qROT,TryFouriers=TRUE)
213# If it seems not working, relaunch source(*) at the script beginning
214# A fast check that it worked  (if NULL, there is a problem...)
215names(StanEmsSCM[[1]])
216
217# To remove heavy data, especially if you want to save the emulators
218#for ( i in 1:qROT ) {
219#  StanEmsSCM[[i]]$StanModel <- NULL
220#}
221#save(StanEmsSCM,file="StanEmsSCM.RData")
222#load("StanEmsSCM.RData")
223
224for ( i in 1:qROT ) {
225  pdf(file=paste("WAVE",WAVEN,"/LOO_EOF",sprintf("%2.2i",i),".pdf",sep=""))
226  tLOOs1 <- LOO.plot(StanEmulator = StanEmsSCM[[i]], ParamNames = colnames(StanEmsSCM[[i]]$Design))
227  title(main=paste("WAVE #",WAVEN,"- LOO - EOF #",i,sep=""),outer=TRUE)
228  dev.off() # Closing the pdf file
229}
230
231#Step 7: History Matching
232###NOTE IF WE WILL RULE OUT ALL OF SPACE, THERE IS A DISCREPANCY SCALING STEP TO AVOID THIS, SEE SPATIALDEMO AND USE CAUTION!
233# At this stage no error for the obs
234#FieldHM <- PredictAndHM(rotSCM, ObsDat, StanEmsSCM, tDataSCM, ns = 10000, Error = 0*diag(nlevout), Disc = Disc, weightinv = DiscInv)
235FieldHM <- PredictAndHM(rotSCM, ObsDat, StanEmsSCM, tDataSCM, ns = 10000, Error = diag(dataLES[,NLES+2]), Disc = Disc, weightinv = DiscInv)
236print("Summary of the implausibility:")
237summary(FieldHM$impl)
238#FieldHM$bound
239
240# Plotting the 10 best emulated profiles (among the 10000) and the best one (in blue)
241pdf(file=paste("WAVE",WAVEN,"/EOFs_best.pdf",sep=""))
242par(mfrow = c(1,1))
243plot(x=dataLES[,2],y=dataLES[,1],type='l',lwd=2,col=2,xlab=variable,ylab="Altitude",xlim=c(min(dataSCM[,2:NRUNS+1]),max(dataSCM[,2:NRUNS+1])))
244title(main=paste("WAVE #",WAVEN,"- Best (?) profiles",sep=""))
245for(j in 2:NRUNS+1){
246  lines(x=dataSCM[,j],y=dataSCM[,1],col=8,lwd=0.5)
247}
248lines(x=dataLES[,2],y=dataLES[,1],type='l',lwd=2,col=2)
249
250inds <- which(FieldHM$impl <= quantile(FieldHM$impl, probs = 0.001)) # plot 10 profiles with the lowest implausibility
251for(k in inds){
252  anss <- Reconstruct(FieldHM$Expectation[k,],rotSCM$tBasis[,1:qROT])+rotSCM$EnsembleMean
253  lines(x=anss,y=dataSCM[,1],col="green",lwd=1.5)
254}
255ans <- Reconstruct(FieldHM$Expectation[which.min(FieldHM$impl),],rotSCM$tBasis[,1:qROT])+rotSCM$EnsembleMean
256lines(x=ans,y=dataSCM[,1],col="blue",lwd=1.5) # adding best run
257dev.off() # Closing the pdf file
258
259# Create density plot
260source("HistoryMatching/HistoryMatching.R")
261source("HistoryMatching/impLayoutplot.R")
262ImpData <- cbind(FieldHM$Design, FieldHM$impl)
263# First Version
264ImpList <- CreateImpList(whichVars = 1:nparam, VarNames = colnames(tDataSCM)[1:nparam], ImpData, nEms=qROT, Resolution=c(15,15), whichMax=1, Cutoff=FieldHM$bound)
265imp.layoutm11(ImpList,VarNames = colnames(tDataSCM)[1:nparam],VariableDensity=TRUE,newPDF=TRUE,the.title=paste("WAVE",WAVEN,"/NROY_v1.pdf",sep=""),newPNG=FALSE,newJPEG=FALSE,newEPS=FALSE,Points=NULL)
266
267# Second Version
268ImpList <- CreateImpList(whichVars = 1:nparam, VarNames = colnames(tDataSCM)[1:nparam], ImpData, nEms=1, Resolution=c(15,15), whichMax=1, Cutoff=FieldHM$bound)
269tMaxImp <- max(FieldHM$impl)
270tbound <- FieldHM$bound
271breakVec <- c(ceiling(seq(from=0,to=tbound,len=7)) , tMaxImp+1)
272imp.layoutm11(ImpList,VarNames = colnames(tDataSCM)[1:nparam],VariableDensity=FALSE,newPDF=TRUE,the.title=paste("WAVE",WAVEN,"/NROY_v2.pdf",sep=""),newPNG=FALSE,newJPEG=FALSE,newEPS=FALSE,Points=NULL)
273
274# assembling pdf files into just one
275# At this time, it seems not to work when launch with Rscript
276#system(paste("cd WAVE",WAVEN,"; pdfjoin -o results.pdf EOFs_InputProfiles.pdf EOFs_InputProfiles_errors.pdf EOFs_InputProfiles_anomalies.pdf EOFs.pdf EOF_ExplainedVariance.pdf rotEOFs.pdf LOO_EOF*.pdf EOFs_best.pdf NROY_v1.pdf NROY_v2.pdf",sep=""))
277#system(paste("cd WAVE",WAVEN,"; rm -f EOFs_InputProfiles.pdf EOFs_InputProfiles_errors.pdf EOFs_InputProfiles_anomalies.pdf EOFs.pdf EOF_ExplainedVariance.pdf rotEOFs.pdf LOO_EOF*.pdf EOFs_best.pdf NROY_v1.pdf NROY_v2.pdf",sep=""))
Note: See TracBrowser for help on using the repository browser.