content
stringlengths
0
14.9M
filename
stringlengths
44
136
phi.test <- function(yuima, H0, H1, phi, print=FALSE,...){ phiname <- deparse(substitute(phi)) if(missing(phi)){ phi <- function(x) 1-x+x*log(x) phiname <- "1-x+x*log(x)" } d.size <- yuima@[email protected] n <- length(yuima)[1] env <- new.env() assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) for(t in 1:(n-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) est <- FALSE if(missing(H1)){ cat("\nestimating parameters via QMLE...\n") H1 <- coef(qmle(yuima, ...)) est <- TRUE } g0 <- quasiloglvec(yuima=yuima, param=H0, print=print, env) g1 <- quasiloglvec(yuima=yuima, param=H1, print=print, env) y <- exp(g1-g0) div <- mean(phi(y), na.rm=TRUE) stat <- 2*sum(phi(y), na.rm=TRUE) df <- length(H0) val <- list(div=div, stat=stat, H0=H0, H1=H1, phi=phiname, phi=phi, pvalue=1-pchisq(stat, df=df), df=df,est=est) attr(val, "class") <- "phitest" return( val ) } print.phitest <- function(x,...){ symnum(x$pvalue, corr = FALSE, na = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", "**", "*", ".", " "))->Signif cat(sprintf("Phi-Divergence test statistic based on phi = '%s'\n",x$phi) ) nm <- names(x$H0) cat("H0: ") cat(sprintf("%s = %s", nm, format(x$H0,digits=3,nsmall=3))) cat("\nversus\n") cat("H1: ") cat(sprintf("%s = %s", nm, format(x$H1[nm],digits=3,nsmall=3))) if(x$est) cat("\nH1 parameters estimated using QMLE") cat(sprintf("\n\nTest statistic = %s, df = %d, p-value = %s %s\n", format(x$stat,digits=2,nsmall=3), x$df, format(x$pvalue), Signif)) cat("---\nSignif. codes: ", attr(Signif, "legend"), "\n") }
/scratch/gouwar.j/cran-all/cranData/yuima/R/phi.test.R
# poisson.random.sampling # returns sample of data using poisson sampling setGeneric("poisson.random.sampling", function(x, rate, n) standardGeneric("poisson.random.sampling") ) setMethod("poisson.random.sampling", "yuima.data", function(x, rate, n){ Data <- get.zoo.data(x) if(missing(rate)){ rate <- rep(0.01,length(Data)) } for(i in 1:(length(Data))) { T <- end(Data[[i]])-start(Data[[i]]) Num <- length(Data[[i]]) deltat <- T /(Num-1) # expectation value of length Elength <- T*n*rate[i] ## make random numbers following exponential distribution Time <- diffinv(rexp(Elength,rate=deltat*n*rate[i])) # make up a deficit while(Time[length(Time)]< Num){ # adding random numbers (by 10% of Elength) Time2 <- diffinv(rexp(trunc(Elength/10+1),rate=deltat*n*rate[i]))+Time[length(Time)] # restrain duplication Time <- append(Time,Time2[-1]) } ## making time index # get rid of first element of X and elements that over n # round Time to unit xTime<-trunc(Time[0<Time & Num>Time]) # get rid of elements of value = 0 xTime<-xTime[0<xTime] # time index : (xTime-1)*deltat(X) idx <- unique(xTime) Data[[i]] <- Data[[i]][idx] } return(setData(original.data=Data)) } ) setMethod("poisson.random.sampling","yuima",function(x,rate,n) return(poisson.random.sampling(x@data,rate,n)))
/scratch/gouwar.j/cran-all/cranData/yuima/R/poisson.random.sampling.R
# Podolskij-Ziggel's Jump Test pz.test <- function(yuima, p = 4, threshold = "local", tau = 0.05){ data <- get.zoo.data(yuima) d.size <- length(data) adx <- vector(d.size,mode="list") for(d in 1:d.size){ X <- as.numeric(data[[d]]) idt <- which(is.na(X)) if(length(idt>0)){ X <- X[-idt] } if(length(X)<2) { stop("length of data (w/o NA) must be more than 1") } adx[[d]] <- abs(diff(X)) } n <- sapply(adx, "length") if(threshold == "local"){ thr <- local_univ_threshold(data) }else if(threshold == "PZ"){ thr <- 2.3^2 * mpv(yuima, r = c(1, 1)) * n^(-0.8) }else{ thr <- threshold } # core part result <- vector(d.size, mode = "list") for(d in 1:d.size){ # thresholding tr.idx <- (adx[[d]]^2 <= thr[[d]]) eta <- sample(c(1 - tau, 1 + tau), size = n[d], replace = TRUE) numer <- sum(adx[[d]]^p * (1 - eta * tr.idx)) denom <- tau * sqrt(sum(adx[[d]]^(2*p) * tr.idx)) PZ <- numer/denom pval <- pnorm(PZ,lower.tail=FALSE) result[[d]] <- list(statistic=c(PZ=PZ),p.value=pval, method="Podolskij-Ziggel jump test", data.names=paste("x",d,sep="")) class(result[[d]]) <- "htest" } return(result) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/pz.test.R
##:: function qgv ##:: Estimating the local Holder exponent of the path and the constant qgv<- function(yuima, filter.type="Daubechies", order=2, a=NULL){ call <- match.call() if(missing(yuima)){ yuima.stop("yuima object is missing.") } # if(class(yuima)!="yuima"){ if(!inherits(yuima,"yuima")){ yuima.stop("an object of class yuima is needed.") } Ddiffx0 <- D(yuima@model@diffusion[[1]],yuima@[email protected]) == 0 Ddifft0 <- D(yuima@model@diffusion[[1]],yuima@[email protected]) == 0 bconst<-FALSE Hconst<-FALSE diffnoparam<-length(yuima@model@parameter@diffusion)==0 if (Ddiffx0 & Ddifft0 & diffnoparam){ if(eval(yuima@model@diffusion[[1]])==0){ yuima.stop("the model has no fractional part.") } bconst<-TRUE } y<-yuima@model@drift dx <- D(y,yuima@[email protected]) bt <- D(y,yuima@[email protected])==0 bxx <- D(dx,yuima@[email protected])==0 dbx <- D(yuima@model@diffusion[[1]],yuima@[email protected])==0 dbt <- D(yuima@model@diffusion[[1]],yuima@[email protected])==0 isfOU<-(bxx && bt) && (dbx && dbt) if (!is.na(yuima@model@hurst)){ yuima.warn("No Hurst exponent will be estimated") Hconst<-TRUE } H <- yuima@model@hurst sdH<-NA if(Hconst & bconst){ x<-c(H,eval(yuima@model@diffusion[[1]])) names(x)<-c("hurst","const") sdx<-diag(c(NA,NA)) colnames(sdx)<-names(x) rownames(sdx)<-names(x) sdx[2,1] <- sdx[1,2] <- NA obj <- list(coefficients=x,vcov=sdx,call=call) class(obj) <- "qgv" return(obj) } isregular<-yuima@sampling@regular if (!isregular){ yuima.stop("qgv method is only working for regular grid.") } if (!(order %in% 1:10)){ yuima.warn("Classical filter implement are of order ranged in [1,10], order have been fixed to 2.") order=2 } if (missing(a)){ if (filter.type=="Daubechies"){ if (order==2){ a<-1/sqrt(2)*c(.4829629131445341, -.8365163037378077, .2241438680420134, .1294095225512603) }else{ yuima.warn("There is no such order Daubechies' filter implemented, order have been fixed to 2.") a<-1/sqrt(2)*c(.4829629131445341, -.8365163037378077, .2241438680420134, .1294095225512603) order=2 } }else if (filter.type=="Classical"){ mesh<-0:order a=(-1)^(1-mesh)/2^order*choose(order,mesh) }else{ yuima.warn("No such type of filter. Filter have been fixed to Daubechies' filter of order 2.") a<-1/sqrt(2)*c(.4829629131445341, -.8365163037378077, .2241438680420134, .1294095225512603) order=2 } } L<-length(a) a2<-rep(0,2*L) a2[seq(1,2*L,by=2)]<-a process<-yuima@[email protected][[1]] N<-length(process) #Computation of the generalized quadratic variations V1<-sum(filter(process,a)^2,na.rm=TRUE) V2<-sum(filter(process,a2)^2,na.rm=TRUE) if(!Hconst){ H<-1/2*log2(V2/V1) } nconst <- "const" sdC<-NA C <- NA if(isfOU){ if( bconst||(H>=1)||(H<=0)){ if(diffnoparam){ C<-eval(yuima@model@diffusion[[1]]) } }else{ #Compute the estimation of the constant C. delta<-yuima@sampling@delta constfilt<-sum(a%*%t(a)*abs(matrix(0:(L-1),L,L)-matrix(0:(L-1),L,L,byrow=TRUE))^(2*H)) C<- sqrt(-2*V1/(N-L)/(constfilt*delta^(2*H))) nconst<-as.character(yuima@model@diffusion[[1]]) } } else { nconst<- as.character(yuima@model@diffusion[[1]]) } if(isfOU){ #Compute the standard error infty<-100 C11<-rep(0,2*infty+1) C11bis<-rep(0,2*infty+1) C12<-rep(0,2*infty+1) C22<-rep(0,2*infty+1) l<-order+1 for (i in (-infty:infty)){ for (q in 0:l){ for (r in 0:l){ C11[i+infty+1]<-C11[i+infty+1]+a[q+1]*a[r+1]*abs(q-r+i)^(2*H) } } for (q in 0:l){ for (r in 0:l){ C12[i+infty+1]<-C12[i+infty+1]+a[q+1]*a[r+1]*abs(2*q-r+i)^(2*H) } } for (q in 0:l){ for (r in 0:l){ C22[i+infty+1]<-C22[i+infty+1]+a[q+1]*a[r+1]*abs(2*q-2*r+i)^(2*H) } } for (q in 0:(2*l)){ for (r in 0:(2*l)){ C11bis[i+infty+1]<-C11bis[i+infty+1]+a2[q+1]*a2[r+1]*abs(q-r+i)^(2*H) } } } rho11<-1/2*sum((C11/C11[infty+1])^2) rho11dil<-1/2*sum((C11bis/C11bis[infty+1])^2) rho12<-1/2*sum((C12/2^H/C11[infty+1])^2) rho22<-1/2*sum((C22/2^H/2^H/C11[infty+1])^2) sigma1<-1/(log(2))^2*(rho11+rho11dil-2*rho12) if((!Hconst)&(H>0)){ sdH<-sqrt(sigma1)/sqrt(N) } if ((H>0)&(H<1)&(!bconst)){ sigma2<-C^2/2*sigma1 sdC<-sqrt(sigma2)/sqrt(N)*log(N) } } nconst <- gsub("[()]", "", nconst) x<-c(H,C) names(x)<-c("hurst",nconst) sdx<-diag(c(sdH,sdC)) colnames(sdx)<-names(x) rownames(sdx)<-names(x) sdx[2,1] <- sdx[1,2] <- NA obj <- list(coefficients=x,vcov=sdx,call=call) class(obj) <- "qgv" return(obj) } print.qgv<-function(x,...){ tmp <- rbind(x$coefficients, diag(x$vcov)) rownames(tmp) <- c("Estimate", "Std. Error") cat("\nFractional OU estimation\n") print(tmp) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/qgv.R
##::quasi-likelihood function ##::extract drift term from yuima ##::para: parameter of drift term (theta2) ### TO BE FIXED: all caculations should be made on a private environment to ### avoid problems. ### I have rewritten drift.term and diff.term instead of calc.drift and ### calc.diffusion to make them independent of the specification of the ### parameters. S.M.I. 22/06/2010 drift.term <- function(yuima, theta, env){ r.size <- yuima@[email protected] d.size <- yuima@[email protected] modelstate <- yuima@[email protected] DRIFT <- yuima@model@drift # n <- length(yuima)[1] n <- dim(env$X)[1] drift <- matrix(0,n,d.size) tmp.env <- new.env(parent = env) ##Kurisaki 4/4/2021 assign(yuima@[email protected], env$time, envir=tmp.env) for(i in 1:length(theta)){ assign(names(theta)[i],theta[[i]], envir=tmp.env) } for(d in 1:d.size){ assign(modelstate[d], env$X[,d], envir=tmp.env) } for(d in 1:d.size){ drift[,d] <- eval(DRIFT[d], envir=tmp.env) } return(drift) } diffusion.term <- function(yuima, theta, env){ r.size <- yuima@[email protected] d.size <- yuima@[email protected] modelstate <- yuima@[email protected] DIFFUSION <- yuima@model@diffusion # n <- length(yuima)[1] n <- dim(env$X)[1] tmp.env <- new.env(parent = env) ##Kurisaki 4/4/2021 assign(yuima@[email protected], env$time, envir=tmp.env) diff <- array(0, dim=c(d.size, r.size, n)) for(i in 1:length(theta)){ assign(names(theta)[i],theta[[i]],envir=tmp.env) } for(d in 1:d.size){ assign(modelstate[d], env$X[,d], envir=tmp.env) } for(r in 1:r.size){ for(d in 1:d.size){ diff[d, r, ] <- eval(DIFFUSION[[d]][r], envir=tmp.env) } } return(diff) } ## Koike's code ##::extract jump term from yuima ##::gamma: parameter of diffusion term (theta3) measure.term <- function(yuima, theta, env){ r.size <- yuima@[email protected] d.size <- yuima@[email protected] modelstate <- yuima@[email protected] n <- dim(env$X)[1] tmp.env <- new.env(parent = env) # 4/17/2021 Kito assign(yuima@[email protected], env$time, envir =tmp.env) JUMP <- yuima@[email protected] measure <- array(0, dim=c(d.size, r.size, n)) for(i in 1:length(theta)){ assign(names(theta)[i],theta[[i]],envir=tmp.env) } for(d in 1:d.size){ assign(modelstate[d], env$X[,d],envir=tmp.env) } for(r in 1:r.size){ #for(d.tmp in 1:d){ if(d.size==1){ measure[1,r,] <- eval(JUMP[[r]],envir=tmp.env) }else{ for(d in 1:d.size){ measure[d,r,] <- eval(JUMP[[d]][r],envir=tmp.env) } } } return(measure) } ### I have rewritten qmle as a version of ml.ql ### This function has an interface more similar to mle. ### ml.ql is limited in that it uses fixed names for drift and diffusion ### parameters, while yuima model allows for any names. ### also, I am using the same interface of optim to specify upper and lower bounds ### S.M.I. 22/06/2010 is.Poisson <- function(obj){ if(is(obj,"yuima")) return(is(obj@model, "yuima.poisson")) if(is(obj,"yuima.model")) return(is(obj, "yuima.poisson")) return(FALSE) } is.CARMA <- function(obj){ if(is(obj,"yuima")) return(is(obj@model, "yuima.carma")) if(is(obj,"yuima.model")) return(is(obj, "yuima.carma")) return(FALSE) } qmle <- function(yuima, start, method="L-BFGS-B", fixed = list(), print=FALSE, envir=globalenv(), ##Kurisaki 4/4/2021 lower, upper, joint=FALSE, Est.Incr="NoIncr",aggregation=TRUE, threshold=NULL,rcpp=FALSE, ...){ if(Est.Incr=="Carma.Inc"){ Est.Incr<-"Incr" } if(Est.Incr=="Carma.Par"){ Est.Incr<-"NoIncr" } if(Est.Incr=="Carma.IncPar"){ Est.Incr<-"IncrPar" } if(is(yuima@model, "yuima.carma")){ NoNeg.Noise<-FALSE cat("\nStarting qmle for carma ... \n") } if(is.CARMA(yuima)&& length(yuima@model@[email protected])!=0){ method<-"L-BFGS-B" } call <- match.call() if( missing(yuima)) yuima.stop("yuima object is missing.") if(is.COGARCH(yuima)){ if(missing(lower)) lower <- list() if(missing(upper)) upper <- list() res <- NULL if("grideq" %in% names(as.list(call)[-(1:2)])){ res <- PseudoLogLik.COGARCH(yuima, start, method=method, fixed = list(), lower, upper, Est.Incr, call, aggregation = aggregation, ...) }else{ res <- PseudoLogLik.COGARCH(yuima, start, method=method, fixed = list(), lower, upper, Est.Incr, call, grideq = FALSE, aggregation = aggregation,...) } return(res) } if(is.PPR(yuima)){ if(missing(lower)) lower <- list() if(missing(upper)) upper <- list() # res <- NULL # if("grideq" %in% names(as.list(call)[-(1:2)])){ res <- quasiLogLik.PPR(yuimaPPR = yuima, parLambda = start, method=method, fixed = list(), lower, upper, call, ...) # }else{ # res <- PseudoLogLik.COGARCH(yuima, start, method=method, fixed = list(), # lower, upper, Est.Incr, call, grideq = FALSE, aggregation = aggregation,...) # } return(res) } orig.fixed <- fixed orig.fixed.par <- names(orig.fixed) if(is.Poisson(yuima)) threshold <- 0 ## param handling ## FIXME: maybe we should choose initial values at random within lower/upper ## at present, qmle stops if( missing(start) ) yuima.stop("Starting values for the parameters are missing.") #14/12/2013 We modify the QMLE function when the model is a Carma(p,q). # In this case we use a two step procedure: # First) The Coefficient are obtained by QMLE computed using the Kalman Filter. # Second) Using the result in Brockwell, Davis and Yang (2007) we retrieve # the underlying Levy. The estimated increments are used to find the L?vy parameters. # if(is(yuima@model, "yuima.carma")){ # yuima.warm("two step procedure for carma(p,q)") # return(null) # } # ### 7/8/2021 Kito if(length(fixed) > 0 && !is.Poisson(yuima) && !is.CARMA(yuima) && !is.COGARCH(yuima)) { new.yuima.list <- changeFixedParametersToConstant(yuima, fixed) new.yuima <- new.yuima.list$new.yuima qmle.env <- new.yuima.list$env # new params new.start = start[!is.element(names(start), names(fixed))] new.lower = lower[!is.element(names(lower), names(fixed))] new.upper = upper[!is.element(names(upper), names(fixed))] #Kurisaki 5/23/2021 res <- qmle(new.yuima, start = new.start, method = method, fixed = list(), print = print, envir = qmle.env, lower = new.lower, upper = new.upper, joint = joint, Est.Incr = Est.Incr, aggregation = aggregation, threshold = threshold, rcpp = rcpp, ...) res@call <- match.call() res@model <- yuima@model fixed.res <- fixed mode(fixed.res) <- "numeric" res@fullcoef <- c(res@fullcoef,fixed.res) res@fixed <- fixed.res return(res) } yuima.nobs <- as.integer(max(unlist(lapply(get.zoo.data(yuima),length))-1,na.rm=TRUE)) diff.par <- yuima@model@parameter@diffusion # 24/12 if(is.CARMA(yuima) && length(diff.par)==0 && length(yuima@model@parameter@jump)!=0){ diff.par<-yuima@model@parameter@jump } if(is.CARMA(yuima) && length(yuima@model@parameter@jump)!=0){ CPlist <- c("dgamma", "dexp") codelist <- c("rIG", "rgamma") if(yuima@[email protected]=="CP"){ tmp <- regexpr("\\(", yuima@model@measure$df$exp)[1] measurefunc <- substring(yuima@model@measure$df$exp, 1, tmp-1) if(!is.na(match(measurefunc,CPlist))){ yuima.warn("carma(p,q): the qmle for a carma(p,q) driven by a Compound Poisson with no-negative random size") NoNeg.Noise<-TRUE # we need to add a new parameter for the mean of the Noise if((yuima@model@info@q+1)==(yuima@model@info@q+1)){ start[["mean.noise"]]<-1 } # return(NULL) } } if(yuima@[email protected]=="code"){ #if(class(yuima@model@measure$df)=="yuima.law"){ if(inherits(yuima@model@measure$df, "yuima.law")){ # YK, Mar. 22, 2022 measurefunc <- "yuima.law" } else{ tmp <- regexpr("\\(", yuima@model@measure$df$exp)[1] measurefunc <- substring(yuima@model@measure$df$exp, 1, tmp-1) } if(!is.na(match(measurefunc,codelist))){ yuima.warn("carma(p,q): the qmle for a carma(p,q) driven by a non-Negative Levy will be implemented as soon as possible") NoNeg.Noise<-TRUE if((yuima@model@info@q+1)==(yuima@model@info@q+1)){ start[["mean.noise"]]<-1 } #return(NULL) } } # yuima.warn("carma(p,q): the qmle for a carma(p,q) driven by a Jump process will be implemented as soon as possible ") # return(NULL) } # 24/12 if(is.CARMA(yuima) && length(yuima@model@[email protected])>0){ yuima.warn("carma(p,q): the case of lin.par will be implemented as soon as") return(NULL) } drift.par <- yuima@model@parameter@drift #01/01 we introduce the new variable in order # to take into account the parameters in the starting conditions if(is.CARMA(yuima)){ #if(length(yuima@model@[email protected])!=0){ xinit.par <- yuima@model@parameter@xinit #} } # SMI-2/9/14: measure.par is used for Compound Poisson # and CARMA, jump.par only by CARMA jump.par <- NULL if(is.CARMA(yuima)){ jump.par <- yuima@model@parameter@jump measure.par <- yuima@model@parameter@measure } else { if(length(yuima@model@parameter@jump)!=0){ measure.par <- unique(c(yuima@model@parameter@measure,yuima@model@parameter@jump)) } else { measure.par <- yuima@model@parameter@measure } } # jump.par is used for CARMA common.par <- yuima@model@parameter@common JointOptim <- joint if(is.CARMA(yuima) && length(yuima@model@parameter@jump)!=0){ if(any((match(jump.par, drift.par)))){ JointOptim <- TRUE yuima.warn("Drift and diffusion parameters must be different. Doing joint estimation, asymptotic theory may not hold true.") } } if(length(common.par)>0){ JointOptim <- TRUE yuima.warn("Drift and diffusion parameters must be different. Doing joint estimation, asymptotic theory may not hold true.") # 24/12 # if(is(yuima@model, "yuima.carma")){ # JointOptim <- TRUE # yuima.warm("Carma(p.q): The case of common parameters in Drift and Diffusion Term will be implemented as soon as possible,") # #return(NULL) # } } # if(!is(yuima@model, "yuima.carma")){ # if(length(jump.par)+yuima@[email protected] == "CP") # yuima.stop("Cannot estimate the jump models, yet") # } if(!is.list(start)) yuima.stop("Argument 'start' must be of list type.") fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) if(is.CARMA(yuima) && (length(yuima@model@[email protected])!=0)){ # 01/01 We modify the code for considering # the loc.par in yuima.carma model fullcoef<-c(fullcoef, yuima@model@[email protected]) } if(is.CARMA(yuima) && (NoNeg.Noise==TRUE)){ if((yuima@model@info@q+1)==yuima@model@info@p){ mean.noise<-"mean.noise" fullcoef<-c(fullcoef, mean.noise) } } # if(is.CARMA(yuima) && (yuima@[email protected] == "CP")){ fullcoef<-c(fullcoef, measure.par) #} if(is.CARMA(yuima)){ if(length(yuima@model@parameter@xinit)>1){ #fullcoef<-unique(c(fullcoef,yuima@model@parameter@xinit)) condIniCarma<-!(yuima@model@parameter@xinit%in%fullcoef) if(sum(condIniCarma)>0){ NamesInitial<- yuima@model@parameter@xinit[condIniCarma] start <- as.list(unlist(start)[!names(unlist(start))%in%(NamesInitial)]) } } } npar <- length(fullcoef) fixed.par <- names(fixed) # We use Fixed.par when we consider a Carma with scale parameter fixed.carma=NULL if(is.CARMA(yuima) && (length(measure.par) > 0)){ if(!missing(fixed)){ if(names(fixed) %in% measure.par){ idx.fixed.carma<-match(names(fixed),measure.par) idx.fixed.carma<-idx.fixed.carma[!is.na(idx.fixed.carma)] if(length(idx.fixed.carma)!=0){ fixed.carma<-as.numeric(fixed[measure.par[idx.fixed.carma]]) names(fixed.carma)<-measure.par[idx.fixed.carma] } } } upper.carma=NULL if(!missing(upper)){ if(names(upper) %in% measure.par){ idx.upper.carma<-match(names(upper),measure.par) idx.upper.carma<-idx.upper.carma[!is.na(idx.upper.carma)] if(length(idx.upper.carma)!=0){ upper.carma<-as.numeric(upper[measure.par[idx.upper.carma]]) names(upper.carma)<-measure.par[idx.upper.carma] } } } lower.carma=NULL if(!missing(lower)){ if(names(lower) %in% measure.par){ idx.lower.carma<-match(names(lower),measure.par) idx.lower.carma<-idx.lower.carma[!is.na(idx.lower.carma)] if(length(idx.lower.carma)!=0){ lower.carma<-as.numeric(lower[measure.par[idx.lower.carma]]) names(lower.carma)<-measure.par[idx.lower.carma] } } } for( j in c(1:length(measure.par))){ if(is.na(match(measure.par[j],names(fixed)))){ fixed.par <- c(fixed.par,measure.par[j]) fixed[measure.par[j]]<-start[measure.par[j]] } } } if (any(!(fixed.par %in% fullcoef))) yuima.stop("Some named arguments in 'fixed' are not arguments to the supplied yuima model") nm <- names(start) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'start' are not arguments to the supplied yuima model") start <- start[order(oo)] nm <- names(start) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) # SMI-2/9/14: idx.measure for CP idx.measure <- match(measure.par, nm) #01/01 if(is.CARMA(yuima)){ # if(length(yuima@model@[email protected])!=0){ idx.xinit <- as.integer(na.omit(match(xinit.par,nm)))# We need to add idx if NoNeg.Noise is TRUE #} } #if(is.null(fixed.carma)){ idx.fixed <- match(fixed.par, nm) # }else{ # dummynm <- nm[!(nm %in% fixed.par)] # idx.fixed <- match(fixed.par, dummynm) # } orig.idx.fixed <- idx.fixed tmplower <- as.list( rep( -Inf, length(nm))) names(tmplower) <- nm if(!missing(lower)){ idx <- match(names(lower), names(tmplower)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmplower[ idx ] <- lower } lower <- tmplower tmpupper <- as.list( rep( Inf, length(nm))) names(tmpupper) <- nm if(!missing(upper)){ idx <- match(names(upper), names(tmpupper)) if(any(is.na(idx))) yuima.stop("names in 'lower' do not match names fo parameters") tmpupper[ idx ] <- upper } upper <- tmpupper d.size <- yuima@[email protected] if (is.CARMA(yuima)){ # 24/12 d.size <-1 } n <- length(yuima)[1] env <- new.env(parent = envir) ##Kurisaki 4/4/2021 assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) # SMI-2/9/14: for CP assign("Cn.r", numeric(n-1), envir=env) if(length(yuima@[email protected]) == 0) threshold <- 0 # there are no jumps, we take all observations if (is.CARMA(yuima)){ #24/12 If we consider a carma model, # the observations are only the first column of env$X # assign("X", as.matrix(onezoo(yuima)), envir=env) # env$X<-as.matrix(env$X[,1]) # assign("deltaX", matrix(0, n-1, d.size)[,1], envir=env) env$X<-as.matrix(env$X[,1]) # env$X<-na.omit(as.matrix(env$X[,1])) env$deltaX<-as.matrix(env$deltaX[,1]) assign("time.obs",length(env$X),envir=env) # env$time.obs<-length(env$X) #p <-yuima@model@info@p assign("p", yuima@model@info@p, envir=env) assign("q", yuima@model@info@q, envir=env) assign("V_inf0", matrix(diag(rep(1,env$p)),env$p,env$p), envir=env) # env$X<-as.matrix(env$X[,1]) # env$deltaX<-as.matrix(env$deltaX[,1]) # assign("time.obs",length(env$X), envir=env) # p <-yuima@model@info@p # assign("V_inf0", matrix(diag(rep(1,p)),p,p), envir=env) } assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) for(t in 1:(n-1)){ env$deltaX[t,] <- env$X[t+1,] - env$X[t,] if(!is.CARMA(yuima)) env$Cn.r[t] <- ((sqrt( env$deltaX[t,] %*% env$deltaX[t,])) <= threshold) } if(length(yuima@[email protected]) == 0) env$Cn.r <- rep(1, length(env$Cn.r)) # there are no jumps, we take all observations assign("h", deltat(yuima@[email protected][[1]]), envir=env) #SMI: 2/9/214 jump if(length(yuima@[email protected]) > 0 && yuima@[email protected] == "CP"){ # "yuima.law" LM 13/05/2018 #if(class(yuima@model@measure$df)=="yuima.law"){ if(inherits(yuima@model@measure$df, "yuima.law")){ # YK, Mar. 22, 2022 args <- yuima@model@parameter@measure }else{ args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1",yuima@model@measure$df$expr,perl=TRUE)), ",")) } idx.intensity <- numeric(0) if(length(measure.par) > 0){ for(i in 1:length(measure.par)){ if(sum(grepl(measure.par[i],yuima@model@measure$intensity))) idx.intensity <- append(idx.intensity,i) } } assign("idx.intensity", idx.intensity, envir=env) assign("measure.var", args[1], envir=env) } f <- function(p) { mycoef <- as.list(p) if(!is.CARMA(yuima)){ if(length(c(idx.fixed,idx.measure))>0) ## SMI 2/9/14 names(mycoef) <- nm[-c(idx.fixed,idx.measure)] ## SMI 2/9/14 else names(mycoef) <- nm } else { if(length(idx.fixed)>0) names(mycoef) <- nm[-idx.fixed] else names(mycoef) <- nm } mycoef[fixed.par] <- fixed minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } # SMI-2/9/14: fpsi <- function(p){ mycoef <- as.list(p) idx.cont <- c(idx.diff,idx.drift) if(length(c(idx.fixed,idx.cont))>0) names(mycoef) <- nm[-c(idx.fixed,idx.cont)] else names(mycoef) <- nm mycoef[fixed.par] <- fixed # print(mycoef) #print(p) minusquasipsi(yuima=yuima, param=mycoef, print=print, env=env) } fj <- function(p) { mycoef <- as.list(p) # names(mycoef) <- nm if(!is.CARMA(yuima)){ idx.fixed <- orig.idx.fixed if(length(c(idx.fixed,idx.measure))>0) ## SMI 2/9/14 names(mycoef) <- nm[-c(idx.fixed,idx.measure)] ## SMI 2/9/14 else names(mycoef) <- nm } else { names(mycoef) <- nm mycoef[fixed.par] <- fixed } mycoef[fixed.par] <- fixed minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } oout <- NULL HESS <- matrix(0, length(nm), length(nm)) colnames(HESS) <- nm rownames(HESS) <- nm HaveDriftHess <- FALSE HaveDiffHess <- FALSE HaveMeasHess <- FALSE if(length(start)){ if(JointOptim){ ### joint optimization old.fixed <- fixed new.start <- start old.start <- start if(!is.CARMA(yuima)){ if(length(c(idx.fixed,idx.measure))>0) new.start <- start[-c(idx.fixed,idx.measure)] # considering only initial guess for } if(length(new.start)>1){ #??multidimensional optim # Adjust lower for no negative Noise if(is.CARMA(yuima) && (NoNeg.Noise==TRUE)) if(mean.noise %in% names(lower)){lower[mean.noise]<-10^-7} oout <- optim(new.start, fj, method = method, hessian = TRUE, lower=lower, upper=upper) if(length(fixed)>0) oout$par[fixed.par]<- unlist(fixed)[fixed.par] if(is.CARMA(yuima)){ HESS <- oout$hessian } else { HESS[names(new.start),names(new.start)] <- oout$hessian } if(is.CARMA(yuima) && length(yuima@model@[email protected])!=0){ b0<-paste0(yuima@model@[email protected],"0",collapse="") idx.b0<-match(b0,rownames(HESS)) HESS<-HESS[-idx.b0,] HESS<-HESS[,-idx.b0] } # if(is.CARMA(yuima) && length(yuima@model@parameter@measure)!=0){ # for(i in c(1:length(fixed.par))){ # indx.fixed<-match(fixed.par[i],rownames(HESS)) # HESS<-HESS[-indx.fixed,] # HESS<-HESS[,-indx.fixed] # } # if(is.CARMA(yuima) && (NoNeg.Noise==TRUE)){ # idx.noise<-(match(mean.noise,rownames(HESS))) # HESS<-HESS[-idx.noise,] # HESS<-HESS[,-idx.noise] # } # } if(is.CARMA(yuima)&& length(fixed)>0 && length(yuima@model@parameter@measure)==0){ for(i in c(1:length(fixed.par))){ indx.fixed<-match(fixed.par[i],rownames(HESS)) HESS<-HESS[-indx.fixed,] HESS<-HESS[,-indx.fixed] } } if(is.CARMA(yuima) && length(yuima@model@parameter@measure)!=0){ for(i in c(1:length(fixed.par))){ indx.fixed<-match(fixed.par[i],rownames(HESS)) HESS<-HESS[-indx.fixed,] HESS<-HESS[,-indx.fixed] } if(is.CARMA(yuima) && (NoNeg.Noise==TRUE)){ idx.noise<-(match(mean.noise,rownames(HESS))) HESS<-HESS[-idx.noise,] HESS<-HESS[,-idx.noise] } } HaveDriftHess <- TRUE HaveDiffHess <- TRUE } else { ### one dimensional optim # YK Mar. 13, 2021: bug fixed #opt1 <- optimize(f, ...) ## an interval should be provided #oout <- list(par = opt1$minimum, value = opt1$objective) opt1 <- optimize(f, lower = lower[[names(new.start)]], upper = upper[[names(new.start)]], ...) oout <- list(par = opt1$minimum, value = opt1$objective) names(oout$par) <- names(new.start) } ### endif( length(start)>1 ) theta1 <- oout$par[diff.par] theta2 <- oout$par[drift.par] } else { ### first diffusion, then drift theta1 <- NULL old.fixed <- fixed old.start <- start if(length(idx.diff)>0){ ## DIFFUSION ESTIMATIOn first old.fixed <- fixed old.start <- start old.fixed.par <- fixed.par new.start <- start[idx.diff] # considering only initial guess for diffusion new.fixed <- fixed if(length(idx.drift)>0) new.fixed[nm[idx.drift]] <- start[idx.drift] fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.diff] mydots <- as.list(call)[-(1:2)] mydots$print <- NULL mydots$rcpp <- NULL #KK 08/07/16 mydots$fixed <- NULL mydots$fn <- as.name("f") mydots$start <- NULL mydots$par <- unlist(new.start) mydots$hessian <- FALSE mydots$upper <- as.numeric(unlist( upper[ nm[idx.diff] ])) mydots$lower <- as.numeric(unlist( lower[ nm[idx.diff] ])) mydots$joint <- NULL # LM 08/03/16 mydots$aggregation <- NULL # LM 08/03/16 mydots$threshold <- NULL #SMI 2/9/14 mydots$envir <- NULL ##Kurisaki 4/4/2021 mydots$Est.Incr <- NULL ##Kurisaki 4/10/2021 mydots$print <- NULL ##Kito 4/17/2021 mydots$aggregation <- NULL ##Kito 4/17/2021 mydots$rcpp <- NULL ##Kito 4/17/2021 if((length(mydots$par)>1) | any(is.infinite(c(mydots$upper,mydots$lower)))){ mydots$method<-method ##song oout <- do.call(optim, args=mydots) } else { mydots$f <- mydots$fn mydots$fn <- NULL mydots$par <- NULL mydots$hessian <- NULL mydots$interval <- as.numeric(c(unlist(lower[diff.par]),unlist(upper[diff.par]))) mydots$lower <- NULL mydots$upper <- NULL mydots$method<- NULL mydots$envir <- NULL ##Kurisaki 4/4/2021 mydots$Est.Incr <- NULL ##Kurisaki 4/8/2021 mydots$print <- NULL ##Kito 4/17/2021 mydots$aggregation <- NULL ##Kito 4/17/2021 mydots$rcpp <- NULL ##Kito 4/17/2021 opt1 <- do.call(optimize, args=mydots) theta1 <- opt1$minimum names(theta1) <- diff.par oout <- list(par = theta1, value = opt1$objective) } theta1 <- oout$par fixed <- old.fixed start <- old.start fixed.par <- old.fixed.par } ## endif(length(idx.diff)>0) theta2 <- NULL if(length(idx.drift)>0){ ## DRIFT estimation with first state diffusion estimates fixed <- old.fixed start <- old.start old.fixed.par <- fixed.par new.start <- start[idx.drift] # considering only initial guess for drift new.fixed <- fixed new.fixed[names(theta1)] <- theta1 fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) names(new.start) <- nm[idx.drift] mydots <- as.list(call)[-(1:2)] mydots$print <- NULL mydots$rcpp <- NULL #KK 08/07/16 mydots$fixed <- NULL mydots$fn <- as.name("f") mydots$threshold <- NULL #SMI 2/9/14 mydots$start <- NULL mydots$par <- unlist(new.start) mydots$hessian <- FALSE mydots$upper <- unlist( upper[ nm[idx.drift] ]) mydots$lower <- unlist( lower[ nm[idx.drift] ]) mydots$joint <- NULL # LM 08/03/16 mydots$aggregation <- NULL # LM 08/03/16# LM 08/03/16 mydots$envir <- NULL ##Kurisaki 4/4/2021 mydots$Est.Incr <- NULL ##Kurisaki 4/8/2021 mydots$print <- NULL ##Kito 4/17/2021 mydots$aggregation <- NULL ##Kito 4/17/2021 mydots$rcpp <- NULL ##Kito 4/17/2021 if(length(mydots$par)>1 | any(is.infinite(c(mydots$upper,mydots$lower)))){ if(is.CARMA(yuima)){ if(NoNeg.Noise==TRUE){ if((yuima@model@info@q+1)==yuima@model@info@p){ mydots$lower[names(start["NoNeg.Noise"])]<-10^(-7) } } if(length(yuima@model@[email protected])!=0){ name_b0<-paste0(yuima@model@[email protected],"0",collapse="") index_b0<-match(name_b0,nm) mydots$lower[index_b0]<-1 mydots$upper[index_b0]<-1+10^(-7) } if (length(yuima@model@[email protected])!=0){ mydots$upper <- unlist( upper[ nm ]) mydots$lower <- unlist( lower[ nm ]) idx.tot<-unique(c(idx.drift,idx.xinit)) new.start <- start[idx.tot] names(new.start) <- nm[idx.tot] mydots$par <- unlist(new.start) } } # END if(is.CARMA) mydots$method <- method #song oout1 <- do.call(optim, args=mydots) # oout1 <- optim(mydots$par,f,method = "L-BFGS-B" , lower = mydots$lower, upper = mydots$upper) } else { mydots$f <- mydots$fn mydots$fn <- NULL mydots$par <- NULL mydots$hessian <- NULL mydots$method<-NULL mydots$interval <- as.numeric(c(lower[drift.par],upper[drift.par])) mydots$envir <- NULL ##Kurisaki 4/4/2021 mydots$Est.Incr <- NULL ##Kurisaki 4/8/2021 mydots$print <- NULL ##Kito 4/17/2021 mydots$aggregation <- NULL ##Kito 4/17/2021 mydots$rcpp <- NULL ##Kito 4/17/2021 opt1 <- do.call(optimize, args=mydots) theta2 <- opt1$minimum names(theta2) <- drift.par oout1 <- list(par = theta2, value = as.numeric(opt1$objective)) } theta2 <- oout1$par fixed <- old.fixed start <- old.start old.fixed.par <- fixed.par } ## endif(length(idx.drift)>0) oout1 <- list(par= c(theta1, theta2)) if (! is.CARMA(yuima)){ if(length(c(diff.par, diff.par))>0) names(oout1$par) <- c(diff.par,drift.par) } oout <- oout1 } ### endif JointOptim } else { list(par = numeric(0L), value = f(start)) } fMeas <- function(p) { mycoef <- as.list(p) # if(! is.CARMA(yuima)){ # # names(mycoef) <- drift.par # mycoef[measure.par] <- coef[measure.par] #} minusquasipsi(yuima=yuima, param=mycoef, print=print, env=env) # minusquasilogl(yuima=yuima, param=mycoef, print=print, env) } fDrift <- function(p) { mycoef <- as.list(p) if(! is.CARMA(yuima)){ names(mycoef) <- drift.par mycoef[diff.par] <- coef[diff.par] } minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } fDiff <- function(p) { mycoef <- as.list(p) if(! is.CARMA(yuima)){ names(mycoef) <- diff.par mycoef[drift.par] <- coef[drift.par] } minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } # coef <- oout$par #control=list() #par <- coef #names(par) <- unique(c(diff.par, drift.par)) # nm <- unique(c(diff.par, drift.par)) # START: ESTIMATION OF CP part theta3 <- NULL if(length(idx.measure)>0 & !is.CARMA(yuima)){ idx.cont <- c(idx.drift,idx.diff) fixed <- old.fixed start <- old.start old.fixed.par <- fixed.par new.fixed <- fixed new.start <- start[idx.measure] # considering only initial guess for measure new.fixed <- fixed new.fixed[names(theta1)] <- theta1 new.fixed[names(theta2)] <- theta2 fixed <- new.fixed fixed.par <- names(fixed) idx.fixed <- match(fixed.par, nm) # names(new.start) <- nm[idx.drift] names(new.start) <- nm[idx.measure] mydots <- as.list(call)[-(1:2)] # mydots$print <- NULL mydots$threshold <- NULL mydots$fixed <- NULL mydots$fn <- as.name("fpsi") mydots$start <- NULL mydots$threshold <- NULL #SMI 2/9/14 mydots$envir <- NULL ##Kurisaki 4/4/2021 mydots$Est.Incr <- NULL ##Kurisaki 4/8/2021 mydots$print <- NULL ##Kito 4/17/2021 mydots$aggregation <- NULL ##Kito 4/17/2021 mydots$rcpp <- NULL ##Kito 4/17/2021 mydots$par <- unlist(new.start) mydots$hessian <- TRUE mydots$joint <- NULL mydots$upper <- unlist( upper[ nm[idx.measure] ]) mydots$lower <- unlist( lower[ nm[idx.measure] ]) mydots$method <- method oout3 <- do.call(optim, args=mydots) theta3 <- oout3$par #print(theta3) HESS[measure.par,measure.par] <- oout3$hessian HaveMeasHess <- TRUE fixed <- old.fixed start <- old.start fixed.par <- old.fixed.par } # END: ESTIMATION OF CP part if(!is.CARMA(yuima)){ oout4 <- list(par= c(theta1, theta2, theta3)) names(oout4$par) <- c(diff.par,drift.par,measure.par) oout <- oout4 } coef <- oout$par control=list() par <- coef if(!is.CARMA(yuima)){ names(par) <- unique(c(diff.par, drift.par,measure.par)) nm <- unique(c(diff.par, drift.par,measure.par)) } else { names(par) <- unique(c(diff.par, drift.par)) nm <- unique(c(diff.par, drift.par)) } #return(oout) if(is.CARMA(yuima) && length(yuima@model@parameter@measure)!=0){ nm <-c(nm,measure.par) if((NoNeg.Noise==TRUE)){nm <-c(nm,mean.noise)} nm<-unique(nm) } if(is.CARMA(yuima) && (length(yuima@model@[email protected])!=0)){ nm <-unique(c(nm,yuima@model@[email protected])) } conDrift <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(drift.par)), ndeps = rep.int(0.001, length(drift.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) conDiff <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(diff.par)), ndeps = rep.int(0.001, length(diff.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) conMeas <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(measure.par)), ndeps = rep.int(0.001, length(measure.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) if(is.CARMA(yuima) && length(yuima@model@[email protected])!=0 ){ conDrift <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(c(drift.par,yuima@model@[email protected]))), ndeps = rep.int(0.001, length(c(drift.par,yuima@model@[email protected]))), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) conDiff <- list(trace = 5, fnscale = 1, parscale = rep.int(5, length(diff.par)), ndeps = rep.int(0.001, length(diff.par)), maxit = 100L, abstol = -Inf, reltol = sqrt(.Machine$double.eps), alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10) } if(!HaveDriftHess & (length(drift.par)>0)){ #hess2 <- .Internal(optimhess(coef[drift.par], fDrift, NULL, conDrift)) if(!is.CARMA(yuima)){ hess2 <- optimHess(coef[drift.par], fDrift, NULL, control=conDrift) HESS[drift.par,drift.par] <- hess2 } else{ names(coef) <- c(drift.par,yuima@model@[email protected]) hess2 <- optimHess(coef, fDrift, NULL, control=conDrift) HESS <- hess2 } if(is.CARMA(yuima) && length(yuima@model@[email protected])!=0){ b0<-paste0(yuima@model@[email protected],"0",collapse="") idx.b0<-match(b0,rownames(HESS)) HESS<-HESS[-idx.b0,] HESS<-HESS[,-idx.b0] } } if(!HaveDiffHess & (length(diff.par)>0)){ hess1 <- optimHess(coef[diff.par], fDiff, NULL, control=conDiff) HESS[diff.par,diff.par] <- hess1 } oout$hessian <- HESS if(!HaveMeasHess & (length(measure.par) > 0) & !is.CARMA(yuima)){ hess1 <- optimHess(coef[measure.par], fMeas, NULL, control=conMeas) oout$hessian[measure.par,measure.par] <- hess1 } # vcov <- if (length(coef)) # solve(oout$hessian) # else matrix(numeric(0L), 0L, 0L) vcov <- matrix(NA, length(coef), length(coef)) if (length(coef)) { rrr <- try(solve(oout$hessian), TRUE) if(class(rrr)[1] != "try-error") vcov <- rrr } mycoef <- as.list(coef) if(!is.CARMA(yuima)){ names(mycoef) <- nm } idx.fixed <- orig.idx.fixed mycoef.cont <- mycoef if(length(c(idx.fixed,idx.measure)>0)) # SMI 2/9/14 mycoef.cont <- mycoef[-c(idx.fixed,idx.measure)] # SMI 2/9/14 min.diff <- 0 min.jump <- 0 if(length(c(diff.par,drift.par))>0 & !is.CARMA(yuima)){ # LM 04/09/14 min.diff <- minusquasilogl(yuima=yuima, param=mycoef[c(diff.par,drift.par)], print=print, env,rcpp=rcpp) }else{ if(length(c(diff.par,drift.par))>0 & is.CARMA(yuima)){ min.diff <- minusquasilogl(yuima=yuima, param=mycoef, print=print, env,rcpp=rcpp) } } if(length(c(measure.par))>0 & !is.CARMA(yuima)) min.jump <- minusquasipsi(yuima=yuima, param=mycoef[measure.par], print=print, env=env) min <- min.diff + min.jump if(min==0) min <- NA dummycov<-matrix(0,length(coef),length(coef)) rownames(dummycov)<-names(coef) colnames(dummycov)<-names(coef) dummycov[rownames(vcov),colnames(vcov)]<-vcov vcov<-dummycov # new("mle", call = call, coef = coef, fullcoef = unlist(mycoef), # vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, # method = method) #LM 11/01 if(!is.CARMA(yuima)){ if(length(yuima@[email protected]) > 0 && yuima@[email protected] == "CP"){ final_res<-new("yuima.CP.qmle", Jump.times=env$time[env$Cn.r==0], Jump.values=env$deltaX[env$Cn.r==0,], X.values=env$X[env$Cn.r==0,], model=yuima@model, call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs, threshold=threshold) } else { final_res<-new("yuima.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs, model=yuima@model) } } else { if( Est.Incr=="IncrPar" || Est.Incr=="Incr" ){ final_res<-new("yuima.carma.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs, logL.Incr = NULL) }else{ if(Est.Incr=="NoIncr"){ final_res<-new("yuima.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs , model=yuima@model) return(final_res) }else{ yuima.warn("The variable Est.Incr is not correct. See qmle documentation for the allowed values ") final_res<-new("mle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs) return(final_res) } } } if(!is.CARMA(yuima)){ return(final_res) }else { param<-coef(final_res) observ<-yuima@data model<-yuima@model info<-model@info numb.ar<-info@p name.ar<-paste([email protected],c(numb.ar:1),sep="") ar.par<-param[name.ar] numb.ma<-info@q name.ma<-paste([email protected],c(0:numb.ma),sep="") ma.par<-param[name.ma] loc.par=NULL if (length([email protected])!=0){ loc.par<-param[[email protected]] } scale.par=NULL if (length([email protected])!=0){ scale.par<-param[[email protected]] } lin.par=NULL if (length([email protected])!=0){ lin.par<-param[[email protected]] } if(min(yuima.PhamBreton.Alg(ar.par[numb.ar:1]))>=0){ cat("\n Stationarity condition is satisfied...\n Starting Estimation Increments ...\n") }else{ yuima.warn("Insert constraints in Autoregressive parameters for enforcing stationarity" ) cat("\n Starting Estimation Increments ...\n") } ttt<[email protected][[1]] tt<-index(ttt) y<-coredata(ttt) if(NoNeg.Noise==TRUE && (info@p==(info@q+1))){final_res@coef[mean.noise]<-mean(y)/tail(ma.par,n=1)*ar.par[1]} levy<-yuima.CarmaNoise(y,tt,ar.par,ma.par, loc.par, scale.par, lin.par, NoNeg.Noise) inc.levy<-NULL if (!is.null(levy)){ inc.levy<-diff(t(levy)) } # INSERT HERE THE NECESSARY STEPS FOR FINDING THE PARAMETERS OF LEVY if(Est.Incr=="Carma.Inc"||Est.Incr=="Incr"){ # inc.levy.fin<-zoo(inc.levy,tt,frequency=1/env$h) inc.levy.fin<-zoo(inc.levy,tt[(1+length(tt)-length(inc.levy)):length(tt)]) carma_final_res<-new("yuima.carma.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, Incr.Lev = inc.levy.fin, model = yuima@model, nobs=yuima.nobs, logL.Incr = NULL) return(carma_final_res) } cat("\nStarting Estimation parameter Noise ...\n") dummycovCarmapar<-vcov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))] if(!is.null(loc.par)){ dummycovCarmapar<-vcov[unique(c(drift.par,diff.par,[email protected])), unique(c(drift.par,diff.par,[email protected]))] } dummycovCarmaNoise<-vcov[unique(measure.par),unique(c(measure.par))] #we need to adjusted dummycoeffCarmapar<-coef[unique(c(drift.par,diff.par))] if(!is.null(loc.par)){ dummycoeffCarmapar<-coef[unique(c(drift.par,diff.par,[email protected]))] } dummycoeffCarmaNoise<-coef[unique(c(measure.par))] coef<-NULL coef<-c(dummycoeffCarmapar,dummycoeffCarmaNoise) names.par<-c(unique(c(drift.par,diff.par)),unique(c(measure.par))) if(!is.null(loc.par)){ names.par<-c(unique(c(drift.par,diff.par,[email protected])),unique(c(measure.par))) } names(coef)<-names.par cov<-NULL cov<-matrix(0,length(names.par),length(names.par)) rownames(cov)<-names.par colnames(cov)<-names.par if(is.null(loc.par)){ cov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))]<-dummycovCarmapar }else{ cov[unique(c(drift.par,diff.par,[email protected])),unique(c(drift.par,diff.par,[email protected]))]<-dummycovCarmapar } cov[unique(c(measure.par)),unique(c(measure.par))]<-dummycovCarmaNoise if(length([email protected])!=0){ if([email protected]=="CP"){ name.func.dummy <- as.character(model@measure$df$expr[1]) name.func<- substr(name.func.dummy,1,(nchar(name.func.dummy)-1)) names.measpar<-as.vector(strsplit(name.func,', '))[[1]][-1] valuemeasure<-as.numeric(names.measpar) name.int.dummy <- as.character(model@measure$intensity) valueintensity<-as.numeric(name.int.dummy) NaIdx<-which(!is.na(c(valueintensity,valuemeasure))) if(length(NaIdx)!=0){ yuima.warn("the constrained MLE for levy increment will be implemented as soon as possible") carma_final_res<-new("yuima.carma.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, Incr.Lev = inc.levy, model = yuima@model, logL.Incr = NULL) return(carma_final_res) } if(aggregation==TRUE){ if(floor(yuima@sampling@n/yuima@sampling@Terminal)!=yuima@sampling@n/yuima@sampling@Terminal){ yuima.stop("the n/Terminal in sampling information is not an integer. Set Aggregation=FALSE") } inc.levy1<-diff(cumsum(c(0,inc.levy))[seq(from=1, to=yuima@sampling@n[1], by=(yuima@sampling@n/yuima@sampling@Terminal)[1] )]) }else{ inc.levy1<-inc.levy } names.measpar<-c(name.int.dummy, names.measpar) if(measurefunc=="dnorm"){ # result.Lev<-yuima.Estimation.CPN(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) } if(measurefunc=="dgamma"){ # result.Lev<-yuima.Estimation.CPGam(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) } if(measurefunc=="dexp"){ # result.Lev<-yuima.Estimation.CPExp(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) } Inc.Parm<-result.Lev$estLevpar IncVCOV<-result.Lev$covLev names(Inc.Parm)[NaIdx]<-measure.par rownames(IncVCOV)[NaIdx]<-as.character(measure.par) colnames(IncVCOV)[NaIdx]<-as.character(measure.par) coef<-NULL coef<-c(dummycoeffCarmapar,Inc.Parm) names.par<-names(coef) cov<-NULL cov<-matrix(0,length(names.par),length(names.par)) rownames(cov)<-names.par colnames(cov)<-names.par if(is.null(loc.par)){ cov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))]<-dummycovCarmapar }else{ cov[unique(c(drift.par,diff.par,[email protected])),unique(c(drift.par,diff.par,[email protected]))]<-dummycovCarmapar } cov[names(Inc.Parm),names(Inc.Parm)]<-IncVCOV } if(yuima@[email protected]=="code"){ # # "rIG", "rNIG", "rgamma", "rbgamma", "rvgamma" #if(class(model@measure$df)=="yuima.law"){ if(inherits(model@measure$df, "yuima.law")){ # YK, Mar. 22, 2022 valuemeasure <- "yuima.law" NaIdx<-NULL }else{ name.func.dummy <- as.character(model@measure$df$expr[1]) name.func<- substr(name.func.dummy,1,(nchar(name.func.dummy)-1)) names.measpar<-as.vector(strsplit(name.func,', '))[[1]][-1] valuemeasure<-as.numeric(names.measpar) NaIdx<-which(!is.na(valuemeasure)) } if(length(NaIdx)!=0){ yuima.warn("the constrained MLE for levy increment will be implemented as soon as possible") carma_final_res<-new("yuima.carma.qmle", call = call, coef = coef, fullcoef = unlist(mycoef), vcov = vcov, min = min, details = oout, minuslogl = minusquasilogl, method = method, Incr.Lev = inc.levy, model = yuima@model, logL.Incr = NULL) return(carma_final_res) } if(aggregation==TRUE){ if(all(floor(yuima@sampling@n/yuima@sampling@Terminal)!=yuima@sampling@n/yuima@sampling@Terminal)){ yuima.stop("the n/Terminal in sampling information is not an integer. Aggregation=FALSE is recommended") } inc.levy1<-diff(cumsum(c(0,inc.levy))[seq(from=1, to=yuima@sampling@n[1], by=(yuima@sampling@n/yuima@sampling@Terminal)[1] )]) }else{ inc.levy1<-inc.levy } if(measurefunc=="yuima.law"){ dummyParMeas<-c(coef[measure.par],1) names(dummyParMeas)<-c(measure.par,yuima@[email protected]) cond <- length(dens(yuima@model@measure$df,x=as.numeric(inc.levy1),param=as.list(dummyParMeas))) if(cond==0){ result.Lev <- list(estLevpar=coef[measure.par], covLev=matrix(NA, length(coef[measure.par]), length(coef[measure.par])) ) yuima.warn("Levy measure parameters can not be estimated.") }else{ dummyMyfunMeas<-function(par, Law, Data, time, param.name, name.time){ dummyParMeas<-c(par,time) names(dummyParMeas)<-c(param.name,name.time) v <- log(pmax(na.omit(dens(Law,x=Data,param=as.list(dummyParMeas))), 10^(-40))) v1 <- v[!is.infinite(v)] return(-sum(v1)) #-sum(dens(Law,x=Data,param=as.list(dummyParMeas),log = TRUE),na.rm=TRUE) } # aa <- dummyMyfunMeas(par=coef[measure.par], Law=yuima@model@measure$df, # Data=as.numeric(inc.levy), # time=yuima@sampling@delta, param.name=measure.par, # name.time = yuima@[email protected]) if(aggregation){ mytime<-1 }else{ mytime<-yuima@sampling@delta inc.levy1<- as.numeric(inc.levy1) } prova <- optim(fn = dummyMyfunMeas, par = coef[measure.par], method = method,Law=yuima@model@measure$df, Data=inc.levy1, time=mytime, param.name=measure.par, name.time = yuima@[email protected]) Heeee<-optimHess(fn = dummyMyfunMeas, par = coef[measure.par], Law=yuima@model@measure$df, Data=inc.levy1, time=mytime, param.name=measure.par, name.time = yuima@[email protected]) result.Lev <- list(estLevpar=prova$par,covLev=solve(Heeee)) } } if(measurefunc=="rIG"){ # result.Lev<-list(estLevpar=coef[ names.measpar], # covLev=matrix(NA, # length(coef[ names.measpar]), # length(coef[ names.measpar])) # ) # result.Lev<-yuima.Estimation.IG(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) # result.Levy<-gigFit(inc.levy) # Inc.Parm<-coef(result.Levy) # IncVCOV<--solve(gigHessian(inc.levy, param=Inc.Parm)) } if(measurefunc=="rNIG"){ # result.Lev<-yuima.Estimation.NIG(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) } if(measurefunc=="rbgamma"){ result.Lev<-list(estLevpar=coef[ names.measpar], covLev=matrix(NA, length(coef[ names.measpar]), length(coef[ names.measpar])) ) } if(measurefunc=="rvgamma"){ # result.Lev<-yuima.Estimation.VG(Increment.lev=inc.levy1,param0=coef[ names.measpar], # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma) result.Lev<-yuima.Estimation.Lev(Increment.lev=inc.levy1, param0=coef[ names.measpar], fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measurefunc, [email protected], dt=env$h, aggregation=aggregation) } Inc.Parm<-result.Lev$estLevpar IncVCOV<-result.Lev$covLev names(Inc.Parm)[NaIdx]<-measure.par rownames(IncVCOV)[NaIdx]<-as.character(measure.par) colnames(IncVCOV)[NaIdx]<-as.character(measure.par) coef<-NULL coef<-c(dummycoeffCarmapar,Inc.Parm) names.par<-names(coef) cov<-NULL cov<-matrix(0,length(names.par),length(names.par)) rownames(cov)<-names.par colnames(cov)<-names.par if(is.null(loc.par)){ cov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))]<-dummycovCarmapar }else{ cov[unique(c(drift.par,diff.par,[email protected])),unique(c(drift.par,diff.par,[email protected]))]<-dummycovCarmapar } cov[names(Inc.Parm),names(Inc.Parm)]<-IncVCOV } } # dummycovCarmapar<-vcov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))] # dummycovCarmaNoise<-vcov[unique(measure.par),unique(c(measure.par))] #we need to adjusted # dummycoeffCarmapar<-coef[unique(c(drift.par,diff.par))] # dummycoeffCarmaNoise<-coef[unique(c(measure.par))] # coef<-NULL # coef<-c(dummycoeffCarmapar,dummycoeffCarmaNoise) # names.par<-c(unique(c(drift.par,diff.par)),unique(c(measure.par))) # names(coef)<-names.par # cov<-NULL # cov<-matrix(0,length(names.par),length(names.par)) # rownames(cov)<-names.par # colnames(cov)<-names.par # cov[unique(c(drift.par,diff.par)),unique(c(drift.par,diff.par))]<-dummycovCarmapar # cov[unique(c(measure.par)),unique(c(measure.par))]<-dummycovCarmaNoise # carma_final_res<-list(mle=final_res,Incr=inc.levy,model=yuima) if(Est.Incr=="Carma.IncPar"||Est.Incr=="IncrPar"){ #inc.levy.fin<-zoo(inc.levy,tt,frequency=1/env$h) inc.levy.fin<-zoo(inc.levy,tt[(1+length(tt)-length(inc.levy)):length(tt)]) carma_final_res<-new("yuima.carma.qmle", call = call, coef = coef, fullcoef = unlist(coef), vcov = cov, min = min, details = oout, minuslogl = minusquasilogl, method = method, Incr.Lev = inc.levy.fin, model = yuima@model, nobs=yuima.nobs, logL.Incr = tryCatch(-result.Lev$value,error=function(theta){NULL})) }else{ if(Est.Incr=="Carma.Par"||Est.Incr=="NoIncr"){ carma_final_res<-new("mle", call = call, coef = coef, fullcoef = unlist(coef), vcov = cov, min = min, details = oout, minuslogl = minusquasilogl, method = method, nobs=yuima.nobs) } } return(carma_final_res) } } # SMI-2/9/14 CP minusquasipsi <- function(yuima, param, print=FALSE, env){ idx.intensity <- env$idx.intensity fullcoef <- yuima@model@parameter@all measurecoef <- param[unique(c(yuima@model@parameter@measure,yuima@model@parameter@jump))] #print(measurecoef) #cat("\n***\n") npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) #print(param) #cat("\n***\n") #print(fullcoef) #cat("\n***\n") if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] h <- env$h Dn.r <- !env$Cn.r # if(length(idx.intensity)){ # intensity <- unlist(measurecoef[idx.intensity]) #}else{ # intensity <- eval(yuima@model@measure$intensity, envir=env) #} # print(intensity) #print(str(env$time)) # tmp.env <- new.env() #for(i in 1:length(param)){ # assign(names(param)[i],param[[i]],envir=tmp.env) #} #print(ls(env)) d.size <- yuima@[email protected] n <- length(yuima)[1] myidx <- which(Dn.r)[-n] measure <- measure.term(yuima, param, env) QL <- 0 dx <- env$deltaX measure.var <- env$measure.var for(i in 1:length(measurecoef)) #if(!is.Poisson(yuima)){ # if(is.na(match(i,idx.intensity))) # assign(names(measurecoef)[i],measurecoef[i][[1]], envir=env) # } else { assign(names(measurecoef)[i],measurecoef[i][[1]], envir=env) # } # print("### ls(env)") # print(ls(env)) if(is.null(dim(measure[,,1]))){ # one-dimensional for(t in myidx){ iC <- 1/measure[, , t] assign(measure.var,iC%*%dx[t,],envir=env) assign(yuima@[email protected], env$time[t], envir=env) # print("### t") #print(t) #print(env$time[t]) intensity <- eval(yuima@model@measure$intensity, envir=env) #print("intensity") #print(intensity) dF <- intensity*eval(yuima@model@measure$df$expr,envir=env)/iC logpsi <- 0 if(dF>0) logpsi <- log(dF) QL <- QL + logpsi } } else { for(t in myidx){ iC <- solve(measure[, , t]) assign(measure.var,iC%*%dx[t,], envir=env) assign(yuima@[email protected], env$time[t], envir=env) intensity <- eval(yuima@model@measure$intensity, envir=env) dF <- intensity*eval(yuima@model@measure$df$expr,envir=env)*det(iC) logpsi <- 0 if(dF>0) logpsi <- log(dF) QL <- QL + logpsi } } myf <- function(x) { f1 <- function(u){ assign(yuima@[email protected], u, envir=env) intensity <- eval(yuima@model@measure$intensity, envir=env) } sapply(x, f1) } # print(myf(1)) # print(str( try(integrate(f=myf, lower=yuima@sampling@Initial, upper=yuima@sampling@Terminal,subdivisions=100),silent=TRUE ))) myint <- integrate(f=myf, lower=yuima@sampling@Initial, upper=yuima@sampling@Terminal,subdivisions=100)$value # print(myint) #print(-h*intensity*(n-1)) # QL <- QL -h*intensity*(n-1) QL <- QL -myint if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") return(1e10) } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } if(is.infinite(QL)) return(1e10) return(as.numeric(-QL)) } quasilogl <- function(yuima, param, print=FALSE,rcpp=FALSE){ d.size <- yuima@[email protected] if (is(yuima@model, "yuima.carma")){ # 24/12 d.size <-1 } n <- length(yuima)[1] env <- new.env() assign("X", as.matrix(onezoo(yuima)), envir=env) assign("deltaX", matrix(0, n-1, d.size), envir=env) assign("Cn.r", rep(1,n-1), envir=env) if(is.CARMA(yuima)){ env$X<-as.matrix(env$X[,1]) env$deltaX<-as.matrix(env$deltaX[,1]) env$time.obs<-length(env$X) assign("p", yuima@model@info@p, envir=env) assign("q", yuima@model@info@q, envir=env) assign("V_inf0", matrix(diag(rep(1,env$p)),env$p,env$p), envir=env) } for(t in 1:(n-1)) env$deltaX[t,] <- env$X[t+1,] - env$X[t,] assign("h", deltat(yuima@[email protected][[1]]), envir=env) assign("time", as.numeric(index(yuima@[email protected][[1]])), envir=env) -minusquasilogl(yuima=yuima, param=param, print=print, env,rcpp=rcpp) } minusquasilogl <- function(yuima, param, print=FALSE, env,rcpp=FALSE){ diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift if(is.CARMA(yuima)){ if(length(yuima@model@[email protected])!=0){ xinit.par <- yuima@model@parameter@xinit } } if(is.CARMA(yuima) && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@jump)!=0){ diff.par<-yuima@model@parameter@jump # measure.par<-yuima@model@parameter@measure } if(is.CARMA(yuima) && length(yuima@model@[email protected])==0 && length(yuima@model@parameter@measure)!=0){ measure.par<-yuima@model@parameter@measure } # 24/12 if(is.CARMA(yuima) && length(yuima@model@[email protected])>0 ){ yuima.warn("carma(p,q): the case of lin.par will be implemented as soon as") return(NULL) } if(is.CARMA(yuima)){ xinit.par <- yuima@model@parameter@xinit } drift.par <- yuima@model@parameter@drift fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) if(is.CARMA(yuima)){ if(length(xinit.par)>0) fullcoef <- c(fullcoef, xinit.par) } if(is.CARMA(yuima) && (length(yuima@model@parameter@measure)!=0)) fullcoef<-c(fullcoef, measure.par) if(is.CARMA(yuima)){ if("mean.noise" %in% names(param)){ mean.noise<-"mean.noise" fullcoef <- c(fullcoef, mean.noise) NoNeg.Noise<-TRUE } } npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) if(is.CARMA(yuima)){ idx.xinit <-as.integer(na.omit(match(xinit.par, nm))) } h <- env$h Cn.r <- env$Cn.r theta1 <- unlist(param[idx.diff]) theta2 <- unlist(param[idx.drift]) n.theta1 <- length(theta1) n.theta2 <- length(theta2) n.theta <- n.theta1+n.theta2 if(is.CARMA(yuima)){ theta3 <- unlist(param[idx.xinit]) n.theta3 <- length(theta3) n.theta <- n.theta1+n.theta2+n.theta3 } d.size <- yuima@[email protected] n <- length(yuima)[1] if (is.CARMA(yuima)){ # 24/12 d.size <-1 # We build the two step procedure as described in # if(length(yuima@model@[email protected])!=0){ prova<-as.numeric(param) #names(prova)<-fullcoef[oo] names(prova)<-names(param) param<-prova[c(length(prova):1)] time.obs<-env$time.obs y<-as.numeric(env$X) u<-env$h p<-env$p q<-env$q # p<-yuima@model@info@p ar.par <- yuima@model@[email protected] name.ar<-paste0(ar.par, c(1:p)) # q <- yuima@model@info@q ma.par <- yuima@model@[email protected] name.ma<-paste0(ma.par, c(0:q)) if (length(yuima@model@[email protected])==0){ a<-param[name.ar] # a_names<-names(param[c(1:p)]) # names(a)<-a_names b<-param[name.ma] # b_names<-names(param[c((p+1):(length(param)-p+1))]) # names(b)<-b_names if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } sigma<-tail(param,1) }else {sigma<-1} NoNeg.Noise<-FALSE if(is.CARMA(yuima)){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } if(NoNeg.Noise==TRUE){ if (length(b)==p){ #mean.noise<-param[mean.noise] # Be useful for carma driven by a no negative levy process mean.y<-mean(y) #mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma #param[mean.noise]<-mean.y/(tail(b,n=1)/tail(a,n=1)*sigma) }else{ mean.y<-0 } y<-y-mean.y } # V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y, u, a, b, sigma,time.obs,V_inf0,p,q) }else{ # 01/01 # ar.par <- yuima@model@[email protected] # name.ar<-paste0(ar.par, c(1:p)) a<-param[name.ar] # ma.par <- yuima@model@[email protected] # q <- yuima@model@info@q name.ma<-paste0(ma.par, c(0:q)) b<-param[name.ma] if(length(yuima@model@[email protected])!=0){ if(length(b)==1){ b<-1 } else{ indx_b0<-paste0(yuima@model@[email protected],"0",collapse="") b[indx_b0]<-1 } scale.par <- yuima@model@[email protected] sigma <- param[scale.par] } else{sigma <- 1} loc.par <- yuima@model@[email protected] mu <- param[loc.par] NoNeg.Noise<-FALSE if(is.CARMA(yuima)){ if("mean.noise" %in% names(param)){ NoNeg.Noise<-TRUE } } # Lines 883:840 work if we have a no negative noise if(is.CARMA(yuima)&&(NoNeg.Noise==TRUE)){ if (length(b)==p){ mean.noise<-param[mean.noise] # Be useful for carma driven by levy process # mean.y<-mean.noise*tail(b,n=1)/tail(a,n=1)*sigma mean.y<-mean(y-mu) }else{ mean.y<-0 } y<-y-mean.y } y.start <- y-mu #V_inf0<-matrix(diag(rep(1,p)),p,p) V_inf0<-env$V_inf0 p<-env$p q<-env$q strLog<-yuima.carma.loglik1(y.start, u, a, b, sigma,time.obs,V_inf0,p,q) } QL<-strLog$loglikCdiag # }else { # yuima.warn("carma(p,q): the scale parameter is equal to 1. We will implemented as soon as possible") # return(NULL) # } } else if (!rcpp) { drift <- drift.term(yuima, param, env) diff <- diffusion.term(yuima, param, env) QL <- 0 pn <- 0 vec <- env$deltaX-h*drift[-n,] K <- -0.5*d.size * log( (2*pi*h) ) dimB <- dim(diff[, , 1]) if(is.null(dimB)){ # one dimensional X for(t in 1:(n-1)){ yB <- diff[, , t]^2 logdet <- log(yB) pn <- Cn.r[t]*(K - 0.5*logdet-0.5*vec[t, ]^2/(h*yB)) QL <- QL+pn } } else { # multidimensional X for(t in 1:(n-1)){ yB <- diff[, , t] %*% t(diff[, , t]) logdet <- log(det(yB)) if(is.infinite(logdet) ){ # should we return 1e10? pn <- log(1) yuima.warn("singular diffusion matrix") return(1e10) }else{ pn <- (K - 0.5*logdet + ((-1/(2*h))*t(vec[t, ])%*%solve(yB)%*%vec[t, ]))*Cn.r[t] QL <- QL+pn } } } } else { drift_name <- yuima@model@drift diffusion_name <- yuima@model@diffusion ####data <- yuima@[email protected] data <- matrix(0,length(yuima@[email protected][[1]]),d.size) for(i in 1:d.size) data[,i] <- as.numeric(yuima@[email protected][[i]]) env$data <- data ##Kurisaki 5/29/2021 thetadim <- length(yuima@model@parameter@all) noise_number <- yuima@[email protected] assign(yuima@[email protected],env$time[-length(env$time)],envir = env) ##Kurisaki 5/29/2021 for(i in 1:d.size) assign(yuima@[email protected][i], data[-length(data[,1]),i],envir = env) ##Kurisaki 5/29/2021 for(i in 1:thetadim) assign(names(param)[i], param[[i]],envir = env) ##Kurisaki 5/29/2021 d_b <- NULL for(i in 1:d.size){ if(length(eval(drift_name[[i]],envir = env))==(length(data[,1])-1)){ ##Kurisaki 5/29/2021 d_b[[i]] <- drift_name[[i]] #this part of model includes "x"(state.variable) } else{ if(is.na(c(drift_name[[i]][2]))){ #ex. yuima@model@drift=expression(0) (we hope "expression((0))") drift_name[[i]] <- parse(text=paste(sprintf("(%s)", drift_name[[i]])))[[1]] } d_b[[i]] <- parse(text=paste("(",drift_name[[i]][2],")*rep(1,length(data[,1])-1)",sep="")) #vectorization } } v_a<-matrix(list(NULL),d.size,noise_number) for(i in 1:d.size){ for(j in 1:noise_number){ if(length(eval(diffusion_name[[i]][[j]],envir = env))==(length(data[,1])-1)){ ##Kurisaki 5/29/2021 v_a[[i,j]] <- diffusion_name[[i]][[j]] #this part of model includes "x"(state.variable) } else{ if(is.na(c(diffusion_name[[i]][[j]][2]))){ diffusion_name[[i]][[j]] <- parse(text=paste(sprintf("(%s)", diffusion_name[[i]][[j]])))[[1]] } v_a[[i,j]] <- parse(text=paste("(",diffusion_name[[i]][[j]][2],")*rep(1,length(data[,1])-1)",sep="")) #vectorization } } } #for(i in 1:d) assign(yuima@[email protected][i], data[-length(data[,1]),i]) dx_set <- as.matrix((data-rbind(numeric(d.size),as.matrix(data[-length(data[,1]),])))[-1,]) drift_set <- diffusion_set <- NULL #for(i in 1:thetadim) assign(names(param)[i], param[[i]]) for(i in 1:d.size) drift_set <- cbind(drift_set,eval(d_b[[i]],envir = env)) ##Kurisaki 5/29/2021 for(i in 1:noise_number){ for(j in 1:d.size) diffusion_set <- cbind(diffusion_set,eval(v_a[[j,i]],envir = env)) ##Kurisaki 5/29/2021 } QL <- (likndim(dx_set,drift_set,diffusion_set,env$h)*(-0.5) + (n-1)*(-0.5*d.size * log( (2*pi*env$h) ))) } if(!is.finite(QL)){ yuima.warn("quasi likelihood is too small to calculate.") return(1e10) } if(print==TRUE){ yuima.warn(sprintf("NEG-QL: %f, %s", -QL, paste(names(param),param,sep="=",collapse=", "))) } #cat(sprintf("\n%.5f ", -QL)) if(is.infinite(QL)) return(1e10) return(as.numeric(-QL)) } MatrixA<-function (a) { #Build Matrix A in the state space representation of Carma(p,q) #given the autoregressive coefficient pp = length(a) af = cbind(rep(0, pp - 1), diag(pp - 1)) af = rbind(af, -a[pp:1]) return(af) } # yuima.Vinfinity<-function(elForVInf,v){ # # We find the infinity stationary variance-covariance matrix # A<-elForVInf$A # sigma<-elForVInf$sigma # # #p<-dim(A)[1] # # p<-elForVInf$p # ATrans<-elForVInf$ATrans # matrixV<-elForVInf$matrixV # matrixV[upper.tri(matrixV,diag=TRUE)]<-v # matrixV<-as.matrix(forceSymmetric(matrixV)) # #matrixV[lower.tri(matrixV)]<-matrixV[upper.tri(matrixV)] # # l<-rbind(matrix(rep(0,p-1),p-1,1),1) # # matrixV<-matrix(v,p,p) # # lTrans<-elForVInf$lTrans # l<-elForVInf$l # # # RigSid<-l%*%elForVInf$lTrans # Matrixobj<-A%*%matrixV+matrixV%*%ATrans+sigma^2*RigSid # obj<-sum(Matrixobj^2) # obj # } #carma.kalman<-function(y, tt, p, q, a,bvector, sigma){ carma.kalman<-function(y, u, p, q, a,bvector, sigma, times.obs, V_inf0){ #new Code A<-MatrixA(a) expA<-expm(A*u,method="Pade",order=6, trySym=FALSE, do.sparseMsg = FALSE) V_inf<-V0inf(a,p,sigma) expAT<-t(expA) Qmatr <- V_inf - expA %*% V_inf %*% expAT statevar<-numeric(length=p) SigMatr <- V_inf+0 sd_2<-0 Result<-numeric(length=2) Kgain<-numeric(length=p) dum_zc<-numeric(length=p) Mat22int<-numeric(length=(p*p)) loglstar<- .Call("Cycle_Carma", y, statevar, expA, as.integer(length(y)), as.integer(p), Qmatr, SigMatr, bvector, Result, Kgain, dum_zc, Mat22int, PACKAGE="yuima") return(list(loglstar=loglstar[1]-0.5*log(2*pi)*times.obs,s2hat=loglstar[2])) # # Old version # # # V_inf0<-matrix(diag(rep(1,p)),p,p) # # A<-MatrixA(a) # # u<-diff(tt)[1] # # # # Amatx<-yuima.carma.eigen(A) # # expA<-Amatx$vectors%*%expm(diag(Amatx$values*u), # # method="Pade", # # order=6, # # trySym=TRUE, # # do.sparseMsg = TRUE)%*%solve(Amatx$vectors) # # # if(!is.complex(Amatx$values)){ # # expA<-Amatx$vectors%*%diag(exp(Amatx$values*u))%*%solve(Amatx$vectors) # # }else{ # expA<-expm(A*u,method="Pade",order=6, trySym=FALSE, do.sparseMsg = FALSE) # # } # #expA<-yuima.exp(A*u) # # v<-as.numeric(V_inf0[upper.tri(V_inf0,diag=TRUE)]) # # ATrans<-t(A) # matrixV<-matrix(0,p,p) # #l.dummy<-c(rep(0,p-1),1) # l<-rbind(matrix(rep(0,p-1),p-1,1),1) # #l<-matrix(l.dummy,p,1) # #lTrans<-matrix(l.dummy,1,p) # lTrans<-t(l) # elForVInf<-new.env() # elForVInf$A<-A # elForVInf$ATrans<-ATrans # elForVInf$lTrans<-lTrans # elForVInf$l<-l # elForVInf$matrixV<-matrixV # elForVInf$sigma<-sigma # # elForVInf<-list(A=A, # # ATrans=ATrans, # # lTrans=lTrans, # # l=l, # # matrixV=matrixV, # # sigma=sigma) # # # V_inf_vect<-nlm(yuima.Vinfinity, v, # elForVInf = elForVInf)$estimate # # V_inf_vect<-nlminb(start=v,objective=yuima.Vinfinity, elForVInf = elForVInf)$par # # V_inf_vect<-optim(par=v,fn=yuima.Vinfinity,method="L-BFGS-B", elForVInf = elForVInf)$par # V_inf<-matrix(0,p,p) # # V_inf[upper.tri(V_inf,diag=TRUE)]<-V_inf_vect # V_inf<-forceSymmetric(V_inf) # # V_inf[abs(V_inf)<= 1.e-06]=0 # # # A<-MatrixA(a) # # expA<-expm(A*u,method="Pade",order=6, trySym=FALSE, do.sparseMsg = FALSE) # # # # V_inf<-V0inf(a,p,sigma) # # # # # expAT<-t(expA) # #SIGMA_err<-V_inf-expA%*%V_inf%*%t(expA) # SigMatr<-V_inf-expA%*%V_inf%*%expAT # statevar<-matrix(rep(0, p),p,1) # Qmatr<-SigMatr # # # set # #statevar<-statevar0 # # # SigMatr<-expA%*%V_inf%*%t(expA)+Qmatr # # #SigMatr<-Qmatr # SigMatr<-V_inf # # zc<-matrix(bvector,1,p) # loglstar <- 0 # loglstar1 <- 0 # # # zcT<-matrix(bvector,p,1) # zcT<-t(zc) # for(t in 1:times.obs){ # # prediction # statevar<-expA%*%statevar # SigMatr<-expA%*%SigMatr%*%expAT+Qmatr # # forecast # Uobs<-y[t]-zc%*%statevar # dum.zc<-zc%*%SigMatr # sd_2<-dum.zc%*%zcT # # sd_2<-zc%*%SigMatr%*%zcT # Inv_sd_2<-1/sd_2 # #correction # Kgain<-SigMatr%*%zcT%*%Inv_sd_2 # statevar<-statevar+Kgain%*%Uobs # #SigMatr<-SigMatr-Kgain%*%zc%*%SigMatr # SigMatr<-SigMatr-Kgain%*%dum.zc # term_int<--0.5*(log(sd_2)+Uobs%*%Uobs%*%Inv_sd_2) # loglstar<-loglstar+term_int # } # return(list(loglstar=(loglstar-0.5*log(2*pi)*times.obs),s2hat=sd_2)) } V0inf<-function(a,p,sigma){ # This code is based on the paper A continuous-time ARMA process Tsai-Chan 2000 # we need to find the values along the diagonal #l<-c(numeric(length=(p-1)),0.5) # B_{p*p}V^{*}_{p*1}=-sigma^2*l/2 B<-matrix(0,nrow=p,ncol=p) aa <- -rev(a) # B1<-.Call("Coeffdiag_B", as.integer(p), aa, B, # PACKAGE="yuima") # B<-matrix(0,nrow=p,ncol=p) for(i in 1:p){ # Condition on B for(j in 1:p){ if ((2*j-i) %in% c(1:p)){ B[i,j]<-(-1)^(j-i)*aa[2*j-i] } if((2*j-i)==(p+1)){ B[i,j]<-(-1)^(j-i-1) } } } Vdiag <- -solve(B)[,p]*0.5*sigma^2 #V <- diag(Vdiag) if(length(Vdiag)>1){ V <- diag(Vdiag) }else{V <- as.matrix(Vdiag)} # we insert the values outside the diagonal for(i in 1:p){ for(j in (i+1):p){ if((i+j) %% 2 == 0){ # if even V[i,j]=(-1)^((i-j)/2)*V[(i+j)/2,(i+j)/2] V[j,i]=V[i,j] } } } return(V) } # CycleCarma<-function(y, statevar, expA, times.obs=integer(), # p=integer(), Qmatr, SigMatr, zc, loglstar){ # # expAT=t(expA) # # zcT=t(zc) # # for(t in 1:times.obs){ # # t=1 # # # # prediction # # statevar <- expA %*% statevar # # SigMatr <- expA %*% SigMatr %*% t(expA) + Qmatr # # # forecast # # Uobs <- y[t] - zc %*% statevar # 1 - 1Xp px1 # # dum.zc <- zc %*% SigMatr # 1xp pxp # # sd_2 <- dum.zc %*% t(zc) # 1xp px1 # # Inv_sd_2 <- 1/sd_2 # # #correction # # Kgain <- SigMatr %*% t(zc) %*% Inv_sd_2 # pxp px1*1 # # statevar <- statevar+Kgain %*% Uobs # px1+px1 # # SigMatr <- SigMatr - Kgain %*% dum.zc # pxp-px1 1x+ # # term_int<- -0.5 * (log(sd_2)+ Uobs %*% Uobs %*% Inv_sd_2) # every entries are scalars # # loglstar <- loglstar + term_int # every entries are scalars # # } # # expA=matrix(c(1:16),nrow=4,ncol=4) # # SigMatr=matrix(c(1:16),nrow=4,ncol=4)+1 # # Qmatr=matrix(c(1:16),nrow=4,ncol=4)+2 # # vvvvv<-expA%*%SigMatr # # ppppp<-expA%*%SigMatr%*%t(expA)+Qmatr # rY=as.numeric(y) # rStateVar=as.numeric(statevar) # rExpA=as.numeric(expA) # rtime_obs=times.obs # p=p # rQmatr=as.numeric(Qmatr) # rSigMatr=as.numeric(SigMatr) # rZc=as.numeric(zc) # rLogstar=loglstar # In_dum=0 # sd_2=0 # rMat21=numeric(length=p) # rdum_zc=numeric(length=p) # rMat22int=numeric(length=p*p) # rMat22est=numeric(length=p*p) # rKgain=numeric(length=p) # for(t in 1:rtime_obs){ # # prediction # for(i in 1:p){ # rMat21[(i-1)+1] = 0 # for(j in 1:p){ # # statevar <- expA %*% statevar: px1=pxp px1 # rMat21[(i-1)+1] = rMat21[(i-1)+1]+rExpA[(i-1)+(j-1)*p+1]*rStateVar[(j-1)+1] # } # rStateVar[(i-1)+1] = rMat21[(i-1)+1] # statevar <- expA %*% statevar # } # # # SigMatr <- expA %*% SigMatr %*% expAT + Qmatr: pxp = pxp pxp pxp # # First We compute rMat22int <- expA %*% SigMatr : pxp = pxp pxp # for(i in 1:p){ # for(j in 1:p){ # rMat22int[(i-1)+(j-1)*p+1]=0 # for(h in 1:p){ # rMat22int[(i-1)+(j-1)*p+1]=rMat22int[(i-1)+(j-1)*p+1]+rExpA[(i-1)+(h-1)*p+1]* # rSigMatr[(h-1)+(j-1)*p+1] # } # } # } # # Second We compute rMat22est <- rMat22int %*% t(expA) + Qmatr: pxp = pxp pxp + pxp # for(i in 1:p){ # for(j in 1:p){ # rMat22est[(i-1)+(j-1)*p+1]=0 # for(h in 1:p){ # rMat22est[(i-1)+(j-1)*p+1]=rMat22est[(i-1)+(j-1)*p+1]+rMat22int[(i-1)+(h-1)*p+1]*rExpA[(j-1)+(h-1)*p+1] # # } # rSigMatr[(i-1)+(j-1)*p+1]=rMat22est[(i-1)+(j-1)*p+1]+rQmatr[(i-1)+(j-1)*p+1] # } # } # # # forecast # # # Uobs <- y[t] - zc %*% statevar # 1 - 1Xp px1 # rMat22est[1]=0 # for(i in c(1:p)){ # rMat22est[1]=rMat22est[1]+rZc[i]*rStateVar[i] # } # Uobs=rY[t]-rMat22est[1] # # # dum.zc <- zc %*% SigMatr # 1xp pxp # # # for(i in c(1:p)){ # rdum_zc[i]=0 # for(j in c(1:p)){ # rdum_zc[i]=rdum_zc[i]+rZc[j]*rSigMatr[(i-1)*h+j-1+1] # } # } # # sd_2 <- dum.zc %*% zcT # 1xp px1 # sd_2=0 # for(i in c(1:p)){ # sd_2=sd_2+rdum_zc[i]*rZc[i] # } # # #correction # # Kgain <- SigMatr %*% zcT %*% 1/sd_2 # pxp px1*1 # for(i in c(1:p)){ # rMat21[i]=0 # for(j in c(1:p)){ # rMat21[i]=rMat21[i]+rSigMatr[(i-1)+(j-1)*p+1]*rZc[j] # } # rKgain[i]=rMat21[i]/sd_2 # } # # # # statevar <- statevar+Kgain %*% Uobs # px1+px1 # for(i in c(1:p)){ # rStateVar[i] = rStateVar[i] + rKgain[i]*Uobs # } # # SigMatr <- SigMatr - Kgain %*% dum.zc # pxp-px1 1xp # for(i in c(1:p)){ # for(j in c(1:p)){ # rSigMatr[(i-1)+(j-1)*p+1] =rSigMatr[(i-1)+(j-1)*p+1]-rKgain[i]*rdum_zc[j] # } # } # # term_int = -0.5 * (log(sd_2)+ Uobs * Uobs * 1/sd_2) # every entries are scalars # loglstar = loglstar + term_int # every entries are scalars # # # } # Res<-matrix(c(loglstar,sd_2),nrow=2,ncol=1) # return(Res) # } #yuima.PhamBreton.Inv<-function(gamma){ # p<-length(gamma) # a<-gamma[p:1] # if(p>2){ # x<-polynom() # f0<-1*x^0 # f1<-x # f2<-x*f1+gamma[1]*f0 # for(t in 2:(p-1)){ # f0<-f1 # f1<-f2 # f2<-x*f1+gamma[t]*f0 # } # finpol<-f2+gamma[p]*f1 # a <- coef(finpol)[p:1] # } # return(a) # } #yuima.carma.loglik1<-function (y, tt, a, b, sigma) yuima.carma.loglik1<-function (y, u, a, b, sigma,time.obs,V_inf0,p,q) { #This code compute the LogLik using kalman filter # if(a_0!=0){we need to correct the Y_t for the mean} # if(sigma!=1){we need to write} #p <- as.integer(length(a)) # p <- length(a) # bvector <- rep(0, p) # q <- length(b) bvector <- c(b, rep(0, p - q-1)) sigma<-sigma y<-y #xxalt<-carma.kalman(y, tt, p, q, a,bvector,sigma) xxalt<-carma.kalman(y, u, p, q, a,bvector,sigma,time.obs,V_inf0) list(loglikCdiag = xxalt$loglstar,s2hat=xxalt$s2hat) } # returns the vector of log-transitions instead of the final quasilog quasiloglvec <- function(yuima, param, print=FALSE, env){ diff.par <- yuima@model@parameter@diffusion drift.par <- yuima@model@parameter@drift fullcoef <- NULL if(length(diff.par)>0) fullcoef <- diff.par if(length(drift.par)>0) fullcoef <- c(fullcoef, drift.par) npar <- length(fullcoef) nm <- names(param) oo <- match(nm, fullcoef) if(any(is.na(oo))) yuima.stop("some named arguments in 'param' are not arguments to the supplied yuima model") param <- param[order(oo)] nm <- names(param) idx.diff <- match(diff.par, nm) idx.drift <- match(drift.par, nm) h <- env$h theta1 <- unlist(param[idx.diff]) theta2 <- unlist(param[idx.drift]) n.theta1 <- length(theta1) n.theta2 <- length(theta2) n.theta <- n.theta1+n.theta2 d.size <- yuima@[email protected] n <- length(yuima)[1] drift <- drift.term(yuima, param, env) diff <- diffusion.term(yuima, param, env) QL <- numeric(n-1) ## here is the difference pn <- 0 vec <- env$deltaX-h*drift[-n,] K <- -0.5*d.size * log( (2*pi*h) ) dimB <- dim(diff[, , 1]) if(is.null(dimB)){ # one dimensional X for(t in 1:(n-1)){ yB <- diff[, , t]^2 logdet <- log(yB) pn <- K - 0.5*logdet-0.5*vec[t, ]^2/(h*yB) QL[t] <- pn } } else { # multidimensional X for(t in 1:(n-1)){ yB <- diff[, , t] %*% t(diff[, , t]) logdet <- log(det(yB)) if(is.infinite(logdet) ){ # should we return 1e10? pn <- log(1) yuima.warn("singular diffusion matrix") return(1e10) }else{ pn <- K - 0.5*logdet + ((-1/(2*h))*t(vec[t, ])%*%solve(yB)%*%vec[t, ]) QL[t] <- pn } } } return(QL) } setMethod("summary", "yuima.qmle", function (object, ...) { cmat <- cbind(Estimate = object@coef, `Std. Error` = sqrt(diag(object@vcov))) m2logL <- 2 * object@min Additional.Info <- list() if(is(object@model,"yuima.carma")){ Additional.Info <-list(Stationarity = Diagnostic.Carma(object)) } tmp <- new("summary.yuima.qmle", call = object@call, coef = cmat, m2logL = m2logL, model = object@model, Additional.Info = Additional.Info ) tmp } ) setMethod("show", "summary.yuima.qmle", function (object) { cat("Quasi-Maximum likelihood estimation\n\nCall:\n") print(object@call) cat("\nCoefficients:\n") print(coef(object)) cat("\n-2 log L:", object@m2logL, "\n") if(length([email protected])>0){ if(is(object@model,"yuima.carma")){ Dummy<-paste0("\nCarma(",object@model@info@p,",",object@model@info@q,")", collapse = "") if([email protected]$Stationarity){ cat(Dummy,"model: Stationarity conditions are satisfied.\n") }else{ cat(Dummy,"model: Stationarity conditions are not satisfied.\n") } } } } ) setMethod("plot",signature(x="yuima.CP.qmle"), function(x, ...){ t <- [email protected] X <- [email protected] points(x=t,y=X, ...) } ) setMethod("summary", "yuima.CP.qmle", function (object, ...) { cmat <- cbind(Estimate = object@coef, `Std. Error` = sqrt(diag(object@vcov))) m2logL <- 2 * object@min x <- [email protected] j <- [email protected] t <- [email protected] tmp <- new("summary.yuima.CP.qmle", call = object@call, coef = cmat, m2logL = m2logL, NJ = length(t), MeanJ = mean(j,na.rm=TRUE), SdJ = sd(j,na.rm=TRUE), MeanT = mean(diff(t),na.rm=TRUE), X.values = x, Jump.values = j, Jump.times = t, model = object@model, threshold=object@threshold ) tmp } ) setMethod("show", "summary.yuima.CP.qmle", function (object) { cat("Quasi-Maximum likelihood estimation\n\nCall:\n") print(object@call) cat("\nCoefficients:\n") print(coef(object)) cat("\n-2 log L:", object@m2logL, "\n") cat(sprintf("\n\nNumber of estimated jumps: %d\n",object@NJ)) cat(sprintf("\nAverage inter-arrival times: %f\n",object@MeanT)) cat(sprintf("\nAverage jump size: %f\n",object@MeanJ)) cat(sprintf("\nStandard Dev. of jump size: %f\n",object@SdJ)) cat(sprintf("\nJump Threshold: %f\n",object@threshold)) cat("\nSummary statistics for jump times:\n") print(summary([email protected])) cat("\nSummary statistics for jump size:\n") print(summary([email protected],na.rm=TRUE)) cat("\n") } ) # Utilities for estimation of levy in continuous arma model setMethod("summary", "yuima.carma.qmle", function (object, ...) { cmat <- cbind(Estimate = object@coef, `Std. Error` = sqrt(diag(object@vcov))) m2logL <- 2 * object@min data<-Re(coredata([email protected])) data<- data[!is.na(data)] Additional.Info <- list() if(is(object@model,"yuima.carma")){ Additional.Info <-list(Stationarity = Diagnostic.Carma(object)) } tmp <- new("summary.yuima.carma.qmle", call = object@call, coef = cmat, m2logL = m2logL, MeanI = mean(data), SdI = sd(data), logLI = [email protected], TypeI = object@[email protected], NumbI = length(data), StatI = summary(data), Additional.Info = Additional.Info, model = object@model ) tmp } ) setMethod("show", "summary.yuima.carma.qmle", function (object) { cat("Two Stage Quasi-Maximum likelihood estimation\n\nCall:\n") print(object@call) cat("\nCoefficients:\n") print(coef(object)) cat("\n-2 log L:", object@m2logL, "\n") cat(sprintf("\n\nNumber of increments: %d\n",object@NumbI)) cat(sprintf("\nAverage of increments: %f\n",object@MeanI)) cat(sprintf("\nStandard Dev. of increments: %f\n",object@SdI)) if(!is.null(object@logLI)){ cat(sprintf("\n\n-2 log L of increments: %f\n",-2*object@logLI)) } cat("\nSummary statistics for increments:\n") print(object@StatI) cat("\n") if(length([email protected])>0){ if(is(object@model,"yuima.carma")){ Dummy<-paste0("\nCarma(",object@model@info@p,",",object@model@info@q,")", collapse = "") if([email protected]$Stationarity){ cat(Dummy,"model: Stationarity conditions are satisfied.\n") }else{ cat(Dummy,"model: Stationarity conditions are not satisfied.\n") } } } } ) # Plot Method for yuima.carma.qmle setMethod("plot",signature(x="yuima.carma.qmle"), function(x, ...){ Time<-index([email protected]) Incr.L<-coredata([email protected]) if(is.complex(Incr.L)){ yuima.warn("Complex increments. We plot only the real part") Incr.L<-Re(Incr.L) } plot(x=Time,y=Incr.L, ...) } ) #Density code for compound poisson #CPN dCPN<-function(x,lambda,mu,sigma){ a<-min(mu-100*sigma,min(x)-1) b<-max(mu+100*sigma,max(x)+1) ChFunToDens.CPN <- function(n, a, b, lambda, mu, sigma) { i <- 0:(n-1) # Indices dx <- (b-a)/n # Step size, for the density x <- a + i * dx # Grid, for the density dt <- 2*pi / ( n * dx ) # Step size, frequency space c <- -n/2 * dt # Evaluate the characteristic function on [c,d] d <- n/2 * dt # (center the interval on zero) t <- c + i * dt # Grid, frequency space charact.CPN<-function(t,lambda,mu,sigma){ normal.y<-exp(1i*t*mu-sigma^2*t^2/2) y<-exp(lambda*(normal.y-1)) } phi_t <- charact.CPN(t,lambda,mu,sigma) X <- exp( -(0+1i) * i * dt * a ) * phi_t Y <- fft(X) density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y data.frame( i = i, t = t, characteristic_function = phi_t, x = x, density = Re(density) ) } invFFT<-ChFunToDens.CPN(lambda=lambda,mu=mu,sigma=sigma,n=2^10,a=a,b=b) dens<-approx(invFFT$x,invFFT$density,x) return(dens$y) } # CExp dCPExp<-function(x,lambda,rate){ a<-10^-6 b<-max(1/rate*10 +1/rate^2*10 ,max(x[!is.na(x)])+1) ChFunToDens.CPExp <- function(n, a, b, lambda, rate) { i <- 0:(n-1) # Indices dx <- (b-a)/n # Step size, for the density x <- a + i * dx # Grid, for the density dt <- 2*pi / ( n * dx ) # Step size, frequency space c <- -n/2 * dt # Evaluate the characteristic function on [c,d] d <- n/2 * dt # (center the interval on zero) t <- c + i * dt # Grid, frequency space charact.CPExp<-function(t,lambda,rate){ normal.y<-(rate/(1-1i*t)) # exp(1i*t*mu-sigma^2*t^2/2) y<-exp(lambda*(normal.y-1)) } phi_t <- charact.CPExp(t,lambda,rate) X <- exp( -(0+1i) * i * dt * a ) * phi_t Y <- fft(X) density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y data.frame( i = i, t = t, characteristic_function = phi_t, x = x, density = Re(density) ) } invFFT<-ChFunToDens.CPExp(lambda=lambda,rate=rate,n=2^10,a=a,b=b) dens<-approx(invFFT$x[!is.na(invFFT$density)],invFFT$density[!is.na(invFFT$density)],x) return(dens$y[!is.na(dens$y)]) } # CGamma dCPGam<-function(x,lambda,shape,scale){ a<-10^-6 b<-max(shape*scale*10 +shape*scale^2*10 ,max(x[!is.na(x)])+1) ChFunToDens.CPGam <- function(n, a, b, lambda, shape,scale) { i <- 0:(n-1) # Indices dx <- (b-a)/n # Step size, for the density x <- a + i * dx # Grid, for the density dt <- 2*pi / ( n * dx ) # Step size, frequency space c <- -n/2 * dt # Evaluate the characteristic function on [c,d] d <- n/2 * dt # (center the interval on zero) t <- c + i * dt # Grid, frequency space charact.CPGam<-function(t,lambda,shape,scale){ normal.y<-(1-1i*t*scale)^(-shape) # exp(1i*t*mu-sigma^2*t^2/2) y<-exp(lambda*(normal.y-1)) } phi_t <- charact.CPGam(t,lambda,shape,scale) X <- exp( -(0+1i) * i * dt * a ) * phi_t Y <- fft(X) density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y data.frame( i = i, t = t, characteristic_function = phi_t, x = x, density = Re(density) ) } invFFT<-ChFunToDens.CPGam(lambda=lambda,shape=shape,scale=scale,n=2^10,a=a,b=b) dens<-approx(invFFT$x[!is.na(invFFT$density)],invFFT$density[!is.na(invFFT$density)],x) return(dens$y[!is.na(dens$y)]) } minusloglik.Lev <- function(par,env){ if(env$measure.type=="code"){ if(env$measure=="rNIG"){ alpha<-par[1] beta<-par[2] delta<-par[3] mu<-par[4] f<-dNIG(env$data,alpha,beta,delta,mu) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) }else{ if(env$measure=="rvgamma"){ lambda<-par[1] alpha<-par[2] beta<-par[3] mu<-par[4] f<-dvgamma(env$data,lambda,alpha,beta,mu) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) }else{ if(env$measure=="rIG"){ delta<-par[1] gamma<-par[2] f<-dIG(env$data,delta,gamma) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) } } } }else{ if(env$measure=="dnorm"){ lambda<-par[1] mu<-par[2] sigma<-par[3] f<-dCPN(env$data,lambda,mu,sigma) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) }else{ if(env$measure=="dexp"){ lambda<-par[1] rate<-par[2] # -sum(log(dCPExp(env$data,lambda,rate))) f<-dCPExp(env$data,lambda,rate) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) }else{ if(env$measure=="dgamma"){ lambda<-par[1] shape<-par[2] scale<-par[3] # -sum(log(dCPGam(env$data,lambda,shape,scale))) f<-dCPGam(env$data,lambda,shape,scale) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] -sum(v1) } } } } } Lev.hessian<-function (params,env){ logLik.Lev <- function(params){ if(env$measure.type=="code"){ if(env$measure=="rNIG"){ alpha<-params[1] beta<-params[2] delta<-params[3] mu<-params[4] # return(sum(log(dNIG(env$data,alpha,beta,delta,mu)))) f<-dNIG(env$data,alpha,beta,delta,mu) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] return(sum(v1)) }else{ if(env$measure=="rvgamma"){ lambda<-params[1] alpha<-params[2] beta<-params[3] mu<-params[4] #return(sum(log(dvgamma(env$data,lambda,alpha,beta,mu)))) f<-dvgamma(env$data,lambda,alpha,beta,mu) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] return(sum(v1)) }else{ if(env$measure=="rIG"){ delta<-params[1] gamma<-params[2] f<-dIG(env$data,delta,gamma) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] return(sum(v1)) }else{ if(env$measure=="rgamma"){ shape<-params[1] rate<-params[2] f<-dgamma(env$data,shape,rate) v<-log(as.numeric(na.omit(f))) v1<-v[!is.infinite(v)] return(sum(v1)) } } } } }else{ if(env$measure=="dnorm"){ lambda<-params[1] mu<-params[2] sigma<-params[3] return(sum(log(dCPN(env$data,lambda,mu,sigma)))) }else{ if(env$measure=="dexp"){ lambda<-params[1] rate<-params[2] return(sum(log(dCPExp(env$data,lambda,rate)))) }else{ if(env$measure=="dgamma"){ lambda<-params[1] shape<-params[2] scale<-params[3] return(sum(log(dCPGam(env$data,lambda,shape,scale)))) } } } } } hessian<-tryCatch(optimHess(par=params, fn=logLik.Lev), error=function(theta){matrix(NA,env$lengpar,env$lengpar)}) if(env$aggregation==FALSE){ if(env$measure.type=="CP"){ Matr.dum<-diag(c(1/env$dt, rep(1, (length(params)-1)))) }else{ if(env$measure=="rNIG"){ Matr.dum<-diag(c(1,1,1/env$dt,1/env$dt)) }else{ if(env$measure=="rvgamma"){ Matr.dum<-diag(c(1/env$dt,1,1,1/env$dt)) }else{ if(env$measure=="rIG"){ Matr.dum<-diag(c(1/env$dt,1)) }else{ if(env$measure=="rgamma"){ Matr.dum<-diag(c(1/env$dt,1)) } } } } } cov<--Matr.dum%*%solve(hessian)%*%Matr.dum }else{ cov<--solve(hessian) } return(cov) } yuima.Estimation.Lev<-function(Increment.lev,param0, fixed.carma=fixed.carma, lower.carma=lower.carma, upper.carma=upper.carma, measure=measure, measure.type=measure.type, dt=env$h, aggregation=aggregation){ env<-new.env() env$data<-Increment.lev env$measure<-measure env$measure.type<-measure.type # Only one problem env$dt<-dt if(aggregation==FALSE){ if(measure.type=="code"){ if(env$measure=="rNIG"){ #Matr.dum<-diag(c(1,1,1/env$dt,1/env$dt)) param0[3]<-param0[3]*dt param0[4]<-param0[4]*dt }else{ if(env$measure=="rvgamma"){ #Matr.dum<-diag(c(1/env$dt,1,1,1/env$dt)) param0[1]<-param0[1]*dt param0[4]<-param0[4]*dt }else{ if(env$measure=="rIG"){ #Matr.dum<-diag(c(1/env$dt,1)) param0[1]<-param0[1]*dt }else{ if(env$measure=="rgamma"){ param0[1]<-param0[1]*dt } } } } }else{ param0[1]<-param0[1]*dt } } # For NIG if(measure.type=="code"){ if(measure=="rNIG"){ ui<-rbind(c(1, -1, 0, 0),c(1, 1, 0, 0),c(1, 0, 0, 0),c(0, 0, 1, 0)) ci<-c(0,0,0,10^(-6)) }else{ if(measure=="rvgamma"){ ui<-rbind(c(1,0, 0, 0),c(0, 1, 1, 0),c(0, 1,-1, 0),c(0, 1,0, 0)) ci<-c(10^-6,10^-6,10^(-6), 0) }else{ if(measure=="rIG"){ ui<-rbind(c(1,0),c(0, 1)) ci<-c(10^-6,10^-6) }else{ if(measure=="rgamma"){ ui<-rbind(c(1,0),c(0, 1)) ci<-c(10^-6,10^-6) } } } } }else{ if(measure=="dnorm"){ ui<-rbind(c(1,0,0),c(0,0,1)) ci<-c(10^-6,10^-6) }else{ if(measure=="dexp"){ ui<-rbind(c(1,0),c(0,1)) ci<-c(10^-6,10^-6) }else{ if(measure=="dgamma"){ ui<-rbind(c(1,0,0),c(0,1,0),c(0,0,1)) ci<-c(10^-6,10^-6,10^-6) } } } } if(!is.null(lower.carma)){ lower.con<-matrix(0,length(lower.carma),length(param0)) rownames(lower.con)<-names(lower.carma) colnames(lower.con)<-names(param0) numb.lower<-length(lower.carma) lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) dummy.lower.names<-paste0(names(lower.carma),".lower") rownames(lower.con)<-dummy.lower.names names(lower.carma)<-dummy.lower.names ui<-rbind(ui,lower.con) ci<-c(ci,lower.carma) #idx.lower.carma<-match(names(lower.carma),names(param0)) } if(!is.null(upper.carma)){ upper.con<-matrix(0,length(upper.carma),length(param0)) rownames(upper.con)<-names(upper.carma) colnames(upper.con)<-names(param0) numb.upper<-length(upper.carma) upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) dummy.upper.names<-paste0(names(upper.carma),".upper") rownames(upper.con)<-dummy.upper.names names(upper.carma)<-dummy.upper.names ui<-rbind(ui,upper.con) ci<-c(ci,-upper.carma) } if(!is.null(fixed.carma)){ names.fixed<-names(fixed.carma) numb.fixed<-length(fixed.carma) fixed.con<-matrix(0,length(fixed.carma),length(param0)) rownames(fixed.con)<-names(fixed.carma) colnames(fixed.con)<-names(param0) fixed.con.bis<-fixed.con fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") rownames(fixed.con)<-dummy.fixed.names rownames(fixed.con.bis)<-dummy.fixed.bis.names names(fixed.carma)<-dummy.fixed.names ui<-rbind(ui,fixed.con,fixed.con.bis) ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) #ci<-c(ci,-fixed.carma,fixed.carma) } lengpar<-length(param0) paramLev<-NA*c(1:length(lengpar)) env$lengpar<-lengpar firs.prob<-tryCatch(constrOptim(theta=param0, f=minusloglik.Lev,grad=NULL,ui=ui,ci=ci,env=env), error=function(theta){NULL}) if(!is.null(firs.prob)){ paramLev<-firs.prob$par names(paramLev)<-names(param0) if(!is.null(fixed.carma)){ paramLev[names.fixed]<-fixed.carma names(paramLev)<-names(param0) } }else{warning("the start value for levy measure is outside of the admissible region")} env$aggregation<-aggregation if(is.na(paramLev[1])){ covLev<-matrix(0,length(paramLev),length(paramLev)) }else{ covLev<-Lev.hessian(params=paramLev,env) rownames(covLev)<-names(paramLev) if(!is.null(fixed.carma)){ covLev[names.fixed,]<-matrix(0,numb.fixed,lengpar) } colnames(covLev)<-names(paramLev) if(!is.null(fixed.carma)){ covLev[,names.fixed]<-matrix(0,lengpar,numb.fixed) } } if(aggregation==FALSE){ if(measure.type=="code"){ if(env$measure=="rNIG"){ #Matr.dum<-diag(c(1,1,1/env$dt,1/env$dt)) paramLev[3]<-paramLev[3]/dt paramLev[4]<-paramLev[4]/dt }else{ if(env$measure=="rvgamma"){ #Matr.dum<-diag(c(1/env$dt,1,1,1/env$dt)) paramLev[1]<-paramLev[1]/dt paramLev[4]<-paramLev[4]/dt }else{ if(env$measure=="rIG"){ #Matr.dum<-diag(c(1/env$dt,1)) paramLev[1]<-paramLev[1]/dt }else{ if(env$measure=="rgamma"){ paramLev[1]<-paramLev[1]/dt } } } } }else{ paramLev[1]<-paramLev[1]/dt } } results<-list(estLevpar=paramLev,covLev=covLev, value=firs.prob$value) return(results) } # Normal Inverse Gaussian # yuima.Estimation.NIG<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # # minusloglik.dNIG<-function(par,data){ # alpha<-par[1] # beta<-par[2] # delta<-par[3] # mu<-par[4] # -sum(log(dNIG(data,alpha,beta,delta,mu))) # } # # data<-Increment.lev # # # Only one problem # # # ui<-rbind(c(1, -1, 0, 0),c(1, 1, 0, 0),c(1, 0, 0, 0),c(0, 0, 1, 0)) # ci<-c(0,0,0,10^(-6)) # # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # # # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dNIG,grad=NULL,ui=ui,ci=ci,data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:length(lengpar)) # # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # }else{warning("the start value for levy measure is outside of the admissible region")} # # NIG.hessian<-function (data,params){ # logLik.NIG <- function(params) { # # alpha<-params[1] # beta<-params[2] # delta<-params[3] # mu<-params[4] # # return(sum(log(dNIG(data,alpha,beta,delta,mu)))) # } # hessian<-optimHess(par=params, fn=logLik.NIG) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA,length(paramLev),length(paramLev)) # }else{ # covLev<-NIG.hessian(data=as.numeric(data),params=paramLev) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # } # # # # # Variance Gaussian # # yuima.Estimation.VG<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # # minusloglik.dVG<-function(par,data){ # lambda<-par[1] # alpha<-par[2] # beta<-par[3] # mu<-par[4] # -sum(log(dvgamma(data,lambda,alpha,beta,mu))) # } # # data<-Increment.lev # # ui<-rbind(c(1,0, 0, 0),c(0, 1, 1, 0),c(0, 1,-1, 0),c(0, 1,0, 0)) # ci<-c(10^-6,10^-6,10^(-6), 0) # # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # # # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dVG,grad=NULL,ui=ui,ci=ci,data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:length(lengpar)) # # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # } # # # VG.hessian<-function (data,params){ # logLik.VG <- function(params) { # # lambda<-params[1] # alpha<-params[2] # beta<-params[3] # mu<-params[4] # # return(sum(log(dvgamma(data,lambda,alpha,beta,mu)))) # } # # hessian <- tsHessian(param = params, fun = logLik.VG) # #hessian<-optimHess(par, fn, gr = NULL,data=data) # hessian<-optimHess(par=params, fn=logLik.VG) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA,length(paramLev),length(paramLev)) # }else{ # covLev<-VG.hessian(data=as.numeric(data),params=paramLev) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # } # # # Inverse Gaussian # # yuima.Estimation.IG<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # # minusloglik.dIG<-function(par,data){ # delta<-par[1] # gamma<-par[2] # f<-dIG(data,delta,gamma) # v<-log(as.numeric(na.omit(f))) # v1<-v[!is.infinite(v)] # -sum(v1) # } # # data<-Increment.lev # # ui<-rbind(c(1,0),c(0, 1)) # ci<-c(10^-6,10^-6) # # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # # # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dIG, # grad=NULL, # ui=ui, # ci=ci, # data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:length(lengpar)) # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # } # # IG.hessian<-function (data,params){ # logLik.IG <- function(params) { # # delta<-params[1] # gamma<-params[2] # f<-dIG(data,delta,gamma) # v<-log(as.numeric(na.omit(f))) # v1<-v[!is.infinite(v)] # return(sum(v1)) # } # # hessian <- tsHessian(param = params, fun = logLik.VG) # #hessian<-optimHess(par, fn, gr = NULL,data=data) # hessian<-optimHess(par=params, fn=logLik.IG) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA,length(paramLev),length(paramLev)) # }else{ # covLev<-IG.hessian(data=as.numeric(data),params=paramLev) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # } # # # Compound Poisson-Normal # # yuima.Estimation.CPN<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # dCPN<-function(x,lambda,mu,sigma){ # a<-min(mu-100*sigma,min(x)-1) # b<-max(mu+100*sigma,max(x)+1) # ChFunToDens.CPN <- function(n, a, b, lambda, mu, sigma) { # i <- 0:(n-1) # Indices # dx <- (b-a)/n # Step size, for the density # x <- a + i * dx # Grid, for the density # dt <- 2*pi / ( n * dx ) # Step size, frequency space # c <- -n/2 * dt # Evaluate the characteristic function on [c,d] # d <- n/2 * dt # (center the interval on zero) # t <- c + i * dt # Grid, frequency space # charact.CPN<-function(t,lambda,mu,sigma){ # normal.y<-exp(1i*t*mu-sigma^2*t^2/2) # y<-exp(lambda*(normal.y-1)) # } # phi_t <- charact.CPN(t,lambda,mu,sigma) # X <- exp( -(0+1i) * i * dt * a ) * phi_t # Y <- fft(X) # density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y # data.frame( # i = i, # t = t, # characteristic_function = phi_t, # x = x, # density = Re(density) # ) # } # invFFT<-ChFunToDens.CPN(lambda=lambda,mu=mu,sigma=sigma,n=2^12,a=a,b=b) # dens<-approx(invFFT$x,invFFT$density,x) # return(dens$y) # } # # minusloglik.dCPN<-function(par,data){ # lambda<-par[1] # mu<-par[2] # sigma<-par[3] # -sum(log(dCPN(data,lambda,mu,sigma))) # } # # data<-Increment.lev # # ui<-rbind(c(1,0,0),c(0,0,1)) # ci<-c(10^-6,10^-6) # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dCPN, # grad=NULL, # ui=ui, # ci=ci, # data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:lengpar) # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # } # # CPN.hessian<-function (data,params,lengpar){ # logLik.CPN <- function(params) { # # lambda<-params[1] # mu<-params[2] # sigma<-params[3] # return(sum(log(dCPN(data,lambda,mu,sigma)))) # } # # hessian <- tsHessian(param = params, fun = logLik.VG) # #hessian<-optimHess(par, fn, gr = NULL,data=data) # hessian<-tryCatch(optimHess(par=params, fn=logLik.CPN), # error=function(theta){matrix(NA,lengpar,lengpar)}) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA, lengpar,lengpar) # }else{ # covLev<-CPN.hessian(data=as.numeric(data),params=paramLev,lengpar=lengpar) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # } # # yuima.Estimation.CPExp<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # dCPExp<-function(x,lambda,rate){ # a<-10^-6 # b<-max(1/rate*10 +1/rate^2*10 ,max(x[!is.na(x)])+1) # ChFunToDens.CPExp <- function(n, a, b, lambda, rate) { # i <- 0:(n-1) # Indices # dx <- (b-a)/n # Step size, for the density # x <- a + i * dx # Grid, for the density # dt <- 2*pi / ( n * dx ) # Step size, frequency space # c <- -n/2 * dt # Evaluate the characteristic function on [c,d] # d <- n/2 * dt # (center the interval on zero) # t <- c + i * dt # Grid, frequency space # charact.CPExp<-function(t,lambda,rate){ # normal.y<-(rate/(1-1i*t)) # # exp(1i*t*mu-sigma^2*t^2/2) # y<-exp(lambda*(normal.y-1)) # } # phi_t <- charact.CPExp(t,lambda,rate) # X <- exp( -(0+1i) * i * dt * a ) * phi_t # Y <- fft(X) # density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y # data.frame( # i = i, # t = t, # characteristic_function = phi_t, # x = x, # density = Re(density) # ) # } # invFFT<-ChFunToDens.CPExp(lambda=lambda,rate=rate,n=2^12,a=a,b=b) # dens<-approx(invFFT$x[!is.na(invFFT$density)],invFFT$density[!is.na(invFFT$density)],x) # return(dens$y[!is.na(dens$y)]) # } # # minusloglik.dCPExp<-function(par,data){ # lambda<-par[1] # rate<-par[2] # -sum(log(dCPExp(data,lambda,rate))) # } # # data<-Increment.lev # # ui<-rbind(c(1,0),c(0,1)) # ci<-c(10^-6,10^-6) # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dCPExp, # grad=NULL, # ui=ui, # ci=ci, # data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:length(lengpar)) # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # } # # # CPExp.hessian<-function (data,params){ # logLik.CPExp <- function(params) { # # lambda<-params[1] # rate<-params[2] # # return(sum(log(dCPExp(data,lambda,rate)))) # } # # hessian <- tsHessian(param = params, fun = logLik.VG) # #hessian<-optimHess(par, fn, gr = NULL,data=data) # hessian<-optimHess(par=params, fn=logLik.CPExp) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA,length(paramLev),length(paramLev)) # }else{ # covLev<-CPExp.hessian(data=as.numeric(data),params=paramLev) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # } # # yuima.Estimation.CPGam<-function(Increment.lev,param0, # fixed.carma=fixed.carma, # lower.carma=lower.carma, # upper.carma=upper.carma){ # dCPGam<-function(x,lambda,shape,scale){ # a<-10^-6 # b<-max(shape*scale*10 +shape*scale^2*10 ,max(x[!is.na(x)])+1) # ChFunToDens.CPGam <- function(n, a, b, lambda, shape,scale) { # i <- 0:(n-1) # Indices # dx <- (b-a)/n # Step size, for the density # x <- a + i * dx # Grid, for the density # dt <- 2*pi / ( n * dx ) # Step size, frequency space # c <- -n/2 * dt # Evaluate the characteristic function on [c,d] # d <- n/2 * dt # (center the interval on zero) # t <- c + i * dt # Grid, frequency space # charact.CPGam<-function(t,lambda,shape,scale){ # normal.y<-(1-1i*t*scale)^(-shape) # # exp(1i*t*mu-sigma^2*t^2/2) # y<-exp(lambda*(normal.y-1)) # } # phi_t <- charact.CPGam(t,lambda,shape,scale) # X <- exp( -(0+1i) * i * dt * a ) * phi_t # Y <- fft(X) # density <- dt / (2*pi) * exp( - (0+1i) * c * x ) * Y # data.frame( # i = i, # t = t, # characteristic_function = phi_t, # x = x, # density = Re(density) # ) # } # invFFT<-ChFunToDens.CPGam(lambda=lambda,shape=shape,scale=scale,n=2^12,a=a,b=b) # dens<-approx(invFFT$x[!is.na(invFFT$density)],invFFT$density[!is.na(invFFT$density)],x) # return(dens$y[!is.na(dens$y)]) # } # # minusloglik.dCPGam<-function(par,data){ # lambda<-par[1] # shape<-par[2] # scale<-par[3] # -sum(log(dCPGam(data,lambda,shape,scale))) # } # # data<-Increment.lev # # ui<-rbind(c(1,0,0),c(0,1,0),c(0,1,0)) # ci<-c(10^-6,10^-6,10^-6) # # if(!is.null(lower.carma)){ # lower.con<-matrix(0,length(lower.carma),length(param0)) # rownames(lower.con)<-names(lower.carma) # colnames(lower.con)<-names(param0) # numb.lower<-length(lower.carma) # lower.con[names(lower.carma),names(lower.carma)]<-1*diag(numb.lower) # dummy.lower.names<-paste0(names(lower.carma),".lower") # rownames(lower.con)<-dummy.lower.names # names(lower.carma)<-dummy.lower.names # ui<-rbind(ui,lower.con) # ci<-c(ci,lower.carma) # #idx.lower.carma<-match(names(lower.carma),names(param0)) # } # if(!is.null(upper.carma)){ # upper.con<-matrix(0,length(upper.carma),length(param0)) # rownames(upper.con)<-names(upper.carma) # colnames(upper.con)<-names(param0) # numb.upper<-length(upper.carma) # upper.con[names(upper.carma),names(upper.carma)]<--1*diag(numb.upper) # dummy.upper.names<-paste0(names(upper.carma),".upper") # rownames(upper.con)<-dummy.upper.names # names(upper.carma)<-dummy.upper.names # ui<-rbind(ui,upper.con) # ci<-c(ci,-upper.carma) # } # if(!is.null(fixed.carma)){ # names.fixed<-names(fixed.carma) # numb.fixed<-length(fixed.carma) # fixed.con<-matrix(0,length(fixed.carma),length(param0)) # rownames(fixed.con)<-names(fixed.carma) # colnames(fixed.con)<-names(param0) # fixed.con.bis<-fixed.con # fixed.con[names(fixed.carma),names(fixed.carma)]<--1*diag(numb.fixed) # fixed.con.bis[names(fixed.carma),names(fixed.carma)]<-1*diag(numb.fixed) # dummy.fixed.names<-paste0(names(fixed.carma),".fixed.u") # dummy.fixed.bis.names<-paste0(names(fixed.carma),".fixed.l") # rownames(fixed.con)<-dummy.fixed.names # rownames(fixed.con.bis)<-dummy.fixed.bis.names # names(fixed.carma)<-dummy.fixed.names # ui<-rbind(ui,fixed.con,fixed.con.bis) # ci<-c(ci,-fixed.carma-10^-6,fixed.carma-10^-6) # #ci<-c(ci,-fixed.carma,fixed.carma) # } # # # firs.prob<-tryCatch(constrOptim(theta=param0, # f=minusloglik.dCPGam, # grad=NULL, # ui=ui, # ci=ci, # data=data), # error=function(theta){NULL}) # # lengpar<-length(param0) # paramLev<-NA*c(1:length(lengpar)) # if(!is.null(firs.prob)){ # paramLev<-firs.prob$par # names(paramLev)<-names(param0) # if(!is.null(fixed.carma)){ # paramLev[names.fixed]<-fixed.carma # names(paramLev)<-names(param0) # } # } # # # CPGam.hessian<-function (data,params){ # logLik.CPGam <- function(params) { # # lambda<-params[1] # shape<-params[2] # scale<-params[3] # # return(sum(log(dCPGam(data,lambda,shape,scale)))) # } # # hessian <- tsHessian(param = params, fun = logLik.VG) # #hessian<-optimHess(par, fn, gr = NULL,data=data) # hessian<-optimHess(par=params, fn=logLik.CPGam) # cov<--solve(hessian) # return(cov) # } # # if(is.na(paramLev)){ # covLev<-matrix(NA,length(paramLev),length(paramLev)) # }else{ # covLev<-CPGam.hessian(data=as.numeric(data),params=paramLev) # rownames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[names.fixed,]<-matrix(NA,numb.fixed,lengpar) # } # colnames(covLev)<-names(paramLev) # if(!is.null(fixed.carma)){ # covLev[,names.fixed]<-matrix(NA,lengpar,numb.fixed) # } # } # results<-list(estLevpar=paramLev,covLev=covLev) # return(results) # }
/scratch/gouwar.j/cran-all/cranData/yuima/R/qmle.R
######################################################################## # Stepwise estimation for ergodic Levy driven SDE ######################################################################## #qmleLevy<-function(yuima,start,lower,upper,joint = FALSE,third = FALSE, # Est.Incr = c("NoIncr","Incr","IncrPar"), # aggregation = TRUE) qmleLevy<-function(yuima,start,lower,upper,joint = FALSE,third = FALSE, Est.Incr = "NoIncr", aggregation = TRUE) { oldyuima<-yuima #line1 myjumpname <- yuima@[email protected] mymeasureparam <- yuima@model@parameter@measure if(!(Est.Incr %in% c("NoIncr","Incr","IncrPar"))) stop("Argument'Est.Incr' must be one of \"NoIncr\",\"Incr\" or \"IncrPar\"") call <- match.call() truestart<-start cat("\nStarting QGMLE for SDE ... \n") parameter<-yuima@model@parameter@all orig.mylaw<-yuima@model@measure mylaw<-yuima@model@measure$df numbLev<-length(yuima@[email protected]) if(missing(yuima)) yuima.stop("yuima object is missing.") if(!is(yuima,"yuima")) yuima.stop("This function is for yuima-class.") if(length(yuima@model@parameter@jump)>0) paracoef <- yuima@model@parameter@jump if(length(yuima@model@parameter@drift)>0) paracoef <- c(paracoef, yuima@model@parameter@drift) if(Est.Incr == "IncrPar"){ start0<-start lower0<-lower upper0<-upper lev.names<-yuima@model@parameter@measure } DRIFT <- yuima@model@drift JUMP <- yuima@[email protected] sdeModel<-yuima@model if(length(sdeModel@parameter@measure)!=0){ nPar<-length(sdeModel@parameter@measure) for(i in c(1:nPar)){ assign(x = sdeModel@parameter@measure[i], value = start[[sdeModel@parameter@measure[i]]]) } names1 <- names(start) index <- which(names1 %in% sdeModel@parameter@measure) start <- start[-index] names1 <- names(lower) index <- which(names1 %in% sdeModel@parameter@measure) lower <- lower[-index] names1 <- names(upper) index <- which(names1 %in% sdeModel@parameter@measure) upper <- upper[-index] } #if(class(sdeModel@measure$df)!="yuima.law"){ if(!inherits(sdeModel@measure$df, "yuima.law")){ # fixed by YK code <- suppressWarnings(sub("^(.+?)\\(.+", "\\1", sdeModel@measure$df$expr, perl=TRUE)) candinoise<-c("rNIG","rvgamma","rnts","rbgamma") if(is.na(match(code,candinoise))){ yuima.stop("This function works only for the standardized normal inverse Gaussian process, variance gamma process, bilateral gamma process, and normal tempered stable process now.") } if(length(sdeModel@xinit) == 1){ args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", sdeModel@measure$df$expr, perl=TRUE)), ",")) if(code == "rNIG"){ if(!((abs(eval(parse(text = paste("(",args[5] ,")+(", args[3], ")*(", args[4], ")/sqrt((", args[2], ")^2-(", args[3], ")^2)" )))) < 10^(-10)) && (abs(eval(parse(text = paste("(",args[2], ")^2*(", args[4], ")/(sqrt((", args[2], ")^2-(", args[3], ")^2))^3"))) -1) < 10^(-10)))) { yuima.stop("This function is only for standardized Levy noises.") } } else if(code == "rvgamma"){ if(!((abs(eval(parse(text = paste("(", args[5], ")+2*(", args[2], ")*(", args[4], ")/((", args[3], ")^2-(" , args[4], ")^2)" )))) < 10^(-10)) && (abs(eval(parse(text = paste("2*((", args[2], ")*(", args[3], ")^2+(", args[4], ")^2)", "/((" , args[3], ")^2-(", args[4], ")^2)^2"))) - 1) < 10^(-10)))) { yuima.stop("This function is only for standardized Levy noises") } } else if((code == "rnts")){ if(!((abs(eval(parse(text = paste("(", args[6], ")-(", args[2], ")*(", args[3], ")*(", args[4], ")^((", args[2], ")-1)*gamma(1-(", args[2], "))*(-1/(", args[2],"))*(", args[5], ")" )))) < 10^(-10)) &&(abs(eval(parse(text = paste("(", args[3], ")*(", args[2],")*((", args[2], ")-1)*gamma(1-(", args[2], "))*(-1/(", args[2],"))*(", args[4], ")^((",args[2], ")-2)*(", args[5], ")^2-(", args[2], ")*(", args[3], ")*(", args[4], ")^((", args[2], ")-1)*gamma(1-(", args[2], "))*(-1/(", args[2],"))" ))) - 1) < 10^(-10)))) { yuima.stop("This function is only for standardized Levy processes.") } }else if(code == "rbgamma"){ if(!((abs(eval(parse(text = paste("(", args[2], ")/(", args[3],")-(", args[4],")/(", args[5], ")")))) < 10^(-10)) && (abs(eval(parse(text = paste("(", args[2], ")/(", args[3], ")^2","+(", args[4],")/(", args[5],")^2" ))) - 1) < 10^(-10) ))) { yuima.stop("This function is only for standardized Levy processes.") } } }else{ warning("In this version, the standardized conditions on multidimensional noises can not be verified. The expressions of mean and variance are given in help page.") # The noise condition checker below does not work now (YU: 3/23). # args <- suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", sdeModel@measure$df$expr, perl=TRUE)) # yuimaEnv <- new.env() # yuimaEnv$mean <- switch(code, # rNIG = function(x=1,alpha,beta,delta0,mu,Lambda){mu+as.vector(delta0/(sqrt(alpha^2-t(beta)%*%Lambda%*%beta)))*Lambda%*%beta}, # rnts = function(x=1,alpha,a,b,beta,mu,Lambda){mu+gamma(1-alpha)*a*b^(alpha-1)*Lambda%*%beta}, # rvgamma = function(x=1,lambda,alpha,beta,mu,Lambda){mu+as.vector(2*lambda/(alpha^2-t(beta)%*%Lambda%*%beta)^2)*beta} # ) # # yuimaEnv$covariance <- switch(code, # rNIG = function(x=1,alpha,beta,delta0,mu,Lambda){as.vector(delta0/(sqrt(alpha^2-t(beta)%*%Lambda%*%beta))^3)*Lambda%*%beta%*%t(beta)%*%Lambda+as.vector(delta0/sqrt(alpha^2-t(beta)%*%Lambda%*%beta))*Lambda}, # rnts = function(x=1,alpha,a,b,beta,mu,Lambda){a*(1-alpha)*gamma(1-alpha)*b^(alpha-2)*Lambda%*%beta%*%t(beta)%*%Lambda+a*gamma(1-alpha)*b^(alpha-1)*Lambda}, # rvgamma = function(x=1,lambda,alpha,beta,mu,Lambda){as.vector(4*lambda/(alpha^2-t(beta)%*%Lambda%*%beta)^2)*Lambda%*%beta%*%t(beta)%*%Lambda+as.vector(2*lambda/alpha^2-t(beta)%*%Lambda%*%beta)*Lambda} # ) # judgemean<-sum(eval(parse(text = paste("mean","(",args,")")),yuimaEnv)==numeric(length(sdeModel@xinit))) # judgecovariance<-sum(eval(eval(parse(text = paste("covariance","(",args,")")),yuimaEnv)==diag(1,length(sdeModel@xinit)))) # if(!((judgemean==length(sdeModel@xinit))&&(judgecovariance==length(sdeModel@xinit)*length(sdeModel@xinit)))) # { # yuima.stop("This function is only for standardized Levy processes.") # } } }else{fullcoef<-NULL} yuima@sampling@delta <- yuima@sampling@delta[1] yuima@[email protected] <- as.integer(yuima@[email protected]) if(!joint){ DRIFT <- yuima@model@drift DRPAR <- yuima@model@parameter@drift if(length(yuima@model@parameter@jump)>0) fullcoef <- yuima@model@parameter@jump if(length(DRPAR)>0) fullcoef <- c(fullcoef, DRPAR) oo <- match(yuima@model@parameter@all, fullcoef) yuima@model@parameter@all <- yuima@model@parameter@all[order(oo)] oo <- match(names(start), fullcoef) start <- start[order(oo)] oo <- match(names(upper), fullcoef) upper <- upper[order(oo)] oo <- match(names(lower), fullcoef) lower <- lower[order(oo)] yuima@model@diffusion <- yuima@[email protected] yuima@model@parameter@diffusion <- yuima@model@parameter@jump[1:length(yuima@model@parameter@jump)] yuima@model@parameter@all <- yuima@model@parameter@diffusion for(i in 1:length(yuima@model@drift)){ yuima@model@drift[i] <- expression((0)) } yuima@[email protected] <- list() yuima@model@parameter@drift <- character(0) yuima@model@measure <- list() yuima@[email protected] <- character(0) yuima@[email protected] <- character(0) yuima@model@parameter@jump <- character(0) yuima@model@parameter@measure <- character(0) diffstart <- start[1:length(yuima@model@parameter@diffusion)] diffupper <- upper[1:length(yuima@model@parameter@diffusion)] difflower <- lower[1:length(yuima@model@parameter@diffusion)] fres <- qmle(yuima=yuima,start=diffstart,lower=difflower,upper=diffupper,rcpp = TRUE,joint = FALSE,method = "L-BFGS-B") DiffHessian<- fres@details$hessian #182 DIPAR <- yuima@model@parameter@diffusion DIFFUSION <- yuima@model@diffusion yuima@model@parameter@all <- DRPAR yuima@model@parameter@drift <- DRPAR yuima@model@drift <- DRIFT dristart <- start[-(1:length(yuima@model@parameter@diffusion))] driupper <- upper[-(1:length(yuima@model@parameter@diffusion))] drilower <- lower[-(1:length(yuima@model@parameter@diffusion))] partcoef <- yuima@model@parameter@diffusion ov <- match(yuima@model@parameter@drift,partcoef) ovp <- which(!is.na(ov)) if(length(ovp)>0) {yuima@model@parameter@drift <- yuima@model@parameter@drift[-ovp]} yuima@model@parameter@all <- yuima@model@parameter@drift ma <- match(names(fres@coef),partcoef) sort <- fres@coef[order(ma)] esti <- numeric(length(partcoef)) newdiff <- yuima@model@diffusion newdri <- yuima@model@drift for(i in 1:length(partcoef)) { esti[i] <- as.character(fres@coef[[i]]) } if(length(yuima@model@drift) == 1){ for(i in 1:length(partcoef)) { newdri <- gsub(partcoef[i],esti[i],newdri) yuima@model@drift[1] <- parse(text = newdri[1]) newdiff[[1]] <- gsub(partcoef[i],esti[i],newdiff[[1]]) yuima@model@diffusion[[1]] <- parse(text = newdiff[[1]]) } }else{ for(i in 1:length(partcoef)) { for(j in 1:length(yuima@model@drift)) { newdri[j] <- gsub(partcoef[i],esti[i],newdri[j]) yuima@model@drift[j] <- parse(text = newdri[j]) } for(k in 1:length(yuima@model@diffusion)){ for(l in 1:length(yuima@model@diffusion[[1]])){ newdiff[[k]][l] <- gsub(partcoef[i],esti[i],newdiff[[k]][l]) yuima@model@diffusion[[k]][l] <- parse(text = newdiff[[k]][l]) } } } } yuima@model@parameter@diffusion <- character(0) sres<-qmle(yuima=yuima,start=dristart,lower=drilower,upper=driupper,rcpp = TRUE,method = "L-BFGS-B") DriftHessian <- sres@details$hessian #239 if((length(ovp) == 0) && (third)){ yuima@model@diffusion <- DIFFUSION yuima@model@drift <- DRIFT yuima@model@parameter@diffusion <- DIPAR yuima@model@parameter@all <- DIPAR newdri <- yuima@model@drift for(i in 1:length(sres@coef)) { esti[i] <- as.character(sres@coef[[i]]) } if(length(yuima@model@drift)==1){ for(i in 1:length(sres@coef)) { newdri <- gsub(yuima@model@parameter@drift[i],esti[i],newdri) yuima@model@drift[1] <- parse(text=newdri[1]) } }else{ for(i in 1:length(sres@coef)) { for(j in 1:length(yuima@model@drift)) { newdri[j] <- gsub(yuima@model@parameter@drift[i],esti[i],newdri[j]) yuima@model@drift[j] <- parse(text = newdri[j]) } } } yuima@model@parameter@drift <- character(0) too <- match(names(fres@coef),names(diffstart)) diffstart <- diffstart[order(too)] for(i in 1:length(diffstart)){ diffstart[[i]] <- fres@coef[[i]] } tres <- qmle(yuima=yuima,start=diffstart,lower=difflower,upper=diffupper,rcpp = TRUE,joint = FALSE,method = "L-BFGS-B") res <- list(first = fres@coef, second = sres@coef, third = tres@coef) }else if((length(ovp) > 0) || !(third)){ coef<-c(sres@coef,fres@coef) mycoef<-unlist(truestart) #mycoef1<-mycoef[names(coef)] mycoef2<-mycoef[!names(mycoef)%in%names(coef)] mycoef<-c(coef,mycoef2) vcov0<-matrix(NA,nrow = length(coef),ncol=length(coef)) rownames(vcov0)<-names(coef) colnames(vcov0)<-names(coef) min0<- c(fres@min,sres@min) details0<-list(sres@details,fres@details) nobs0<-sres@nobs res<-new("yuima.qmle", call = call, coef = coef, fullcoef = mycoef, vcov = vcov0, min = min0, details = details0, minuslogl = minusquasilogl, method = sres@method, nobs=nobs0, model=sdeModel) # res <- list(first = fres@coef, second = sres@coef)} if(length(oldyuima@[email protected])==1){ myGamhat <- matrix(0,length(coef),length(coef)) myGamhat[1:dim(DiffHessian)[1],1:dim(DiffHessian)[2]]<-DiffHessian myGamhat[dim(DiffHessian)[1]+1:dim(DriftHessian)[1],dim(DiffHessian)[1]+1:dim(DriftHessian)[2]]<-DriftHessian#293 myGamhat<-myGamhat/oldyuima@sampling@Terminal }else{ myGamhat <- matrix(0,length(coef),length(coef)) myGamhat[1:dim(DiffHessian)[1],1:dim(DiffHessian)[2]]<-DiffHessian*oldyuima@sampling@Terminal/oldyuima@sampling@n myGamhat[dim(DiffHessian)[1]+1:dim(DriftHessian)[1],dim(DiffHessian)[1]+1:dim(DriftHessian)[2]]<-DriftHessian#293 myGamhat<-myGamhat/oldyuima@sampling@Terminal } }else{ yuima.stop("third estimation may be theoretical invalid under the presence of an overlapping parameter.") } }else{ if(third){ yuima.stop("third estimation does not make sense in joint estimation.") } if(length(yuima@model@parameter@jump)>0) fullcoef <- yuima@model@parameter@jump if(length(yuima@model@parameter@drift)>0) fullcoef <- c(fullcoef, yuima@model@parameter@drift) oo <- match(yuima@model@parameter@all, fullcoef) yuima@model@parameter@all <- yuima@model@parameter@all[order(oo)] yuima@model@parameter@all <- yuima@model@parameter@all[1:length(which(!is.na(oo)))] yuima@model@diffusion <- yuima@[email protected] yuima@[email protected] <- list() yuima@model@parameter@diffusion <- yuima@model@parameter@jump[1:length(yuima@model@parameter@jump)] yuima@model@measure <- list() yuima@[email protected] <- character(0) yuima@[email protected] <- character(0) yuima@model@parameter@jump <- character(0) yuima@model@parameter@measure <- character(0) # jres<-qmle(yuima,start = start,lower = lower,upper = upper,rcpp = TRUE, joint = TRUE,method = "L-BFGS-B") # res<-list(joint = jres@coef) res<-qmle(yuima,start = start,lower = lower,upper = upper,rcpp = TRUE, joint = TRUE, method = "L-BFGS-B") } if(Est.Incr == "NoIncr"){ return(res) } cat("\nStarting Estimation of Levy Increments ... \n") data <- get.zoo.data(yuima) s.size<-yuima@sampling@n if(length(data)==1){ X<-as.numeric(data[[1]]) pX<-X[1:(s.size-1)] inc<-double(s.size-1) inc<-X[2:(s.size)]-pX }else{ pX<- simplify2array(lapply(X = data, FUN = as.numeric)) pX<-pX[-nrow(pX),] inc<- simplify2array(lapply(X = data, FUN = function(X){diff(as.numeric(X))})) } modeltime<-yuima@[email protected] modelstate<-yuima@[email protected] tmp.env<-new.env() #if(joint){ coeffic<- coef(res) # }else{ # coeffic<- res[[1]] # if(length(res)>1){ # for(j in c(2:length(res))){ # coeffic<-c(coeffic,res[[j]]) # } # } # #} mp<-match(names(coeffic),parameter) esort <- coeffic[order(mp)] for(i in 1:length(coeffic)) { assign(parameter[i],esort[[i]],envir=tmp.env) } # DRIFT <- yuima@model@drift # JUMP <- yuima@[email protected] if(length(yuima@[email protected])==1){ #parameter<-yuima@model@parameter@all #resi<-double(s.size-1) assign(modeltime,yuima@sampling@delta,envir=tmp.env) h<-yuima@sampling@delta assign(modelstate,pX,envir=tmp.env) jump.term<-eval(JUMP[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(jump.term)==1){ jump.term <- rep(jump.term, s.size-1) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size-1) } # vectorization (note. if an expression type object does not include state.variable, the length of the item after "eval" operation is 1.) # for(s in 1:(s.size-1)){ # nova<-sqrt((jump.term)^2) # normalized variance # resi[s]<-(1/(nova[s]))*(inc[s]-h*drif.term[s]) # } nova<-sqrt((jump.term)^2) resi<-(1/(nova[1:(s.size-1)]))*(inc[1:(s.size-1)]-h*drif.term[1:(s.size-1)]) if(length(oldyuima@[email protected])==1){ coefSigdiff<- 1/h*sum(resi^4) #389 resi coefDriftSig <- 1/h*sum(resi^3) } if(aggregation){ Ter <- yuima@sampling@Terminal ures <- numeric(floor(Ter)) for(l in 1:floor(Ter)){ ures[l] <- sum(resi[(floor((l-1)/h)):(floor(l/h)-1)]) } res.incr<-ures }else{ res.incr<-resi } }else{ h<-yuima@sampling@delta Tbig<-dim(inc)[1] assign(modeltime,h,envir=tmp.env) numbofvar<- length(modelstate) for(j in c(1:numbofvar)){ assign(modelstate[j],pX[,j],envir=tmp.env) } drif.term<-array(0,c(Tbig,numbofvar)) for(i in c(1:numbofvar)) drif.term [,i]<- eval(DRIFT[i],envir=tmp.env) # Check using variable in the drift # jump.term<-sapply(1:numbofvar,function(i){ # sapply(1:numbLev, function(j){ # eval(JUMP[[i]][j],envir=tmp.env) # },simplify = TRUE) # },simplify = TRUE) jump.term<-array(0,c(numbofvar,numbLev,Tbig)) for(i in c(1:numbofvar)){ for(j in c(1:numbLev)) jump.term[i,j, ] <- eval(JUMP[[i]][j],envir=tmp.env) } # if(dim(jump.term)[1]==numbofvar){ # if(dim(jump.term)[2]==numbofvar){ # if(det(jump.term)==0){ # Invjump.term<-solve(t(jump.term)%*%jump.term)%*%t(jump.term) # }else{ # Invjump.term<-solve(jump.term) # } # }else{ # Invjump.term<-solve(t(jump.term)%*%jump.term)%*%t(jump.term) # } # Invjump.term <- Invjump.term%o%rep(1,Tbig) # }else{ # # } # DeltaInc<-(inc-drif.term*h) if(dim(jump.term)[1]==numbofvar){ if(dim(jump.term)[2]==numbofvar){ resi<-t(sapply(i:Tbig,function(i){ if(det(jump.term[,,i])==0){ step1<-t(jump.term[,,i])%*%jump.term[,,i] if(det(step1)==0){ Invjump.term<-diag(rep(1,dim(step1)[1])) }else{ Invjump.term<-solve(step1)%*%t(jump.term[,,i]) } }else{ Invjump.term<-solve(jump.term[,,i]) } Invjump.term%*% DeltaInc[i,] } ) ) }else{ resi<-t(sapply(i:Tbig,function(i){ step1<-t(jump.term[,,i])%*%jump.term[,,i] if(det(step1)==0){ Invjump.term<-diag(rep(1,dim(step1)[1])) }else{ Invjump.term<-solve(step1)%*%t(jump.term[,,i]) } Invjump.term%*% DeltaInc[i,] } ) ) } } if(aggregation){ Ter <- min(floor(yuima@sampling@Terminal)) res.incr<-t(sapply(1:Ter,function(i) colSums(resi[(floor((i-1)/h)):(floor(i/h)-1),]) )) }else{ res.incr<-resi } } if(aggregation){ if(!is.matrix(res.incr)){ res.incr<- as.matrix(res.incr) } if(dim(res.incr)[2]==1){ colnames(res.incr)<[email protected] }else{ colnames(res.incr)<-paste0([email protected],c(1:dim(res.incr)[2])) } Incr.Lev <- zooreg(data=res.incr) Incr.Lev<- setData(original.data = Incr.Lev) }else{ Incr.Lev <- zoo(res.incr,order.by=yuima@sampling@grid[[1]][-1]) Incr.Lev <- setData(original.data=Incr.Lev) } if(length(oldyuima@[email protected])==1){ mydiff<-oldyuima@[email protected][[1]] mydiffDer <-deriv(mydiff,oldyuima@model@parameter@jump) myenvdiff<- new.env() if(length(oldyuima@model@parameter@jump)>=1){ for(i in c(1:length(oldyuima@model@parameter@jump))){ assign(value=coef[oldyuima@model@parameter@jump[i]],x=oldyuima@model@parameter@jump[i],envir=myenvdiff) } } EvalPartDiff <- Vectorize(FUN= function(myenvdiff,mydiffDer, data){ assign(x=oldyuima@[email protected], value=data,envir = myenvdiff) return(attr(eval(mydiffDer, envir=myenvdiff),"gradient"))},vectorize.args = "data") DiffJumpCoeff<-EvalPartDiff(myenvdiff,mydiffDer, data=pX) if(!is.matrix(DiffJumpCoeff)){ sigmadiffhat<- as.matrix(sum(DiffJumpCoeff^2/jump.term[1:(oldyuima@sampling@n-1)]^2)/(oldyuima@sampling@n))*coefSigdiff DiffJumpCoeff<- t(DiffJumpCoeff) }else{ sigmadiffhat<- matrix(0,dim(DiffJumpCoeff)[1],dim(DiffJumpCoeff)[1]) for(t in c(1:dim(DiffJumpCoeff)[2])){ sigmadiffhat <-sigmadiffhat+as.matrix(DiffJumpCoeff[,t])%*%DiffJumpCoeff[,t]/jump.term[t]^2 } sigmadiffhat<- sigmadiffhat/(oldyuima@sampling@n)*coefSigdiff } mydrift<-oldyuima@model@drift[[1]] mydriftDer <-deriv(mydrift,oldyuima@model@parameter@drift) myenvdrift<- new.env() if(length(oldyuima@model@parameter@drift)>=1){ for(i in c(1:length(oldyuima@model@parameter@drift))){ assign(value=coef[oldyuima@model@parameter@drift[i]],x=oldyuima@model@parameter@drift[i],envir=myenvdrift) } } DriftDerCoeff<-EvalPartDiff(myenvdrift,mydriftDer, data=pX) if(!is.matrix(DriftDerCoeff)){ # sigmadrifthat<- as.matrix(sum(DriftDerCoeff^2/jump.term[1:(oldyuima@sampling@n-1)]^2)/(oldyuima@sampling@n))*coefDriftSig sigmadrifthat<- as.matrix(sum(DriftDerCoeff^2/jump.term[1:(oldyuima@sampling@n-1)]^2)/(oldyuima@sampling@n)) DriftDerCoeff <- t(DriftDerCoeff) }else{ sigmadrifthat<- matrix(0,dim(DriftDerCoeff)[1],dim(DriftDerCoeff)[1]) for(t in c(1:dim(DriftDerCoeff)[2])){ sigmadrifthat <-sigmadrifthat+as.matrix(DriftDerCoeff[,t])%*%DriftDerCoeff[,t]/jump.term[t]^2 } sigmadrifthat<- sigmadrifthat/(oldyuima@sampling@n) } sigmadriftdiff <- matrix(0, dim(sigmadrifthat)[2],dim(sigmadiffhat)[1]) for(t in c(1:dim(DriftDerCoeff)[2])) sigmadriftdiff<-sigmadriftdiff+DriftDerCoeff[,t]%*%t(DiffJumpCoeff[,t]) #sigmadriftdiff<-sigmadriftdiff/oldyuima@sampling@n sigmadriftdiff<-sigmadriftdiff/oldyuima@sampling@n*coefDriftSig MatSigmaHat <- rbind(cbind(sigmadiffhat,t(sigmadriftdiff)),cbind(sigmadriftdiff,sigmadrifthat)) res@coef<-res@coef[c(oldyuima@model@parameter@jump,oldyuima@model@parameter@drift)] res@vcov<-solve(t(myGamhat)%*%solve(MatSigmaHat)%*%myGamhat*oldyuima@sampling@Terminal) } if(Est.Incr == "Incr"){ if(length(oldyuima@[email protected])==1){ result<- new("yuima.qmleLevy.incr",Incr.Lev=Incr.Lev, Data = yuima@data, yuima=res) }else{ result<- new("yuima.qmleLevy.incr",Incr.Lev=Incr.Lev, Data = yuima@data, yuima=res) vcovLevyNoMeas <- function(myres, Gammahat0, sq=TRUE){ #myres <- res.VG2 DeltaX <- apply(myres@[email protected],2,diff) myData<- myres@[email protected] CmatExpr<- myres@[email protected] ncolC <-length(myres@[email protected][[1]]) param <- myres@coef[myres@model@parameter@jump] aexpr<- myres@model@drift namedrift<-myres@model@parameter@drift pardrif <- myres@coef[namedrift] avect_exp<-myres@model@drift Jac_Drift <- function(aexpr,namedrift,nobs=length(aexpr)){ lapply(X=c(1:nobs),FUN=function(X,namedrift,aexpr){ return(deriv(aexpr[X],namedrift)) },namedrift=namedrift,aexpr=aexpr) } Jac_DriftExp <- Jac_Drift(aexpr=avect_exp,namedrift) FUNDum<-function(foo,myenv) sapply(foo, function(x,env) eval(x,envir = env), env= myenv) h<-diff(time(myres@[email protected][[1]]))[1] dummyf1n<- function(DeltaX, Cmat, h){ C2<-t(Cmat)%*%Cmat dec <- chol(C2) # Eventualy Add a tryCatch tmp <- t(DeltaX)%*%solve(C2)%*%DeltaX logretval <- -h*sum(log(diag(dec))) - 0.5 * as.numeric(tmp) return(logretval) } dummyInc<- function(DeltaX,Cmat, avect,h,sq=TRUE){ if(sq){ Incr <- solve(Cmat)%*%(DeltaX-avect*h) }else{ C2<-t(Cmat)%*%Cmat Incr <- solve(C2)%*%Cmat%*%(DeltaX-avect*h) } return(Incr) } dummyf2n<- function(DeltaX, avect, Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect tmp <- t(Incr)%*%solve(C2)%*%Incr logretval <- - 0.5/h * as.numeric(tmp) return(logretval) } dumGrad_f2n<-function(DeltaX, avect, Jac_a,Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect Grad<-t(Jac_a)%*%solve(C2)%*%Incr return(Grad) } f1n_j<-function(x, myObsDelta, CmatExpr,h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef ) return(dummyf1n(DeltaX=myObsDelta, Cmat=Cmat, h=h)) } Incr_Func <- function(x, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq=TRUE){ names(myData)<-myres@[email protected] newenv <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenv ) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenv) } return(dummyInc(DeltaX= myObsDelta,Cmat, avect,h,sq=sq)) } f2n_j <- function(x, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) } return(dummyf2n(DeltaX=myObsDelta, avect=avect, Cmat=Cmat, h=h)) } Gradf2n_j <-function(x, parDiff, myObsDelta, CmatExpr, avect_exp, Jac_DriftExp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) Jac_a<- matrix(0,dd,length(x)) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) Jac_a[j,]<-attr(eval(Jac_DriftExp[[j]],envir=newenvDriftCoef),"gradient") } return(dumGrad_f2n(DeltaX=myObsDelta, avect=avect, Jac_a=Jac_a, Cmat=Cmat, h=h)) } # f1n_j(x=param, myObsDelta=DeltaX[1,], CmatExpr=CmatExpr, h=h) #i=1 # debug(dummyInc) # Incr_Func(x=c(param,pardrif), myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, sq=TRUE) # f1n_j(x=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres) # f2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, avect_exp=avect_exp, # h=h, myData=myData[i,], myres=myres) # Gradf2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, # avect_exp, Jac_DriftExp, h, myData[i,], myres) del <- 10^-3 dummy <- t(rep(1,length(param))) myeta<- as.matrix(param)%*%dummy dummyG <- t(rep(1,length(c(param,pardrif)))) globalmyeta <- as.matrix(c(param,pardrif))%*%dummyG Incr <- del*diag(rep(1,dim(myeta)[1])) GlobIncr <- del*diag(rep(1,dim(globalmyeta)[1])) Sigma_gamma <- matrix(0 ,length(param),length(param)) Sigma_alpha <- matrix(0 ,length(pardrif),length(pardrif)) Sigma_algam <- matrix(0 ,length(pardrif),length(param)) histDeltaf1n_j_delta <-matrix(0 , dim(DeltaX)[1],length(param)) histDeltaf2n_j_delta <- matrix(0 , dim(DeltaX)[1],length(pardrif)) # histb_incr <- array(0, c(dim(DeltaX)[2],dim(DeltaX)[1],length(c(param,pardrif)))) for(i in c(1:dim(DeltaX)[1])){ Deltaf1n_j_delta<-sapply(X=1:dim(myeta)[1], FUN = function(X,myObsDelta, CmatExpr, h, myData, myres,del){ par1<-myeta[,X]+Incr[,X] #par[oldyuima@model@[email protected]]<-1 f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) par2<-myeta[,X]-Incr[,X] f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) return((f1-f2)/(2*del)) }, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres, del=del) # DeltaInc <- sapply(X=1:dim(GlobIncr)[1], # FUN = function(X, myObsDelta, CmatExpr,avect_exp, h, # myData, myres, del, sq){ # par1<-globalmyeta[,X]+GlobIncr[,X] # # # f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) # f1<-Incr_Func(x=par1, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) # par2<-globalmyeta[,X]-GlobIncr[,X] # f2<-Incr_Func(x=par2, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) # #f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) # return((f1-f2)/(2*del)) # }, # myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, del=del,sq=sq # ) # # histDeltaf1n_j_delta[i, ]<-Deltaf1n_j_delta #histb_incr[ , i, ] <- DeltaInc Sigma_gamma <- Sigma_gamma + as.matrix(Deltaf1n_j_delta)%*%t(Deltaf1n_j_delta) Deltaf2n_j_delta<- Gradf2n_j(x=pardrif, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, avect_exp, Jac_DriftExp, h, myData[i,], myres) histDeltaf2n_j_delta[i,]<-Deltaf2n_j_delta Sigma_alpha <- Sigma_alpha + Deltaf2n_j_delta%*%t(Deltaf2n_j_delta) Sigma_algam <- Sigma_algam + Deltaf2n_j_delta%*%t(Deltaf1n_j_delta) #cat("\n",i) } Tn<-tail(time(myres@[email protected]),1L) Sigma_gamma0<-Sigma_gamma/Tn Sigma_alpha0 <- Sigma_alpha/Tn Sigma_algam0 <- Sigma_algam/Tn Sigma0 <- cbind(rbind(Sigma_gamma0,Sigma_algam0),rbind(t(Sigma_algam0),Sigma_alpha0)) InvGammaHAT <- solve(Gammahat0) vcov <- InvGammaHAT %*% Sigma0 %*% InvGammaHAT/Tn myres@vcov<- vcov return(myres) } if(length(result@[email protected])==length(result@[email protected][[1]])){ sq<-TRUE }else{ sq<-FALSE } result<-vcovLevyNoMeas(myres=result, Gammahat0=myGamhat, sq=sq) } return(result) } cat("\nEstimation Levy parameters ... \n") #if(class(mylaw)=="yuima.law"){ if(inherits(mylaw, "yuima.law")){ # YK, Mar. 22, 2022 if(aggregation){ minusloglik <- function(para){ para[length(para)+1]<-1 names(para)[length(para)]<-yuima@[email protected] -sum(dens(object=mylaw, x=res.incr, param = para, log = TRUE), na.rm = T) } }else{ minusloglik <- function(para){ para[length(para)+1] <- yuima@sampling@delta names(para)[length(para)]<-yuima@[email protected] -sum(dens(object=mylaw, x=res.incr, param = para, log = TRUE), na.rm = T) } } para <- start0[lev.names] lowerjump <- lower0[lev.names] upperjump <- upper0[lev.names] esti <- optim(fn = minusloglik, lower = lowerjump, upper = upperjump, par = para, method = "L-BFGS-B") HessianEta <- optimHess(par=esti$par, fn=minusloglik) res@coef<-c(res@coef,esti$par) res@fullcoef[names(para)]<-esti$par if(length(oldyuima@[email protected])==1 & is(oldyuima@model@measure$df, "yuima.law")){ if(!aggregation){ Ter <- yuima@sampling@Terminal ures <- numeric(floor(Ter)) for(l in 1:floor(Ter)){ ures[l] <- sum(resi[(floor((l-1)/h)):(floor(l/h)-1)]) } } mypar<-res@coef[oldyuima@model@parameter@measure] mypar[oldyuima@model@[email protected]]<-1 fdataeta<-dens(object=oldyuima@model@measure$df,x=ures,param=mypar)# f(eps, eta) del <- 10^-3 fdatadeltaeta<- dens(object=oldyuima@model@measure$df,x=ures+del,param=mypar) # f(eps + delta, eta) dummy <- t(rep(1,length(mypar[oldyuima@model@[email protected]]))) myeta<- as.matrix(mypar[oldyuima@model@[email protected]])%*%dummy myetapert <- myeta+del*diag(rep(1,dim(myeta)[1])) fdataetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[oldyuima@model@[email protected]]<-1 dens(object=oldyuima@model@measure$df,x=ures,param=par) } )# f(eps, eta+delta) fdatadeltaetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[oldyuima@model@[email protected]]<-1 dens(object=oldyuima@model@measure$df,x=ures+del,param=par) } ) # f(eps +deta, eta+delta) term1<-1/(fdataeta) term2 <- fdatadeltaeta*term1%*%dummy term2 <- fdatadeltaetadelta-term2*fdataetadelta mixpartial<-t((as.matrix(term1)%*%dummy)/del^2*term2/oldyuima@sampling@Terminal) # construction of b_i # DiffJumpCoeff, DriftDerCoeff, jump.term length(resi) # step1 <- t(DiffJumpCoeff)%*%DiffJumpCoeff DerMeta <- 1/del*(fdataetadelta - as.matrix(fdataeta)%*%rep(1,dim(fdataetadelta)[2]))*(as.matrix(term1)%*%rep(1,dim(fdataetadelta)[2])) SigmaEta <- t(DerMeta)%*%DerMeta/oldyuima@sampling@Terminal #SigmaEtaAlpha<- 1/oldyuima@sampling@n*DriftDerCoeff%*%(t(DiffJumpCoeff)/(as.matrix(jump.term[-length(jump.term)]^2)%*%rep(1,dim(DiffJumpCoeff)[1])) ) SigmaEtaAlpha<- 1/oldyuima@sampling@n*DriftDerCoeff%*%(t(DiffJumpCoeff)/(as.matrix(jump.term^2)%*%rep(1,dim(DiffJumpCoeff)[1])) ) SigmaEtaAlpha <- SigmaEtaAlpha*sum(resi^3)/oldyuima@sampling@delta b_i <- matrix(0,floor(Ter),length(c(oldyuima@model@parameter@drift, oldyuima@model@parameter@jump))) Coef1 <- matrix(0,floor(Ter),length( oldyuima@model@parameter@jump)) Coef2 <- matrix(0,floor(Ter),length( oldyuima@model@parameter@drift)) for(l in 1:floor(Ter)){ pos <- (floor((l-1)/h)):(floor(l/h)-1) if(length(oldyuima@model@parameter@jump)==1){ b_i[l,1:length(oldyuima@model@parameter@jump)] <- sum(-DiffJumpCoeff[,pos]*resi[pos]/jump.term[pos]) Coef1[l,]<-sum(DiffJumpCoeff[,pos]/jump.term[pos]*(resi[pos]^2-h)) }else{ interm <- as.matrix(resi[pos]/jump.term[pos]) b_i[l,1:length(oldyuima@model@parameter@jump)] <- -t(DiffJumpCoeff[,pos]%*%interm) interm2 <- as.matrix((resi[pos]^2-h)/jump.term[pos]) Coef1[l,] <-DiffJumpCoeff[,pos]%*%interm2 } if(length(oldyuima@model@parameter@drift)==1){ b_i[l,1:length(oldyuima@model@parameter@drift)+length(oldyuima@model@parameter@jump)] <- -sum(h* DriftDerCoeff[,pos]%*%jump.term[pos]) Coef2[l,]<-sum(DriftDerCoeff[,pos]/jump.term[pos]*(resi[pos])) }else{ b_i[l,1:length(oldyuima@model@parameter@drift)+length(oldyuima@model@parameter@jump)] <--h* DriftDerCoeff[,pos]%*%jump.term[pos] interm3 <- as.matrix((resi[pos])/jump.term[pos]) Coef2[l,] <-DriftDerCoeff[,pos]%*%interm3 } } MatrUnder <- mixpartial%*%b_i I_n <- cbind(rbind(myGamhat,MatrUnder),rbind(matrix(0, dim(myGamhat)[1],dim(HessianEta)[2]),HessianEta/oldyuima@sampling@Terminal)) SigmaGammaEta <- t(DerMeta)%*%Coef1/Ter SigmaAlphaEta <- t(DerMeta)%*%Coef2/Ter # dim(fdataetadelta), length(fdataeta), length(term1) dum <- cbind(SigmaGammaEta , SigmaAlphaEta) MatSigmaHat1<- rbind(cbind(MatSigmaHat,t(dum)),cbind(dum,SigmaEta)) InvIn<- solve(I_n) res@vcov <-InvIn%*%MatSigmaHat1%*%t(InvIn)/Ter colnames(res@vcov)<-names(res@fullcoef) #res@vcov<-rbind(res@vcov,matrix(NA,nrow=length(esti$par),ncol=dim(res@vcov)[2])) rownames(res@vcov)<-names(res@fullcoef) res@min<-c(res@min,esti$value) res@nobs<-c(res@nobs,length([email protected][[1]])) result<- new("yuima.qmleLevy.incr",Incr.Lev=Incr.Lev, minusloglLevy = minusloglik,logL.Incr=-esti$value, Data = yuima@data, yuima=res, Levydetails=esti) }else{ Tn<-yuima@sampling@Terminal HessianEta_divTn <- HessianEta/Tn if(!aggregation){ Ter <- min(floor(yuima@sampling@Terminal)) ures<-t(sapply(1:Ter,function(i) colSums(resi[(floor((i-1)/h)):(floor(i/h)-1),]) )) #yuima.stop("da fare") vcovLevy1 <- function(myres, HessianEta_divTn, Gammahat0, ures, sq=TRUE){ #myres <- res.VG2 DeltaX <- apply(myres@[email protected],2,diff) myData<- myres@[email protected] CmatExpr<- myres@[email protected] ncolC <-length(myres@[email protected][[1]]) param <- myres@coef[myres@model@parameter@jump] aexpr<- myres@model@drift namedrift<-myres@model@parameter@drift pardrif <- myres@coef[namedrift] avect_exp<-myres@model@drift Jac_Drift <- function(aexpr,namedrift,nobs=length(aexpr)){ lapply(X=c(1:nobs),FUN=function(X,namedrift,aexpr){ return(deriv(aexpr[X],namedrift)) },namedrift=namedrift,aexpr=aexpr) } Jac_DriftExp <- Jac_Drift(aexpr=avect_exp,namedrift) FUNDum<-function(foo,myenv) sapply(foo, function(x,env) eval(x,envir = env), env= myenv) h<-diff(time(myres@[email protected][[1]]))[1] dummyf1n<- function(DeltaX, Cmat, h){ C2<-t(Cmat)%*%Cmat dec <- chol(C2) # Eventualy Add a tryCatch tmp <- t(DeltaX)%*%solve(C2)%*%DeltaX logretval <- -h*sum(log(diag(dec))) - 0.5 * as.numeric(tmp) return(logretval) } dummyInc<- function(DeltaX,Cmat, avect,h,sq=TRUE){ if(sq){ Incr <- solve(Cmat)%*%(DeltaX-avect*h) }else{ C2<-t(Cmat)%*%Cmat Incr <- solve(C2)%*%Cmat%*%(DeltaX-avect*h) } return(Incr) } dummyf2n<- function(DeltaX, avect, Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect tmp <- t(Incr)%*%solve(C2)%*%Incr logretval <- - 0.5/h * as.numeric(tmp) return(logretval) } dumGrad_f2n<-function(DeltaX, avect, Jac_a,Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect Grad<-t(Jac_a)%*%solve(C2)%*%Incr return(Grad) } f1n_j<-function(x, myObsDelta, CmatExpr,h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef ) return(dummyf1n(DeltaX=myObsDelta, Cmat=Cmat, h=h)) } Incr_Func <- function(x, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq=TRUE){ names(myData)<-myres@[email protected] newenv <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenv ) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenv) } return(dummyInc(DeltaX= myObsDelta,Cmat, avect,h,sq=sq)) } f2n_j <- function(x, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) } return(dummyf2n(DeltaX=myObsDelta, avect=avect, Cmat=Cmat, h=h)) } Gradf2n_j <-function(x, parDiff, myObsDelta, CmatExpr, avect_exp, Jac_DriftExp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) Jac_a<- matrix(0,dd,length(x)) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) Jac_a[j,]<-attr(eval(Jac_DriftExp[[j]],envir=newenvDriftCoef),"gradient") } return(dumGrad_f2n(DeltaX=myObsDelta, avect=avect, Jac_a=Jac_a, Cmat=Cmat, h=h)) } # f1n_j(x=param, myObsDelta=DeltaX[1,], CmatExpr=CmatExpr, h=h) #i=1 # debug(dummyInc) # Incr_Func(x=c(param,pardrif), myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, sq=TRUE) # f1n_j(x=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres) # f2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, avect_exp=avect_exp, # h=h, myData=myData[i,], myres=myres) # Gradf2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, # avect_exp, Jac_DriftExp, h, myData[i,], myres) del <- 10^-3 dummy <- t(rep(1,length(param))) myeta<- as.matrix(param)%*%dummy dummyG <- t(rep(1,length(c(param,pardrif)))) globalmyeta <- as.matrix(c(param,pardrif))%*%dummyG Incr <- del*diag(rep(1,dim(myeta)[1])) GlobIncr <- del*diag(rep(1,dim(globalmyeta)[1])) Sigma_gamma <- matrix(0 ,length(param),length(param)) Sigma_alpha <- matrix(0 ,length(pardrif),length(pardrif)) Sigma_algam <- matrix(0 ,length(pardrif),length(param)) histDeltaf1n_j_delta <-matrix(0 , dim(DeltaX)[1],length(param)) histDeltaf2n_j_delta <- matrix(0 , dim(DeltaX)[1],length(pardrif)) histb_incr <- array(0, c(dim(DeltaX)[2],dim(DeltaX)[1],length(c(param,pardrif)))) for(i in c(1:dim(DeltaX)[1])){ Deltaf1n_j_delta<-sapply(X=1:dim(myeta)[1], FUN = function(X,myObsDelta, CmatExpr, h, myData, myres,del){ par1<-myeta[,X]+Incr[,X] #par[oldyuima@model@[email protected]]<-1 f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) par2<-myeta[,X]-Incr[,X] f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) return((f1-f2)/(2*del)) }, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres, del=del) DeltaInc <- sapply(X=1:dim(GlobIncr)[1], FUN = function(X, myObsDelta, CmatExpr,avect_exp, h, myData, myres, del, sq){ par1<-globalmyeta[,X]+GlobIncr[,X] # f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) f1<-Incr_Func(x=par1, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) par2<-globalmyeta[,X]-GlobIncr[,X] f2<-Incr_Func(x=par2, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) #f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) return((f1-f2)/(2*del)) }, myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, del=del,sq=sq ) histDeltaf1n_j_delta[i, ]<-Deltaf1n_j_delta histb_incr[ , i, ] <- DeltaInc Sigma_gamma <- Sigma_gamma + as.matrix(Deltaf1n_j_delta)%*%t(Deltaf1n_j_delta) Deltaf2n_j_delta<- Gradf2n_j(x=pardrif, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, avect_exp, Jac_DriftExp, h, myData[i,], myres) histDeltaf2n_j_delta[i,]<-Deltaf2n_j_delta Sigma_alpha <- Sigma_alpha + Deltaf2n_j_delta%*%t(Deltaf2n_j_delta) Sigma_algam <- Sigma_algam + Deltaf2n_j_delta%*%t(Deltaf1n_j_delta) #cat("\n",i) } Tn<-tail(time(myres@[email protected]),1L) Sigma_gamma0<-Sigma_gamma/Tn Sigma_alpha0 <- Sigma_alpha/Tn Sigma_algam0 <- Sigma_algam/Tn Sigma0 <- cbind(rbind(Sigma_gamma0,Sigma_algam0),rbind(t(Sigma_algam0),Sigma_alpha0)) myLogDens <- function(x, myObsDelta, CmatExpr,h,myData, myres, pos){ return(f1n_j(x, myObsDelta[pos, ], CmatExpr,h,myData=myData[pos,], myres=myres)) } myLogDens2<- function(x, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres, pos){ return(f2n_j(x, parDiff, myObsDelta[pos, ], CmatExpr, avect_exp, h, myData[pos,], myres)) #return(f1n_j(x, myObsDelta[pos, ], CmatExpr,h,myData=myData[pos,], myres=myres)) } VectLogDens<-Vectorize(FUN=myLogDens,vectorize.args = "pos") #VectLogDens2<-Vectorize(FUN=myLogDens2,vectorize.args = "pos") mylogLik<- function(par,DeltaX,CmatExpr, myData, myres, h, Tn, nobs=dim(DeltaX)[1]){ term<-VectLogDens(x=par, myObsDelta=DeltaX, CmatExpr=CmatExpr,h=h, myData=myData, myres=myres,pos=c(1:nobs)) return(sum(term)/Tn) } mylogLik2<- function(par, parDiff, myObsDelta, CmatExpr, avect_exp, h, Tn, myData, myres, nobs=dim(DeltaX)[1]){ # term<-VectLogDens2(x=par, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres, # pos=c(1:nobs)) term<-0 for(j in c(1:nobs)){ term<-term+f2n_j(x=par, parDiff, myObsDelta[j, ], CmatExpr, avect_exp, h, myData[j,], myres) } return(term/Tn) } GradlogLik2<-function(par, parDiff, myObsDelta, CmatExpr, avect_exp, h, Tn, myData, myres, nobs=dim(DeltaX)[1]){ term<-matrix(0, length(par),1) for(j in c(1:nobs)){ term <- term + Gradf2n_j(x=par, parDiff, myObsDelta=myObsDelta[j, ], CmatExpr, avect_exp, Jac_DriftExp, h, myData=myData[j,], myres) } return(as.numeric(term)/Tn) } # Gammahat <- optimHess(par=param,fn=mylogLik, # DeltaX=DeltaX,CmatExpr=CmatExpr, # h=h, Tn=Tn, nobs=dim(DeltaX)[1], # myData=myData, myres=myres) # GammaAlfahat <- optimHess(par=pardrif,fn=mylogLik2,gr=GradlogLik2, # parDiff=param, myObsDelta=DeltaX, # CmatExpr=CmatExpr, avect_exp=avect_exp, h=h, # Tn=Tn, nobs=dim(DeltaX)[1], myData=myData, myres=myres) # # Gammahat0 <- cbind(rbind(Gammahat,matrix(0,dim(GammaAlfahat)[1],dim(Gammahat)[2])), # rbind(matrix(0,dim(Gammahat)[2],dim(GammaAlfahat)[1]),GammaAlfahat)) uhistDeltaf1n_j<- matrix(0,floor(Tn),length(param)) uhistDeltaf2n_j<- matrix(0,floor(Tn),length(pardrif)) aaa<-length(c(param,pardrif)) uhistb_incr <- array(0, c(dim(DeltaX)[2],floor(Tn),aaa)) for(l in 1:floor(Tn)){ #ures[l] <- sum(resi[(floor((l-1)/h)):(floor(l/h)-1)]) uhistDeltaf1n_j[l, ] <- colSums(histDeltaf1n_j_delta[(floor((l-1)/h)):(floor(l/h)-1),]) uhistDeltaf2n_j[l, ] <- colSums(histDeltaf2n_j_delta[(floor((l-1)/h)):(floor(l/h)-1),]) for(i in c(1:aaa)){ dumIn <- histb_incr[,(floor((l-1)/h)):(floor(l/h)-1),i] uhistb_incr[,l,i]<- rowSums(dumIn) } } nMeaspar<-myres@model@parameter@measure mypar_meas0 <- myres@coef[nMeaspar]#res@coef[oldyuima@model@parameter@measure] mypar_meas <- c(mypar_meas0,1) # ures<[email protected]@original.data names(mypar_meas)<-c(nMeaspar,myres@model@[email protected]) fdataeta<-dens(object=myres@model@measure$df,x=ures,param=mypar_meas)# f(eps, eta) del <- 10^-3 dummy <- t(rep(1,length(mypar_meas[myres@model@[email protected]]))) myeta<- as.matrix(mypar_meas[myres@model@[email protected]])%*%dummy myetapert <- myeta+del*diag(rep(1,dim(myeta)[1])) fdataetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[myres@model@[email protected]]<-1 dens(object=myres@model@measure$df,x=ures,param=par) } )# f(eps, eta+delta) term1<-1/(fdataeta) dummyvecdel<-numeric(length=dim(ures)[2]) fdatadeltaeta<- matrix(0,floor(Tn),dim(ures)[2]) mixpartial <-array(0,c(length(nMeaspar),floor(Tn),dim(ures)[2])) for(j in c(1:dim(ures)[2])){ dummyvecdel[j]<-del fdatadeltaeta[,j]<- dens(object=myres@model@measure$df,x=ures+rep(1,dim(ures)[1])%*%t(dummyvecdel),param=mypar_meas) fdatadeltaetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[myres@model@[email protected]]<-1 dens(object=myres@model@measure$df,x=ures+rep(1,dim(ures)[1])%*%t(dummyvecdel),param=par) } ) # f(eps +deta, eta+delta) dummyvecdel<-numeric(length=dim(ures)[2]) term2 <- fdatadeltaeta[,j]*term1%*%dummy term2 <- fdatadeltaetadelta-term2*fdataetadelta mixpartial[,,j]<-t((as.matrix(term1)%*%dummy)/del^2*term2/Tn) } DerMeta <- 1/del*(fdataetadelta - as.matrix(fdataeta)%*%rep(1,dim(fdataetadelta)[2]))*(as.matrix(term1)%*%rep(1,dim(fdataetadelta)[2])) SigmaEta <- t(DerMeta)%*%DerMeta/Tn minusloglik <- function(para){ para[length(para)+1]<-1 names(para)[length(para)]<-myres@[email protected] -sum(dens(object=myres@model@measure$df, x=ures, param = para, log = TRUE), na.rm = T)/Tn } # HessianEta_divTn <- optimHess(par=mypar_meas0, fn=minusloglik) Gammaeta_theta <- matrix(0,length(mypar_meas0), aaa) for(t in c(1:floor(Tn))){ Gammaeta_theta<-Gammaeta_theta+mixpartial[,t,]%*%uhistb_incr[,t,] } GammaEta_Theta<- -1/Tn*Gammaeta_theta Sigma_eta_theta<-t(DerMeta)%*%cbind(uhistDeltaf1n_j,uhistDeltaf2n_j)/Tn Sigma <- cbind(rbind(Sigma0,Sigma_eta_theta),rbind(t(Sigma_eta_theta),SigmaEta)) GammaHAT<-cbind(rbind(Gammahat0, GammaEta_Theta), rbind(t(GammaEta_Theta), HessianEta_divTn)) InvGammaHAT <- solve(GammaHAT) vcov <- InvGammaHAT %*% Sigma %*% InvGammaHAT/Tn myres@vcov<- vcov return(myres) } } res@vcov<-cbind(res@vcov,matrix(NA,ncol=length(esti$par),nrow=dim(res@vcov)[1])) res@vcov<-rbind(res@vcov,matrix(NA,nrow=length(esti$par),ncol=dim(res@vcov)[2])) colnames(res@vcov)<-names(res@fullcoef) #res@vcov<-rbind(res@vcov,matrix(NA,nrow=length(esti$par),ncol=dim(res@vcov)[2])) rownames(res@vcov)<-names(res@fullcoef) res@min<-c(res@min,esti$value) res@nobs<-c(res@nobs,length([email protected][[1]])) result<- new("yuima.qmleLevy.incr",Incr.Lev=Incr.Lev, minusloglLevy = minusloglik,logL.Incr=-esti$value, Data = yuima@data, yuima=res, Levydetails=esti) if(length(result@[email protected])==length(result@[email protected][[1]])){ sq<-TRUE }else{ sq<-FALSE } if(!aggregation){ result <- vcovLevy1(myres = result, HessianEta_divTn = HessianEta_divTn, Gammahat0 = myGamhat, ures = ures, sq=TRUE) }else{ vcovLevy <- function(myres, HessianEta_divTn, Gammahat0, sq=TRUE){ #myres <- res.VG2 DeltaX <- apply(myres@[email protected],2,diff) myData<- myres@[email protected] CmatExpr<- myres@[email protected] ncolC <-length(myres@[email protected][[1]]) param <- myres@coef[myres@model@parameter@jump] aexpr<- myres@model@drift namedrift<-myres@model@parameter@drift pardrif <- myres@coef[namedrift] avect_exp<-myres@model@drift Jac_Drift <- function(aexpr,namedrift,nobs=length(aexpr)){ lapply(X=c(1:nobs),FUN=function(X,namedrift,aexpr){ return(deriv(aexpr[X],namedrift)) },namedrift=namedrift,aexpr=aexpr) } Jac_DriftExp <- Jac_Drift(aexpr=avect_exp,namedrift) FUNDum<-function(foo,myenv) sapply(foo, function(x,env) eval(x,envir = env), env= myenv) h<-diff(time(myres@[email protected][[1]]))[1] dummyf1n<- function(DeltaX, Cmat, h){ C2<-t(Cmat)%*%Cmat dec <- chol(C2) # Eventualy Add a tryCatch tmp <- t(DeltaX)%*%solve(C2)%*%DeltaX logretval <- -h*sum(log(diag(dec))) - 0.5 * as.numeric(tmp) return(logretval) } dummyInc<- function(DeltaX,Cmat, avect,h,sq=TRUE){ if(sq){ Incr <- solve(Cmat)%*%(DeltaX-avect*h) }else{ C2<-t(Cmat)%*%Cmat Incr <- solve(C2)%*%Cmat%*%(DeltaX-avect*h) } return(Incr) } dummyf2n<- function(DeltaX, avect, Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect tmp <- t(Incr)%*%solve(C2)%*%Incr logretval <- - 0.5/h * as.numeric(tmp) return(logretval) } dumGrad_f2n<-function(DeltaX, avect, Jac_a,Cmat, h){ C2 <- t(Cmat)%*%Cmat Incr <- DeltaX-h*avect Grad<-t(Jac_a)%*%solve(C2)%*%Incr return(Grad) } f1n_j<-function(x, myObsDelta, CmatExpr,h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef ) return(dummyf1n(DeltaX=myObsDelta, Cmat=Cmat, h=h)) } Incr_Func <- function(x, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq=TRUE){ names(myData)<-myres@[email protected] newenv <- list2env(as.list(c(x,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenv ) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenv) } return(dummyInc(DeltaX= myObsDelta,Cmat, avect,h,sq=sq)) } f2n_j <- function(x, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) } return(dummyf2n(DeltaX=myObsDelta, avect=avect, Cmat=Cmat, h=h)) } Gradf2n_j <-function(x, parDiff, myObsDelta, CmatExpr, avect_exp, Jac_DriftExp, h, myData, myres){ names(myData)<-myres@[email protected] newenvJumpCoef <- list2env(as.list(c(parDiff,myData))) Cmat<-sapply(X=CmatExpr, FUN=FUNDum, myenv=newenvJumpCoef) newenvDriftCoef <- list2env(as.list(c(x,myData))) dd<-length(avect_exp) avect<-numeric(length=dd) Jac_a<- matrix(0,dd,length(x)) for(j in c(1:dd)){ avect[j]<-eval(avect_exp[j],envir=newenvDriftCoef) Jac_a[j,]<-attr(eval(Jac_DriftExp[[j]],envir=newenvDriftCoef),"gradient") } return(dumGrad_f2n(DeltaX=myObsDelta, avect=avect, Jac_a=Jac_a, Cmat=Cmat, h=h)) } # f1n_j(x=param, myObsDelta=DeltaX[1,], CmatExpr=CmatExpr, h=h) #i=1 # debug(dummyInc) # Incr_Func(x=c(param,pardrif), myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, sq=TRUE) # f1n_j(x=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres) # f2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, avect_exp=avect_exp, # h=h, myData=myData[i,], myres=myres) # Gradf2n_j(x, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, # avect_exp, Jac_DriftExp, h, myData[i,], myres) del <- 10^-3 dummy <- t(rep(1,length(param))) myeta<- as.matrix(param)%*%dummy dummyG <- t(rep(1,length(c(param,pardrif)))) globalmyeta <- as.matrix(c(param,pardrif))%*%dummyG Incr <- del*diag(rep(1,dim(myeta)[1])) GlobIncr <- del*diag(rep(1,dim(globalmyeta)[1])) Sigma_gamma <- matrix(0 ,length(param),length(param)) Sigma_alpha <- matrix(0 ,length(pardrif),length(pardrif)) Sigma_algam <- matrix(0 ,length(pardrif),length(param)) histDeltaf1n_j_delta <-matrix(0 , dim(DeltaX)[1],length(param)) histDeltaf2n_j_delta <- matrix(0 , dim(DeltaX)[1],length(pardrif)) histb_incr <- array(0, c(dim(DeltaX)[2],dim(DeltaX)[1],length(c(param,pardrif)))) for(i in c(1:dim(DeltaX)[1])){ Deltaf1n_j_delta<-sapply(X=1:dim(myeta)[1], FUN = function(X,myObsDelta, CmatExpr, h, myData, myres,del){ par1<-myeta[,X]+Incr[,X] #par[oldyuima@model@[email protected]]<-1 f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) par2<-myeta[,X]-Incr[,X] f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) return((f1-f2)/(2*del)) }, myObsDelta=DeltaX[i,], CmatExpr=CmatExpr, h=h, myData=myData[i,], myres=myres, del=del) DeltaInc <- sapply(X=1:dim(GlobIncr)[1], FUN = function(X, myObsDelta, CmatExpr,avect_exp, h, myData, myres, del, sq){ par1<-globalmyeta[,X]+GlobIncr[,X] # f1<-f1n_j(x=par1, myObsDelta, CmatExpr, h, myData, myres) f1<-Incr_Func(x=par1, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) par2<-globalmyeta[,X]-GlobIncr[,X] f2<-Incr_Func(x=par2, myObsDelta, CmatExpr,avect_exp, h, myData, myres, sq) #f2<-f1n_j(x=par2, myObsDelta, CmatExpr, h, myData, myres) return((f1-f2)/(2*del)) }, myObsDelta=DeltaX[i,], CmatExpr,avect_exp, h, myData=myData[i,], myres, del=del,sq=sq ) histDeltaf1n_j_delta[i, ]<-Deltaf1n_j_delta histb_incr[ , i, ] <- DeltaInc Sigma_gamma <- Sigma_gamma + as.matrix(Deltaf1n_j_delta)%*%t(Deltaf1n_j_delta) Deltaf2n_j_delta<- Gradf2n_j(x=pardrif, parDiff=param, myObsDelta=DeltaX[i,], CmatExpr, avect_exp, Jac_DriftExp, h, myData[i,], myres) histDeltaf2n_j_delta[i,]<-Deltaf2n_j_delta Sigma_alpha <- Sigma_alpha + Deltaf2n_j_delta%*%t(Deltaf2n_j_delta) Sigma_algam <- Sigma_algam + Deltaf2n_j_delta%*%t(Deltaf1n_j_delta) #cat("\n",i) } Tn<-tail(time(myres@[email protected]),1L) Sigma_gamma0<-Sigma_gamma/Tn Sigma_alpha0 <- Sigma_alpha/Tn Sigma_algam0 <- Sigma_algam/Tn Sigma0 <- cbind(rbind(Sigma_gamma0,Sigma_algam0),rbind(t(Sigma_algam0),Sigma_alpha0)) myLogDens <- function(x, myObsDelta, CmatExpr,h,myData, myres, pos){ return(f1n_j(x, myObsDelta[pos, ], CmatExpr,h,myData=myData[pos,], myres=myres)) } myLogDens2<- function(x, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres, pos){ return(f2n_j(x, parDiff, myObsDelta[pos, ], CmatExpr, avect_exp, h, myData[pos,], myres)) #return(f1n_j(x, myObsDelta[pos, ], CmatExpr,h,myData=myData[pos,], myres=myres)) } VectLogDens<-Vectorize(FUN=myLogDens,vectorize.args = "pos") #VectLogDens2<-Vectorize(FUN=myLogDens2,vectorize.args = "pos") mylogLik<- function(par,DeltaX,CmatExpr, myData, myres, h, Tn, nobs=dim(DeltaX)[1]){ term<-VectLogDens(x=par, myObsDelta=DeltaX, CmatExpr=CmatExpr,h=h, myData=myData, myres=myres,pos=c(1:nobs)) return(sum(term)/Tn) } mylogLik2<- function(par, parDiff, myObsDelta, CmatExpr, avect_exp, h, Tn, myData, myres, nobs=dim(DeltaX)[1]){ # term<-VectLogDens2(x=par, parDiff, myObsDelta, CmatExpr, avect_exp, h, myData, myres, # pos=c(1:nobs)) term<-0 for(j in c(1:nobs)){ term<-term+f2n_j(x=par, parDiff, myObsDelta[j, ], CmatExpr, avect_exp, h, myData[j,], myres) } return(term/Tn) } GradlogLik2<-function(par, parDiff, myObsDelta, CmatExpr, avect_exp, h, Tn, myData, myres, nobs=dim(DeltaX)[1]){ term<-matrix(0, length(par),1) for(j in c(1:nobs)){ term <- term + Gradf2n_j(x=par, parDiff, myObsDelta=myObsDelta[j, ], CmatExpr, avect_exp, Jac_DriftExp, h, myData=myData[j,], myres) } return(as.numeric(term)/Tn) } # Gammahat <- optimHess(par=param,fn=mylogLik, # DeltaX=DeltaX,CmatExpr=CmatExpr, # h=h, Tn=Tn, nobs=dim(DeltaX)[1], # myData=myData, myres=myres) # GammaAlfahat <- optimHess(par=pardrif,fn=mylogLik2,gr=GradlogLik2, # parDiff=param, myObsDelta=DeltaX, # CmatExpr=CmatExpr, avect_exp=avect_exp, h=h, # Tn=Tn, nobs=dim(DeltaX)[1], myData=myData, myres=myres) # # Gammahat0 <- cbind(rbind(Gammahat,matrix(0,dim(GammaAlfahat)[1],dim(Gammahat)[2])), # rbind(matrix(0,dim(Gammahat)[2],dim(GammaAlfahat)[1]),GammaAlfahat)) uhistDeltaf1n_j<- matrix(0,floor(Tn),length(param)) uhistDeltaf2n_j<- matrix(0,floor(Tn),length(pardrif)) aaa<-length(c(param,pardrif)) uhistb_incr <- array(0, c(dim(DeltaX)[2],floor(Tn),aaa)) for(l in 1:floor(Tn)){ #ures[l] <- sum(resi[(floor((l-1)/h)):(floor(l/h)-1)]) uhistDeltaf1n_j[l, ] <- colSums(histDeltaf1n_j_delta[(floor((l-1)/h)):(floor(l/h)-1),]) uhistDeltaf2n_j[l, ] <- colSums(histDeltaf2n_j_delta[(floor((l-1)/h)):(floor(l/h)-1),]) for(i in c(1:aaa)){ dumIn <- histb_incr[,(floor((l-1)/h)):(floor(l/h)-1),i] uhistb_incr[,l,i]<- rowSums(dumIn) } } nMeaspar<-myres@model@parameter@measure mypar_meas0 <- myres@coef[nMeaspar]#res@coef[oldyuima@model@parameter@measure] mypar_meas <- c(mypar_meas0,1) ures<[email protected]@original.data names(mypar_meas)<-c(nMeaspar,myres@model@[email protected]) fdataeta<-dens(object=myres@model@measure$df,x=ures,param=mypar_meas)# f(eps, eta) del <- 10^-3 dummy <- t(rep(1,length(mypar_meas[myres@model@[email protected]]))) myeta<- as.matrix(mypar_meas[myres@model@[email protected]])%*%dummy myetapert <- myeta+del*diag(rep(1,dim(myeta)[1])) fdataetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[myres@model@[email protected]]<-1 dens(object=myres@model@measure$df,x=ures,param=par) } )# f(eps, eta+delta) term1<-1/(fdataeta) dummyvecdel<-numeric(length=dim(ures)[2]) fdatadeltaeta<- matrix(0,floor(Tn),dim(ures)[2]) mixpartial <-array(0,c(length(nMeaspar),floor(Tn),dim(ures)[2])) for(j in c(1:dim(ures)[2])){ dummyvecdel[j]<-del fdatadeltaeta[,j]<- dens(object=myres@model@measure$df,x=ures+rep(1,dim(ures)[1])%*%t(dummyvecdel),param=mypar_meas) fdatadeltaetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] par[myres@model@[email protected]]<-1 dens(object=myres@model@measure$df,x=ures+rep(1,dim(ures)[1])%*%t(dummyvecdel),param=par) } ) # f(eps +deta, eta+delta) dummyvecdel<-numeric(length=dim(ures)[2]) term2 <- fdatadeltaeta[,j]*term1%*%dummy term2 <- fdatadeltaetadelta-term2*fdataetadelta mixpartial[,,j]<-t((as.matrix(term1)%*%dummy)/del^2*term2/Tn) } DerMeta <- 1/del*(fdataetadelta - as.matrix(fdataeta)%*%rep(1,dim(fdataetadelta)[2]))*(as.matrix(term1)%*%rep(1,dim(fdataetadelta)[2])) SigmaEta <- t(DerMeta)%*%DerMeta/Tn minusloglik <- function(para){ para[length(para)+1]<-1 names(para)[length(para)]<-myres@[email protected] -sum(dens(object=myres@model@measure$df, x=ures, param = para, log = TRUE), na.rm = T)/Tn } # HessianEta_divTn <- optimHess(par=mypar_meas0, fn=minusloglik) Gammaeta_theta <- matrix(0,length(mypar_meas0), aaa) for(t in c(1:floor(Tn))){ Gammaeta_theta<-Gammaeta_theta+mixpartial[,t,]%*%uhistb_incr[,t,] } GammaEta_Theta<- -1/Tn*Gammaeta_theta Sigma_eta_theta<-t(DerMeta)%*%cbind(uhistDeltaf1n_j,uhistDeltaf2n_j)/Tn Sigma <- cbind(rbind(Sigma0,Sigma_eta_theta),rbind(t(Sigma_eta_theta),SigmaEta)) GammaHAT<-cbind(rbind(Gammahat0, GammaEta_Theta), rbind(t(GammaEta_Theta), HessianEta_divTn)) InvGammaHAT <- solve(GammaHAT) vcov <- InvGammaHAT %*% Sigma %*% InvGammaHAT/Tn myres@vcov<- vcov return(myres) } result <- vcovLevy(result,HessianEta_divTn,myGamhat,sq=sq) } #result <- vcovLevy(result,HessianEta_divTn,myGamhat,sq=sq) # colnames(result@vcov)<-names(res@fullcoef) # rownames(result@vcov)<-names(res@fullcoef) } # colnames(res@vcov)<-names(res@fullcoef) # #res@vcov<-rbind(res@vcov,matrix(NA,nrow=length(esti$par),ncol=dim(res@vcov)[2])) # rownames(res@vcov)<-names(res@fullcoef) # res@min<-c(res@min,esti$value) # res@nobs<-c(res@nobs,length([email protected][[1]])) return(result) }else{ dist <- substr(as.character(orig.mylaw$df$expr), 2, 10^3) startjump <- start0[lev.names] lowerjump <- lower0[lev.names] upperjump <- upper0[lev.names] if(length(startjump) == -1){ logdens <- function(para){ exlogdens <- parse(text = sprintf("log(d%s)", dist)) assign(myjumpname, ures, envir = tmp.env) assign(mymeasureparam, para, envir = tmp.env) sum(eval(exlogdens, envir = tmp.env)) } mydens <-function(para){ exdens <- parse(text = sprintf("d%s", dist)) assign(myjumpname, ures, envir = tmp.env) assign(mymeasureparam, para, envir = tmp.env) eval(exdens, envir = tmp.env) } intervaljump <- c(lowerjump[[1]], upperjump[[1]]) esti <- optimize(logdens, interval = intervaljump, maximum = TRUE) return(list(sde=esort, meas=esti$maximum)) }else{ logdens <- function(para){ exlogdens <- parse(text = sprintf("log(d%s)", dist)) assign(oldyuima@[email protected], ures, envir = tmp.env) for(i in c(1:length(oldyuima@model@parameter@measure))) assign(oldyuima@model@parameter@measure[i], para[[oldyuima@model@parameter@measure[i]]], envir = tmp.env) -sum(eval(exlogdens, envir = tmp.env),na.rm = T) } mydens1 <-function(par,x){ exdens <- parse(text = sprintf("d%s", dist)) assign(myjumpname, x, envir = tmp.env) assign(mymeasureparam, par, envir = tmp.env) eval(exdens, envir = tmp.env) } esti <- optim(fn=logdens, lower = lowerjump, upper = upperjump, par = startjump, method = "L-BFGS-B") HessianEta <- optimHess(par=esti$par, fn=logdens) res@coef<-c(res@coef,esti$par) res@fullcoef[lev.names]<-esti$par if(length(oldyuima@[email protected])==1){ if(!aggregation){ Ter <- yuima@sampling@Terminal ures <- numeric(floor(Ter)) for(l in 1:floor(Ter)){ ures[l] <- sum(resi[(floor((l-1)/h)):(floor(l/h)-1)]) } } mypar<-res@coef[oldyuima@model@parameter@measure] #mypar[oldyuima@model@[email protected]]<-1 fdataeta<-mydens1(par=mypar,x=ures)# f(eps, eta) del <- 10^-3 fdatadeltaeta<- mydens1(par=mypar,x=ures+del) # f(eps + delta, eta) dummy <- t(rep(1,length(mypar[lev.names]))) myeta<- as.matrix(mypar[lev.names])%*%dummy myetapert <- myeta+del*diag(rep(1,dim(myeta)[1])) fdataetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] #par[oldyuima@model@[email protected]]<-1 mydens1(par=par,x=ures) } )# f(eps, eta+delta) fdatadeltaetadelta<-sapply(X=1:dim(myeta)[1],FUN = function(X){ par<-myetapert[,X] #par[oldyuima@model@[email protected]]<-1 mydens1(par=par,x=ures+del) } ) # f(eps +deta, eta+delta) term1<-1/(fdataeta) term2 <- fdatadeltaeta*term1%*%dummy term2 <- fdatadeltaetadelta-term2*fdataetadelta mixpartial<-t((as.matrix(term1)%*%dummy)/del^2*term2/oldyuima@sampling@Terminal) # construction of b_i # DiffJumpCoeff, DriftDerCoeff, jump.term length(resi) # step1 <- t(DiffJumpCoeff)%*%DiffJumpCoeff DerMeta <- 1/del*(fdataetadelta - as.matrix(fdataeta)%*%rep(1,dim(fdataetadelta)[2]))*(as.matrix(term1)%*%rep(1,dim(fdataetadelta)[2])) SigmaEta <- t(DerMeta)%*%DerMeta/oldyuima@sampling@Terminal #SigmaEtaAlpha<- 1/oldyuima@sampling@n*DriftDerCoeff%*%(t(DiffJumpCoeff)/(as.matrix(jump.term[-length(jump.term)]^2)%*%rep(1,dim(DiffJumpCoeff)[1])) ) SigmaEtaAlpha<- 1/oldyuima@sampling@n*DriftDerCoeff%*%(t(DiffJumpCoeff)/(as.matrix(jump.term^2)%*%rep(1,dim(DiffJumpCoeff)[1])) ) SigmaEtaAlpha <- SigmaEtaAlpha*sum(resi^3)/oldyuima@sampling@delta b_i <- matrix(0,floor(Ter),length(c(oldyuima@model@parameter@drift, oldyuima@model@parameter@jump))) Coef1 <- matrix(0,floor(Ter),length( oldyuima@model@parameter@jump)) Coef2 <- matrix(0,floor(Ter),length( oldyuima@model@parameter@drift)) for(l in 1:floor(Ter)){ pos <- (floor((l-1)/h)):(floor(l/h)-1) if(length(oldyuima@model@parameter@jump)==1){ b_i[l,1:length(oldyuima@model@parameter@jump)] <- sum(-DiffJumpCoeff[,pos]*resi[pos]/jump.term[pos]) Coef1[l,]<-sum(DiffJumpCoeff[,pos]/jump.term[pos]*(resi[pos]^2-h)) }else{ interm <- as.matrix(resi[pos]/jump.term[pos]) b_i[l,1:length(oldyuima@model@parameter@jump)] <- -t(DiffJumpCoeff[,pos]%*%interm) interm2 <- as.matrix((resi[pos]^2-h)/jump.term[pos]) Coef1[l,] <-DiffJumpCoeff[,pos]%*%interm2 } if(length(oldyuima@model@parameter@drift)==1){ b_i[l,1:length(oldyuima@model@parameter@drift)+length(oldyuima@model@parameter@jump)] <- -sum(h* DriftDerCoeff[,pos]%*%jump.term[pos]) Coef2[l,]<-sum(DriftDerCoeff[,pos]/jump.term[pos]*(resi[pos])) }else{ b_i[l,1:length(oldyuima@model@parameter@drift)+length(oldyuima@model@parameter@jump)] <--h* DriftDerCoeff[,pos]%*%jump.term[pos] interm3 <- as.matrix((resi[pos])/jump.term[pos]) Coef2[l,] <-DriftDerCoeff[,pos]%*%interm3 } } MatrUnder <- mixpartial%*%b_i I_n <- cbind(rbind(myGamhat,MatrUnder),rbind(matrix(0, dim(myGamhat)[1],dim(HessianEta)[2]),HessianEta/oldyuima@sampling@Terminal)) SigmaGammaEta <- t(DerMeta)%*%Coef1/Ter SigmaAlphaEta <- t(DerMeta)%*%Coef2/Ter # dim(fdataetadelta), length(fdataeta), length(term1) dum <- cbind(SigmaGammaEta , SigmaAlphaEta) MatSigmaHat1<- rbind(cbind(MatSigmaHat,t(dum)),cbind(dum,SigmaEta)) InvIn<- solve(I_n) res@vcov <-InvIn%*%MatSigmaHat1%*%t(InvIn)/Ter }else{ res@vcov<-cbind(res@vcov,matrix(NA,ncol=length(esti$par),nrow=dim(res@vcov)[1])) } colnames(res@vcov)<-names(res@fullcoef) #res@vcov<-rbind(res@vcov,matrix(NA,nrow=length(esti$par),ncol=dim(res@vcov)[2])) rownames(res@vcov)<-names(res@fullcoef) res@min<-c(res@min,esti$value) res@nobs<-c(res@nobs,length([email protected][[1]])) result<- new("yuima.qmleLevy.incr",Incr.Lev=Incr.Lev, minusloglLevy = logdens,logL.Incr=-esti$value, Data = yuima@data, yuima=res, Levydetails=esti) return(result) #return(list(sde=esort, meas=esti$par)) } } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/qmleLevy.R
################################################################## ###### "Random number generators and ###### related density functions for yuima packages" ################################################################## ## Bilateral gamma rbgamma <- function(x,delta.plus,gamma.plus,delta.minus,gamma.minus){ if( delta.plus <= 0 ) stop("delta.plus must be positive.") if( gamma.plus <= 0 ) stop("gamma.plus must be positive.") if( delta.minus <= 0 ) stop("delta.minus must be positive.") if( gamma.minus <= 0 ) stop("gamma.minus must be positive.") X <- rgamma(x,delta.plus,gamma.plus) - rgamma(x,delta.minus,gamma.minus) return(X) } # "dbgamma" by YU. dbgamma<-function(x,delta.plus,gamma.plus,delta.minus,gamma.minus){ ## Error check if(length(delta.plus)!=1||length(gamma.plus)!=1||length(delta.minus)!=1||length(gamma.minus)!=1) stop("All of the parameters are numeric.") if(delta.plus<=0||gamma.plus<=0||delta.minus<=0||gamma.minus<=0) stop("All of the parameters are positive.") leng <- length(x) dens <- numeric(leng) for(i in 1:leng){ if(x[i]>=0){ ## On the positive line funcp<-function(x,y){y^{delta.minus-1}*(x+y/(gamma.plus+gamma.minus))^{delta.plus-1}*exp(-y)} intp<-function(x){integrate(funcp,lower=0,upper=Inf,x=x)$value} intvecp<-function(x)sapply(x,intp) dens[i]<-gamma.plus^delta.plus*gamma.minus^delta.minus/((gamma.plus+gamma.minus)^delta.minus*gamma(delta.plus)*gamma(delta.minus))*exp(-gamma.plus*x[i])*intvecp(x[i]) }else{ ## On the negative line funcm<-function(x,y){y^{delta.plus-1}*(-x+y/(gamma.plus+gamma.minus))^{delta.minus-1}*exp(-y)} intm<-function(x){integrate(funcm,lower=0,upper=Inf,x=x)$value} intvecm<-function(x)sapply(x,intm) dens[i]<-gamma.plus^delta.plus*gamma.minus^delta.minus/((gamma.plus+gamma.minus)^delta.plus*gamma(delta.minus)*gamma(delta.plus))*exp(gamma.minus*x[i])*intvecm(x[i]) } } dens } ## Generalized inverse Gaussian rGIG<-function(x,lambda,delta,gamma){ if((delta < 0)||(gamma<0)){ stop("delta and gamma must be nonnegative.") } if((delta == 0) && (lambda <= 0)){ stop("delta must be positive when lambda is nonpositive.") } if((gamma == 0) && (lambda >= 0)){ stop("gamma must be positive when lambda is nonnegative.") } if(lambda >= 0){ if(delta == 0){ ## gamma case X<-rgamma(x, lambda, 1/(2*gamma^2)) } if(gamma == 0){ ## inverse gamma case X<-delta^2/(2*rgamma(x,-lambda,1)) } if(delta != 0){ X<-.C("rGIG", as.integer(x), as.double(lambda), as.double(delta^2), as.double(gamma^2), rn = double(length = x))$rn} } else{ Y<-.C("rGIG", as.integer(x), as.double(-lambda), as.double(gamma^2), as.double(delta^2), rn = double(length = x))$rn X<-1/Y } return(X) } dGIG<-function(x,lambda,delta,gamma){ if(x <= 0) stop("x must be positive") if((delta < 0)||(gamma<0)){ stop("delta and gamma must be nonnegative.") } if((delta == 0) && (lambda <= 0)){ stop("delta must be positive when lambda is nonpositive.") } if((gamma == 0) && (lambda >= 0)){ stop("gamma must be positive when lambda is nonnegative.") } if(delta == 0){ ## gamma case dens <- dgamma(x,lambda,1/(2*gamma^2)) } if(gamma == 0){ ## inverse gamma case dens <- x^(lambda-1)*exp(-1/2*delta/x)/(gamma(-lambda)*2^(-lambda)*delta^(2*lambda)) }else{ dens <- 1/2*(gamma/delta)^lambda*1/besselK(gamma*delta,lambda)*x^(lambda-1)*exp(-1/2*(delta^2/x+gamma^2*x)) } return(dens) } ## Generalized hyperbolic rGH<-function(x,lambda,alpha,beta,delta,mu,Lambda){ if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(missing(Lambda)) Lambda <- NA if( alpha < 0 ){ stop("alpha must be nonnegative.") } ## variance gamma case if(delta == 0){ X<-rvgamma(x,lambda,alpha,beta,mu,lambda) } ## univariate case if(any(is.na(Lambda))){ if(length(mu)!=1 || length(beta)!=1){ stop("Error: wrong input dimension.") } tmp <- as.numeric(alpha^2 - beta^2) if( tmp < 0 ){ stop("alpha^2 - beta^2 must be nonnegative value.") } if(((alpha == 0)||(tmp == 0)) && (lambda >= 0)){ stop("alpha and alpha^2 - beta^2 must be positive when lambda is nonnegative.") } Z<-rGIG(x,lambda,delta,sqrt(tmp)) N<-rnorm(x,0,1) X<-mu + beta*Z + sqrt(Z)*N } else{## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp <- as.numeric(alpha^2 - t(beta) %*% Lambda %*% beta) if(tmp < 0){ stop("alpha^2 - t(beta) %*% Lambda %*% beta must be nonnegative") } if(((alpha == 0)||(tmp == 0))&&(lambda >=0)){ stop("alpha and alpha^2 - t(beta) %*% Lambda %*% beta must be positive when lambda is nonnegative.") } Z<-rGIG(x,lambda,delta,sqrt(tmp)) N<-rnorm(x*length(beta),0,1) sqrt.L <- svd(Lambda) sqrt.L <- sqrt.L$u %*% diag(sqrt(sqrt.L$d)) %*% t(sqrt.L$v) X <- mu + t(matrix(rep(Z,length(beta)),x,length(beta))) * matrix(rep(Lambda %*% beta,x),length(beta),x)+t(matrix(rep(sqrt(Z),length(beta)),x,length(beta))) * (sqrt.L %*% t(matrix(N,x,length(beta)))) } return(X) } dGH<-function(x,lambda,alpha,beta,delta,mu,Lambda){ if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(missing(Lambda)) Lambda <- NA if( alpha < 0 ){ stop("alpha must be nonnegative.") } ## variance gamma case if(delta == 0){ X<-dvgamma(x,lambda,alpha,beta,mu,Lambda) } ## univariate case if(any(is.na(Lambda))){ if(length(mu)!=1 || length(beta)!=1){ stop("Error: wrong input dimension.") } tmp <- as.numeric(alpha^2 - beta^2) if( tmp < 0 ){ stop("alpha^2 - beta^2 must be nonnegative value.") } if(((alpha == 0)||(tmp == 0)) && (lambda >= 0)){ stop("alpha and alpha^2 - beta^2 must be positive when lambda is nonnegative.") } nu<--2*lambda if(alpha == 0){## gamma = 0 (in gig), scaled t-distribution dens<-gamma((nu+1)/2)*(1+((x-mu)/delta)^2)^(-(nu+1)/2)/(delta*sqrt(pi)*gamma(nu/2)) }else if(tmp == 0){## skewed t-distribution dens<-delta^nu*exp(beta*(x-mu))*gamma((nu+1)/2)*besselK(abs(beta)*sqrt(delta^2+(x-mu)^2),(nu+1)/2)/(2^((nu-1)/2)*sqrt(pi)*gamma(nu/2)*(sqrt(delta^2+(x-mu)^2)/abs(beta))^((nu+1)/2)) }else{ dens<-tmp^(lambda/2)*sqrt(delta^2+(x-mu)^2)^(lambda-1/2)*besselK(alpha*sqrt(delta^2+(x-mu)^2),lambda-1/2)*exp(beta*(x-mu))/(sqrt(2*pi)*alpha^(lambda-1/2)*delta^lambda*besselK(delta*sqrt(tmp),lambda)) } } else{## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp <- as.numeric(alpha^2 - t(beta) %*% Lambda %*% beta) if(tmp < 0){ stop("alpha^2 - t(beta) %*% Lambda %*% beta must be nonnegative") } if(((alpha == 0)||(tmp == 0))&&(lambda >=0)){ stop("alpha and alpha^2 - t(beta) %*% Lambda %*% beta must be positive when lambda is nonnegative.") } Lambdainv<-solve(Lambda) nu<--2*lambda d<-nrow(Lambda) if(alpha == 0){ ## gamma = 0 (in gig) multivariate scaled t-distribution dens<-gamma((nu+d)/2)*(1+t(x-mu)%*%Lambdainv%*%(x-mu)/delta^2)^(-(nu+d)/2)/(pi^(d/2)*gamma(nu/2)*delta^d) }else if(tmp == 0){ ## multivariate skewed t-distribution dens<-delta^nu*exp(t(beta)%*%(x-mu))*besselK(alpha*sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu)),-(nu+d)/2)/((pi)^(d/2)*2^((nu+d)/2-1)*(sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu))/alpha)^((nu+d)/2)*gamma(nu/2)) }else{ dens<-exp(t(beta)%*%(x-mu))*(sqrt(tmp)/delta)^lambda*besselK(alpha*sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu)),-(nu+d)/2)/((2*pi)^(d/2)*besselK(delta*sqrt(tmp),lambda)*(sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu))/alpha)^(d/2-lambda)) } } return(dens) } ## (Multivariate) Variance gamma rvgamma <- function(x,lambda,alpha,beta,mu,Lambda){ ## Error check if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(missing(Lambda)) Lambda <- NA if(any(is.na(Lambda))){ ## univariate case if(length(mu)!=1 || length(beta)!=1){ stop("Error: wrong input dimension.") } tmp <- as.numeric(alpha^2 - beta^2) if( lambda <= 0 ){ stop("lambda must be positive.") } if( alpha <= 0 ){ stop("alpha must be positive.") } if( tmp <= 0 ){ stop("alpha^2 - beta^2 must be positive value.") } tau <- rgamma(x,lambda,tmp/2) eta <- rnorm(x) ## z <- mu + beta * tau * Lambda + sqrt(tau * Lambda) * eta z <- mu + beta * tau + sqrt(tau) * eta X <- z return(X) }else{ ## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp <- as.numeric(alpha^2 - t(beta) %*% Lambda %*% beta) if( lambda <= 0 ) stop("lambda must be positive.") if( alpha <= 0 ) stop("alpha must be positive.") if( tmp <=0) stop("alpha^2 - t(beta) %*% Lambda %*% beta must be positive.") tau <- rgamma(x,lambda,tmp/2) eta <- rnorm(x*length(beta)) sqrt.L <- svd(Lambda) sqrt.L <- sqrt.L$u %*% diag(sqrt(sqrt.L$d)) %*% t(sqrt.L$v) z <- mu + t(matrix(rep(tau,length(beta)),x,length(beta))) * matrix(rep(Lambda %*% beta,x),length(beta),x)+t(matrix(rep(sqrt(tau),length(beta)),x,length(beta))) * (sqrt.L %*% t(matrix(eta,x,length(beta)))) X <- z return(X) } } dvgamma <- function(x,lambda,alpha,beta,mu,Lambda){ ## Error check if(length(lambda)!=1||length(alpha)!=1) stop("alpha and lambda must be positive reals.") if( lambda <= 0 ) stop("lambda must be positive.") if( alpha <= 0 ) stop("alpha must be positive.") if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(missing(Lambda)) Lambda <- NA if(any(is.na(Lambda))){ ## univariate case if(length(mu)!=1 || length(beta)!=1){ stop("Error: wrong input dimension.") } if( alpha^2 - beta^2 <= 0 ) stop("alpha^2 - beta^2 must be positive.") dens <- exp(beta*(x-mu))*((alpha^2 - beta^2)^(lambda))*besselK(alpha*abs(x-mu),lambda-1/2)*abs(x-mu)^(lambda-1/2)/(gamma(lambda)*sqrt(pi)*((2*alpha)^(lambda-1/2))) dens} else{ ## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp <- as.numeric(alpha^2 - t(beta) %*% Lambda %*% beta) if( tmp <=0) stop("alpha^2 - t(beta) %*% Lambda %*% beta must be positive.") Lambdainv<-solve(Lambda) dens<- exp(t(beta)%*%(x-mu))*(alpha^2-t(beta)%*%Lambda%*%beta)^(lambda)*besselK(alpha*sqrt(t(x-mu)%*%Lambdainv%*%(x-mu)),lambda-nrow(Lambda)/2)*sqrt(t(x-mu)%*%Lambdainv%*%(x-mu))^{lambda-nrow(Lambda)/2}/(gamma(lambda)*pi^{nrow(Lambda)/2}*2^{nrow(Lambda)/2+lambda-1}*alpha^{lambda-nrow(Lambda)/2}) dens } } ## Inverse Gaussian rIG <- function(x,delta,gamma){ if( delta <= 0 ) stop("delta must be positive.") if( gamma <= 0 ) stop("gamma must be positive.") V <- rchisq(x,df=1); z1 <- ( delta/gamma + V/(2*gamma^2) ) - sqrt( V*delta/(gamma^3) + ( V/(2*gamma^2) )^2 ) U <- runif(x,min=0,max=1) idx <- which( U < (delta/(delta+gamma*z1)) ) z2 <- (delta/gamma)^2 /z1[-idx] ret <- numeric(x) ret[idx] <- z1[idx] ret[-idx] <- z2 return(ret) } dIG <- function(x,delta,gamma){ if(x <= 0) stop("x must be positive") if( delta <= 0 ) stop("delta must be positive.") if( gamma <= 0 ) stop("gamma must be positive.") dens <- delta*exp(delta*gamma)*(x^(-3/2))*exp(-((delta^2)/x+x*gamma^2)/2)/sqrt(2*pi) dens } ## (Multivariate) Normal inverse Gaussian rNIG <- function(x,alpha,beta,delta,mu,Lambda){ ## Error check #print(match.call()) if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(length(alpha)>1||length(delta)>1) stop("alpha and delta must be positive reals.") if( alpha < 0 ) stop("alpha must be nonnegative.") if( delta <= 0 ) stop("delta must be positive.") if(missing(Lambda)) Lambda <- NA if(any(is.na(Lambda)) & length(Lambda)==1){ ## univariate case gamma <- sqrt(alpha^2 - beta^2) if(gamma <0){ stop("alpha^2-beta^2 must be positive.") } if (gamma == 0) { V = rnorm(x)^2 Z = delta * delta/V X = sqrt(Z) * rnorm(x) }else{ Z <- rIG(x,delta,gamma) N <- rnorm(x,0,1) X <- mu + beta*Z + sqrt(Z)*N } return(X) }else{ ## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp <- as.numeric(alpha^2 - t(beta) %*% Lambda %*% beta) if(tmp <0){ stop("alpha^2 - t(beta) %*% Lambda %*% beta must be nonnegative.") } gamma <- sqrt(tmp) } tau <- rIG(x,delta,gamma) eta <- rnorm(x*length(beta)) sqrt.L <- svd(Lambda) sqrt.L <- sqrt.L$u %*% diag(sqrt(sqrt.L$d)) %*% t(sqrt.L$v) z <- mu + t(matrix(rep(tau,length(beta)),x,length(beta))) * matrix(rep(Lambda %*% beta,x),length(beta),x)+t(matrix(rep(sqrt(tau),length(beta)),x,length(beta))) * (sqrt.L %*% t(matrix(eta,x,length(beta)))) X <- z # print(str(X)) return(X) } dNIG <- function(x,alpha,beta,delta,mu,Lambda){ ## Error check #print(match.call()) if(length(alpha)>1||length(delta)>1) stop("alpha and delta must be positive reals.") if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if( alpha < 0 ) stop("alpha must be nonnegative.") if( delta <= 0 ) stop("delta must be positive.") if(missing(Lambda)) Lambda <- NA if(any(is.na(Lambda))){ #univraiate case if(length(beta)>1||length(mu)>1) stop("beta and mu must be numeric") if( alpha^2 - beta^2 < 0 ) stop("alpha^2 - beta^2 must be nonnegative.") dens <- alpha*delta*exp(delta*sqrt(alpha^{2}-beta^{2})+beta*(x-mu))*besselK(alpha*sqrt(delta^{2}+(x-mu)^{2}),1)/(pi*sqrt(delta^{2}+(x-mu)^{2})) dens }else{ #multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if(sum((Lambda-t(Lambda))*(Lambda-t(Lambda)))!=0){ stop("Lambda must be a symmetric matrix") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if(nrow(Lambda)!=length(mu)){ stop("Dimension of Lambda and mu must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tmp<-alpha-t(beta)%*%Lambda%*%beta if(tmp <0){ stop("alpha^2 - t(beta) %*% Lambda %*% beta must be nonnegative.") } Lambdainv<-solve(Lambda) dens<- alpha^{(nrow(Lambda)+1)/2}*delta*exp(delta*sqrt(tmp)+t(beta)%*%(x-mu))*besselK(alpha*sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu)),nrow(Lambda))/(2^{(nrow(Lambda)-1)/2}*pi^{(nrow(Lambda)+1)/2}*(sqrt(delta^2+t(x-mu)%*%Lambdainv%*%(x-mu)))^{(nrow(Lambda)+1)/2}) dens } } ## ## One-dim. NIG ## rNIG <- function(x,alpha=1,beta=0,delta=1,mu=0){ ## gamma <- sqrt(alpha^2 - beta^2) ## if (gamma == 0) { ## V = rnorm(x)^2 ## Z = delta * delta/V ## X = sqrt(Z) * rnorm(x) ## }else{ ## Z <- rIG(x,delta,gamma) ## N <- rnorm(x,0,1) ## X <- mu + beta*Z + sqrt(Z)*N ## } ## return(X) ## } ## Univariate non-Gaussian stable: corrected Weron's algorithm incorporated ## (20160114, HM) "dstable" still unavailable in YUIMA... incorporate "stabledist" package? rstable <- function(x,alpha,beta,sigma,gamma){ if( alpha <= 0 || alpha > 2) stop("The index alpha must take values in (0,2].") if( beta < -1 || beta > 1) stop("The skeweness beta must take values in [-1,1].") if( sigma <= 0 ) stop("The scale sigma must be positive.") a <- (1 + (beta*tan(alpha*pi/2))^2)^(1/(2*alpha)) b <- atan(beta*tan(alpha*pi/2))/alpha u <- runif(x,-pi/2,pi/2) v <- rexp(x,1) if(alpha!=1){ s <- a * (sin(alpha*(u+b))/cos(u)^(1/alpha)) * (cos(u-alpha*(u+b))/v)^((1-alpha)/alpha) X <- sigma * s + gamma * rep(1,x) }else{ s <- (2/pi) * ((pi/2 +beta*u)*tan(u) - beta * log((pi/2)*v*cos(u)/(beta*u + pi/2))) X <- sigma * s + (gamma + (2/pi)*beta*sigma*log(sigma)) * rep(1,x) } return(X) } ## rstable <- function(x,alpha,beta,sigma, gamma, eps){ ## a <- (1 + (beta*tan(alpha*pi/2))^2)^(1/(2*alpha)) ## b <- atan(beta*tan(alpha*pi/2))/alpha ## u <- runif(x,-pi/2,pi/2) ## v <- rexp(x,1) ## if(alpha!=1){ ## s <- a * (sin(alpha*(u+b))/cos(u)^(1/alpha)) * (cos(u-alpha*(u+b))/v)^((1-alpha)/alpha) ## }else{ ## s <- (2/pi) * ((pi/2 +beta*u)*tan(u) - beta * log(v*cos(u)/(beta*u + pi/2))) ## } ## X <- (eps^(1/alpha)) * sigma * s + gamma * eps * rep(1,x) ## return(X) ## } ## Positive exponentially tempered stable (AR method) rpts<-function(x,alpha,a,b){ if( alpha <= 0 | alpha>= 1 ) stop("alpha must lie in (0,1).") if( a <= 0 ) stop("a must be positive value.") if( b <= 0 ) stop("b must be positive value.") ar<-exp(a*gamma(-alpha)*b^(alpha)) if(ar <= 0.1) stop("Acceptance rate is too small.") else .C("rpts",as.integer(x),as.double(alpha),as.double(a),as.double(b),rn=double(length=x))$rn} ## Normal tempered stable rnts<-function(x,alpha,a,b,beta,mu,Lambda){ ## Error check if(length(mu)!=length(beta)){ stop("Error: wrong input dimension.") } if(missing(Lambda)) Lambda <- NA if( alpha <= 0 || alpha > 2 ){ stop("The index alpha must take values in (0,2].") } if( a <= 0 ) stop("a must be positive value.") if( b <= 0 ) stop("b must be positive value.") if(any(is.na(Lambda))){ ## univariate case if(length(mu)!=1 || length(beta)!=1){ stop("Error: wrong input dimension.") } tau <- rpts(x,alpha,a,b) eta <- rnorm(x) ## z <- mu + beta * tau * Lambda + sqrt(tau * Lambda) * eta z <- mu + beta * tau + sqrt(tau) * eta X <- z return(X) }else{ ## multivariate case if( nrow(Lambda)!=ncol(Lambda)){ stop("Lambda must be a square matrix.") } if( nrow(Lambda)!=length(beta)){ stop("Dimension of Lambda and beta must be equal.") } if(nrow(Lambda)!=length(mu)){ stop("Dimension of Lambda and mu must be equal.") } if( min(eigen(Lambda)$value) <= 10^(-15) ){ stop("Lambda must be positive definite.") } if( det(Lambda) > 1+10^(-15) || det(Lambda) < 1-10^(-15) ){ stop("The determinant of Lambda must be 1.") } tau<-rpts(x,alpha,a,b) eta <- rnorm(x*length(beta)) sqrt.L <- svd(Lambda) sqrt.L <- sqrt.L$u %*% diag(sqrt(sqrt.L$d)) %*% t(sqrt.L$v) z <- mu + t(matrix(rep(tau,length(beta)),x,length(beta))) * matrix(rep(Lambda %*% beta,x),length(beta),x)+t(matrix(rep(sqrt(tau),length(beta)),x,length(beta))) * (sqrt.L %*% t(matrix(eta,x,length(beta)))) z<-mu+ t(matrix(rep(tau,length(beta)),x,length(beta))) * matrix(rep(Lambda %*% beta,x),length(beta),x)+t(matrix(rep(sqrt(tau),length(beta)),x,length(beta))) * (sqrt.L %*% t(matrix(eta,x,length(beta)))) X <- z return(X) } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/rng.R
sampling2grid <- function(samp){ #Check if there is already a grid if (length(samp@grid)>0){ #It is the general case where there is a grid #including irregular deterministic case return(samp@grid) } #Check if this grid is random if (samp@random==FALSE){ #Regular deterministic grid return(seq(samp@Initial[1],samp@Terminal[1],length=samp@n[1]+1)) #Attention! do not treat multifrequency grid } return(1) #To do: Random grid }
/scratch/gouwar.j/cran-all/cranData/yuima/R/sampling2grid.R
setMethod("initialize", "carma.info", function(.Object, p=numeric(), q=numeric(), loc.par=character(), scale.par=character(), ar.par=character(), ma.par=character(), lin.par=character(), Carma.var=character(), Latent.var=character(), XinExpr=logical()){ .Object@p <- p .Object@q <- q [email protected] <- loc.par [email protected] <- scale.par [email protected] <- ar.par [email protected] <- ma.par [email protected] <- lin.par [email protected] <- Carma.var [email protected] <- Latent.var .Object@XinExpr <- XinExpr return(.Object) }) setMethod("initialize", "yuima.carma", function(.Object, info = new("carma.info"), drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = expression(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "x", jump.variable = "z", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical()){ .Object@info <- info .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- hurst [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag return(.Object) }) setCarma<-function(p, q, loc.par=NULL, scale.par=NULL, ar.par="a", ma.par="b", lin.par=NULL, Carma.var="v", Latent.var="x", XinExpr=FALSE, Cogarch=FALSE, ...){ # We use the same parametrization as in Brockwell (2000) # mydots$Carma.var= V # mydots$Latent.var= X ????? # The Carma model is defined by two equations: # \begin{eqnarray} # V_{t}&=&\alpha_{0}+a'Y_{t-}\\ # dY_{t}&=& BY_{t-}dt+ e dL\\ # \end{eqnarray} # p is the number of the moving average parameters \alpha # q is the number of the autoregressive coefficient \beta #Default parameters if (is.null(scale.par)){ ma.par1<-ma.par } else{ ma.par1<-paste(scale.par,ma.par,sep="*") } call <- match.call() quadratic_variation<-FALSE mydots <- as.list(call)[-(1:2)] # hurst<-0.5 # jump.coeff <- character() # measure <- list() # measure.type <- character() # state.variable <- "Y" # jump.variable <- "z" # time.variable <- "t" # mydots$xinit<- NULL if (is.null(mydots$hurst)){ mydots$hurst<-0.5 } if(is.null(mydots$time.variable)){ mydots$time.variable<-"t" } if(is.null(mydots$jump.variable)){ mydots$jump.variable<-"z" } # if(is.null(mydots$xinit)){ # if(is.null(mydots$XinExpr)){ # mydots$xinit<-as.character(0*c(1:p)) # }else{ # if(mydots$XinExpr==TRUE){ # Int.Var<-paste(Latent.var,"0",sep="") # mydots$xinit<-paste(Int.Var,c(0:(p-1)),sep="") # } # } # } else{ # dummy<-as.character(mydots$xinit) # mydots$xinit<-dummy[-1] # } if(is.null(mydots$xinit)){ if(XinExpr==FALSE){ mydots$xinit<-as.character(0*c(1:p)) }else{ if(XinExpr==TRUE){ Int.Var<-paste(Latent.var,"0",sep="") if(Cogarch==FALSE){ mydots$xinit<-paste(Int.Var,c(0:(p-1)),sep="") }else{ mydots$xinit<-paste(Int.Var,c(1:p),sep="") } } } } else{ dummy<-as.character(mydots$xinit) mydots$xinit<-dummy[-1] } if(p<q){ yuima.stop("order of AR must be larger than MA order") } beta_coeff0<-paste("-",ar.par,sep="") beta_coeff<-paste(beta_coeff0,p:1,sep="") if(Cogarch==FALSE){ coeff_alpha<-c(paste(ma.par1,0:q,sep=""),as.character(matrix(0,1,p-q-1))) }else{ coeff_alpha<-c(paste(ma.par1,1:(q+1),sep=""),as.character(matrix(0,1,p-q-1))) } fin_alp<-length(coeff_alpha) if(Cogarch==FALSE){ Y_coeff<-paste(Latent.var,0:(p-1),sep="") # Y_coeff<-paste(Int.Var,0:(p-1),sep="") }else{ Y_coeff<-paste(Latent.var,1:p,sep="") } fin_Y<-length(Y_coeff) # V1<-paste(coeff_alpha,Y_coeff,sep="*") V1<-paste(coeff_alpha,mydots$xinit,sep="*") V2<-paste(V1,collapse="+") # alpha0<-paste(ma.par1,0,sep="") if(is.null(loc.par)){ Vt<-V2 V<-paste0("(",V2,")",collapse="") } else { Vt<-paste(loc.par,V2,sep="+") V<-paste0("(",Vt,")",collapse="") } drift_last_cond<-paste(paste(beta_coeff,Y_coeff,sep="*"),collapse="") # Drift condition for the dV_{t} drift_first_cond_1<-c(paste(coeff_alpha[-fin_alp],Y_coeff[-1],sep="*")) drift_first_cond_2<-paste(drift_first_cond_1,collapse="+") drift_first_cond_a<-paste("(",drift_last_cond,")",sep="") drift_first_cond_b<-paste(coeff_alpha[fin_alp],drift_first_cond_a,sep="*") drift_first_cond<-paste(drift_first_cond_2,drift_first_cond_b,sep="+") if(length(Y_coeff)>1) {drift_Carma<-c(drift_first_cond,Y_coeff[2:length(Y_coeff)],drift_last_cond)}else {drift_Carma<-c(drift_first_cond,drift_last_cond)} # We need to consider three different situations if(is.null(mydots$jump.coeff) & is.null(mydots$measure) & is.null(mydots$measure.type) & quadratic_variation==FALSE){ # The Carma model is driven by a Brwonian motion if (is.null(lin.par)){ diffusion_Carma<-matrix(c(coeff_alpha[fin_alp],as.character(matrix(0,(p-1),1)),"1"),(p+1),1) # Latent.var<-Y_coeff Model_Carma<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, hurst=mydots$hurst, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(Vt,mydots$xinit)) #25/11 # # carma.info<-new("carma.info", # p=p, # q=q, # loc.par="character", # scale.par="character", # ar.par=ar.par, # ma.par=ma.par, # Carma.var=Carma.var, # Latent.var=Latent.var, # XinExpr=XinExpr) if(length(Model_Carma)==0){ stop("Yuima model was not built") } else { # return(Model_Carma1) } } else{ if(ma.par==lin.par){ first_term<-paste(coeff_alpha[fin_alp],V,sep="*") diffusion_Carma<-matrix(c(first_term,as.character(matrix(0,(p-1),1)),V),(p+1),1) if(Cogarch==FALSE){ Model_Carma<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, hurst=mydots$hurst, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(Vt,mydots$xinit)) }else{# We add this part to have as initial condition for the COGARCH model V_0=a_0+a'X_0 LM 13/02/2015 V01<-paste(coeff_alpha,mydots$xinit,sep="*") V02<-paste(V01,collapse="+") V0t<-paste(loc.par,V02,sep="+") Model_Carma<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, hurst=mydots$hurst, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(V0t,mydots$xinit)) } # return(Model_Carma1) }else{ # coeff_gamma<-c(paste(lin.par,1:p,sep=""),as.character(matrix(0,1,p-q))) coeff_gamma<-c(paste(lin.par,1:p,sep="")) Gamma1<-paste(coeff_gamma,Y_coeff,sep="*") Gamma2<-paste(Gamma1,collapse="+") gamma0<-paste(lin.par,0,sep="") Gammat<-paste(gamma0,Gamma2,sep="+") Gamma<-paste("(",Gammat,")",collapse="") first_term<-paste(coeff_alpha[fin_alp],Gamma,sep="*") diffusion_Carma<-matrix(c(first_term,as.character(matrix(0,(p-1),1)),Gamma),(p+1),1) # Model_Carma1<-setModel(drift=drift_Carma, # diffusion=diffusion_Carma, # hurst=mydots$hurst, # state.variable=c(Carma.var,Y_coeff), # solve.variable=c(Carma.var,Y_coeff), # xinit=c(V,mydots$xinit)) Model_Carma<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, hurst=mydots$hurst, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(Vt,mydots$xinit)) # return(Model_Carma1) } } } else { if( is.null(mydots$jump.coeff) & is.null(mydots$measure) & is.null(mydots$measure.type) & is.null(lin.par) & quadratic_variation==TRUE){ stop("The CoGarch model requires a Carma process driven by the discrete part of the quadratic covariation: You Must specify the Levy Measure") } else { if(quadratic_variation==FALSE & is.null(lin.par)){ # warning("At the moment, we need specify the underlying L?vy directly") # diffusion_Carma<-matrix(c(coeff_alpha[fin_alp],as.character(matrix(0,(q-1),1)),"1"),(q+1),1) # Model_Carma1<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, # hurst=hurst, state.variable=c(V,Y_coeff), solve.variable=c(V,Y_coeff)) # under_Lev1<-setModel(drift="0",diffusion="0",jump.coeff="1" , # measure=measure ,measure.type=measure.type , # jump.variable=jump.variable , time.variable=time.variable) # if(length(Model_Carma1)==0){ # stop("Yuima model was not built") # } else { # Model_Carma<-Carma_Model() # Model_Carma@model <- Model_Carma1 # Model_Carma@Cogarch_Model_Log <- Cogarch_Model # Model_Carma@Under_Lev <-under_Lev1 # return(Model_Carma) # } # LM 27/09 We use a modified # setModel that allows us to build a sde where the slot [email protected] is an vector # jump_Carma<-matrix(c(coeff_alpha[fin_alp],as.character(matrix(0,(q-1),1)),"1"),(q+1),1) jump_Carma<-c(coeff_alpha[fin_alp],as.character(matrix(0,(p-1),1)),"1") # Model_Carma<-setModel(drift=drift_Carma, # diffusion = NULL, # hurst=mydots$hurst, # jump.coeff=jump_Carma, # measure=eval(mydots$measure), # measure.type=mydots$measure.type, # jump.variable=mydots$jump.variable, # time.variable=mydots$time.variable, # state.variable=c(Carma.var,Y_coeff), # solve.variable=c(Carma.var,Y_coeff), # xinit=c(V,mydots$xinit)) # Model_Carma<-setModel(drift=drift_Carma, diffusion = NULL, hurst=mydots$hurst, jump.coeff=as.matrix(jump_Carma), measure=eval(mydots$measure), measure.type=eval(mydots$measure.type), jump.variable=mydots$jump.variable, time.variable=mydots$time.variable, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(Vt,mydots$xinit)) # return(Model_Carma) } else { if (quadratic_variation==FALSE ){ # Selecting Quadratic_Variation==FALSE and specifying the Heteroskedatic.param in the model, # The coefficient of the error term is a vector in which the last element is an affine linear function # of the vector space Y # We have to consider two different cases: # a) The last component of the error term is $V_{t-}=\alpha_{0}+a'Y_{t-}$. Usually # this condition is used for the definition of the COGARCH(p,q) introduced in Brockwell and Davis and # b) The last component of the error term is a linear function of the state variable $Y_{t}$ # different of the observable variable V. if(ma.par==lin.par){ jump_first_comp<-paste(coeff_alpha[fin_alp],V,sep="*") jump_Carma<-c(jump_first_comp,as.character(matrix(0,(p-1),1)),V) }else{ # coeff_gamma<-c(paste(lin.par,1:p,sep=""),as.character(matrix(0,1,q-p))) coeff_gamma<-c(paste(lin.par,1:p,sep="")) Gamma1<-paste(coeff_gamma,Y_coeff,sep="*") Gamma2<-paste(Gamma1,collapse="+") gamma0<-paste(lin.par,0,sep="") Gammat<-paste(gamma0,Gamma2,sep="+") Gamma<-paste("(",Gammat,")",collapse="") jump_first_comp<-paste(coeff_alpha[fin_alp],Gamma,sep="*") jump_Carma<-c(jump_first_comp,as.character(matrix(0,(p-1),1)),Gamma) } # Model_Carma<-setModel(drift=drift_Carma, # diffusion =NULL, # hurst=0.5, # jump.coeff=jump_Carma, # measure=eval(mydots$measure), # measure.type=mydots$measure.type, # jump.variable=mydots$jump.variable, # time.variable=mydots$time.variable, # state.variable=c(Carma.var,Y_coeff), # solve.variable=c(Carma.var,Y_coeff), # c(V,mydots$xinit)) # return(Model_Carma) } Model_Carma<-setModel(drift=drift_Carma, diffusion =NULL, hurst=mydots$hurst, jump.coeff=jump_Carma, measure=eval(mydots$measure), measure.type=mydots$measure.type, jump.variable=mydots$jump.variable, time.variable=mydots$time.variable, state.variable=c(Carma.var,Y_coeff), solve.variable=c(Carma.var,Y_coeff), xinit=c(Vt,mydots$xinit)) # return(Model_Carma) if(quadratic_variation==TRUE){ # stop("Work in Progress: Implementation of CARMA model for CoGarch. We need the increments of Quadratic Variation") # # diffusion_first_cond<-paste(coeff_alpha[fin_alp],V,sep="*") # diffusion_Carma<-matrix(c(diffusion_first_cond,as.character(matrix(0,(q-1),1)),Vt),(q+1),1) # # At the present time, Yuima does not support Multi - Jumps # Model_Carma1<-setModel(drift=drift_Carma, diffusion=diffusion_Carma, # hurst=hurst, state.variable=c(V,Y_coeff), solve.variable=c(V,Y_coeff)) # under_Lev1<-setModel(drift="0",diffusion="0",jump.coeff="1" , # measure=measure ,measure.type=measure.type , # jump.variable=jump.variable , time.variable=time.variable) # if(length(Model_Carma1)==0){ # stop("Yuima model was not built") # } else { # Model_Carma<-Carma_Model() # Model_Carma@model <- Model_Carma1 # Model_Carma@Cogarch_Model_Log <- Cogarch_Model # Model_Carma@Under_Lev <-under_Lev1 # return(Model_Carma) # } # } } } } # 25/11 if(is.null(loc.par)){loc.par<-character()} if(is.null(scale.par)){scale.par<-character()} if(is.null(lin.par)){lin.par<-character()} carmainfo<-new("carma.info", p=p, q=q, loc.par=loc.par, scale.par=scale.par, ar.par=ar.par, ma.par=ma.par, lin.par=lin.par, Carma.var=Carma.var, Latent.var=Latent.var, XinExpr=XinExpr) Model_Carma1<-new("yuima.carma", info=carmainfo, drift=Model_Carma@drift, diffusion =Model_Carma@diffusion, hurst=Model_Carma@hurst, [email protected], measure=Model_Carma@measure, [email protected], parameter=Model_Carma@parameter, [email protected], [email protected], [email protected], noise.number = [email protected], equation.number = [email protected], dimension = Model_Carma@dimension, [email protected], xinit=Model_Carma@xinit, J.flag = [email protected] ) return(Model_Carma1) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/setCarma.R
setMethod("initialize", "cogarch.info", function(.Object, p=numeric(), q=numeric(), ar.par=character(), ma.par=character(), loc.par=character(), Cogarch.var=character(), V.var=character(), Latent.var=character(), XinExpr=logical(), measure=list(), measure.type=character()){ .Object@p <- p .Object@q <- q [email protected] <- ar.par [email protected] <- ma.par [email protected] <- loc.par [email protected] <- Cogarch.var [email protected] <- V.var [email protected] <- Latent.var .Object@XinExpr <- XinExpr .Object@measure<-measure [email protected]<-measure.type return(.Object) }) setMethod("initialize", "yuima.cogarch", function(.Object, info = new("cogarch.info"), drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = list(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "x", jump.variable = "z", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical() # quadr.var=new("quadratic.variation") ){ .Object@info <- info .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- hurst [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag #[email protected] <- quadr.var return(.Object) }) setCogarch<-function(p, q, ar.par="b", ma.par="a", loc.par="a0", Cogarch.var="g", V.var="v", Latent.var="y", jump.variable="z", time.variable="t", measure=NULL, measure.type=NULL, XinExpr=FALSE, startCogarch=0, work=FALSE,...){ # We use the same parametrization as in Brockwell (2000) call <- match.call() mydots <- as.list(call)[-(1:2)] if (work==TRUE){ Model_Cogarch=NULL return(Model_Cogarch) } if(is.null(measure)){ yuima.warn("The Levy measure must be specified. The Brownian is not allowed as underlying process for Cogarch model.") return(NULL) } if(is.null(measure.type)){ yuima.warn("The measure.type must be specified. See yuima documentation.") return(NULL) } # We need to build the auxiliar carma model that is the variance process # If we consider a Cogarch(p,q) the variance process is a Carma(q,p-1) model if(is.null(mydots$xinit)){ aux.Carma<-setCarma(p=q, q=p-1, ar.par=ar.par, ma.par=ma.par, loc.par=loc.par, lin.par=ma.par, Carma.var=V.var, Latent.var=Latent.var, XinExpr=XinExpr, Cogarch=TRUE) # In order to have a representation of a Cogarch(p,q) model coherent with the # Chaadra Brockwell and Davis we need to modify the slot xinit and drift[1] }else{ if(!is.null(mydots$xinit)){ aux.Carma<-setCarma(p=q, q=p-1, loc.par=loc.par, ar.par=ar.par, ma.par=ma.par, lin.par=ma.par, Carma.var=V.var, Latent.var=Latent.var, xinit=mydots$xinit, Cogarch=TRUE) # In order to have a representation of a Cogarch(p,q) model coherent with the # Chaadra Brockwell and Davis we need to modify the slot xinit and drift[1] } } newdrift<-c(0,as.character(aux.Carma@drift)) newdiffusion<-c(0,as.character(eval(aux.Carma@diffusion))) line1<-c(paste0("sqrt(",V.var,")"),as.character(matrix(0,nrow=(q+1),ncol=1))) dumm<-as.character(eval(aux.Carma@diffusion)) len.dumm<-length(dumm) line2<-character(length = (len.dumm+1)) line2[1]<-"0" for(i in 1:length(dumm)){ dumm.tmp<-nchar(x=dumm[i]) line2[i+1]<-substring(dumm[i],13,dumm.tmp-2) } state<-c(Cogarch.var,[email protected]) # We need now to modify the setModel in order to introduce a new component that represents # the discrete parts of the quadratic variation. # A possible solution is to write a new class that extends the yuima.model class and gives the possibility # to add the additional components. # The way to introduce the differentiation of the discrete part of the quadratic variation have to follow the same # structure used for the jump component. Lev.coeff<-matrix(c(line1,line2),ncol=2) resdummy1<-setModel(drift=newdrift, jump.coeff=Lev.coeff, #quadr.coeff=line2, measure=measure, measure.type=measure.type, #quadr.measure=measure, #quadr.measure.type=measure.type, state.variable=state, jump.variable=jump.variable, #quadr.variable=quadr.variable, time.variable=time.variable, xinit=c(startCogarch,as.character(aux.Carma@xinit))) resdummy2 <- new("cogarch.info", p=p, q=q, ar.par=ar.par, ma.par=ma.par, loc.par=loc.par, Cogarch.var=Cogarch.var, V.var=V.var, Latent.var=Latent.var, XinExpr=XinExpr, measure=measure, measure.type=measure.type ) # res.quadr.var<-new("quadratic.variation", # [email protected]@quadr.coeff, # [email protected]@measure, # [email protected]@measure.type, # [email protected]@parms.quadr, # parms.quadr.meas = [email protected]@parms.quadr.meas, # quadr.variable = [email protected]@quadr.variable, # Q.flag = [email protected]@Q.flag) res<-new("yuima.cogarch", info=resdummy2, drift= resdummy1@drift, diffusion= resdummy1@diffusion, hurst=resdummy1@hurst, [email protected], measure= resdummy1@measure, measure.type= [email protected], parameter= resdummy1@parameter, state.variable= [email protected], jump.variable= [email protected], time.variable= [email protected], noise.number= [email protected], equation.number= [email protected], dimension= resdummy1@dimension, solve.variable= [email protected], xinit= resdummy1@xinit, J.flag = [email protected] # quadr.var=res.quadr.var ) return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/setCogarch.R
setHawkes <- function(lower.var="0", upper.var = "t", var.dt = "s", process = "N", dimension = 1, intensity = "lambda", ExpKernParm1="c", ExpKernParm2 ="a", const = "nu", measure = NULL, measure.type = NULL){ if(dimension==1){ if(is.null(measure)){ my.rPPR1 <- function(n){ res <- t(t(rep(1,n))) return(res) } my.dPPR1 <-function(x){ res<-1 return(res) } # yuima.law for the underlying source of randomness Law.PPR1 <- setLaw(rng = my.rPPR1, density = my.dPPR1) measure <- list(df = Law.PPR1) measure.type <- "code" } }else{ if(is.null(measure)){ yuima.stop("Missing argument measure: see setHawkes documentation") } } PROCESS <- paste0(process,c(1:dimension)) leng <- length(PROCESS) mod1 <- setModel(drift = rep("0",leng), diffusion = matrix("0",leng,leng), jump.coeff = diag("1",leng,leng), measure = measure, measure.type = measure.type, solve.variable = PROCESS) INTENSITY <- as.list(paste0(intensity,c(1:dimension))) gFun <- paste0(const,c(1:dimension)) Ccoeff<-as.character(MatrCoeff(ExpKernParm1, dimension)) Acoeff<-as.character(MatrCoeff(ExpKernParm2, dimension)) Kernelpar<-c(Acoeff,Ccoeff) Kernel<- matrix(paste0(Ccoeff,"*exp(-",Acoeff,"*(","t-",var.dt,"))"),dimension, dimension) res <- aux.setPPR(yuima = mod1, counting.var=PROCESS, gFun, Kernel, var.dx = PROCESS, var.dt = var.dt, lambda.var = INTENSITY, lower.var=lower.var, upper.var = upper.var, nrow =dimension ,ncol=dimension, general = FALSE) return(res) } MatrCoeff<-function(lett, dimension){ c1<-paste0(lett,c(1:dimension)) cMatrix<-matrix(NA,dimension,dimension) for(i in c(1:dimension)){ cMatrix[i,]<-paste0(c1[i],c(1:dimension)) } return(cMatrix) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/setHawkes.R
setMethod("initialize", "yuima.multimodel", function(.Object, #model = new("yuima.model") drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = list(), #jump.coeff = expression(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "x", jump.variable = "z", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical() ){ .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- hurst [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag return(.Object) }) # We need a function that construct a Multivariate Model setMultiModel <- function(drift=NULL, diffusion=NULL, hurst=0.5, jump.coeff=NULL, intensity = NULL, df = NULL, # jump.dimens = NULL, # measure=list(), measure.type=character(), state.variable="x", jump.variable="z", time.variable="t", solve.variable, xinit=NULL){ ## we need a temp env for simplifications yuimaENV <- new.env() ##::measure and jump term ##################################### ##::initialize objects ######## MEASURE <- list() ##::end initialize objects ######## ##::make type function list #### CPlist <- c("dnorm", "dgamma", "dexp", "dconst") codelist <- c("rIG", "rNIG", "rgamma", "rbgamma", "rvgamma", "rstable","rpts","rnts") ## added "rpts" and "rnts" by YU (2016/10/4) ##::end make type function list #### jump.dimens <- dim(jump.coeff)[2] numbMeasure <- length(measure.type) if(numbMeasure>0){ if(numbMeasure!=1){ if(jump.dimens!=numbMeasure){ yuima.stop("dimension of jump is not coherent") } } # if(!length(measure.type)){ # if( length(jump.coeff) || length(measure) ){ # yuima.warn("measure type does not match with jump term.") # return(NULL) # } # jump.variable <- character() measure.par <- character() if(any(measure.type=="CP")){ tmp.measure <- list(df=list(func=vector(mode="list", length=1), expr=as.expression(rep("0",1))), intensity=as.expression(rep("0",length(intensity)))) }else{ tmp.measure <- list(df=list(func=vector(mode="list", length=length(measure.type)), expr=as.expression(rep("0",1)))) } # measure.par <- character() # }else{ # tmp.measure <- list(df=list(func=vector(mode="list", # length=length(measure.type)), # expr=as.expression(rep("0",length(measure.type)))), # intensity=as.expression(rep("0",sum(measure.type=="CP")))) # if( !length(jump.coeff) || !length(measure) ){ # yuima.warn("measure type isn't matched with jump term.") # return(NULL) # # }else # # if(length(jump.coeff)!=1){ # # yuima.warn("multi dimentional jump term is not supported yet.") # # # # return(NULL) # # } # # } if("CP" %in% measure.type){ condCP <- (measure.type%in%"CP") numbCP<-sum(condCP) h <- 0 for(i in c(1:length(measure.type))){ if(length(measure.type[condCP[i]])!=0){ if(!is.na(intensity[i-h])){ tmp.measure$intensity[(i-h)] <- parse(text = intensity[i-h]) } measure.par <- c(measure.par,all.vars(tmp.measure$intensity[(i-h)])) }else{ h<-h+1 } } } tmp.measure$df$expr <- parse(text=df[[1]]) measure.par <- c(measure.par, all.vars(tmp.measure$df$expr)) tmp <- regexpr("\\(", df[[1]])[1] measurefunc <- substring(df[[1]], 1, tmp-1) if(existsFunction(measurefunc)){ tmp.measure$df$func[[1]] <- eval(parse(text=measurefunc)) }else{ if(measurefunc!="yuima.law") yuima.stop("density function for jump must be specified") } # if("CP"%in%measure.type){ # condCP <- (measure.type%in%"CP") # numbCP<-sum(condCP) # h <- 0 # for(i in c(1:length(measure.type))){ # if(length(measure[condCP[i]])!=0){ # tmp.measure$df$expr[i] <- parse(text=measure$df[[i]]) # tmp.measure$intensity[(i-h)] <- parse(text = measure$intensity[i-h]) # # tmp <- regexpr("\\(", measure$df[[i]])[1] # measurefunc <- substring(measure$df[[i]], 1, tmp-1) # if(!is.na(match(measurefunc, codelist))){ # yuima.warn(paste("distribution function", measurefunc, "should be defined as type code.")) # return(NULL) # } # tmp.measure$df$func[[i]] <- eval(parse(text=measurefunc)) # } # h<-h+1 # } # # MEASURE$df$func<-tmp.measure$df$func MEASURE$df$expr<-tmp.measure$df$expr if("CP" %in% measure.type){ MEASURE$intensity<-tmp.measure$intensity } measure.par<-unique(measure.par) n.eqn3 <- dim(jump.coeff)[1] n.jump <- dim(jump.coeff)[2] } # # # ##measure.par$intensity <- unique(all.vars(MEASURE$intensity)) # ##::end check df name #################### # ##::end CP # # } # if("code"%in%measure.type){ ##::code # if(!is.list(measure)){ # measure <- list(df=measure) # } # # else{ # # if(length(measure[[1]])!=1){ # # yuima.warn("multi dimentional jump term is considered.") # # } # ##::naming measure list ############# # # if(is.null(names(measure)) || names(measure)=="df"){ # # names(measure) <- "df" # # }else{ # # yuima.warn("name of measure is incorrect.") # # return(NULL) # # } # ##::end naming measure list ############# # # } # # condcode <- (measure.type%in%"code") # numbcode<-sum(condcode) # h <- 0 # for(i in c(1:length(measure.type))){ # if(condcode[i]){ # tmp.measure$df$expr[i]<-parse(text=measure$df[[i]]) # # tmp <- regexpr("\\(", measure$df[[i]])[1] # measurefunc <- substring(measure$df[[i]], 1, tmp-1) # if(!is.na(match(measurefunc, CPlist))){ # yuima.warn(paste("\ndistribution function", measurefunc, "should be defined as type CP.")) # return(NULL) # }else if(is.na(match(measurefunc, codelist))){ # warning(paste("\ndistribution function", measurefunc, "is not officialy supported as type code.\n")) # } # MEASURE$df$func[[i]] <- eval(parse(text=measurefunc)) # MEASURE$df$expr[i] <- tmp.measure$df$expr[i] # # # # measure.par <- unique(all.vars(MEASURE$df$expr)) # # # # tmp.measure$func # } # } # # if( "CP" %in% measure.type){ # measure.par <- unique( c( all.vars(MEASURE$intensity), all.vars(MEASURE$df$expr) ) ) # }else if("code" %in% measure.type){ # measure.par <- unique( c( all.vars(MEASURE$intensity), all.vars(MEASURE$df$expr) ) ) # } # # # # ##::check df name #################### # # tmp <- regexpr("\\(", measure$df)[1] # # measurefunc <- substring(measure$df, 1, tmp-1) # # if(!is.na(match(measurefunc, CPlist))){ # # yuima.warn(paste("\ndistribution function", measurefunc, "should be defined as type CP.")) # # return(NULL) # # }else if(is.na(match(measurefunc, codelist))){ # # warning(paste("\ndistribution function", measurefunc, "is not officialy supported as type code.\n")) # # } # # ##MEASURE$df$func <- eval(parse(text=measurefunc)) # # MEASURE$df$expr <- parse(text=measure$df) # # # # measure.par <- unique(all.vars(MEASURE$df$expr)) # # ##::end check df name #################### # # ##::end code # }else if(measure.type=="density"){ ##::density # if(length(measure)!=1){ # yuima.warn(paste("length of measure must be one on type", measure.type, ".")) # return(NULL) # } # # if(!is.list(measure)){ # measure <- list(df=measure) # }else{ # if(length(measure[[1]])!=1){ # yuima.warn("multi dimentional jump term is not supported yet.") # return(NULL) # } # # ##::naming measure list ############# # if(is.null(names(measure))){ # names(measure) <- "df" # }else if(names(measure)!="density" && names(measure)!="df"){ # yuima.warn("name of measure is incorrect.") # return(NULL) # } # ##::end naming measure list ############# # } # # ##::check df name #################### # tmp <- regexpr("\\(", measure[[names(measure)]])[1] # measurefunc <- substring(measure[[names(measure)]], 1, tmp-1) # if(!is.na(match(measurefunc, CPlist))){ # yuima.warn(paste("distribution function", measurefunc, "should be defined as type CP.")) # return(NULL) # }else if(!is.na(match(measurefunc, codelist))){ # yuima.warn(paste("distribution function", measurefunc, "should be defined as type code.")) # return(NULL) # } # MEASURE[[names(measure)]]$func <- eval(parse(text=measurefunc)) # MEASURE[[names(measure)]]$expr <- parse(text=measure[[names(measure)]]) # # measure.par <- unique(all.vars(MEASURE[[names(measure)]]$expr)) # ##::end check df name #################### # ##::end density # }else{ ##::else # yuima.warn(paste("measure type", measure.type, "isn't supported.")) # return(NULL) # } # n.eqn3 <- dim(jump.coeff)[1] # n.jump <- length(measure.type) # } ##::end measure and jump term ##################################### ##:: check for errors and reform values if(any(time.variable %in% state.variable)){ yuima.warn("time and state(s) variable must be different.") return(NULL) } if(is.null(dim(drift))){ # this is a vector n.eqn1 <- length(drift) n.drf <- 1 }else{ # it is a matrix n.eqn1 <- dim(drift)[1] n.drf <- dim(drift)[2] } if(is.null(dim(diffusion))){ # this is a vector n.eqn2 <- length(diffusion) n.noise <- 1 }else{ # it is a matrix n.eqn2 <- dim(diffusion)[1] n.noise <- dim(diffusion)[2] } if(is.null(diffusion)){ diffusion <- rep("0", n.eqn1) n.eqn2 <- n.eqn1 n.noise <- 1 } ## TBC n.eqn3 <- n.eqn1 # if(!length(measure)){ # n.eqn3 <- n.eqn1 # } if(n.eqn1 != n.eqn2 || n.eqn1 != n.eqn3){ yuima.warn("Malformed model, number of equations in the drift and diffusion do not match.") return(NULL) } n.eqn <- n.eqn1 if(is.null(xinit)){ # xinit <- numeric(n.eqn) xinit <- character(n.eqn) }else if(length(xinit) != n.eqn){ if(length(xinit)==1){ xinit <- rep(xinit, n.eqn) }else{ yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } if(missing(solve.variable)){ yuima.warn("Solution variable (lhs) not specified. Trying to use state variables.") solve.variable <- state.variable } if(n.eqn != length(solve.variable)){ yuima.warn("Malformed model, number of solution variables (lhs) do no match number of equations (rhs).") return(NULL) } loc.drift <- matrix(drift, n.eqn, n.drf) loc.diffusion <- matrix(diffusion, n.eqn, n.noise) # Modification starting point 6/11 loc.xinit<-matrix(xinit,n.eqn,n.drf) ##:: allocate vectors DRIFT <- vector(n.eqn, mode="expression") DIFFUSION <- vector(n.eqn, mode="list") # Modification starting point 6/11 XINIT<-vector(n.eqn, mode = "expression") ##:: function to make expression from drift characters pre.proc <- function(x){ for(i in 1:length(x)){ if(length(parse(text=x[i]))==0){ x[i] <- "0" } } parse(text=paste(sprintf("(%s)", x), collapse="+")) } ##22/11:: function to simplify expression in drift, diffusion, jump and xinit characters yuima.Simplifyobj<-function(x){ dummy<-yuima.Simplify(x, yuima.env=yuimaENV) dummy1<-yuima.Simplify(dummy, yuima.env=yuimaENV) dummy2<-as.character(dummy1) res<-parse(text=paste0("(",dummy2,")",collapse=NULL)) return(res) } ##:: make expressions of drifts and diffusions and jump for(i in 1:n.eqn){ DRIFT[i] <- pre.proc(loc.drift[i,]) # 22/11 Simplify expressions DRIFT[i] <- yuima.Simplifyobj(DRIFT[i]) # Modification starting point 6/11 XINIT[i]<-pre.proc(loc.xinit[i, ]) XINIT[i]<- yuima.Simplifyobj(XINIT[i]) for(j in 1:n.noise){ expr <- parse(text=loc.diffusion[i,j]) if(length(expr)==0){ expr <- expression(0) # expr must have something } # DIFFUSION[[i]][j] <- expr #22/11 DIFFUSION[[i]][j] <- yuima.Simplifyobj(expr) } #22/11 #if (length(JUMP)>0){ # JUMP[i] <- parse(text=jump.coeff[i]) # JUMP[i] <- yuima.Simplifyobj(JUMP[i]) #} } #print(length(jump.coeff)) #if (length(jump.coeff)==0){ # JUMP <- list(parse(text=jump.coeff)) #}else{ # # JUMP <- vector(n.eqn, mode="expression") # JUMP <- vector(n.eqn, mode="list") #} if(length(jump.coeff)==0){ JUMP <- list() } else { if(length(jump.coeff)==1 & !is.matrix(jump.coeff)){ # is a scalar expr <- parse(text=jump.coeff) if(length(expr)==0){ expr <- expression(0) # expr must have something } JUMP <- list(yuima.Simplifyobj(expr)) } else { # must be matrix, n.col = dimension of Levy noise jump.coeff <- as.matrix(jump.coeff) c.j <- ncol(jump.coeff) r.j <- nrow(jump.coeff) #print(c.j) #print(r.j) #print(jump.coeff) JUMP <- vector(r.j, mode="list") for(i in 1:r.j){ for(j in 1:c.j){ #cat(sprintf("\ni=%d,j=%d\n",i,j)) expr <- parse(text=jump.coeff[i,j]) if(length(expr)==0){ expr <- expression(0) # expr must have something } JUMP[[i]][j] <- yuima.Simplifyobj(expr) } } } } #print(str(JUMP)) # ##:: get parameters in drift expression drift.par <- unique(all.vars(DRIFT)) # Modification starting point 6/11 xinit.par <- unique(all.vars(XINIT)) drift.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), drift.par))) if(length(drift.idx)>0){ drift.par <- drift.par[-drift.idx] } ##:: get parameters in diffusion expression diff.par <- unique(unlist(lapply(DIFFUSION, all.vars))) diff.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), diff.par))) if(length(diff.idx)>0){ diff.par <- diff.par[-diff.idx] } ##:: get parameters in jump expression J.flag <- FALSE # jump.par <- unique(all.vars(JUMP)) jump.par <- unlist(lapply(JUMP,all.vars)) if(is.null(jump.par)) jump.par <- character() if(length(na.omit(match(jump.par, jump.variable)))){ J.flag <- TRUE } jump.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), jump.par))) if(length(jump.idx)>0){ jump.par <- jump.par[-jump.idx] } ##:: get parameters in measure expression measure.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), measure.par))) if(length(measure.idx)>0){ measure.par <- measure.par[-measure.idx] } ##:: order parameters for 'yuima.pars' ##id1 <- which(diff.par %in% drift.par) ##id2 <- which(drift.par %in% diff.par) ##common <- unique(c(diff.par[id1], drift.par[id2])) common <- c(drift.par, diff.par) common <- common[duplicated(common)] common1<-common # modification 06/11 common1 contains only # parameters that appear in both drift and diffusion terms. # Modification 06/11 common contains only parameters that appear # in drift, diff, Jump and xinit if (length(xinit)) { common <- c(common, xinit.par) common <- common[duplicated(common)] common <- c(common, xinit.par) common <- common[duplicated(common)] } if(length(measure.type)){ common <- c(common, jump.par) common <- common[duplicated(common)] common <- c(common, measure.par) common <- common[duplicated(common)] } # all.par <- unique(c(drift.par, diff.par, jump.par, measure.par)) all.par <- unique(c(drift.par, diff.par, jump.par, measure.par, xinit.par)) ##:: instanciate class tmppar <- new("model.parameter", all= all.par, # common= common, common= common1, diffusion= diff.par, drift= drift.par, jump= jump.par, measure= measure.par, xinit=xinit.par) tmp <- new("yuima.multimodel", drift= DRIFT, diffusion= DIFFUSION, hurst=as.numeric(hurst), jump.coeff=JUMP, measure= MEASURE, measure.type= measure.type, parameter= tmppar, state.variable= state.variable, jump.variable= jump.variable, time.variable= time.variable, noise.number= n.noise, equation.number= n.eqn, dimension= c( length(tmppar@all), length(tmppar@common), length(tmppar@diffusion), length(tmppar@drift), length(tmppar@jump), length(tmppar@measure) ), solve.variable= solve.variable, xinit= XINIT, J.flag <- J.flag) return(tmp) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/setMultiModel.R
setMethod("initialize", "yuima.poisson", function(.Object, drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = expression(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "x", jump.variable = "z", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical()){ .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- 0.5 [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag return(.Object) }) setPoisson <- function(intensity=1, df=NULL, scale=1, dimension=1, ...){ poisson.model <- setModel(drift="0", diffusion="0", jump.coeff=as.expression(scale), measure=list(intensity=intensity, df=df), measure.type="CP",...) CPoisson <- new("yuima.poisson", drift=poisson.model@drift, diffusion = poisson.model@diffusion, hurst=poisson.model@hurst, [email protected], measure=poisson.model@measure, [email protected], parameter=poisson.model@parameter, [email protected], [email protected], [email protected], noise.number = [email protected], equation.number = dimension, dimension = dimension, [email protected], xinit=poisson.model@xinit, J.flag = [email protected] ) return(CPoisson) } dconst <- function(x,k=1) k*(x==k) rconst <- function(n,k=1) rep(k,n)
/scratch/gouwar.j/cran-all/cranData/yuima/R/setPoisson.R
setPPR <- function(yuima, counting.var="N", gFun, Kernel, var.dx= "s", var.dt = "s", lambda.var = "lambda", lower.var="0", upper.var = "t", nrow =1 ,ncol=1){ general <- TRUE ret <- aux.setPPR(yuima, counting.var, gFun, Kernel, var.dx, var.dt, lambda.var, lower.var="0", upper.var = "t", nrow =1 ,ncol=1,general =general) return(ret) } aux.setPPR <-function(yuima, counting.var="N", gFun, Kernel, var.dx, var.dt = "s", lambda.var = "lambda", lower.var="0", upper.var = "t", nrow =1 ,ncol=1, general){ g <- setMap(func = gFun, yuima = yuima, nrow = nrow, ncol = ncol) yuimadum <- yuima [email protected] <- var.dt HawkesType <- FALSE if(all(counting.var %in% var.dx)){ HawkesType <- TRUE } if(!HawkesType){ Integral <- setIntegral(yuima=yuimadum, integrand = Kernel, var.dx = var.dx, lower.var = lower.var, upper.var = upper.var, out.var = "", nrow = nrow, ncol = ncol) }else{ Integral <- setIntegral(yuima=yuimadum, integrand = Kernel, var.dx = var.dx, lower.var = lower.var, upper.var = upper.var, out.var = "", nrow = nrow, ncol = ncol) } if(g@Output@dimension[1]!=Integral@Integral@Integrand@dimIntegrand[1]){ yuima.stop("dimension gFun and kernel mismatch") } allparam <- unique(c(yuima@parameter@all, g@Output@param@allparamMap, Integral@[email protected]@Integrandparam)) common <- unique(c(g@Output@param@common, Integral@[email protected]@common)) paramHawkes <- list(allparam = allparam, common = common, gFun = g@Output@param@allparamMap, Kern = Integral@[email protected]@Integrandparam) # IntPPR<- yuima:::setIntegral(yuima=yuimadum, # integrand y= Kernel, var.dx = "N", # lower.var = lower.var, upper.var = upper.var, # out.var = "", nrow = nrow, ncol = ncol) # return(list(Count.Proc = counting.var, # gFun = list(param=g@Output@param, output=g@Output), # Kernel = Integral, paramHawkes = paramHawkes, # model = yuima, SelfEx = HawkesType)) yuima1 <- setYuima(model =yuima) type <- [email protected] if(all(type == "code")){ if(!(is(yuima@measure$df,"yuima.law"))) measure <- list(df = as.character(yuima@measure$df$expr)) }else{ measure <- yuima@measure } if(all(type == "CP")){ if(!(is(yuima@measure$df,"yuima.law"))) measure <- list(intensity = as.character(yuima@measure$intensity), df= as.character(yuima@measure$df$expr)) }else{ measure <- yuima@measure } IntensWithCount<-FALSE if(!is.list(g@Output@formula)){ if(any(counting.var%in%all.vars(g@Output@formula))) IntensWithCount<-TRUE }else{ ddd<- length(g@Output@formula) for(i in c(1:ddd)){ if(any(counting.var%in%all.vars(g@Output@formula[[i]]))) IntensWithCount<-TRUE } } if(any(counting.var%in%Integral@[email protected]@var.dx)) IntensWithCount<-TRUE if(!is.list(Integral@Integral@Integrand@IntegrandList)){ if(any(counting.var%in%all.vars(Integral@Integral@Integrand@IntegrandList))) IntensWithCount<-TRUE }else{ ddd<- length(Integral@Integral@Integrand@IntegrandList) for(i in c(1:ddd)){ if(any(counting.var%in%all.vars(Integral@Integral@Integrand@IntegrandList[[i]]))) IntensWithCount<-TRUE } } RegressWithCount <- FALSE if(general){ covariates<-character() if(sum(!([email protected]))!=0){ condCovariate<-!([email protected]) covariates<[email protected][condCovariate] if(length(covariates)>0){ covariate.drift <- yuima@drift[condCovariate] covariate.diff <- yuima@diffusion[condCovariate] covariate.jump <- [email protected][condCovariate] } if(any(counting.var %in% all.vars(covariate.drift))){ RegressWithCount <-TRUE } ddd.dif <-length(covariate.diff) if(length(covariate.diff)>0){ for(i in c(1:ddd.dif)){ if(any(counting.var %in% all.vars(covariate.diff[[i]]))){ RegressWithCount <-TRUE } } } ddd.jump <-length(covariate.jump) if(length(covariate.jump)>0){ for(i in c(1:ddd.jump)){ if(any(counting.var %in% all.vars(covariate.jump[[i]]))){ RegressWithCount <-TRUE } } } } PPR <- new("info.PPR", allparam = paramHawkes$allparam, allparamPPR = unique(c(paramHawkes$gFun,paramHawkes$Kern)), common = paramHawkes$common, counting.var = counting.var, var.dx = var.dx, upper.var = upper.var, lower.var = lower.var, covariates = covariates, var.dt = var.dt, additional.info = lambda.var, Info.measure = list(type=type,measure=measure), RegressWithCount=RegressWithCount, IntensWithCount=IntensWithCount) ret <- new("yuima.PPR", PPR = PPR, gFun = g@Output, Kernel = Integral@Integral, yuima = yuima1) }else{ PPR <- new("info.PPR", allparam = paramHawkes$allparam, allparamPPR = unique(c(paramHawkes$gFun,paramHawkes$Kern)), common = paramHawkes$common, counting.var = counting.var, var.dx = var.dx, upper.var = upper.var, lower.var = lower.var, covariates = character(), var.dt = var.dt, additional.info = "Exponential Hawkes", Info.measure = list(type=type,measure=measure)) ret <- new("yuima.Hawkes", PPR = PPR, gFun = g@Output, Kernel = Integral@Integral, yuima = yuima1) } return(ret) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/setPpr.R
euler<-function(xinit,yuima,dW,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] Terminal <- yuima@sampling@Terminal[1] Initial <- yuima@sampling@Initial[1] n <- yuima@sampling@n[1] dL <- env$dL # dX <- xinit # 06/11 xinit is an expression: the structure is equal to that of V0 if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } # 06/11 we need a initial variable for X_0 dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } ##:: set time step # delta <- Terminal/n delta <- yuima@sampling@delta ## moving the following lines enclosed if(0) after Levy (YK, Apr 12, 2017) if(0){ ##:: check if DRIFT and/or DIFFUSION has values has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) #print(is.Poisson(sdeModel)) ##:: function to calculate coefficients of dW(including drift term) ##:: common used in Wiener and CP p.b <- function(t, X=numeric(d.size)){ ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) ##:: solve diffusion term if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { ##:: no drift term (faster) tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ # we do not need to evaluate diffusion for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } # for j } # foh i } # !is.Poisson } # else return(tmp) } X_mat <- matrix(0, d.size, n+1) X_mat[,1] <- dX if(has.drift){ ##:: consider drift term to be one of the diffusion term(dW=1) dW <- rbind( rep(1, n)*delta , dW) } }## if(0) finish if(!length([email protected])){ ##:: Wiener Proc ##:: using Euler-Maruyama method if(0){ # old version (Jan 25, 2017) if(var.in.diff & (!is.Poisson(sdeModel))){ ##:: diffusions have state variables and it is not Poisson ##:: calcurate difference eq. for( i in 1:n){ # dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] #dX <- dX + p.b(t=yuima@sampling@Initial+i*delta, X=dX) %*% dW[, i] # LM dX <- dX + p.b(t=yuima@sampling@Initial+(i-1)*delta, X=dX) %*% dW[, i] # YK X_mat[,i+1] <- dX } }else{ ##:: diffusions have no state variables (not use p.b(). faster) sde.tics <- seq(0, Terminal, length=(n+1)) sde.tics <- sde.tics[2:length(sde.tics)] X_mat[, 1] <- dX ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], dX[i]) } assign(modeltime, sde.tics) t.size <- length(sde.tics) ##:: solve diffusion term if(has.drift){ pbdata <- matrix(0, d.size*(r.size+1), t.size) for(i in 1:d.size){ pbdata[(i-1)*(r.size+1)+1, ] <- eval(V0[i], env) for(j in 1:r.size){ pbdata[(i-1)*(r.size+1)+j+1, ] <- eval(V[[i]][j], env) } } dim(pbdata)<-(c(r.size+1, d.size*t.size)) }else{ pbdata <- matrix(0, d.size*r.size, t.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ pbdata[(i-1)*r.size+j, ] <- eval(V[[i]][j], env) } # for j } # for i } # !is.Poisson dim(pbdata)<-(c(r.size, d.size*t.size)) } # else pbdata <- t(pbdata) ##:: calcurate difference eq. for( i in 1:n){ if(!is.Poisson(sdeModel)) dX <- dX + pbdata[((i-1)*d.size+1):(i*d.size), ] %*% dW[, i] X_mat[, i+1] <- dX } } } #if(0){ # currently ignored due to a bug (YK, Feb 23, 2017) # new version (Jan 25, 2017) b <- parse(text=paste("c(",paste(as.character(V0),collapse=","),")")) vecV <- parse(text=paste("c(",paste(as.character(unlist(V)),collapse=","),")")) X_mat <- .Call("euler", dX, Initial, as.integer(r.size), rep(1, n) * delta, dW, modeltime, modelstate, quote(eval(b, env)), quote(eval(vecV, env)), env, new.env(), PACKAGE = "yuima") # PACKAGE is added (YK, Dec 4, 2018) #} #tsX <- ts(data=t(X_mat), deltat=delta , start=0) tsX <- ts(data=t(X_mat), deltat=delta , start = yuima@sampling@Initial) #LM }else{ ##:: Levy ### add (YK, Apr 12, 2017) ##:: check if DRIFT and/or DIFFUSION has values has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) #print(is.Poisson(sdeModel)) ##:: function to calculate coefficients of dW(including drift term) ##:: common used in Wiener and CP p.b <- function(t, X=numeric(d.size)){ ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) ##:: solve diffusion term if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { ##:: no drift term (faster) tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ # we do not need to evaluate diffusion for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } # for j } # foh i } # !is.Poisson } # else return(tmp) } X_mat <- matrix(0, d.size, n+1) X_mat[,1] <- dX if(has.drift){ ##:: consider drift term to be one of the diffusion term(dW=1) dW <- rbind( rep(1, n)*delta , dW) } JP <- [email protected] mu.size <- length(JP) # cat("\n Levy\n") ##:: function to solve c(x,z) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) # tmp <- numeric(d.size) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) # cat("\n inside\n") #print(dim(tmp)) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } # tmp[i] <- eval(JP[i], env) } return(tmp) } # print(ls(env)) ### WHY I AM DOING THIS? # tmp <- matrix(0, d.size, r.size) # #for(i in 1:d.size){ # for(j in 1:r.size){ # cat("\n here\n") # tmp[i,j] <- eval(V[[i]][j],env) # } # for j # } ### if([email protected] == "CP" ){ ##:: Compound-Poisson type ##:: delete 2010/09/13 for simulate func bug fix by s.h ## eta0 <- eval(sdeModel@measure$intensity) ##:: add 2010/09/13 for simulate func bug fix by s.h eta0 <- eval(sdeModel@measure$intensity, env) ## intensity param ##:: get lambda from nu() tmp.expr <- function(my.x){ assign([email protected],my.x) return(eval(sdeModel@measure$df$expr)) } #lambda <- integrate(sdeModel@measure$df$func, 0, Inf)$value * eta0 #lambda <- integrate(tmp.expr, 0, Inf)$value * eta0 ##bug:2013/10/28 dummyList<-as.list(env) # print(str(dummyList)) #print(str(idx.dummy)) lgth.meas<-length(yuima@model@parameter@measure) #if(lgth.meas>1){ if(lgth.meas>0){ # YK Aug 11, 2021 #for(i in c(2:lgth.meas)){ for(i in c(1:lgth.meas)){ # YK Aug 11, 2021 idx.dummy<-yuima@model@parameter@measure[i] #print(i) #print(yuima@model@parameter@measure[i]) assign(idx.dummy,as.numeric(dummyList[idx.dummy])) } } lambda <- integrate(tmp.expr, -Inf, Inf)$value * eta0 ##:: lambda = nu() (p6) # N_sharp <- rpois(1,Terminal*eta0) ##:: Po(Ne) N_sharp <- rpois(1,(Terminal-Initial)*eta0) ##:: Po(Ne) if(N_sharp == 0){ JAMP <- FALSE }else{ JAMP <- TRUE Uj <- sort( runif(N_sharp, Initial, Terminal) ) # Uj <- sort( runif(N_sharp, 0, Terminal) ) ij <- NULL for(i in 1:length(Uj)){ Min <- min(which(Initial+ c(1:n)*delta > Uj[i])) # Min <- min(which(c(1:n)*delta > Uj[i])) ij <- c(ij, Min) } } ##:: make expression to create iid rand J if(grep("^[dexp|dnorm|dgamma|dconst]", sdeModel@measure$df$expr)){ ##:: e.g. dnorm(z,1,1) -> rnorm(mu.size*N_sharp,1,1) F <- suppressWarnings(parse(text=gsub("^d(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", sdeModel@measure$df$expr, perl=TRUE))) }else{ stop("Sorry. CP only supports dconst, dexp, dnorm and dgamma yet.") } ##:: delete 2010/09/13 for simulate func bug fix by s.h ## randJ <- eval(F) ## this expression is evaluated locally not in the yuimaEnv ##:: add 2010/09/13 for simulate func bug fix by s.h F.env <- new.env(parent=env) assign("mu.size", mu.size, envir=F.env) assign("N_sharp", N_sharp, envir=F.env) randJ <- eval(F, F.env) ## this expression is evaluated in the F.env j <- 1 for(i in 1:n){ if(JAMP==FALSE || sum(i==ij)==0){ Pi <- 0 }else{ if(is.null(dL)){ J <- eta0*randJ[j]/lambda j <- j+1 ##cat(paste(J,"\n")) ##Pi <- zeta(dX, J) assign([email protected], J, env) if([email protected]){ J <- 1 } # Pi <- p.b.j(t=i*delta,X=dX) * J #LM #Pi <- p.b.j(t=yuima@sampling@Initial+i*delta,X=dX) * J Pi <- p.b.j(t=yuima@sampling@Initial+(i-1)*delta,X=dX) * J # YK }else{# we add this part since we allow the user to specify the increment of CP LM 05/02/2015 # Pi <- p.b.j(t=i*delta,X=dX) %*% dL[, i] #LM #Pi <- p.b.j(t=yuima@sampling@Initial+i*delta,X=dX) %*% dL[, i] Pi <- p.b.j(t=yuima@sampling@Initial+(i - 1)*delta,X=dX) %*% dL[, i] # YK } ##Pi <- p.b.j(t=i*delta, X=dX) } # dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] + Pi # LM #dX <- dX + p.b(t=yuima@sampling@Initial + i*delta, X=dX) %*% dW[, i] + Pi dX <- dX + p.b(t=yuima@sampling@Initial + (i - 1)*delta, X=dX) %*% dW[, i] + Pi # YK X_mat[, i+1] <- dX } # tsX <- ts(data=t(X_mat), deltat=delta, start=0) #LM tsX <- ts(data=t(X_mat), deltat=delta, start=yuima@sampling@Initial) ##::end CP }else if([email protected]=="code"){ ##:: code type ##:: Jump terms code <- suppressWarnings(sub("^(.+?)\\(.+", "\\1", sdeModel@measure$df$expr, perl=TRUE)) args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", sdeModel@measure$df$expr, perl=TRUE)), ",")) #print(args) dZ <- switch(code, rNIG=paste("rNIG(n, ", args[2], ", ", args[3], ", ", args[4], "*delta, ", args[5], "*delta, ", args[6],")"), rIG=paste("rIG(n,", args[2], "*delta, ", args[3], ")"), rgamma=paste("rgamma(n, ", args[2], "*delta, ", args[3], ")"), rbgamma=paste("rbgamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], "*delta, ", args[5], ")"), ## rngamma=paste("rngamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], ", ", args[5], "*delta, ", args[6], ")"), rvgamma=paste("rvgamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], ", ", args[5], "*delta,", args[6],")"), ## rstable=paste("rstable(n, ", args[2], ", ", args[3], ", ", args[4], ", ", args[5], ", ", args[6], ")") rstable=paste("rstable(n, ", args[2], ", ", args[3], ", ", args[4], "*delta^(1/",args[2],"), ", args[5], "*delta)"), rpts=paste("rpts(n, ", args[2], ", ", args[3], "*delta,", args[4],")"), rnts=paste("rnts(n, ", args[2], ", ", args[3], "*delta,", args[4], ", ", args[5], ", ", args[6],"*delta,", args[7], ")") ) ## added "rpts" and "rnts" by YU (2016/10/4) dummyList<-as.list(env) #print(str(dummyList)) lgth.meas<-length(yuima@model@parameter@measure) #print(lgth.meas) if(lgth.meas!=0){ for(i in c(1:lgth.meas)){ #print(i) #print(yuima@model@parameter@measure[i]) idx.dummy<-yuima@model@parameter@measure[i] #print(str(idx.dummy)) assign(idx.dummy,dummyList[[idx.dummy]]) #print(str(idx.dummy)) #print(str(dummyList[[idx.dummy]])) #print(get(idx.dummy)) } } if(is.null(dZ)){ ##:: "otherwise" cat(paste("Code \"", code, "\" not supported yet.\n", sep="")) return(NULL) } if(!is.null(dL)) dZ <- dL else dZ <- eval(parse(text=dZ)) ##:: calcurate difference eq. #print(str(dZ)) if(is.null(dim(dZ))) dZ <- matrix(dZ,nrow=1) # print(dim(dZ)) # print(str([email protected])) for(i in 1:n){ assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } # cat("\np.b.j call\n") # tmp.j <- p.b.j(t=i*delta, X=dX) #LM #tmp.j <- p.b.j(t=yuima@sampling@Initial+i*delta, X=dX) tmp.j <- p.b.j(t=yuima@sampling@Initial+(i - 1)*delta, X=dX) # YK #print(str(tmp.j)) #cat("\np.b.j cback and dZ\n") # print(str(dZ[,i])) # print(sum(dim(tmp.j))) if(sum(dim(tmp.j))==2) tmp.j <- as.numeric(tmp.j) #print(str(tmp.j)) #print(str(p.b(t = i * delta, X = dX) %*% dW[, i])) # dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] #LM #dX <- dX + p.b(t=yuima@sampling@Initial+i*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] dX <- dX + p.b(t=yuima@sampling@Initial+(i - 1)*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] # YK X_mat[, i+1] <- dX } # tsX <- ts(data=t(X_mat), deltat=delta, start=0) #LM tsX <- ts(data=t(X_mat), deltat=delta, start=yuima@sampling@Initial) ##::end code }else{ cat(paste("Type \"", [email protected], "\" not supported yet.\n", sep="")) return(NULL) } }##::end levy yuimaData <- setData(original.data=tsX) return(yuimaData) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/sim.euler.R
space.discretized<-function(xinit,yuima, env){ ##:: initialize state variable sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] Terminal <- yuima@sampling@Terminal[1] n <- yuima@sampling@n[1] # dX <- xinit if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } # 20/11 we need a initial variable for X_0 dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } ##:: set time step delta <- Terminal/n ##:: using Space-discretized Euler-Maruyama method ##:: function for approximation of function G gfunc <- function(x){ c0 <- 10 c1 <- 10 ret <- rep(0, length(x)) idx <- which(x < 1/c0) ret[idx] <- 1 idx <- which(1/c0 <= x) ret[idx] <- 1-pnorm(x[idx]) for(i in 1:length(idx)){ n <- 1:floor(c1/x[idx[i]]) ret[idx[i]] <- 4 * (ret[idx[i]] - sum( pnorm((4*n+1)*x[idx[i]]) - pnorm((4*n-1)*x[idx[i]]) )) } idx <- which(1 < ret) ret[idx] <- 1 return(ret) } dxx <- 0.0001 xx <- seq(0, 1.7, dxx) ##:: approximate function G(gg) gg <- gfunc(xx) appfunc <- suppressWarnings(approxfun(gg, xx)) ##:: calculate inverse of G unif.a <- runif(n*2) inv.a <- pmin(qnorm(1 - unif.a/4), appfunc(unif.a), na.rm=TRUE) ##:: make random time steps ep <- sqrt(delta) dTW <- (ep/inv.a)^2 time_idx <- cumsum(dTW) ##:: time index should be attached div_sd <- min(which(time_idx > Terminal)) ##:: cut by time=1 time_idx <- time_idx[1:div_sd] ##:: add diffusion term dTW <- rbind(dTW[1:div_sd], t(matrix( (rbinom(div_sd*r.size, 1, 0.5)*2-1) * ep, nrow=div_sd, ncol=r.size) ) ) X_mat <- matrix(0, d.size, div_sd+1) X_mat[,1] <- dX ##:: function to calculate coefficients of dTW p.b <- function(t, X=numeric(d.size)){ ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i],env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j], env) } } return(tmp) } ##:: calcurate difference equation for(i in 1:div_sd){ dX <- dX + p.b(t=time_idx[i], X=dX) %*% dTW[,i] X_mat[,i+1] <- dX } ##tsX <- ts(data=t(X_mat), deltat=delta , start=0) ##:: output zoo data zooX <- zoo(x=t(X_mat), order.by=c(0, time_idx)) yuimaData <- setData(original.data=zooX) return(yuimaData) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/sim.euler.space.discretized.R
# sinc function sinc <- function(x){ out <- rep(1, length(x)) idx <- abs(x) > 1e-7 out[idx] <- sin(x[idx])/x[idx] return(out) } # Littlewood-Paley wavelet function psi.lp <- function(x) 2 * sinc(2 * pi * x) - sinc(pi * x) # coefficient matrices for circulant embedding simBmllag.coef <- function(n, J, rho, theta, delta = 1/2^(J+1)){ if(length(rho) < J + 1) rho <- append(rho, double(J + 1 - length(rho))) if(length(theta) < J + 1) theta <- append(theta, double(J + 1 - length(theta))) m <- 3^ceiling(log(2 * n - 2, base = 3)) M <- as.integer((m - 1)/2) tl <- ((-M):M) * delta c12 <- double(m) for(j in 1:(J + 1)){ c12 <- c12 + 2^(J - j + 1) * delta^2 * rho[j] * psi.lp(2^(J - j + 1) * (tl - theta[j])) } c12 <- c(c12[-(1:M)], c12[1:M]) A12 <- fft(c12) s <- sqrt(delta^2 - Mod(A12)^2) t <- sqrt(2 * (delta + s)) a <- array(0, dim = c(m, 2, 2)) a[ ,1,1] <- (delta + s)/t a[ ,2,2] <- a[ ,1,1] a[ ,1,2] <- A12/t a[ ,2,1] <- Conj(a[ ,1,2]) return(a) } # main function simBmllag <- function(n, J, rho, theta, delta = 1/2^(J+1), imaginary = FALSE){ a <- simBmllag.coef(n, J, rho, theta, delta) m <- dim(a)[1] z1 <- rnorm(m) + 1i * rnorm(m) z2 <- rnorm(m) + 1i * rnorm(m) y1 <- a[ ,1,1] * z1 + a[ ,1,2] * z2 y2 <- a[ ,2,1] * z1 + a[ ,2,2] * z2 dW <- mvfft(cbind(y1, y2))[1:n, ]/sqrt(m) if(imaginary == TRUE){ return(dW) }else{ return(Re(dW)) } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simBmllag.r
## Simulate Cox-Ingersoll-Ross process with parameters alpha, beta and gamma at times specified via time.points simCIR <- function (time.points, n, h, alpha, beta, gamma, equi.dist=FALSE ) { # generate an equidistant time vector of length n+1 and distant h between observations if (equi.dist==TRUE) {time.points <- 0:n*h } # must start in t=0, otherwise t_vec is adjusted if ( time.points[1] != 0 ) { time.points <- c(0, time.points) } # define auxiliary variables, following notation of Malham and Wiese nu <- 4 * alpha / gamma # degrees of freedom eta_vec <- 4 * beta * exp(-beta * diff(time.points) ) / # auxiliary vector for the computation of the (gamma * (1 - exp(-beta * diff(time.points) )) ) # non-centrality parameter in each step # sample X_0 from stationary distribution X <- rgamma(1, scale = gamma / (2 * beta), shape = 2 * alpha / gamma) # compute X_t iteratively, using Prop. 1 from Malham and Wiese (2012) for ( i in seq_along(eta_vec) ) { lambda <- tail(X, 1) * eta_vec[i] # non-centrality parameter of the conditional distribution X <- c(X, rchisq(1, df = nu, ncp = lambda) * exp(-beta * diff(time.points)[i]) / eta_vec[i]) # calculate # next step of the CIR } # return data return(rbind(t = time.points, X = X)) # first row: time points, second row: CIR at time point }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simCIR.R
simCP<-function(xinit,yuima,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] Terminal <- yuima@sampling@Terminal[1] Initial <- yuima@sampling@Initial[1] dimension <- yuima@model@dimension dummy.val <- numeric(dimension) if(length(xinit) != dimension) xinit <- rep(xinit, dimension)[1:dimension] if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],envir=env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, envir=env) if(length(dummy.val)==1){ dummy.val<-rep(dummy.val,dimension) } for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,envir=env) } } else { for(i in 1:dimension){ dummy.val[i] <- eval(xinit[i], envir=env) } } ### Simulation of CP using Lewis' method ##:: Levy JP <- eval([email protected][[1]], envir=env) mu.size <- length(JP) # print(str(JP)) #assign(sdeModel@measure$intensity, env) ## intensity param .CPintensity <- function(.t) { assign(modeltime, .t, envir=env) eval(sdeModel@measure$intensity, envir=env) } dummyList<-as.list(env) lgth.meas<-length(yuima@model@parameter@measure) if(lgth.meas>1){ for(i in c(2:lgth.meas)){ idx.dummy<-yuima@model@parameter@measure[i] assign(idx.dummy,as.numeric(dummyList[idx.dummy])) } } # we use Lewis' acceptance/rejection method #if(grep("^[dexp|dnorm|dgamma|dconst]", sdeModel@measure$df$expr)){ ##:: e.g. dnorm(z,1,1) -> rnorm(mu.size*N_sharp,1,1) F <- suppressWarnings(parse(text=gsub("^d(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", sdeModel@measure$df$expr, perl=TRUE))) #} else{ #stop("Sorry. CP only supports dconst, dexp, dnorm and dgamma yet.") #} ell <- optimize(f=.CPintensity, interval=c(Initial, Terminal), maximum = TRUE)$objective ellMax <- ell * 1.01 time <- Initial E <- Initial # heuristic code to avoid loops nLAMBDA <- ceiling(ellMax*(Terminal-Initial)*1.2) ru1 <- runif(nLAMBDA) ru2 <- runif(nLAMBDA)*ellMax tLAMBDA <- Initial+cumsum( -log(ru1)/ellMax ) idxLAMBDA <- which(tLAMBDA<=Terminal) testLAMBDA <- ru2[idxLAMBDA]<.CPintensity(tLAMBDA[idxLAMBDA]) E <- c(Initial,tLAMBDA[testLAMBDA]) # while(time < Terminal) { # ellMax <- ell(time)*1.01 # time <- time - 1/ellMax * log(runif(1)) # if(runif(1) < .CPintensity(time)/ellMax) # E <- c(E, time) #} N_sharp <- length(E)-1 F.env <- new.env(parent=env) assign("mu.size", mu.size, envir=F.env) assign("N_sharp", N_sharp, envir=F.env) randJ <- eval(F, envir=F.env) ## this expression is evaluated in the F.env randJ <- JP[1]*randJ randJ <- as.matrix(randJ, ncol=yuima@dimension) randJ <- rbind(dummy.val, randJ) CP <- apply(randJ,2,cumsum) tsX <- zoo(x=CP, order.by=E) yuimaData <- setYuima(data=setData(tsX)) yuimaData <- subsampling(yuimaData, sampling=yuima@sampling) return(yuimaData@data) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simCP.R
# funcF # function to calculate F in (13.2) funcF <- function(yuima,X,e,expand.var="e"){ ##:: fix bug 07/23 assign(expand.var, e) division <- yuima@sampling@n[1] #number of observed time F <- getF(yuima@functional) d.size <- yuima@[email protected] k.size <- length(F) modelstate <- yuima@[email protected] XT <- X[division+1,] #X observed last. size:vector[d.size] resF <- numeric(k.size) #values of F. size:vector[k.size] for(d in 1:d.size){ assign(modelstate[d],XT[d]) #input XT in state("x1","x2") to use eval function to F } for(k in 1:k.size){ resF[k] <- eval(F[k]) #calculate F with XT } return(resF) } # funcf # function to calculate fa in (13.2) funcf <- function(yuima,X,e, expand.var){ ##:: fix bug 07/23 assign(expand.var, e) ## division <- yuima@sampling@n #number of observed time division <- yuima@sampling@n[1] F <- getF(yuima@functional) f <- getf(yuima@functional) r.size <- yuima@[email protected] d.size <- yuima@[email protected] k.size <- length(F) modelstate <- yuima@[email protected] resf <- array(0,dim=c(k.size,division,(r.size+1))) #value of f0,f1,~,fr. size:array[k.size,division,r.size+1] for(r in 1:(r.size+1)){ for(t in 1:division){ Xt <- X[t,] #Xt is data X observed on time t. size:vector[d.size] for(d in 1:d.size){ assign(modelstate[d],Xt[d]) #input Xt in state to use eval function to f } for(k in 1:k.size){ resf[k,t,r] <- eval(f[[r]][k]) #calculate k th expression of fr. } } } return(resf) } # funcFe. # function to calculate Fe in (13.2). # core function of 'simFunctional' funcFe. <- function(yuima,X,e,expand.var="e"){ ##:: fix bug 07/23 assign(expand.var, e) ## expand.var F <- getF(yuima@functional) r.size <- yuima@[email protected] d.size <- yuima@[email protected] k.size <- length(F) modelstate <- yuima@[email protected] ## division <- yuima@sampling@n division <- yuima@sampling@n[1] ## 2010/11/13 modified. Currently, division must be the same for each path Terminal <- yuima@sampling@Terminal delta <- Terminal/division #length between observed times dw <- matrix(0,division,r.size+1) #Wr(t) size:matrix[division,r.size+1] dw[,1] <- rep(delta,length=division) #W0(t)=t for(r in 2:(r.size+1)){ tmp <- rnorm(division,0,sqrt(delta)) #calculate Wr(t) tmp <- c(0,tmp) ## dw[,r] <- tmp[-1]-tmp[-(division+1)] #calculate dWr(t) dw[,r] <- diff(tmp) #calculate dWr(t) } resF <- funcF(yuima,X,e,expand.var=expand.var) #calculate F with X,e. size:vector[k.size] resf <- funcf(yuima,X,e,expand.var=expand.var) #calculate f with X,e. size:array[k.size,division,r.size+1] ## 2010/11/13 Fe <- numeric(k.size) for(k in 1:k.size){ Fe[k] <- sum(resf[k,1:division,]*dw)+resF[k] #calculate Fe using resF and resf as (13.2). } return(Fe) } # Get.X.t0 # function to calculate X(t=t0) using runge kutta method Get.X.t0 <- function(yuima, expand.var="e"){ ##:: fix bug 07/23 assign(expand.var,0) ## epsilon=0 r.size <- yuima@[email protected] d.size <- yuima@[email protected] k.size <- length(getF(yuima@functional)) modelstate <- yuima@[email protected] V0 <- yuima@model@drift V <- yuima@model@diffusion Terminal <- yuima@sampling@Terminal[1] ## division <- yuima@sampling@n division <- yuima@sampling@n[1] ## 2010/11/13 ##:: fix bug 07/23 #pars <- #yuima@model@parameter@all[1] #epsilon xinit <- getxinit(yuima@functional) ## init dt <- Terminal/division X <- xinit Xt <- xinit k <- numeric(d.size) k1 <- numeric(d.size) k2 <- numeric(d.size) k3 <- numeric(d.size) k4 <- numeric(d.size) ## runge kutta for(t in 1:division){ ## k1 for(i in 1:d.size){ assign(modelstate[i],Xt[i]) } for(i in 1:d.size){ k1[i] <- dt*eval(V0[i]) } ## k2 for(i in 1:d.size){ assign(modelstate[i],Xt[i]+k1[i]/2) } for(i in 1:d.size){ k2[i] <- dt*eval(V0[i]) } ## k3 for(i in 1:d.size){ assign(modelstate[i],Xt[i]+k2[i]/2) } for(i in 1:d.size){ k3[i] <- dt*eval(V0[i]) } ## k4 for(i in 1:d.size){ assign(modelstate[i],Xt[i]+k3[i]) } for(i in 1:d.size){ k4[i] <- dt*eval(V0[i]) } ## V0(X(t+dt)) k <- (k1+k2+k2+k3+k3+k4)/6 Xt <- Xt+k X <- rbind(X,Xt) } ## return matrix : (division+1)*d rownames(X) <- NULL colnames(X) <- modelstate return(ts(X,deltat=dt[1],start=0)) } # simFunctional # public function to calculate Fe in (13.2). setGeneric("simFunctional", function(yuima, expand.var="e") standardGeneric("simFunctional") ) setMethod("simFunctional", signature(yuima="yuima"), function(yuima, expand.var="e"){ Xlen <- length(yuima@data) if(sum(Xlen != mean(Xlen)) != 0) { yuima.warn("All length must be same yet.") return(NULL) } if( (Xlen[1]-1) != yuima@sampling@n){ yuima.warn("Length of time series and division do not much.") return(NULL) } e <- gete(yuima@functional) ##:: fix bug 07/23 Fe <- funcFe.(yuima,as.matrix(onezoo(yuima)),e,expand.var=expand.var) return(Fe) }) # F0 # public function to calculate Fe at e=0 setGeneric("F0", function(yuima, expand.var="e") standardGeneric("F0") ) setMethod("F0", signature(yuima="yuima"), function(yuima, expand.var="e"){ X.t0 <- Get.X.t0(yuima, expand.var=expand.var) F0 <- funcFe.(yuima, X.t0, 0, expand.var=expand.var) return(F0) }) # Fnorm # public function to calculate (Fe-F0)/e setGeneric("Fnorm", function(yuima, expand.var="e") standardGeneric("Fnorm") ) setMethod("Fnorm", signature(yuima="yuima"), function(yuima, expand.var="e"){ e <- gete(yuima@functional) Fe <- simFunctional(yuima, expand.var=expand.var) F0 <- F0(yuima, expand.var=expand.var) return((Fe-F0)/e) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/simFunctional.R
## We have splitted the simulate function into blocks to allow for future ## methods to be added. S.M.I. & A.B. ## Interface to simulate() changed to match the S3 generic function in the ## package stats ## added an environment to let R find the proper values defined in the main ## body of the function, which in turn calls different simulation methods ## All new simulation methods should look into the yuimaEnv for local variables ## when they need to "eval" R expressions ##:: function simulate ##:: solves SDE and returns result subsampling <- function(x,y) return(x) setGeneric("simulate", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling=sampling, subsampling=subsampling, ... # Initial = 0, Terminal = 1, n = 100, delta, # grid = as.numeric(NULL), random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ) standardGeneric("simulate") ) setMethod("simulate", "yuima.model", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ tmpsamp <- NULL if(missing(sampling)){ tmpsamp <- setSampling(...) # tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, n = n, # delta = delta, grid = grid, random = random, sdelta=sdelta, # sgrid=sgrid, interpolation=interpolation) } else { tmpsamp <- sampling } tmpyuima <- setYuima(model=object, sampling=tmpsamp) out <- simulate(tmpyuima, nsim=nsim, seed=seed, xinit=xinit, true.parameter=true.parameter, space.discretized=space.discretized, increment.W=increment.W, increment.L=increment.L, method=method, hurst=hurst,methodfGn=methodfGn, subsampling=subsampling) return(out) }) # We rewrite the code of simulate method. We build a new internal function aux.simulate containing # the old code. This function starts directly if the model is an object of yuima.model-class # or yuima.carma-class. If the model is an object of class yuima.cogarch, simulate method runs # the internal function aux.simulateCogarch that generates first a path of the underlying levy and then # uses this path to construct the trajectories of the Cogarch model by calling the aux.simulate function. setMethod("simulate", "yuima", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst,methodfGn="WoodChan", sampling, subsampling, Initial = 0, Terminal = 1, n = 100, delta, grid = as.numeric(NULL), random = FALSE, sdelta=as.numeric(NULL), sgrid=as.numeric(NULL), interpolation="none"){ if(is(object,"yuima.LevyRM")){ res <- aux.simulateLevyRM(object = object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } if(is(object@model,"yuima.carmaHawkes")){ if(method == "Thinning"){ res <- aux.simulateCarmaHawkes_thin(object, true.parameter) return(res) } res <- aux.simulateCarmaHawkes(object, true.parameter) return(res) } if(is(object@model,"yuima.cogarch")){ res<-aux.simulateCogarch(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation) }else{ if(is(object@model,"yuima.multimodel")|| is(object@model@measure$df,"yuima.law") ){ res <- aux.simulate.multimodel(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L,method, hurst,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation) }else{ res<-aux.simulate(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L,method, hurst,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation) } } return(res) # ##:: errors checks # # ##:1: error on yuima model # yuima <- object # # if(missing(yuima)){ # yuima.warn("yuima object is missing.") # return(NULL) # } # # tmphurst<-yuima@model@hurst # # if(!missing(hurst)){ # yuima@model@hurst=hurst # } # # if (is.na(yuima@model@hurst)){ # yuima.warn("Specify the hurst parameter.") # return(NULL) # } # # tmpsamp <- NULL # if(is.null(yuima@sampling)){ # if(missing(sampling)){ # tmpsamp <- setSampling(Initial = Initial, # Terminal = Terminal, n = n, delta = delta, # grid = grid, random = random, sdelta=sdelta, # sgrid=sgrid, interpolation=interpolation) # } else { # tmpsamp <- sampling # } # } else { # tmpsamp <- yuima@sampling # } # # yuima@sampling <- tmpsamp # # sdeModel <- yuima@model # Terminal <- yuima@sampling@Terminal[1] # n <- yuima@sampling@n[1] # r.size <- [email protected] # d.size <- [email protected] # # ##:2: error on xinit # if(missing(xinit)){ # xinit <- sdeModel@xinit # } else { # if(length(xinit) != d.size){ # if(length(xinit)==1){ # xinit <- rep(xinit, d.size) # } else { # yuima.warn("Dimension of xinit variables missmatch.") # return(NULL) # } # } # } # # xinit <- as.expression(xinit) # force xinit to be an expression # # # par.len <- length(sdeModel@parameter@all) # # if(missing(true.parameter) & par.len>0){ # true.parameter <- vector(par.len, mode="list") # for(i in 1:par.len) # true.parameter[[i]] <- 0 # names(true.parameter) <- sdeModel@parameter@all # } # # yuimaEnv <- new.env() # # if(par.len>0){ # for(i in 1:par.len){ # pars <- sdeModel@parameter@all[i] # # for(j in 1:length(true.parameter)){ # if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ # assign(sdeModel@parameter@all[i], true.parameter[[j]],yuimaEnv) # } # } # #assign(sdeModel@parameter@all[i], true.parameter[[i]], yuimaEnv) # } # } # # # if(space.discretized){ # if(r.size>1){ # warning("Space-discretized EM cannot be used for multi-dimentional models. Use standard method.") # space.discretized <- FALSE # } # if(length([email protected])){ # warning("Space-discretized EM is for only Wiener Proc. Use standard method.") # space.discretized <- FALSE # } # } # # ##:: Error check for increment specified version. # if(!missing(increment.W) & !is.null(increment.W)){ # if(space.discretized == TRUE){ # yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") # return(NULL) # }else if(dim(increment.W)[1] != r.size){ # yuima.warn("Length of increment's row must be same as yuima@[email protected].") # return(NULL) # }else if(dim(increment.W)[2] != n){ # yuima.warn("Length of increment's column must be same as sampling@n[1].") # return(NULL) # } # } # # ##:: Error check for increment specified version. # if(!missing(increment.L) & !is.null(increment.L)){ # if(space.discretized == TRUE){ # yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") # return(NULL) # }else if(dim(increment.L)[1] != length(yuima@[email protected][[1]]) ){ #r.size){ # yuima.warn("Length of increment's row must be same as yuima@[email protected].") # return(NULL) # }else if(dim(increment.L)[2] != n){ # yuima.warn("Length of increment's column must be same as sampling@n[1].") # return(NULL) # } # } # # # yuimaEnv$dL <- increment.L # # # if(space.discretized){ # ##:: using Space-discretized Euler-Maruyama method # yuima@data <- space.discretized(xinit, yuima, yuimaEnv) # # yuima@model@hurst<-tmphurst # return(yuima) # } # # # ##:: using Euler-Maruyama method # delta <- Terminal/n # # if(missing(increment.W) | is.null(increment.W)){ # # if( sdeModel@hurst!=0.5 ){ # # grid<-sampling2grid(yuima@sampling) # isregular<-yuima@sampling@regular # # if((!isregular) || (methodfGn=="Cholesky")){ # dW<-CholeskyfGn(grid, sdeModel@hurst,r.size) # yuima.warn("Cholesky method for simulating fGn has been used.") # } else { # dW<-WoodChanfGn(grid, sdeModel@hurst,r.size) # } # # } else { # # delta<-Terminal/n # if(!is.Poisson(sdeModel)){ # if pure CP no need to setup dW # dW <- rnorm(n * r.size, 0, sqrt(delta)) # dW <- matrix(dW, ncol=n, nrow=r.size,byrow=TRUE) # } else { # dW <- matrix(0,ncol=n,nrow=1) # maybe to be fixed # } # } # # } else { # dW <- increment.W # } # # if(is.Poisson(sdeModel)){ # yuima@data <- simCP(xinit, yuima, yuimaEnv) # } else { # yuima@data <- euler(xinit, yuima, dW, yuimaEnv) # } # # for(i in 1:length(yuima@[email protected])) # index(yuima@[email protected][[i]]) <- yuima@sampling@grid[[1]] ## to be fixed # yuima@model@xinit <- xinit # yuima@model@hurst <-tmphurst # # if(missing(subsampling)) # return(yuima) # subsampling(yuima, subsampling) # } ) aux.simulate<-function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L,method, hurst,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation){ ##:: errors checks ##:1: error on yuima model yuima <- object if(missing(yuima)){ yuima.warn("yuima object is missing.") return(NULL) } tmphurst<-yuima@model@hurst if(!missing(hurst)){ yuima@model@hurst=hurst } if (is.na(yuima@model@hurst)){ yuima.warn("Specify the hurst parameter.") return(NULL) } tmpsamp <- NULL if(is.null(yuima@sampling)){ if(missing(sampling)){ tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, n = n, delta = delta, grid = grid, random = random, sdelta=sdelta, sgrid=sgrid, interpolation=interpolation) } else { tmpsamp <- sampling } } else { tmpsamp <- yuima@sampling } yuima@sampling <- tmpsamp sdeModel <- yuima@model Terminal <- yuima@sampling@Terminal[1] Initial <- yuima@sampling@Initial[1] n <- yuima@sampling@n[1] r.size <- [email protected] d.size <- [email protected] ##:2: error on xinit if(missing(xinit)){ xinit <- sdeModel@xinit } else { if(length(xinit) != d.size){ if(length(xinit)==1){ xinit <- rep(xinit, d.size) } else { yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } } xinit <- as.expression(xinit) # force xinit to be an expression par.len <- length(sdeModel@parameter@all) if(missing(true.parameter) & par.len>0){ true.parameter <- vector(par.len, mode="list") for(i in 1:par.len) true.parameter[[i]] <- 0 names(true.parameter) <- sdeModel@parameter@all } yuimaEnv <- new.env() if(par.len>0){ for(i in 1:par.len){ pars <- sdeModel@parameter@all[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(sdeModel@parameter@all[i], true.parameter[[j]],yuimaEnv) } } #assign(sdeModel@parameter@all[i], true.parameter[[i]], yuimaEnv) } } if(space.discretized){ if(r.size>1){ warning("Space-discretized EM cannot be used for multi-dimentional models. Use standard method.") space.discretized <- FALSE } if(length([email protected])){ warning("Space-discretized EM is for only Wiener Proc. Use standard method.") space.discretized <- FALSE } } ##:: Error check for increment specified version. if(!missing(increment.W) & !is.null(increment.W)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.W)[1] != r.size){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.W)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } ##:: Error check for increment specified version. if(!missing(increment.L) & !is.null(increment.L)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.L)[1] != length(yuima@[email protected][[1]]) ){ #r.size){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.L)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } yuimaEnv$dL <- increment.L if(space.discretized){ ##:: using Space-discretized Euler-Maruyama method yuima@data <- space.discretized(xinit, yuima, yuimaEnv) yuima@model@hurst<-tmphurst return(yuima) } ##:: using Euler-Maruyama method delta <- (Terminal-Initial)/n if(missing(increment.W) | is.null(increment.W)){ if( sdeModel@hurst!=0.5 ){ grid<-sampling2grid(yuima@sampling) isregular<-yuima@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, sdeModel@hurst,r.size) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, sdeModel@hurst,r.size) } } else { delta<-(Terminal-Initial)/n if(!is.Poisson(sdeModel)){ # if pure CP no need to setup dW dW <- rnorm(n * r.size, 0, sqrt(delta)) dW <- matrix(dW, ncol=n, nrow=r.size,byrow=TRUE) } else { dW <- matrix(0,ncol=n,nrow=1) # maybe to be fixed } } } else { dW <- increment.W } if(is.Poisson(sdeModel)){ yuima@data <- simCP(xinit, yuima, yuimaEnv) } else { yuima@data <- euler(xinit, yuima, dW, yuimaEnv) } for(i in 1:length(yuima@[email protected])) index(yuima@[email protected][[i]]) <- yuima@sampling@grid[[1]] ## to be fixed yuima@model@xinit <- xinit yuima@model@hurst <-tmphurst if(missing(subsampling)) return(yuima) subsampling(yuima, subsampling) } aux.simulateCogarch<-function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation){ yuimaCogarch<-object model<-yuimaCogarch@model info<-model@info samp <- yuimaCogarch@sampling if([email protected]=="CP" && !is.null(increment.L)){ method="euler" } if(method=="euler"||(method=="mixed" && [email protected]=="code")){ if(length(increment.L)==0){ aux.Noise<-setModel(drift="0", diffusion="0", jump.coeff="1", measure=info@measure, [email protected]) # aux.samp<-setSampling(Initial = samp@Initial, Terminal = samp@Terminal[1], n = samp@n[1], delta = samp@delta, # grid=samp@grid, random = samp@random, sdelta=samp@sdelta, # sgrid=samp@sgrid, interpolation=samp@interpolation ) aux.samp<-setSampling(Initial = samp@Initial, Terminal = samp@Terminal[1], n = samp@n[1]) auxModel<-setYuima(model=aux.Noise, sampling= aux.samp) if(length(model@parameter@measure)==0){ aux.incr2<-aux.simulate(object=auxModel, nsim=nsim, seed=seed, space.discretized=space.discretized, increment.W=increment.W, increment.L=increment.L, hurst=0.5,methodfGn=methodfGn) }else{ aux.incr2<-aux.simulate(object=auxModel, nsim=nsim, seed=seed, true.parameter = true.parameter[model@parameter@measure], space.discretized=space.discretized, increment.W=increment.W, increment.L=increment.L, hurst=0.5,methodfGn=methodfGn) } increment<-diff(as.numeric(get.zoo.data(aux.incr2)[[1]])) } else{increment<-increment.L} # Using the simulated increment for generating the quadratic variation # As first step we compute it in a crude way. A more fine approach is based on # the mpv function. quadratVariation <- increment^2 incr.L <- t(matrix(c(increment,quadratVariation),ncol=2)) incr.W <- matrix(0, nrow=1,ncol=length(increment)) # Simulate trajectories Cogarch } d.size <- [email protected] if(missing(xinit)){ xinit <- yuimaCogarch@model@xinit } else { if(length(xinit) != d.size){ if(length(xinit)==1){ xinit <- rep(xinit, d.size) } else { yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } } xinit <- as.expression(xinit) # force xinit to be an expression if(method=="euler"){ # result <- aux.simulate(object=yuimaCogarch, nsim=nsim, seed=seed, xinit=xinit, # true.parameter = true.parameter, # space.discretized = space.discretized,increment.W =incr.W, # increment.L=incr.L, method=method, # hurst=hurst,methodfGn=methodfGn, # sampling=sampling, subsampling=subsampling, # Initial=Initial, Terminal=Terminal, n=n, delta=delta, # grid=grid, random=random, sdelta=sdelta, # sgrid=sgrid, interpolation=interpolation) Terminal <- samp@Terminal[1] Initial <- samp@Initial[1] n <- samp@n[1] Delta <- (Terminal-Initial)/n name.ar <- paste0([email protected],c(1:info@q)) name.ma <- paste0([email protected],c(1:info@p)) name.loc <- [email protected] name.param <- names(true.parameter) parms <- as.numeric(true.parameter) names(parms)<-name.param value.ar <- parms[name.ar] value.ma <- parms[name.ma] value.a0 <- parms[name.loc] AMatrix <- MatrixA(value.ar) avect<-evect<-matrix(0,info@q,1) evect[info@q,] <- 1 avect[c(1,info@p),1] <- value.ma Indent<-diag(info@q) # Inputs: incr.L tavect<-t(avect) ncolsim <- (info@q+2) sim <- matrix(0,n+1,ncolsim) par.len <- length(model@parameter@all) if(missing(true.parameter) & par.len>0){ true.parameter <- vector(par.len, mode="list") for(i in 1:par.len) true.parameter[[i]] <- 0 names(true.parameter) <- model@parameter@all } yuimaEnv <- new.env() if(par.len>0){ for(i in 1:par.len){ pars <- model@parameter@all[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(model@parameter@all[i], true.parameter[[j]], yuimaEnv) } } #assign(sdeModel@parameter@all[i], true.parameter[[i]], yuimaEnv) } } for(i in c(1:ncolsim)){ sim[1,i] <- eval(xinit[i], yuimaEnv) } for(t in c(2:n)){ #sim[t,3:ncolsim] <- value.a0*expm(AMatrix*Delta)%*%evect*incr.L[2,t-1]+ # expm(AMatrix*Delta)%*%(Indent+evect%*%tavect*incr.L[2,t-1])%*%sim[t-1,3:ncolsim] # sim[t,2]<-value.a0+tavect%*%sim[t,3:ncolsim] # sim[t,1]<-sim[t-1,1]+sqrt(sim[t,2])*incr.L[1,t] # sim[t,3:ncolsim]<-expm(AMatrix*Delta)%*%sim[t-1,3:ncolsim]+expm(AMatrix)%*%evect*sim[t-1,2]*incr.L[2,t] sim[t,2]<-value.a0+tavect%*%sim[t-1,3:ncolsim] sim[t,3:ncolsim]<-sim[t-1,3:ncolsim]+(AMatrix*Delta)%*%sim[t-1,3:ncolsim]+evect*sim[t-1,2]*incr.L[2,t] sim[t,1]<-sim[t-1,1]+sqrt(sim[t,2])*incr.L[1,t] } X <- ts(sim[-(samp@n[1]+1),]) Data <- setData(X,delta = Delta,t0=Initial) result <- setYuima(data=Data,model=yuimaCogarch@model, sampling=yuimaCogarch@sampling) }else{ Terminal <- samp@Terminal[1] Initial <- samp@Initial[1] n <- samp@n[1] Delta <- (Terminal-Initial)/n name.ar <- paste0([email protected],c(1:info@q)) name.ma <- paste0([email protected],c(1:info@p)) name.loc <- [email protected] name.param <- names(true.parameter) parms <- as.numeric(true.parameter) names(parms)<-name.param value.ar <- parms[name.ar] value.ma <- parms[name.ma] value.a0 <- parms[name.loc] AMatrix <- MatrixA(value.ar) avect<-evect<-matrix(0,info@q,1) evect[info@q,] <- 1 avect[c(1,info@p),1] <- value.ma Indent<-diag(info@q) # Inputs: incr.L tavect<-t(avect) ncolsim <- (info@q+2) sim <- matrix(0,n+1,ncolsim) par.len <- length(model@parameter@all) if(missing(true.parameter) & par.len>0){ true.parameter <- vector(par.len, mode="list") for(i in 1:par.len) true.parameter[[i]] <- 0 names(true.parameter) <- model@parameter@all } yuimaEnv <- new.env() if(par.len>0){ for(i in 1:par.len){ pars <- model@parameter@all[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(model@parameter@all[i], true.parameter[[j]], yuimaEnv) } } #assign(sdeModel@parameter@all[i], true.parameter[[i]], yuimaEnv) } } for(i in c(1:ncolsim)){ sim[1,i] <- eval(xinit[i], yuimaEnv) } if(yuimaCogarch@[email protected]=="code"){ for(t in c(2:n)){ # sim[t,2]<-value.a0+tavect%*%sim[t,3:ncolsim] # sim[t,1]<-sim[t-1,1]+sqrt(sim[t,2])*incr.L[1,t] # sim[t,3:ncolsim]<-expm(AMatrix*Delta)%*%sim[t-1,3:ncolsim]+expm(AMatrix)%*%evect*sim[t-1,2]*incr.L[2,t] # sim[t,3:ncolsim]<-sim[t-1,3:ncolsim]+AMatrix*Delta%*%sim[t-1,3:ncolsim]+evect*sim[t-1,2]*incr.L[2,t-1] sim[t,2]<-value.a0+tavect%*%sim[t-1,3:ncolsim] sim[t,3:ncolsim] <- value.a0*expm(AMatrix*Delta)%*%evect*incr.L[2,t]+ expm(AMatrix*Delta)%*%(Indent+evect%*%tavect*incr.L[2,t])%*%sim[t-1,3:ncolsim] sim[t,1]<-sim[t-1,1]+sqrt(sim[t,2])*incr.L[1,t] } X <- ts(sim[-(samp@n[1]+1),]) Data <- setData(X,delta = Delta, t0=Initial) result <- setYuima(data=Data,model=yuimaCogarch@model, sampling=yuimaCogarch@sampling) return(result) }else{ lambda <- eval(model@measure$intensity, yuimaEnv) #Simulating jump times #intensity <- lambda*Delta intensity<-lambda jump_time<-numeric() jump_time[1] <- rexp(1, rate = intensity) # In yuima this part is evaluated using function eval Time <-numeric() Time[1] <- jump_time[1] j <- 1 numb_jum<-numeric() # for (i in c(1:n) ){ # numb_jum[i]<-0 # while(Time[j]<i){ # numb_jum[i]<-numb_jum[i]+1 # jump_time[j+1]<-rexp(1,rate=intensity) # Time[j+1]<-Time[j]+jump_time[j+1] # j<-j+1 # } # } while(Time[j] < (Terminal-Initial)){ jump_time[j+1]<-rexp(1,rate=intensity) Time[j+1]<-Time[j]+jump_time[j+1] j<-j+1 } total_NumbJ <- j # Counting the number of jumps # N<-matrix(1,n,1) # N[1,1]<-numb_jum[1] # for(i in c(2:n)){ # N[i,1]=N[i-1,1]+numb_jum[i] # } # Simulating the driving process F <- suppressWarnings(parse(text=gsub("^d(.+?)\\(.+?,", "r\\1(total_NumbJ,", model@measure$df$expr, perl=TRUE))) assign("total_NumbJ",total_NumbJ, envir=yuimaEnv) dL<-eval(F, envir=yuimaEnv) #dL<-rnorm(total_NumbJ,mean=0,sd=1) # L<-matrix(1,total_NumbJ,1) # L[1]<-dL[1] # for(j in c(2:total_NumbJ)){ # L[j]<-L[j-1] + dL[j] # } # Computing the processes V and Y at jump V<-matrix(1,total_NumbJ,1) Y<-matrix(1,info@q,total_NumbJ) Y[,1]<-matrix(sim[1,c(3:(3+info@q-1))],info@q,1) #Starting point for unobservable State Space Process. V[1,]<-value.a0+sum(tavect*Y[,1]) G<-matrix(1, total_NumbJ,1) G[1]<-0 for(j in c(2:total_NumbJ)){ Y[,j]<-as.numeric(expm(AMatrix*jump_time[j])%*%Y[,j-1])+(V[j-1,])*evect*dL[j]^2 V[j,]<-value.a0+sum(tavect*Y[,j]) # } # # Computing the process G at jump time # # for(j in c(2:total_NumbJ)){ G[j]<-G[j-1]+sqrt(V[j-1])*dL[j] } res<-approx(x=c(0,Time), y = c(0,G), xout=seq(0,(Terminal-Initial), by=(Terminal-Initial)/n), method = "constant") sim[,1]<-res$y i<-1 for(j in 1:length(Time)){ while (i*Delta < Time[j] && i <= n){ sim[i+1,3:ncolsim]<-expm(AMatrix*(Time[j]-i*Delta))%*%Y[,j] sim[i+1,2]<-value.a0+as.numeric(tavect%*%sim[i,3:ncolsim]) i<-i+1 } } # # Realizations observed at integer times # i<-1 # while(N[i]==0){ # i <- i+1 # } # # G_obs<-numeric() # # L_obs<-numeric() # # V_obs<-numeric() # # Y_obs<-matrix(0,info@q,) # sim[c(1:(i-1)),1]<-0 # sim[c(i:n),1]<-G[N[c(i:n)]] # # L_obs[c(1:(i-1))]<-0 # # L_obs[c(i:n)]<-L[N[c(i:n)]] # for(j in c(1:(i-1))){ # sim[j,3:ncolsim]<-as.numeric(Y[,j]) # sim[j,2]<-value.a0+tavect%*%expm(AMatrix*j)%*%matrix(1,info@q,1)#Starting point for unobservable State Space Process # } # for(j in c(i:n)){ # sim[j,3:ncolsim]<-as.numeric(Y[,N[j]]) # sim[j,2]<-value.a0+as.numeric(tavect%*%expm(AMatrix*(j-Time[N[j]]))%*%Y[,N[j]]) # } } X <- ts(sim[-1,]) Data <- setData(X,delta = Delta, t0 = Initial) result <- setYuima(data=Data,model=yuimaCogarch@model, sampling=yuimaCogarch@sampling) } if(missing(subsampling)) return(result) subsampling(result, subsampling) #return(result) } # Simulate method for an object of class cogarch.gmm.incr setMethod("simulate","cogarch.est.incr", function(object, nsim=1, seed=NULL, xinit, ...){ out <-aux.simulategmm(object=object, nsim=nsim, seed=seed, xinit=xinit, ...) # out <- simulate(object = model, nsim = nsim, seed=seed, xinit=xinit, # sampling = samp, # method = "euler", # increment.L = t(as.matrix(c(0,Incr.L))), # true.parameter = true.parameter, # ) return(out) } ) aux.simulategmm<-function(object, nsim=1, seed=NULL, xinit, ...){ Time<-index([email protected]) Incr.L<-coredata([email protected]) model <- object@yuima@model EndT <- Time[length(Time)] numb <- (length(Incr.L)+1) valpar<-coef(object) idx <- na.omit(match(names(valpar),model@parameter@xinit)) solnam <- model@parameter@xinit[-idx] solval <- as.numeric(Diagnostic.Cogarch(object, display=FALSE)$meanStateVariable) # solval <-50.33 names(solval) <- solnam true.parameter <- as.list(c(valpar,solval)) samp <- setSampling(Initial = 0, Terminal = EndT, n = numb) out <- simulate(object = model, nsim = nsim, seed=seed, xinit=xinit, sampling = samp, method = "euler", increment.L = t(as.matrix(c(0,Incr.L))), true.parameter = true.parameter ) return(out) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simulate.R
# Method for Map setMethod("simulate", "yuima.Map", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ res <- aux.simulatOutput(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) #aux.simulatOutput<-function(yuima.output, param=list(), sampling){ # param <- list(a=1,b=1,s1=0.1,s2=0.2,a1=0.1,a2=0.1) aux.simulatOutput<-function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst, methodfGn, sampling, subsampling){ mod <- object@model if(missing(sampling)){ sampling <- setSampling() } sim.Inputs <- simulate(mod, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst, methodfGn, sampling, subsampling) for(i in c(1:object@[email protected])){ assign(object@Output@[email protected][[i]], get.zoo.data(sim.Inputs)[[i]]) } assign(object@Output@[email protected], sim.Inputs@sampling@grid[[1]]) par <- unlist(true.parameter) nam <- names(par) for(i in c(1:length(nam))){ assign(nam[i],par[i]) } my.data<-eval(object@Output@formula[[1]]) if(prod(object@Output@dimension)>1){ for(i in c(2:prod(object@Output@dimension))){ my.data<-cbind(my.data, eval(object@Output@formula[[i]])) } } names(my.data)<-object@Output@[email protected] data1 <- setData(my.data) object@data <- data1 return(object) } # Method for Map setMethod("simulate", "yuima.Integral", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ res <- aux.simulatIntegral(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) aux.simulatIntegral <- function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ if(missing(sampling)){ sampling <- setSampling() } param <- unlist(true.parameter) info.par <- object@[email protected] info.var <- object@[email protected] info.int <- object@Integral@Integrand mod1 <- object@model labmod.par <- mod1@parameter@all nm <- names(param) CondModPar <- nm%in%labmod.par ValModPar <- param[CondModPar] IntModPar <- param[!CondModPar] #Simulation Internal trajectories sim.Inputs <- simulate(mod1, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst, methodfGn, sampling) # Data of underlying SDE Data <- get.zoo.data(sim.Inputs) time <- index(sim.Inputs@[email protected]) my.env <- new.env() assign([email protected],time,envir=my.env) for(i in c(1:[email protected])){ assign([email protected][i], as.numeric(Data[[i]]), envir = my.env) } df <- character(length=info.int@dimIntegrand[2]) M.dX <- matrix(0, nrow = info.int@dimIntegrand[2], ncol = sim.Inputs@sampling@n) for(i in c(1:info.int@dimIntegrand[2])){ df[i] <- paste0("diff(as.numeric(",[email protected][i],"))") M.dX[i,] <- eval(parse(text = df[i]), envir = my.env) } for(i in c(1:length(info.par@Integrandparam))){ cond <- nm%in%info.par@Integrandparam[i] if(any(cond)) assign(nm[cond],param[nm[cond]], envir = my.env) } #assign([email protected],time[-length(time)],envir=my.env) # matrInt <-matrix(0, nrow = info.int@dimIntegrand[1], # ncol = info.int@dimIntegrand[2]) res <- NULL PosInMatr <- matrix(c(1:(info.int@dimIntegrand[2]*info.int@dimIntegrand[1])), nrow = info.int@dimIntegrand[1], ncol = info.int@dimIntegrand[2]) my.fun <- function(my.list, my.env, i){ dum <- eval(my.list,envir = my.env) #if(length(dum)==1){ # return(rep(dum,i)) #}else{ return(dum[1:i]) #} } # res<-matrix(0,info.int@dimIntegrand[1],(length(time)-1)) # element <- matrix(0, nrow =info.int@dimIntegrand[1], ncol = 1) # # for(i in c(1:(length(time)-1))){ # assign([email protected],time[i+1],envir=my.env) # Inter2 <- lapply(info.int@IntegrandList, # FUN = my.fun, my.env = my.env, i = i) # for(j in c(1:info.int@dimIntegrand[1])){ # element[j,] <- M.dX[,c(1:i)]%*%matrix(unlist(Inter2[PosInMatr[j,]]), # ncol = info.int@dimIntegrand[2]) # } # res[,i] <- element # } LengTime<-(length(time)-1) my.listenv<-as.list(c(1:LengTime)) names(my.listenv)<- rep("i",LengTime) globalMyEnv <-new.env() globalMyEnv$time <- time globalMyEnv$my.env <- my.env element <- matrix(0, nrow =info.int@dimIntegrand[1], ncol = 1) my.listenv2<-lapply(X=my.listenv, globalMyEnv=globalMyEnv, FUN = function(X,globalMyEnv){ assign([email protected],globalMyEnv$time[X+1], envir= globalMyEnv$my.env) assign(object@[email protected],globalMyEnv$time[c(1:X)], envir= globalMyEnv$my.env) Inter2 <- lapply(info.int@IntegrandList, FUN = my.fun, my.env = globalMyEnv$my.env, i = X) for(j in c(1:info.int@dimIntegrand[1])){ element[j,] <- M.dX[,c(1:X)]%*%matrix(unlist(Inter2[PosInMatr[j,]]), ncol = info.int@dimIntegrand[2]) } list(element) }) res<-as.numeric(unlist(my.listenv2)) res<-matrix(res,info.int@dimIntegrand[1],(length(time)-1)) res <- cbind(0,res) rownames(res) <- object@[email protected]@out.var my.data <- zoo(x = t(res), order.by = time) data1 <- setData(my.data) object@data <- data1 if(missing(subsampling)) return(object) subsampling(object, subsampling) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simulateForMapsIntegralAndOperator.R
setMethod("simulate", "yuima.Hawkes", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ res <- aux.simulatHawkes(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) aux.simulatHawkes<- function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst, methodfGn, sampling, subsampling){ # Here we can construct specific algorithm for the standard Hawkes process res <- aux.simulatPPR(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) # object@[email protected]@allparam # simOzaki.aux(gFun=object@gFun@formula,a,cCoeff, Time, numJump) } setMethod("simulate", "yuima.PPR", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ res <- aux.simulatPPR(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) constHazIntPr <- function(g.Fun , Kern.Fun, covariates, counting.var,statevar=NULL){ numb.Int <- length(g.Fun) Int.Intens <- list() dum.g <- character(length=numb.Int) for(i in c(1:numb.Int)){ dum.g0 <- as.character(g.Fun[i]) dum.g0 <- gsub("(", "( ", fixed=TRUE,x = dum.g0) dum.g0 <- gsub(")", " )", fixed=TRUE,x = dum.g0) if(length(counting.var)>0){ for(j in c(1:length(counting.var))){ my.countOld <- paste0(counting.var[j] ," ") #my.countNew <- paste0("as.numeric(", counting.var[i] ,")") my.countNew <- paste0("(", counting.var[j] ,")") dum.g0 <- gsub(my.countOld, my.countNew, x = dum.g0, fixed=TRUE) my.countOld <- paste0(counting.var[j] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0("(", counting.var[j] ,")") dum.g0 <- gsub(my.countOld, my.countNew, x = dum.g0, fixed=TRUE) } } if(length(covariates)>0){ for(j in c(1:length(covariates))){ my.covarOld <- paste0(covariates[j] ," ") my.covarNew <- covariates[j] dum.g0 <- gsub(my.covarOld, my.covarNew, x = dum.g0, fixed=TRUE) my.covarOld <- paste0(covariates[j] ,"[",[email protected]@upper.var,"]") my.covarNew <- covariates[j] dum.g0 <- gsub(my.covarOld, my.covarNew, x = dum.g0, fixed=TRUE) } } dum.g[i] <- paste("tail(",dum.g0,", n=1L)") } dum.Ker <- as.character(unlist(Kern.Fun@Integrand@IntegrandList)) dum.Ker <- gsub("(", "( ", fixed=TRUE,x = dum.Ker) dum.Ker <- gsub(")", " )", fixed=TRUE,x = dum.Ker) dimKernel<-length(dum.Ker) condIntInKer <- FALSE for(i in c(1:dimKernel)){ if(!condIntInKer) condIntInKer <- statevar%in%all.vars(parse(text=dum.Ker[i])) } if(condIntInKer){ for(i in c(1:length(statevar))){ my.countOld <- paste0(statevar[i] ," ") my.countNew <- paste0( statevar[i] , "ForKernel[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(statevar[i] ,"[",[email protected]@upper.var,"]") # my.countNew <- paste0( counting.var[i] , # "[ as.character( ",[email protected]@upper.var ," ) ]") my.countNew <- paste0( "tail(",statevar[i] ,"ForKernel ,n=1L) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(statevar[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0(statevar[i] , "ForKernel[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } if(length(counting.var)>0){ for(i in c(1:length(counting.var))){ my.countOld <- paste0(counting.var[i] ," ") my.countNew <- paste0( counting.var[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(counting.var[i] ,"[",[email protected]@upper.var,"]") # my.countNew <- paste0( counting.var[i] , # "[ as.character( ",[email protected]@upper.var ," ) ]") my.countNew <- paste0( "tail(",counting.var[i] ,",n=1L) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(counting.var[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0(counting.var[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } if(length(covariates)>0){ for(i in c(1:length(covariates))){ my.countOld <- paste0(covariates[i] ," ") my.countNew <- paste0( covariates[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(covariates[i] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0("tail(", covariates[i] , ", n=1L ) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(covariates[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0( covariates[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } dif.dx <- paste("d",[email protected]@var.dx, sep="") if(Kern.Fun@Integrand@dimIntegrand[1]==1){ dum.Ker <- paste(dum.Ker,dif.dx, sep = "*") }else{ # dum.Ker <- paste(dum.Ker,rep(dif.dx, Kern.Fun@Integrand@dimIntegrand[1]), sep = "*") dum.Ker <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2], byrow=T) dum.Ker <- paste(dum.Ker,dif.dx, sep = "*") dum.Ker <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2], byrow=T) } cond.Sup <- paste([email protected]@var.time, "<", [email protected]@upper.var) dum.Ker <- paste("(",dum.Ker, ") * (", cond.Sup, ")") dum.Ker <- paste0("sum(",dum.Ker,")") if(Kern.Fun@Integrand@dimIntegrand[2]>1 & Kern.Fun@Integrand@dimIntegrand[1]==1){ dum.Ker <- paste(dum.Ker,collapse = " + ") } if(Kern.Fun@Integrand@dimIntegrand[1]>1){ mydum <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2]) dum.Ker <- character(length = Kern.Fun@Integrand@dimIntegrand[1]) for (i in c(1:Kern.Fun@Integrand@dimIntegrand[1])){ dum.Ker[i] <- paste(mydum[i,],collapse = " + ") } #yuima.stop("Check") } # dum.Ker <- paste("(",dum.Ker,") * (") # cond.Sup <- paste([email protected]@var.time, "<", [email protected]@upper.var) # dum.Ker <- paste(dum.Ker, cond.Sup, ")") for(i in c(1:numb.Int)){ Int.Intens[[i]] <- parse(text = paste(dum.g[i], dum.Ker[i], sep = " + ")) } res <- list(Intens = Int.Intens) } aux.simulatPPR<- function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ ROLDVER<-!(is(object@model@measure$df,"yuima.law")) if(ROLDVER){ object <- aux.simulatPPRROldVersion(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) }else{ if(object@PPR@RegressWithCount){ object <-aux.simulatPPRWithCount(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) }else{ posLambda <- object@[email protected] %in% object@[email protected] condInteFeedbackCov <- any(posLambda) if(condInteFeedbackCov){ object <- aux.simulatPPRWithIntesFeedBack(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling, posLambda=posLambda) }else{ object <- aux.simulatPPRROldNew(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) } } } return(object) } eulerPPR<-function(xinit,yuima,Initial,Terminal, dW, n, env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] # Terminal <- yuima@sampling@Terminal[1] # Initial <- yuima@sampling@Initial[1] #n <- ceiling((Terminal-Initial)/yuima@sampling@delta) dL <- env$dL if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } delta <- yuima@sampling@delta if(!length([email protected])){ b <- parse(text=paste("c(",paste(as.character(V0),collapse=","),")")) vecV <- parse(text=paste("c(",paste(as.character(unlist(V)),collapse=","),")")) X_mat <- .Call("euler", dX, Initial, as.integer(r.size), rep(1, n) * delta, dW, modeltime, modelstate, quote(eval(b, env)), quote(eval(vecV, env)), env, new.env()) tsX <- ts(data=t(X_mat), deltat=delta , start = Initial) #LM }else{ has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) p.b <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { ##:: no drift term (faster) tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ # we do not need to evaluate diffusion for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } # for j } # foh i } # !is.Poisson } # else return(tmp) } X_mat <- matrix(0, d.size, (n+1)) X_mat[,1] <- dX if(has.drift){ dW <- rbind( rep(1, n)*delta , dW) } JP <- [email protected] mu.size <- length(JP) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } } return(tmp) } dZ <- dL if(is.null(dim(dZ))) dZ <- matrix(dZ,nrow=1) for(i in 1:n){ # if(i==720 & n==720){ # aa<-NULL # } assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } tmp.j <- p.b.j(t=Initial+(i - 1)*delta, X=dX) # YK if(sum(dim(tmp.j))==2) tmp.j <- as.numeric(tmp.j) dX <- dX + p.b(t=Initial+(i - 1)*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] # YK X_mat[, i+1] <- dX } #tsX <- ts(data=t(X_mat), deltat=delta, start=yuima@sampling@Initial) } return(X_mat) } eulerPPRwithInt<-function(xinit,yuima,Initial,Terminal, dW, dL, n, env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] # Terminal <- yuima@sampling@Terminal[1] # Initial <- yuima@sampling@Initial[1] #n <- ceiling((Terminal-Initial)/yuima@sampling@delta) #dL <- env$dL if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") # return(NULL) dX_dummy <- c(dX_dummy,env[[yuima@[email protected]]]) for(i in 1:length(modelstate)){ if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } delta <- yuima@sampling@delta if(!length([email protected])){ b <- parse(text=paste("c(",paste(as.character(V0),collapse=","),")")) vecV <- parse(text=paste("c(",paste(as.character(unlist(V)),collapse=","),")")) X_mat <- .Call("euler", dX, Initial, as.integer(r.size), rep(1, n) * delta, dW, modeltime, modelstate, quote(eval(b, env)), quote(eval(vecV, env)), env, new.env()) tsX <- ts(data=t(X_mat), deltat=delta , start = Initial) #LM }else{ has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) p.b <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { ##:: no drift term (faster) tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ # we do not need to evaluate diffusion for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } # for j } # foh i } # !is.Poisson } # else return(tmp) } X_mat <- matrix(0, d.size, (n+1)) X_mat[,1] <- dX if(has.drift){ dW <- rbind( rep(1, n)*delta , dW) } JP <- [email protected] mu.size <- length(JP) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } } return(tmp) } dZ <- dL if(is.null(dim(dZ))) dZ <- matrix(dZ,nrow=1) for(i in 1:n){ # if(i==720 & n==720){ # aa<-NULL # } assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } tmp.j <- p.b.j(t=Initial+(i - 1)*delta, X=dX) # YK if(sum(dim(tmp.j))==2) tmp.j <- as.numeric(tmp.j) dX <- dX + p.b(t=Initial+(i - 1)*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] # YK X_mat[, i+1] <- dX } #tsX <- ts(data=t(X_mat), deltat=delta, start=yuima@sampling@Initial) } return(X_mat) } aux.simulatPPRWithCount<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = 0.5, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel object@sampling <- samp randomGenerator<-object@model@measure$df if(missing(increment.W) | is.null(increment.W)){ if( Model@hurst!=0.5 ){ grid<-sampling2grid(object@sampling) isregular<-object@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, Model@hurst,[email protected]) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, Model@hurst,[email protected]) } } else { # delta<-(Terminal-Initial)/n delta <- samp@delta if(!is.Poisson(Model)){ # if pure CP no need to setup dW dW <- rnorm(samp@n * [email protected], 0, sqrt(delta)) dW <- matrix(dW, ncol=samp@n, [email protected],byrow=TRUE) } else { dW <- matrix(0,ncol=samp@n,nrow=1) # maybe to be fixed } } } else { dW <- increment.W } if(missing(xinit)){ if(length(object@model@xinit)!=0){ xinit<-numeric(length=length(object@model@xinit)) for(i in c(1:object@[email protected])) xinit[i] <- eval(object@model@xinit[i]) }else{ xinit <- rep(0,object@[email protected]) object@model@xinit<-xinit } } if(missing(hurst)){ hurst<-0.5 } if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) rownames(Noise.L)<[email protected] #dIncr <- apply(cbind(0,Noise.L),1,diff) Noise.count <- Noise.L[object@[email protected],] Noise.Laux <- Noise.L for(i in c(1:length(object@[email protected]))){ Noise.Laux[object@[email protected][i],]<-0 } } myenv<-new.env() par.len <- length(object@PPR@allparam) if(par.len>0){ for(i in 1:par.len){ pars <- object@PPR@allparam[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(object@PPR@allparam[i], true.parameter[[j]],myenv) } } } } assign("dL",Noise.Laux,myenv) condMatrdW <- is.matrix(dW) if(condMatrdW){ dimdW <- dim(dW)[2] }else{ dimdW <- length(dW) } CovariateSim<- eulerPPR(xinit=xinit,yuima=object,dW=dW, Initial=samp@Initial,Terminal=samp@Terminal,n=samp@n, env=myenv) rownames(CovariateSim)<- [email protected] assign("info.PPR", object@PPR, myenv) dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(CovariateSim[object@PPR@covariates[j],1]), envir = myenv) } } dimNoise<-dim(Noise.Laux) dimCovariateSim <- dim(CovariateSim) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar = object@[email protected])$Intens # Start Simulation PPR compErrHazR4 <- function(samp, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- samp@grid[[1]]<=my.env$t PointIngridInt <- samp@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL # for(h in c(1:Index)){ # Lambdadum <- eval(ExprHaz[[h]], envir = my.env) # Lambda <- rbind(Lambda,Lambdadum) # Lambda <- eval(ExprHaz[[pos]], envir = my.env) # rownames(Lambda) <- [email protected] return(Lambda) } dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) grid <- samp@grid[[1]] const <- -log(runif(gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const Index <- gFun@dimension[1] inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR4(samp, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, myenv, ExprHaz, Time=jumpT, dN, Index, j) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate inter_i[j]<-inter_i[j]+1 if(inter_i[j]>=(dimGrid-1)){ noExit[j] <- FALSE } if(inter_i[j]<dim(CovariateSim)[2]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(CovariateSim[object@PPR@covariates[j],1:inter_i[j]]), envir = myenv) } } } } } i <- min(inter_i) if(any(noExit)){ if(i<dim(CovariateSim)[2]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1]<-Noise.count[i-1] dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1] <- dumdN[i==inter_i] dN <- cbind(dN,dumdN) } # cat("\n ", i, grid[i]) # assign("dL",Noise.Laux,myenv) # # CovariateSim<- eulerPPR(xinit=xinit,yuima=object,dW=dW, # Initial=samp@Initial,Terminal=samp@Terminal, # env=myenv) assign("dL",Noise.Laux[,c((i-1):dimNoise[2])],myenv) xinit <- CovariateSim[,i-1] if(condMatrdW){ CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPR(xinit=xinit, yuima=object,dW=dW[,(i-1):dimdW], Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), env=myenv) }else{ CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPR(xinit=xinit, yuima=object, dW=dW[(i-1):dimdW], Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), env=myenv) } rownames(CovariateSim)<- [email protected] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } tsX <- ts(data=t(CovariateSim), deltat=delta, start=object@sampling@Initial) object@data <- setData(original.data=tsX) for(i in 1:length(object@[email protected])) index(object@[email protected][[i]]) <- object@sampling@grid[[1]] ## to be fixed #object@model@hurst <-tmphurst if(missing(subsampling)) return(object) subsampling(object, subsampling) } aux.simulatPPRWithIntesFeedBack<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling, posLambda=posLambda){ samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel object@sampling <- samp randomGenerator<-object@model@measure$df nameIntensityProc <- object@[email protected] if(missing(increment.W) | is.null(increment.W)){ if( Model@hurst!=0.5 ){ grid<-sampling2grid(object@sampling) isregular<-object@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, Model@hurst,[email protected]) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, Model@hurst,[email protected]) } } else { # delta<-(Terminal-Initial)/n delta <- samp@delta if(!is.Poisson(Model)){ # if pure CP no need to setup dW dW <- rnorm(samp@n * [email protected], 0, sqrt(delta)) dW <- matrix(dW, ncol=samp@n, [email protected],byrow=TRUE) } else { dW <- matrix(0,ncol=samp@n,nrow=1) # maybe to be fixed } } } else { dW <- increment.W } if(missing(xinit)){ if(length(object@model@xinit)!=0){ xinit<-numeric(length=length(object@model@xinit)) for(i in c(1:object@[email protected])) xinit[i] <- eval(object@model@xinit[i]) }else{ xinit <- rep(0,object@[email protected]) object@model@xinit<-xinit } } if(missing(hurst)){ hurst<-0.5 } if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) rownames(Noise.L)<[email protected] #dIncr <- apply(cbind(0,Noise.L),1,diff) Noise.count <- Noise.L[object@[email protected],] Noise.Laux <- Noise.L for(i in c(1:length(object@[email protected]))){ Noise.Laux[object@[email protected][i],]<-0 } } myenv<-new.env() par.len <- length(object@PPR@allparam) if(par.len>0){ for(i in 1:par.len){ pars <- object@PPR@allparam[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(object@PPR@allparam[i], true.parameter[[j]],myenv) } } } } assign("dL",Noise.Laux,myenv) condMatrdW <- is.matrix(dW) if(condMatrdW){ dimdW <- dim(dW)[2] }else{ dimdW <- length(dW) } assign("info.PPR", object@PPR, myenv) dimCov <- length(object@PPR@covariates) dimNoise<-dim(Noise.Laux) # Start Simulation PPR compErrHazR4 <- function(samp, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- samp@grid[[1]]<=my.env$t PointIngridInt <- samp@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL # for(h in c(1:Index)){ # Lambdadum <- eval(ExprHaz[[h]], envir = my.env) # Lambda <- rbind(Lambda,Lambdadum) # Lambda <- eval(ExprHaz[[pos]], envir = my.env) # rownames(Lambda) <- [email protected] return(Lambda) } if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(xinit[j]), envir = myenv) } } CovariateSim <-matrix(0,[email protected],(samp@n+1)) #IntensityProcInter <- matrix(0,length(nameIntensityProc),(samp@n+1)) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar=nameIntensityProc)$Intens IntensityProcInter <- as.matrix(tryCatch(eval(object@gFun@formula,envir=myenv),error =function(){1})) dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) rownames(CovariateSim)<- [email protected] assign(object@[email protected],CovariateSim[object@[email protected],1],envir=myenv) grid <- samp@grid[[1]] const <- -log(runif(gFun@dimension[1])) condMyTR <- const<delta AllnameIntensityProc <- paste0(nameIntensityProc,"ForKernel") assign(AllnameIntensityProc,IntensityProcInter,envir=myenv) while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } jumpT<-NULL i <- 1 Initial_i <- i-1 dimGrid <-length(grid) cond <- const Index <- gFun@dimension[1] inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR4(samp, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, myenv, ExprHaz, Time=jumpT, dN, Index, j) if(is.matrix(posLambda)){}else{ #assign(object@[email protected][posLambda],lambda, envir = myenv) assign(nameIntensityProc,lambda[j], envir = myenv) # myenv[[AllnameIntensityProc]][j,]<-cbind(myenv[[AllnameIntensityProc]][j,], # lambda[j]) assign(AllnameIntensityProc, cbind(t(myenv[[AllnameIntensityProc]][j,]), lambda[j]), envir=myenv) } incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate # if(cond[j]>0){ # dN<-cbind(dN,rep(0,Index)) # } inter_i[j]<-inter_i[j]+1 if(inter_i[j]-1==1){ CovariateSim[,c((inter_i[j]-1):inter_i[j])]<- eulerPPRwithInt(xinit=xinit,yuima=object,dW=dW[,(inter_i[j]-1)], dL=as.matrix(myenv$dL[,c(i-Initial_i)]),Initial=samp@Initial,Terminal=samp@grid[[1]][inter_i[j]],n=1, env=myenv) rownames(CovariateSim)<- [email protected] }else{ CovariateSim[,inter_i[j]]<- eulerPPRwithInt(xinit=CovariateSim[,(inter_i[j]-1)], yuima=object,dW=dW[,(inter_i[j]-1)], dL=as.matrix(myenv$dL[,c(inter_i[j]-1-Initial_i)]), Initial=samp@grid[[1]][(inter_i[j]-1)], Terminal=samp@grid[[1]][inter_i[j]],n=1, env=myenv)[,-1] } # if(inter_i[j]==66){ # aaaaa<-1 # } if(inter_i[j]>=(dimGrid)){ noExit[j] <- FALSE } if(inter_i[j]<=dimGrid){ assign(object@[email protected],CovariateSim[object@[email protected][j],1:inter_i[j]],envir=myenv) dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(jj in c(1:dimCov)){ assign(object@PPR@covariates[jj], as.numeric(CovariateSim[object@PPR@covariates[jj],1:inter_i[j]]), envir = myenv) } } } } } i <- min(inter_i) Initial_i <- i-1 if(any(noExit)){ if(i<dim(CovariateSim)[2]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1]<-Noise.count[i-1] dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1] <- dumdN[i==inter_i] dN <- cbind(dN,dumdN) } # cat("\n ", i, grid[i]) # assign("dL",Noise.Laux,myenv) # # CovariateSim<- eulerPPR(xinit=xinit,yuima=object,dW=dW, # Initial=samp@Initial,Terminal=samp@Terminal, # env=myenv) assign("dL",Noise.Laux[,c((i-1):dimNoise[2])],myenv) xinit <- CovariateSim[,i-1] # if(condMatrdW){ # CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPRwithInt(xinit=xinit, # yuima=object,dW=dW[,(i-1):dimdW], # Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), # env=myenv) # }else{ # CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPRwithInt(xinit=xinit, # yuima=object, dW=dW[(i-1):dimdW], # Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), # env=myenv) # } # # rownames(CovariateSim)<- [email protected] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } tsX <- ts(data=t(CovariateSim), deltat=delta, start=object@sampling@Initial) object@data <- setData(original.data=tsX) for(i in 1:length(object@[email protected])) index(object@[email protected][[i]]) <- object@sampling@grid[[1]] ## to be fixed #object@model@hurst <-tmphurst if(missing(subsampling)) return(object) subsampling(object, subsampling) } aux.simulatPPRROldNew<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = 0.5, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ myhawkesP <- function(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN){ noExit<-TRUE const <- -log(runif(1)) delta <- samp@delta grid <- samp@grid[[1]] while(const<delta){ const <- -log(runif(1)) } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const allconst <- NULL allcond <- NULL allhaz <- NULL while(noExit){ HazardRate<-0 while(cond>0 && noExit){ #lastJump <- tail(jumpT,n=1L) lambda<-compErrHazR2(simMod, Kern, capitalTime=samp@grid[[1]][i], Model, my.env, ExprHaz, Time=jumpT, dN) # lambda<-hawkesInt(mu=mu, alpha=alpha, beta=beta, # timet=grid[i], JumpT=jumpT) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond <- const-HazardRate i<-i+1 if(i>=(dimGrid-1)){ noExit <- FALSE } if(i<dim(simMod@[email protected])[1]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ # my.covdata <- simMod@[email protected][1:i,object@PPR@covariates[j]] # names(my.covdata) <-simMod@sampling@grid[[1]][1:i] # # assign(object@PPR@covariates[j], # my.covdata, # envir = my.env) assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1:i,object@PPR@covariates[j]]), envir = my.env) } } # Line 354 necessary for the development of the code. # cat("\n ", i, grid[i]) } } if(i<dim(simMod@[email protected])[1]){ jumpT<-c(jumpT,grid[i]) # if(i==7001){ # cat("\n",noExit) # } if(dN[1]==0){ #dN <- 1 dN <- simMod@[email protected][i,object@[email protected]]-simMod@[email protected][i-1,object@[email protected]] }else{ dN <- c(dN, simMod@[email protected][i,object@[email protected]]-simMod@[email protected][i-1,object@[email protected]]) } #names(dN)<-jumpT allhaz <- c(allhaz,HazardRate) allcond <- c(allcond,cond) cond <- const allconst <- c(allconst, const) const <- -log(runif(1)) while(const<delta){ const <- -log(runif(1)) } } } return(list(jumpT=jumpT,allcond=allcond,allconst=allconst, allhaz=allhaz)) } #myhawkesPMulti myhawkesPMulti <- function(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN, Index){ #noExit<-TRUE delta <- samp@delta grid <- samp@grid[[1]] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } # while(const<delta){ # const <- -log(runif(1)) # } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR3(simMod, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, my.env, ExprHaz, Time=jumpT, dN, Index, j) # lambda<-hawkesInt(mu=mu, alpha=alpha, beta=beta, # timet=grid[i], JumpT=jumpT) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate inter_i[j]<-inter_i[j]+1 if(inter_i[j]>=(dimGrid-1)){ noExit[j] <- FALSE } if(inter_i[j]<dim(simMod@[email protected])[1]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(jj in c(1:dimCov)){ # my.covdata <- simMod@[email protected][1:i,object@PPR@covariates[j]] # names(my.covdata) <-simMod@sampling@grid[[1]][1:i] # # assign(object@PPR@covariates[j], # my.covdata, # envir = my.env) assign(object@PPR@covariates[jj], as.numeric(simMod@[email protected][1:inter_i[j],object@PPR@covariates[jj]]), envir = my.env) } } # Line 354 necessary for the development of the code. # cat("\n ", i, grid[i]) } } } i <- min(inter_i) if(any(noExit)){ if(i<dim(simMod@[email protected])[1]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- 1 dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- 1 dN <- cbind(dN,dumdN) } #names(dN)<-jumpT # const <- -log(runif(1)) # while(const<delta){ # const <- -log(runif(1)) # } const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } return(list(jumpT=jumpT,dN = dN)) } # compErrHazR2 <- function(simMod, Kern, # capitalTime, Model, my.env, ExprHaz, # Time, dN){ # # dummyLambda <- numeric(length=(samp@n+1)) # if(length([email protected]@var.dx)==1){ # # MyPos <- sum(samp@grid[[1]]<=tail(Time,n=1L)) # assign([email protected]@var.time, Time, envir = my.env) # # cond <- -log(cost)-sum(dummyLambda)*samp@delta # # assign([email protected], capitalTime, envir = my.env) # assign(paste0("d",[email protected]@var.dx), dN, envir =my.env) # # condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t # PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] # CondJumpGrid <- PointIngridInt %in% my.env$s # assign("CondJumpGrid", CondJumpGrid, envir = my.env) # # Lambda <- eval(ExprHaz[[1]], envir=my.env) # return(Lambda) # }else{ # if(Kern@Integrand@dimIntegrand[1]==1){ # assign([email protected]@var.time, Time, envir = my.env) # # cond <- -log(cost)-sum(dummyLambda)*samp@delta # # assign([email protected], capitalTime, envir = my.env) # for(i in c(1:length([email protected]@var.dx)) ){ # if([email protected]@var.dx[i][email protected]){ # assign(paste0("d",[email protected]@var.dx[i]), dN, envir =my.env) # } # if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ # assign(paste0("d",[email protected]@var.dx[i]), # diff(c(0,my.env[[[email protected]@var.dx[i]]])) , # envir =my.env) # } # if([email protected]@var.dx[i]%in%[email protected]){ # assign(paste0("d",[email protected]@var.dx[i]), # diff(c(0,my.env[[[email protected]@var.dx[i]]])) , # envir =my.env) # } # } # condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t # PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] # CondJumpGrid <- PointIngridInt %in% my.env$s # assign("CondJumpGrid", CondJumpGrid, envir = my.env) # # Lambda <- eval(ExprHaz[[1]], envir=my.env) # return(Lambda) # } # } # } compErrHazR2 <- function(simMod, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN){ # dummyLambda <- numeric(length=(samp@n+1)) if(length([email protected]@var.dx)==1){ # MyPos <- sum(samp@grid[[1]]<=tail(Time,n=1L)) assign([email protected]@var.time, Time, envir = my.env) # cond <- -log(cost)-sum(dummyLambda)*samp@delta assign([email protected], capitalTime, envir = my.env) assign(paste0("d",[email protected]@var.dx), dN, envir =my.env) condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- eval(ExprHaz[[1]], envir=my.env) return(Lambda) }else{ if(Kern@Integrand@dimIntegrand[1]==1){ assign([email protected]@var.time, Time, envir = my.env) # cond <- -log(cost)-sum(dummyLambda)*samp@delta assign([email protected], capitalTime, envir = my.env) for(i in c(1:length([email protected]@var.dx)) ){ if([email protected]@var.dx[i][email protected]){ assign(paste0("d",[email protected]@var.dx[i]), dN, envir =my.env) } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } if([email protected]@var.dx[i]%in%[email protected]){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- eval(ExprHaz[[1]], envir=my.env) return(Lambda) } } } compErrHazR3 <- function(simMod, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL # for(h in c(1:Index)){ # Lambdadum <- eval(ExprHaz[[h]], envir = my.env) # Lambda <- rbind(Lambda,Lambdadum) # Lambda <- eval(ExprHaz[[pos]], envir = my.env) # rownames(Lambda) <- [email protected] return(Lambda) } if(missing(hurst)){ hurst<-0.5 } samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel if(missing(xinit)){ if(object@PPR@RegressWithCount){ yuima.warn("Counting Variables are also covariates. In this case, the algorthim will be implemented as soon as possible.") return(NULL) } }else{ if(object@PPR@RegressWithCount){ yuima.warn("Counting Variables are also covariates. In this case, the algorthim will be implemented as soon as possible.") return(NULL) } } if(!object@PPR@RegressWithCount && !object@PPR@IntensWithCount){ auxg <- setMap(func = gFun@formula, yuima =Model) dummyKernIntgrand <- Kern@Integrand@IntegrandList dummyUpperTime<- paste0([email protected]@upper.var, [email protected]@upper.var, collapse = "") dummyTime <[email protected] for(i in c(1:length(dummyKernIntgrand))){ if([email protected]@upper.var %in% all.vars(dummyKernIntgrand[[i]])){ dumExpr <- paste0("substitute(expression(", dummyKernIntgrand[[i]],"), list(", [email protected]@upper.var, " = as.symbol(dummyUpperTime), ", [email protected]@var.time, " = as.symbol([email protected])))") dummyKernIntgrand[[i]] <- eval(parse(text=dumExpr)) } } auxIntMy <- unlist(lapply(dummyKernIntgrand, FUN = function(X){as.character(X)[2]})) auxIntMy <- matrix(auxIntMy, Kern@Integrand@dimIntegrand[1], Kern@Integrand@dimIntegrand[2], byrow=T) if(object@[email protected]@var.dx==object@[email protected]@var.time){ auxInt <- setIntegral(yuima = Model, integrand = auxIntMy, var.dx = [email protected], upper.var = dummyUpperTime, lower.var = [email protected]@lower.var) }else{ auxInt <- setIntegral(yuima = Model, integrand = auxIntMy, var.dx =object@[email protected]@var.dx , upper.var = dummyUpperTime, lower.var = [email protected]@lower.var) } randomGenerator<-object@model@measure$df if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) Noise.W <- t(rnorm(NumbIncr, 0,tForMeas)) if(length(object@model@diffusion[[1]])>1){ for(i in c(2:length(object@model@diffusion[[1]]))){ Noise.W <- rbind(Noise.W, rnorm(NumbIncr, 0,tForMeas)) } } if(missing(xinit)){ simg <- simulate(object = auxg, true.parameter = true.parameter[auxg@Output@param@allparam], sampling = samp, hurst = hurst, increment.W = Noise.W, increment.L = Noise.L) simK <- simulate(object = auxInt, true.parameter = true.parameter[auxInt@[email protected]@allparam], sampling = samp, hurst = hurst, increment.W = Noise.W, increment.L = Noise.L) Lambda.data <- simg@[email protected]+simK@[email protected] Pos<-0 globPos<-Pos condWhile <- TRUE while(condWhile){ Hazard<--cumsum(as.numeric(Lambda.data)[c(Pos:(samp@n+1))])*samp@delta U<-runif(1) CondPos <- log(U)<=Hazard Pos <- Pos+sum(CondPos) if(Pos > (samp@n+1)){ condWhile <- FALSE }else{ globPos <- c(globPos,Pos) } } globPos <- unique(globPos) globPos <- globPos[(globPos<=samp@n)] NewNoise.L <- Noise.L cod <[email protected]%in%object@[email protected] NeWNoise.W<-Noise.W NeWNoise.W[cod,] <- 0 NewNoise.L[cod,] <- 0 NewNoise.L[cod,globPos[-1]] <- Noise.L[cod,globPos[-1]] simM <- simulate(object = Model, true.parameter = true.parameter[Model@parameter@all], sampling = samp, hurst = hurst, increment.W = NeWNoise.W, increment.L = NewNoise.L) object@data <- simM@data object@sampling <- samp return(object) #Lambda.data <- simg@[email protected]+simK@[email protected] }else{ simg <- simulate(object = auxg, xinit=xinit, sampling = samp) } } }else{ if(!object@PPR@RegressWithCount && object@PPR@IntensWithCount){ ## Here we consider the case where we have a counting variable in the intensity but ## we haven't it in the coefficients of the covariates. # Simulation of the noise DummyT <- c(true.parameter[Model@parameter@measure], samp@delta) names(DummyT) <- c(names(true.parameter[Model@parameter@measure]), [email protected]) increment.L <- rand(object = Model@measure$df, n = samp@n , param = DummyT) if(!is.matrix(increment.L)){ increment.L <- matrix(increment.L,ncol = 1) } if(missing(xinit)){ simMod <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simMod <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } colnames(simMod@[email protected]) <- [email protected] Data.tot <- as.matrix(simMod@[email protected]) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar = object@[email protected])$Intens # if(FALSE){ if(length(ExprHaz)>=1){ Time <- samp@Initial my.env <- new.env() assign("info.PPR", object@PPR, my.env) for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i], as.numeric(true.parameter[object@PPR@allparam[i]]), envir = my.env) } dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1,object@PPR@covariates[j]]), envir = my.env) } } if(object@gFun@dimension[1]==1){ #if(FALSE){ IntensityProc <- 0 #set.seed(1) dN <- 0 prova1 <- myhawkesP(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN) }else{ CPP<-FALSE IntensityProc <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) #set.seed(1) dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) prova1 <- myhawkesPMulti(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN, Index = object@gFun@dimension[1]) Time<-unique(prova1$jumpT) dN <- prova1$dN[,1:length(Time)] cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 increment.L[cond, countVar]<-t(dN) if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) } #cond <- samp@grid[[1]][-1] %in% Time[-1] Time<-prova1$jumpT cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) }else{ my.env <- new.env() assign("info.PPR", object@PPR, my.env) # ExprHaz for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i], as.numeric(true.parameter[object@PPR@allparam[i]]), envir = my.env) } dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1,object@PPR@covariates[j]]), envir = my.env) } } CPP<-FALSE IntensityProc <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) #set.seed(1) #dN<-matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) dN <- NULL CondGlobal <- TRUE CondWhile <- TRUE # JumpTime <- samp@grid[[1]] u_bar <- samp@Initial u_old <- samp@Initial jumpT<-NULL posInitial <- 1 while(CondGlobal){ CondWhile <- TRUE const <- log(runif(object@gFun@dimension[1])) delta <- samp@delta grid <- samp@grid[[1]] condMyTR <- -const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- log(runif(length(condMyTR))) condMyTR <- -const<delta }else{ const[condMyTR] <- log(runif(sum(condMyTR))) condMyTR <- -const<delta } } posfin <- sum(samp@grid[[1]]<=u_bar) dimGrid <-length(grid) cond <- const allconst <- NULL allcond <- NULL allhaz <- NULL # if(u_bar>=47.83){ # aaa<-1 # } checkFunDum_old <- const checkFunDum <- const count <- 0 while(CondWhile & count<20){ HowManylambda <- posfin-posInitial+1 lambda <- matrix(NA,object@gFun@dimension[1],HowManylambda) for(hh in c(1:HowManylambda)){ lambda[,hh] <- compErrHazR3(simMod, Kern, capitalTime=samp@grid[[1]][hh+(posInitial-1)], Model, my.env, ExprHaz, Time=jumpT, dN, object@gFun@dimension[1]) } # Find the optimal u_i next as minimum u_next_comp <- numeric(length = object@gFun@dimension[1]) FunDum <- numeric(length=object@gFun@dimension[1]) for(l in c(1:object@gFun@dimension[1])){ FunDum[l] <- const[l] + sum(lambda[l, ]*delta) denomi <- lambda[l,HowManylambda] u_next_comp[l] <- u_bar-FunDum[l]/denomi } u_next <- min(u_next_comp) if(abs(tail(grid[grid<=u_next],1L) - tail(grid[grid<=u_bar],1L))<delta/2){ CondWhile<-FALSE } condpos <- u_next_comp %in% u_next checkFunDumAll <- FunDum[condpos] checkFunDum <- checkFunDumAll if(u_next > u_old){ if(checkFunDum_old<=0){ if(checkFunDum <= 0){ u_old<-u_bar checkFunDum_old <- checkFunDum }else{ checkFunDum_old <- checkFunDum } } u_bar <- u_next }else{ if(CondWhile){ u_bar <- (u_bar + u_old)/2 }else{ u_bar <- u_next } } posfin <- sum(samp@grid[[1]]<=u_bar) count <- count+1 #end while } next_jump <- tail(grid[grid<=u_next],1L) dummydN <- rep(0,object@gFun@dimension[1]) for(hhh in c(1:object@gFun@dimension[1])){ #condJumpComp <- tail(grid[grid<=u_next_comp[hhh]],1L)==u_bar condJumpComp <- u_next == u_next_comp[hhh] if(condJumpComp) dummydN[hhh] <- 1 } dN <- cbind(dN,dummydN) # if(length(jumpT)>0){ # if(abs(tail(jumpT,1L)-u_bar)<(delta-10^(-12))){ # u_bar <- u_bar + delta # } # } if(length(jumpT)>0){ if(tail(jumpT, 1L)+delta >= next_jump){ next_jump <- next_jump+delta } }else{ if(next_jump < delta){ next_jump <- next_jump+delta } } jumpT<-c(jumpT,next_jump) # cat("\n ", c(next_jump, checkFunDum,count)) u_bar <- tail(jumpT,1L) posInitial<- sum(grid<=next_jump) posfin <- posInitial u_old <- next_jump if((next_jump+delta)>=samp@Terminal-delta){ CondGlobal <- FALSE } # end First while } #return(list(dN=dN,jumpT=jumpT)) Time<-jumpT cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) } } } return(NULL) } # SolvePPR <- function(posMid, posLeft, posRight, solveLeft = NULL, solveRight = NULL, # cost, Kern, simMod, samp, Model, ExprHaz, # my.env, Time, IntensityProc){ # # if((posMid+1)>=(samp@n+1)){ # mylist <- list(VeryExit = TRUE) # return(mylist) # } # if((posMid+1)>=(samp@n+1)){ # mylist <- list(VeryExit = TRUE) # return(mylist) # } # # # solveMid<- compErrHazR(posMid, simMod, Kern, samp, Model, my.env, ExprHaz, cost, Time) # if(solveMid$solveLambda <= 0){ # # first check # if(solveMid$solveLambda<0 ){ # if(posLeft == (posMid-1)){ # if(solveLeft*solveMid$solveLambda<0){ # mylist <- list() # mylist$exit <- TRUE # mylist$left <- TRUE # mylist$posLeft <- posMid # mylist$posRight <- samp@n+1 # mylist$solveLeft <- solveMid$solveLambda # mylist$solveRight <- NULL # mylist$Time <- c(Time,samp@grid[[1]][-1][posMid]) # mylist$IntensityProc <- c(IntensityProc, solveMid$dummyLambda) # # return(mylist) # } # } # solveMidLeft <- compErrHazR(posMid-1, simMod, Kern, samp, Model, my.env, ExprHaz, cost, Time) # if(solveMidLeft$solveLambda >=0){ # mylist <- list() # mylist$exit <- TRUE # mylist$left <- TRUE # mylist$posLeft <- posMid-1 # mylist$posRight <- samp@n+1 # mylist$solveLeft <- solveMidLeft$solveLambda # mylist$solveRight <- NULL # mylist$Time <- c(Time,samp@grid[[1]][-1][posMid-1]) # mylist$IntensityProc <- c(IntensityProc, solveMidLeft$dummyLambda) # return(mylist) # }else{ # mylist <- list() # mylist$exit <- FALSE # mylist$left <- TRUE # mylist$posLeft <- posLeft # mylist$posRight <- posMid # mylist$solveLeft <- solveLeft # mylist$solveRight <-solveMidLeft$solveLambda # mylist$Time <- Time # mylist$IntensityProc <- c(IntensityProc) # return(mylist) # } # } # } # if(solveMid$solveLambda==0){ # mylist <- list() # mylist$exit <- TRUE # mylist$left <- FALSE # mylist$posLeft <-posMid # mylist$posRight <- samp@n+1 # mylist$solveLeft <- solveMid$solveLambda # mylist$solveRight <- solveRight # mylist$Time <- c(Time,samp@grid[[1]][-1][posMid-1]) # mylist$IntensityProc <- c(IntensityProc, solveMid$dummyLambda) # return(mylist) # } # if(solveMid$solveLambda > 0 && (posMid+1) <(samp@n+1)){ # solveMidRight <- compErrHazR(posMid+1, simMod, Kern, samp, Model, my.env, ExprHaz, cost, Time) # if(solveMidRight$solveLambda <=0){ # mylist <- list() # mylist$exit <- TRUE # mylist$left <- FALSE # mylist$posLeft <- posMid+1 # mylist$posRight <- samp@n+1 # mylist$solveLeft <- solveMidRight$solveLambda # mylist$solveRight <- solveRight # mylist$Time <- c(Time,samp@grid[[1]][-1][posMid+1]) # mylist$IntensityProc <- c(IntensityProc, solveMidRight$dummyLambda) # return(mylist) # }else{ # mylist <- list() # mylist$exit <- FALSE # mylist$left <- FALSE # mylist$posLeft <- posMid+1 # mylist$posRight <- posRight # mylist$solveLeft <- solveMidRight$solveLambda # mylist$solveRight <-solveRight # mylist$Time <- Time # mylist$IntensityProc <- c(IntensityProc) # return(mylist) # } # } # } # SolvePPR <- function(TopposInGridIn, OldTimePoint, solveLambdaInOld, # cost, Kern, simMod, samp, Model, ExprHaz, dN, # LastTime, my.env, Time, IntensityProc, checkside = FALSE, # solveLeft=NULL, solveRight=NULL){ # # if(is.null(solveLambdaInOld)){ # solveLambdaOld <- -log(cost) # solveLeft <- solveLambdaOld # solveRight <- NULL # dummyLambda <- numeric(length=(TopposInGridIn+1)) # if(length([email protected]@var.dx)==1){ # dN <- rep(0, (TopposInGridIn+1)) # #if(length(Time)==1){ # con <- (samp@grid[[1]] %in% Time) # dN[c(FALSE, con)[c(1:length(dN))]] <- as.numeric(simMod@[email protected][c(FALSE, con[-length(con)]),[email protected]@var.dx] # -simMod@[email protected][con,[email protected]@var.dx]) # #} # }else{ # # } # for(i in c(2:(TopposInGridIn+1))){ # posInGrid <- i # LastTime <- samp@grid[[1]][(posInGrid)] # LastStime <- samp@grid[[1]][c(1:(posInGrid-1))] # assign([email protected], LastTime, envir = my.env) # assign([email protected]@var.time, LastStime, envir = my.env) # assign(paste0("d",[email protected]@var.dx), dN[c(2:posInGrid)], envir =my.env) # dummyLambda[i] <- eval(ExprHaz[[1]], envir=my.env) # } # solveLambdaOld00 <- -log(cost)-sum(dummyLambda[c(sum(samp@grid[[1]]<=tail(Time,n=1L)):(TopposInGridIn+1))]) # if(solveLambdaOld*solveLambdaOld00<0){ # TotposInGrid<-samp@n # mylist <- list(InfTopposInGridInOld = min(TopposInGridIn,TotposInGrid), # supTopposInGridInOld = max(TopposInGridIn,TotposInGrid)) # if(mylist$InfTopposInGridInOld==TopposInGridIn){ # mylist$left <- TRUE # }else{ # mylist$left <- FALSE # } # mylist$TotposInGrid <- TopposInGridIn+1 # mylist$OldSolveLambda <- solveLambdaOld00 # mylist$solveLeft <- solveLambdaOld00 # mylist$solveRight <- solveRight # mylist$exit <- TRUE # mylist$Time <- c(Time,samp@grid[[1]][-1][mylist$TotposInGrid]) # mylist$IntensityProc <- c(IntensityProc, tail(dummyLambda,n=1L)) # return(mylist) # } # # }else{ # if(TopposInGridIn>1){ # solveLambdaOld <- solveLambdaInOld # }else{ # # dummyLambda <- numeric(length=(TopposInGridIn-1)) # if(length([email protected]@var.dx)==1){ # dN <- rep(0, (TopposInGridIn)) # dN[(TopposInGridIn)] <- as.numeric(simMod@[email protected][TopposInGridIn,[email protected]@var.dx] # -simMod@[email protected][TopposInGridIn-1,[email protected]@var.dx]) # }else{ # # } # for(i in c(2:(TopposInGridIn))){ # posInGrid <- i # LastTime <- samp@grid[[1]][(posInGrid)] # LastStime <- samp@grid[[1]][c(1:(posInGrid-1))] # assign([email protected], LastTime, envir = my.env) # assign([email protected]@var.time, LastStime, envir = my.env) # assign(paste0("d",[email protected]@var.dx), dN[c(1:posInGrid)], envir =my.env) # dummyLambda[i] <- eval(ExprHaz[[1]], envir=my.env) # } # # # solveLambdaOld <- -log(cost)-sum(dummyLambda) # # } # } # # TotposInGrid <- floor(abs((OldTimePoint)-TopposInGridIn)/2)+min(TopposInGridIn,(OldTimePoint)) # # cat(sprintf("\n%.5f ", TotposInGrid)) # # # dummyLambda <- numeric(length=(TotposInGrid-1)) # if(length([email protected]@var.dx)==1){ # dN <- rep(0, (TotposInGrid)) # con <- (samp@grid[[1]] %in% Time) # con[TotposInGrid-1] <- TRUE # dN[c(FALSE, con)[c(1:length(dN))]] <- as.numeric(simMod@[email protected][c(FALSE, con[-length(con)]),[email protected]@var.dx] # -simMod@[email protected][con,[email protected]@var.dx]) # }else{ # # } # for(i in c(2:(TotposInGrid))){ # posInGrid <- i # LastTime <- samp@grid[[1]][(posInGrid)] # LastStime <- samp@grid[[1]][c(1:(posInGrid-1))] # assign([email protected], LastTime, envir = my.env) # assign([email protected]@var.time, LastStime, envir = my.env) # assign(paste0("d",[email protected]@var.dx), dN[c(2:posInGrid)], envir =my.env) # dummyLambda[i] <- eval(ExprHaz[[1]], envir=my.env) # } # # # Solvelambda1 <- -log(cost)-sum(dummyLambda[c(sum(samp@grid[[1]]<=tail(Time,n=1L)):(TotposInGrid))]) # TotposInGridFin <- TotposInGrid # # if(Solvelambda1*solveLambdaOld < 0 | Solvelambda1*solveLambdaOld > 0){ # # if(solveLeft*Solvelambda1>0){ # #solveLeft<-Solvelambda1 # TotposInGridFin <- TotposInGridFin+1 # dummyLambda <- numeric(length=(TotposInGridFin)) # }else{ # #solveRight <- Solvelambda1 # TotposInGridFin <- TotposInGridFin-1 # dummyLambda <- numeric(length=(TotposInGridFin-1)) # } # # if(length([email protected]@var.dx)==1){ # dN <- rep(0, (TotposInGridFin)) # # dN[(TotposInGridFin)] <- as.numeric(simMod@[email protected][TotposInGridFin,[email protected]@var.dx] # # -simMod@[email protected][TotposInGridFin-1,[email protected]@var.dx]) # con <- (samp@grid[[1]] %in% Time) # con[TotposInGridFin-1] <- TRUE # dN[c(FALSE, con)[c(1:length(dN))]] <- as.numeric(simMod@[email protected][c(FALSE, con[-length(con)]),[email protected]@var.dx] # -simMod@[email protected][con,[email protected]@var.dx]) # }else{ # # } # for(i in c(2:(TotposInGridFin))){ # posInGrid <- i # LastTime <- samp@grid[[1]][(posInGrid)] # LastStime <- samp@grid[[1]][c(1:(posInGrid-1))] # assign([email protected], LastTime, envir = my.env) # assign([email protected]@var.time, LastStime, envir = my.env) # assign(paste0("d",[email protected]@var.dx), dN[c(2:posInGrid)], envir =my.env) # dummyLambda[i] <- eval(ExprHaz[[1]], envir=my.env) # } # # # Solvelambda2 <- -log(cost)-sum(dummyLambda[c(sum(samp@grid[[1]]<=tail(Time,n=1L)):(TotposInGridFin))]) # if(Solvelambda2*Solvelambda1<0){ # mylist <- list(InfTopposInGridInOld = min(TopposInGridIn,TotposInGridFin), # supTopposInGridInOld = max(TopposInGridIn,TotposInGridFin)) # if(mylist$InfTopposInGridInOld==TopposInGridIn){ # mylist$left <- TRUE # mylist$solveLeft <- solveLeft # mylist$solveRight <- Solvelambda2 # }else{ # mylist$left <- FALSE # mylist$solveRight <- solveRight # mylist$solveLeft <- Solvelambda2 # } # # TotposInGrid <- floor(abs(TotposInGrid-TopposInGridIn)/2)+min(TotposInGrid,TopposInGridIn) # # mylist$TotposInGrid <- TotposInGridFin # mylist$OldSolveLambda <- Solvelambda2 # # mylist$exit <- TRUE # # mylist$Time <- c(Time,my.env$t) # mylist$Time <- c(Time,samp@grid[[1]][-1][mylist$TotposInGrid]) # mylist$IntensityProc<- c(IntensityProc,tail(dummyLambda,n=1L)) # return(mylist) # }else{ # mylist <- list(InfTopposInGridInOld = min(TopposInGridIn,TotposInGridFin), # supTopposInGridInOld = max(TopposInGridIn,TotposInGridFin)) # # if(solveLambdaOld>Solvelambda2){ # mylist$left <- TRUE # mylist$solveLeft <- solveLeft # mylist$solveRight <- Solvelambda2 # }else{ # mylist$left <- FALSE # mylist$solveRight <- solveRight # mylist$solveLeft <- Solvelambda2 # } # } # # if(solveLambdaOld>0){ # # if(solveLambdaOld>Solvelambda2){ # # mylist$left <- TRUE # # }else{ # # TotposInGridFin <- TotposInGridFin-1 # # dummyLambda <- numeric(length=(TotposInGridFin-1)) # # } # # }else{ # # if(solveLambdaOld>Solvelambda1){ # # TotposInGridFin <- TotposInGridFin+1 # # dummyLambda <- numeric(length=(TotposInGridFin)) # # }else{ # # TotposInGridFin <- TotposInGridFin-1 # # dummyLambda <- numeric(length=(TotposInGridFin-1)) # # } # # } # # # TotposInGrid <- floor(abs(TotposInGrid-TopposInGridIn)/2)+min(TotposInGrid,TopposInGridIn) # # mylist$TotposInGrid <- TotposInGridFin # mylist$OldSolveLambda <- Solvelambda2 # mylist$exit <- FALSE # mylist$Time <- Time # mylist$IntensityProc <- IntensityProc # return(mylist) # #repeat # } # # if(Solvelambda1 == 0){ # mylist <- list(InfTopposInGridInOld = min(TopposInGridIn,TotposInGridFin), # supTopposInGridInOld = max(TopposInGridIn,TotposInGridFin)) # if(solveLambdaOld>=Solvelambda1){ # mylist$left <- TRUE # mylist$solveLeft <- solveLeft # mylist$solveRight <- Solvelambda1 # }else{ # mylist$left <- FALSE # mylist$solveRight <- solveRight # mylist$solveLeft <- Solvelambda1 # } # # TotposInGrid <- floor(abs(TotposInGrid-TopposInGridIn)/2)+min(TotposInGrid,TopposInGridIn) # # mylist$TotposInGrid <- TotposInGridFin # mylist$OldSolveLambda <- Solvelambda2 # mylist$exit <- TRUE # # mylist$Time <- c(Time,my.env$t) # mylist$Time <- c(Time,samp@grid[[1]][-1][mylist$TotposInGrid]) # mylist$IntensityProc<- c(IntensityProc,tail(dummyLambda,n=1L)) # return(mylist) # } # } # compErrHazR <- function(TopposInGrid, simMod, Kern, # samp, Model, my.env, ExprHaz, # cost, Time){ # dummyLambda <- numeric(length=(TopposInGrid)) # if(length([email protected]@var.dx)==1){ # dN <- rep(0, TopposInGrid) # # con <- (samp@grid[[1]] %in% c(Time[-1],samp@grid[[1]][TopposInGrid])) # dN[con[c(1:length(dN))]] <- as.numeric(simMod@[email protected][c(FALSE, con[-length(con)]),[email protected]@var.dx] # -simMod@[email protected][con,[email protected]@var.dx]) # }else{} # #for(i in c(1:TopposInGrid)){ # #MyPos # MyPos <- sum(samp@grid[[1]]<=tail(Time,n=1L)) # #dummyLambda <- numeric(length=TopposInGrid) # assign([email protected]@var.time, Time, envir = my.env) # for(i in c(MyPos:TopposInGrid)){ # posInGrid <- i # LastTime <- samp@grid[[1]][-1][(posInGrid)] # #LastStime <- samp@grid[[1]][c(1:posInGrid)] # assign([email protected], LastTime, envir = my.env) # #assign([email protected]@var.time, LastStime, envir = my.env) # #assign(paste0("d",[email protected]@var.dx), dN[c(1:posInGrid)], envir =my.env) # assign(paste0("d",[email protected]@var.dx), 1, envir =my.env) # dummyLambda[i] <- eval(ExprHaz[[1]], envir=my.env) # } # # solveLambda <- -log(cost)-sum(dummyLambda[c(sum(samp@grid[[1]]<=tail(Time,n=1L)):(TopposInGrid))])*samp@delta # solveLambda <- -log(cost)-sum(dummyLambda[c(MyPos:(TopposInGrid))])*samp@delta # res <- list(solveLambda = solveLambda, dummyLambda = tail(dummyLambda,n=1L)) # return(res) # } aux.simulatPPRROldVersion <- function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ Time <- sampling@Terminal numbVardx <- length(object@[email protected]) numbCountVar <- length(object@[email protected]) U <- runif(numbCountVar) my.env<- new.env() true.parameter <- unlist(true.parameter) if(!all(names(true.parameter)==object@PPR@allparam)){ yuima.stop("true.parameters mismatch the model parameters") } for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i],true.parameter[object@PPR@allparam[i]], envir = my.env) } assign("t",object@gFun@[email protected], envir = my.env) nameu <- object@gFun@[email protected] assign("dt",sampling@delta, envir = my.env) if(is.null(increment.W)){ dimW <- length(object@model@diffusion[[1]]) W <- matrix(rnorm(dimW*sampling@n,mean=0,sd= sqrt(sampling@delta)),nrow=dimW,ncol=sampling@n) } Condcovariate <- TRUE if(is.null(increment.L)){ dimL <- length(object@[email protected][[1]]) L <- matrix(0,nrow=dimL,ncol=sampling@n) Condcovariate <- FALSE # if(length(object@PPR@covariates)!=0) # Condcovariate <- TRUE cond <- !(object@[email protected] %in% object@[email protected]) if(any(cond)){ Condcovariate <- TRUE } dimMd <- length(object@[email protected]) dumMod <- setModel(drift = rep("0",dimMd), diffusion = matrix("0",dimMd,1), jump.coeff = diag("1",dimMd,dimMd), measure = object@[email protected]$measure, measure.type = object@[email protected]$type, solve.variable = object@[email protected]) if(length(object@model@parameter@measure)!=0){ simMod <- simulate(object = dumMod, true.parameter = true.parameter[object@model@parameter@measure], sampling = sampling) }else{ simMod <- simulate(object = dumMod, sampling = sampling) } L <- t(diff(simMod@[email protected])) } assign("Condcovariate",Condcovariate, envir = my.env) assign("W", W, envir = my.env) rownames(L)<- object@[email protected] assign("L", L, envir = my.env) assign("All.labKern",object@[email protected],envir = my.env) assign("All.labgFun",object@gFun@param,envir = my.env) Fun1 <- function(u,env){ part <- seq(0,u,by=env$dt) env$t<-part[-length(part)] if(Condcovariate){ yuima<- object@model for(i in c(1:length(object@PPR@covariates))){ assign(object@PPR@covariates[i], eval(yuima@xinit[[email protected]==object@PPR@covariates[i]], envir = env), envir = env) } if(u!=0){ # Mat<-matrix(0,length([email protected]),length(env$t)+1) # for(i in c(1:length([email protected]))){ # Mat[i,1] = eval(yuima@xinit[i],envir = env) # } Linc <- env$L[,c(1:(length(part)-1))] # Linc[[email protected]!=object@PPR@covariates,]<-matrix(0, # sum([email protected]!=object@PPR@covariates), dim(Linc)[2]) Linc[[email protected]!=object@PPR@covariates,] <- 0 DumUnderlMod <- simulate(yuima, true.parameter = true.parameter, increment.L = env$L[,c(1:(length(part)-1))], sampling = setSampling(Terminal = u, n= (length(part)-1))) for(i in c(1:length(object@PPR@covariates))){ VariableDum <- DumUnderlMod@[email protected][,[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } } } (log(env$U)+sum(eval(env$gFun,envir = env)*env$dt))^2 } Fun2 <- function(u,env){ u <- max(env$old_u,u) dumpart <- seq(0,env$old_u, by=env$dt) part <- seq(env$old_u,u,by=env$dt) t_k <- env$t env$t<-part[-length(part)] if(u>=sampling@Terminal){ # Think a better solution my.env$utrue<-u return(0) } if(Condcovariate){ LevIncr <- env$L[, length(dumpart)+c(1:(length(env$t)))] LevIncr[object@[email protected],]<-0 yuima<- object@model xinit<- numeric(length(object@PPR@covariates)) names(xinit)<- object@PPR@covariates for(i in c(1:length(object@PPR@covariates))){ xinit[i] <- env[[object@PPR@covariates[i]]] } xinitCount <- numeric(length(object@[email protected])) names(xinitCount) <- object@[email protected] for(i in c(1:length(xinitCount))){ xinitCount[i] <- tail(env[[object@[email protected][i]]],n = 1) } xinit <- c(xinit,xinitCount) if(part[length(part)]-part[1]!=0){ DumVarCov <- simulate(yuima, true.parameter = true.parameter, increment.L = LevIncr, sampling = setSampling(Terminal = (part[length(part)]-part[1]), n = dim(LevIncr)[2]), xinit=xinit[[email protected]]) for(i in c(1:length(object@PPR@covariates))){ VariableDum <- DumVarCov@[email protected][,[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } }else{ for(i in c(1:length(object@PPR@covariates))){ VariableDum <- xinit[[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } } #Insert Here simulation Covariate } integG <-sum(eval(env$gFun,envir = env)*env$dt) env$s <- unique(c(env$s,t_k))[-length(env$s)] dumt <- env$t num <- length(env$Kern) integKer <- 0 for(j in c(1:length(dumt))){ env$t <- dumt[j] dumKernInt <- 0 for(i in c(1:num)){ lab.dx <- [email protected][i] dumKernInt <- dumKernInt+sum(eval(env$Kern,envir=env)*diff(eval(env[[lab.dx]]))) } integKer <- integKer + dumKernInt } NewTerm <- 0 if(env$Condcovariate){ ## Insert Her } my.env$utrue<-u (log(env$U)+ integG + integKer+NewTerm)^2 } u <- numeric(length = numbCountVar) names(u) <- object@[email protected] for(i in c(1:numbCountVar)){ assign("gFun", object@gFun@formula[[i]], envir=my.env) assign("U",runif(1),envir = my.env) u[i]<- as.numeric(optim(0,Fun1,env=my.env)$par) } t_1 <- min(u) if(t_1>Time){ yuima.stop("No jump occurs in the considered time interval. Increasing Terminal in setSampling is suggested") } condt1<- u%in%t_1 namesContVarJump <- names(u[condt1]) JUMP <- matrix(0,nrow=numbCountVar,ncol=sampling@n) rownames(JUMP)<- object@[email protected] pos<-sum(sampling@grid[[1]][-1]<=t_1) t_1 <- sampling@grid[[1]][-1][pos] recordTime<-c(0,t_1) pos0<-0 JUMP[namesContVarJump, pos] <- L[namesContVarJump, pos] ntot <- sampling@n dL <- L dL[object@[email protected],c((pos0+1):pos)]<-JUMP[object@[email protected],c((pos0+1):pos)] X_mat <- matrix(0, length(object@[email protected]), ntot) rownames(X_mat) <- object@[email protected] dummyX <- simulate(object@model, true.parameter = true.parameter, increment.W = if(is.matrix(W[,1:pos])){W[,1:pos]}else{t(as.matrix(W[,1:pos]))}, increment.L = if(is.matrix(dL[,1:pos])){dL[,1:pos]}else{t(as.matrix(dL[,1:pos]))}, sampling = setSampling(Terminal = t_1, n = t_1/sampling@delta)) X_mat[,1:pos] <- t(dummyX@[email protected])[,-1] t_jump <- t_1 if(length(object@[email protected]@var.dx)==1){ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 1, diff) }else{ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 2, diff) } Index <- matrix(c(1:prod(object@Kernel@Integrand@dimIntegrand)), nrow = object@Kernel@Integrand@dimIntegrand[1], ncol = object@Kernel@Integrand@dimIntegrand[2]) assign(object@[email protected]@var.time, sampling@grid[[1]][c((pos0+1):(pos))], envir = my.env) assign(object@gFun@[email protected], t_1, envir = my.env) for(i in c(1:object@Kernel@Integrand@dimIntegrand[2])){ assign(object@[email protected]@var.dx[i], as.numeric(Comulat.dx[,i]), envir = my.env) } KernDum <- list() for(i in c(1:object@Kernel@Integrand@dimIntegrand[1])){ dumKern <- expression() for(j in c(1:object@Kernel@Integrand@dimIntegrand[2])){ id <- as.numeric(Index[i,j]) dumKern <- c(dumKern,object@Kernel@Integrand@IntegrandList[[id]]) } KernDum[[i]] <- dumKern } udumm <- numeric(length = numbCountVar) names(udumm) <- object@[email protected]@var.dx assign("L",dL,envir = my.env) pos0 <- pos assign("pos0", pos, envir = my.env) assign("old_u",t_1, envir = my.env) while(t_jump<Time){ oldt_1<-t_1 for(i in c(1:numbCountVar)){ assign("gFun", object@gFun@formula[[i]], envir=my.env) assign("Kern", KernDum[[i]], envir=my.env) my.env$utrue<-0 while(my.env$utrue<oldt_1){ assign("U",runif(1),envir = my.env) optim((t_1+2*my.env$dt),Fun2,method = "Nelder-Mead", env=my.env)$par u[i] <- as.numeric(my.env$utrue) } } t_1 <- min(u) condt1<- u%in%t_1 namesContVarJump <- names(u[condt1]) mypos<-sum(sampling@grid[[1]][-1]<=t_1) if((pos0+1)<mypos){ pos<-sum(sampling@grid[[1]][-1]<=t_1) t_jump<- t_1 t_1 <- sampling@grid[[1]][-1][pos] recordTime<-c(recordTime,t_1) #if(t_1!=sampling@Terminal){ pos <- min(pos,dim(L)[2]) JUMP[namesContVarJump, pos] <- L[namesContVarJump, pos] dL[object@[email protected],c((pos0+1):pos)]<-JUMP[object@[email protected],c((pos0+1):pos)] aa<-setSampling(Terminal = (t_1-my.env$old_u), n = length((pos0+1):pos)) dummyX <- simulate(object@model, true.parameter = true.parameter, increment.W = if(is.matrix(W[,(pos0+1):pos])){W[,(pos0+1):pos]}else{t(as.matrix(W[,(pos0+1):pos]))}, increment.L = if(is.matrix(dL[,(pos0+1):pos])){dL[,(pos0+1):pos]}else{t(as.matrix(dL[,(pos0+1):pos]))}, sampling = aa, xinit=X_mat[,(pos0)]) X_mat[,(pos0+1):pos] <- t(dummyX@[email protected])[,-1] if(length(object@[email protected]@var.dx)==1){ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 1, diff) }else{ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 2, diff) } if(!is.matrix(Comulat.dx)){ Comulat.dx <-t(as.matrix(Comulat.dx)) } Index <- matrix(c(1:prod(object@Kernel@Integrand@dimIntegrand)), nrow = object@Kernel@Integrand@dimIntegrand[1], ncol = object@Kernel@Integrand@dimIntegrand[2]) assign(object@[email protected]@var.time, sampling@grid[[1]][c((pos0+1):(pos))], envir = my.env) assign(object@gFun@[email protected], t_1, envir = my.env) for(i in c(1:object@Kernel@Integrand@dimIntegrand[2])){ assign(object@[email protected]@var.dx[i], as.numeric(Comulat.dx[,i]), envir = my.env) } pos0<-pos assign("pos0", pos, envir = my.env) assign("old_u",t_1, envir = my.env) #} } assign("L",dL,envir = my.env) } X_mat[namesContVarJump,pos]<-X_mat[namesContVarJump,pos] res.dum <- list(X_mat=X_mat,timeJump = recordTime, grid=sampling) solve.variable <-unique(c(object@[email protected])) N.VarPPR<-length(solve.variable) dummy.mod <- setModel(drift=rep("0",N.VarPPR), diffusion = NULL, jump.coeff = diag(rep("1",N.VarPPR)), measure = object@[email protected]$measure, measure.type = object@[email protected]$type, solve.variable = solve.variable, xinit=c(object@model@xinit)) mynewincr <- if(is.matrix(res.dum$X_mat)){t(as.matrix(apply(cbind(0,res.dum$X_mat),1,diff)))}else{apply(cbind(0,res.dum$X_mat),1,diff)} interResMod <- simulate(object = dummy.mod, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) resGfun<-new("yuima.Map", Output = object@gFun, yuima=setYuima(model=dummy.mod,sampling = sampling)) interResGfun <- simulate(object = resGfun, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) dummyObject <- object@Kernel [email protected]@out.var <-object@[email protected] resInt <- new("yuima.Integral", Integral = dummyObject, yuima = setYuima(model=dummy.mod,sampling = sampling)) interResInt <- simulate(object = resInt, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) DataIntensity <- interResGfun@[email protected] + interResInt@[email protected] InterMDia<-zoo(interResMod@[email protected], order.by = index(DataIntensity)) Alldata <-merge(InterMDia,DataIntensity) colnames(Alldata)<-c(solve.variable,object@[email protected]) # for(i in c(1:N.VarPPR)){ # assign(solve.variable[i],interRes@[email protected][,i],envir=my.env) # } # dummy<-NULL # for(t in c(1:length(object@[email protected]))){ # dummy <-eval(object@gFun) # assign(object@[email protected][[]]) # } object@data<-setData(Alldata) return(object) } # simOzaki.aux<-function(gFun,a,cCoeff, Time, numJump){ # t_k<-0 # N<-0 # S<-1 # # T_k<-c(t_k) # # N_k<-c(N) # U<-runif(1) # t_k <- -log(U)/gFun # if(t_k<Time){ # T_k<-c(T_k,t_k) # N<-N+numJump # N_k<-c(N_k, N) # } # while(t_k<=Time){ # U<-runif(1) # optim.env<-new.env() # assign("U",U,envir=optim.env) # assign("t_k",t_k,envir=optim.env) # assign("c",cCoeff,envir=optim.env) # assign("a",a,envir=optim.env) # assign("S",S,envir=optim.env) # assign("gFun",gFun,envir=optim.env) # # min<-function(u,env){ # U<-env$U # t_k<-env$t_k # c<-env$c # a<-env$a # S<-env$S # gFun<-env$gFun # y<-(log(U)+gFun*(u-t_k)+c/a*S*(1-exp(-a*(u-t_k))))^2 # } # y<-optim(par=t_k,min, env=optim.env )$par # S<- exp(-a*(y-t_k))*S+1 # t_k<-y # T_k<-c(T_k,t_k) # N<-N+numJump # N_k<-c(N_k, N) # } # return(list(T_k=T_k,N_k=N_k)) # }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simulateForPpr.R
# setMethod("simulate", "yuima.multimodel", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, #Initial = 0, Terminal = 1, n = 100, delta, # grid, random = FALSE, sdelta=as.numeric(NULL), # sgrid=as.numeric(NULL), interpolation="none" ...){ tmpsamp <- NULL if(missing(sampling)){ tmpsamp <- setSampling(...) # tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, n = n, # delta = delta, grid = grid, random = random, sdelta=sdelta, # sgrid=sgrid, interpolation=interpolation) } else { tmpsamp <- sampling } tmpyuima <- setYuima(model=object, sampling=tmpsamp) out <- simulate(tmpyuima, nsim=nsim, seed=seed, xinit=xinit, true.parameter=true.parameter, space.discretized=space.discretized, increment.W=increment.W, increment.L=increment.L, method=method, hurst=hurst,methodfGn=methodfGn, subsampling=subsampling) return(out) }) aux.simulate.multimodel<-function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L,method, hurst=0.5,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation){ ##:: errors checks if(is(object@model@measure$df,"yuima.law")&& is.null(increment.L)){ samp<- object@sampling randomGenerator<-object@model@measure$df if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n[1] if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise<- rand(object = randomGenerator, n=NumbIncr, param=measureparam) }else{ # Just For Irregular Grid tForMeas<-diff(samp@grid[[1]]-samp@Initial) my.InternalFunforLevy<-function(tForMeas, randomGenerator, true.parameter,object){ if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise<- rand(object = randomGenerator, n=samp@n[1], param=measureparam) } Noise<-sapply(X=tForMeas, FUN=my.InternalFunforLevy, randomGenerator=randomGenerator, true.parameter=true.parameter, object=object) } increment.L=Noise if(is(object@model@measure$df,"yuima.law")&&!is.null(increment.L)){ dummy<-object dummy@model@measure$df <- expression() if(missing(xinit)){ res<- aux.simulate.multimodel(object=dummy, nsim, xinit=object@model@xinit ,seed, true.parameter, space.discretized, increment.W, increment.L = t(increment.L), method, hurst, methodfGn, sampling=object@sampling) }else{ res<- aux.simulate.multimodel(object=dummy, nsim, xinit, seed, true.parameter, space.discretized, increment.W, increment.L = increment.L, method, hurst, methodfGn, sampling=object@sampling) } res@model <- object@model if(missing(subsampling)) return(res) return(subsampling(res, subsampling)) } } ##:1: error on yuima model yuima <- object samp <- object@sampling if(missing(yuima)){ yuima.warn("yuima object is missing.") return(NULL) } tmphurst<-yuima@model@hurst if(!missing(hurst)){ yuima@model@hurst=hurst } if (is.na(yuima@model@hurst)){ yuima.warn("Specify the hurst parameter.") return(NULL) } tmpsamp <- NULL if(is.null(yuima@sampling)){ if(missing(sampling)){ tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, n = n, delta = delta, grid = grid, random = random, sdelta=sdelta, sgrid=sgrid, interpolation=interpolation) } else { tmpsamp <- sampling } } else { tmpsamp <- yuima@sampling } yuima@sampling <- tmpsamp sdeModel <- yuima@model Terminal <- yuima@sampling@Terminal[1] n <- yuima@sampling@n[1] r.size <- [email protected] d.size <- [email protected] ##:2: error on xinit if(missing(xinit)){ xinit <- sdeModel@xinit } else { if(length(xinit) != d.size){ if(length(xinit)==1){ xinit <- rep(xinit, d.size) } else { yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } } xinit <- as.expression(xinit) # force xinit to be an expression par.len <- length(sdeModel@parameter@all) if(missing(true.parameter) & par.len>0){ true.parameter <- vector(par.len, mode="list") for(i in 1:par.len) true.parameter[[i]] <- 0 names(true.parameter) <- sdeModel@parameter@all } yuimaEnv <- new.env() if(par.len>0){ for(i in 1:par.len){ pars <- sdeModel@parameter@all[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(sdeModel@parameter@all[i], true.parameter[[j]],yuimaEnv) } } #assign(sdeModel@parameter@all[i], true.parameter[[i]], yuimaEnv) } } if(space.discretized){ if(r.size>1){ warning("Space-discretized EM cannot be used for multi-dimentional models. Use standard method.") space.discretized <- FALSE } if(length([email protected])){ warning("Space-discretized EM is for only Wiener Proc. Use standard method.") space.discretized <- FALSE } } ##:: Error check for increment specified version. if(!missing(increment.W) & !is.null(increment.W)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.W)[1] != r.size){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.W)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } ##:: Error check for increment specified version. if(!missing(increment.L) & !is.null(increment.L)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.L)[1] != length(yuima@[email protected][[1]]) ){ #r.size){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.L)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } yuimaEnv$dL <- increment.L if(space.discretized){ ##:: using Space-discretized Euler-Maruyama method yuima@data <- space.discretized(xinit, yuima, yuimaEnv) yuima@model@hurst<-tmphurst return(yuima) } ##:: using Euler-Maruyama method delta <- samp@delta if(missing(increment.W) | is.null(increment.W)){ if( sdeModel@hurst!=0.5 ){ grid<-sampling2grid(yuima@sampling) isregular<-yuima@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, sdeModel@hurst,r.size) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, sdeModel@hurst,r.size) } } else { delta<-samp@delta if(!is.Poisson(sdeModel)){ # if pure CP no need to setup dW dW <- rnorm(n * r.size, 0, sqrt(delta)) dW <- matrix(dW, ncol=n, nrow=r.size,byrow=TRUE) } else { dW <- matrix(0,ncol=n,nrow=1) # maybe to be fixed } } } else { dW <- increment.W } # if(is.Poisson(sdeModel)){ # yuima@data <- simCP(xinit, yuima, yuimaEnv) # } else { # yuima@data <- euler(xinit, yuima, dW, yuimaEnv) # } if(is(sdeModel,"yuima.multimodel")&&!is(sdeModel@measure$df,"yuima.law")){ if(length([email protected])==1){ if([email protected]=="CP"){ intens <- as.character(sdeModel@measure$intensity) dens <- as.character(sdeModel@measure$df$expr) dumCP <- setPoisson(intensity = intens, df = dens, dimension = length([email protected][[1]])) dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = dummSamp@Terminal, n = dummSamp@n) traj <- simulate(object = dumCP, sampling = samp, true.parameter = true.parameter) Incr.levy <- diff(traj@[email protected][[1]]) if(length(traj@[email protected])>1){ for(i in c(2:length(traj@[email protected]))){ Incr.levy<-cbind(Incr.levy,diff(traj@[email protected][[i]])) } } }else{ dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = dummSamp@Terminal, n = dummSamp@n) xinitCode <- yuima@model@xinit dimJumpCoeff <- length(yuima@[email protected][[1]]) dumjumpCoeff <- matrix(as.character(diag(rep(1,dimJumpCoeff))),dimJumpCoeff,dimJumpCoeff) Dumsolve.variable<-paste0("MyLevyDum",c(1:dimJumpCoeff)) if(!is(sdeModel@measure$df,"yuima.law")){ LevyMod <- setMultiModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, df = as.character(sdeModel@measure$df$expr), measure.type = [email protected], solve.variable = Dumsolve.variable) }else{ LevyMod <- setModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, measure = sdeModel@measure, measure.type = [email protected], solve.variable = Dumsolve.variable) } yuimaLevy <- setYuima(model=LevyMod, sampling = samp) yuimaLevy@model@dimension <- dimJumpCoeff traj<- simCode(xinit=xinitCode,yuima = yuimaLevy, env=yuimaEnv) Incr.levy <- diff(traj@[email protected][[1]]) if(length(traj@[email protected])>1){ for(i in c(2:length(traj@[email protected]))){ Incr.levy<-cbind(Incr.levy,diff(traj@[email protected][[i]])) } } #yuima.stop("code multivariate Levy will be implemented as soon as possible") } }else{ if(any([email protected]=="CP")){ intens <- as.character(sdeModel@measure$intensity) dens <- as.character(sdeModel@measure$df$expr) # If we consider independence between CP and the Other Levy # we have: numbLev <- length([email protected]) posCPindex <- c(1:numbLev)[[email protected]%in%"CP"] CPmeasureComp <- paste0(dens,"[,c(",toString(posCPindex),")]") intens <- as.character(sdeModel@measure$intensity) dumCP <- setPoisson(intensity = intens, df = CPmeasureComp, dimension = length(posCPindex)) # Simulation CP part dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = unique(dummSamp@Terminal), n = unique(dummSamp@n)) trajCP <- simulate(object = dumCP, sampling = samp, true.parameter = true.parameter) dimJumpCoeff <- length(yuima@[email protected]) dumjumpCoeff <- matrix(as.character(diag(rep(1,dimJumpCoeff))),dimJumpCoeff,dimJumpCoeff) Dumsolve.variable <- paste0("MyLevyDum",c(1:dimJumpCoeff)) dummy.measure.code <- as.character(sdeModel@measure$df$expr) LevyMod <- setMultiModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, df = dummy.measure.code, measure.type = "code", solve.variable = Dumsolve.variable) yuimaLevy <- setYuima(model=LevyMod, sampling = samp) yuimaLevy@model@dimension <- dimJumpCoeff trajcode<- simCode(xinit=rep("0",length=dimJumpCoeff), yuima = yuimaLevy, env=yuimaEnv) countCP <- 0 countcode <- 0 if(yuima@[email protected][1]=="CP"){ Incr.levy <- as.matrix(as.numeric(diff(trajCP@[email protected][[1]]))) countcode <- countcode+1 }else{ if(yuima@[email protected][1]=="code"){ Incr.levy <- as.matrix(as.numeric(diff(trajcode@[email protected][[1]]))) countCP <- countCP+1 } } if(length(yuima@[email protected])>1){ for(i in c(2:length(yuima@[email protected]))){ if(yuima@[email protected][i]=="CP"){ Incr.levy<-cbind(Incr.levy,as.numeric(diff(trajCP@[email protected][[(i-countCP)]]))) countcode <- countcode+1 }else{ if(yuima@[email protected][i]=="code"){ Incr.levy <- cbind(Incr.levy,as.numeric(diff(trajcode@[email protected][[i]]))) countCP <- countCP+1 } } } } # yuima.stop("Levy with CP and/or code") } } } if(!is.null(increment.L)) Incr.levy<-t(increment.L) assign("dL",t(Incr.levy),envir=yuimaEnv) sim <- Multi.Euler(xinit,yuima,dW,env=yuimaEnv) yuima@[email protected]<-as.list(numeric(length=length([email protected]))) #LM nov2016 # yuima@[email protected]<[email protected] for(i in 1:length(yuima@[email protected])){ yuima@[email protected][[i]]<[email protected][[i]] index(yuima@[email protected][[i]]) <- yuima@sampling@grid[[1]] }## to be fixed yuima@[email protected] <- [email protected] yuima@model@xinit <- xinit yuima@model@hurst <-tmphurst if(missing(subsampling)) return(yuima) subsampling(yuima, subsampling) } simCode <- function(xinit,yuima,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] Terminal <- yuima@sampling@Terminal[1] Initial <- yuima@sampling@Initial[1] dimension <- yuima@model@dimension dummy.val <- numeric(dimension) if(length(xinit) != dimension) xinit <- rep(xinit, dimension)[1:dimension] if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],envir=env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, envir=env) if(length(dummy.val)==1){ dummy.val<-rep(dummy.val,dimension) } for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,envir=env) } } else { for(i in 1:dimension){ dummy.val[i] <- eval(xinit[i], envir=env) } } ### Simulation of CP using Lewis' method ##:: Levy JP <- eval([email protected][[1]], envir=env) mu.size <- length(JP) # print(str(JP)) #assign(sdeModel@measure$intensity, env) ## intensity param # .CPintensity <- function(.t) { # assign(modeltime, .t, envir=env) # eval(sdeModel@measure$intensity, envir=env) # } dummyList<-as.list(env) lgth.meas<-length(yuima@model@parameter@measure) if(lgth.meas>1){ for(i in c(2:lgth.meas)){ idx.dummy<-yuima@model@parameter@measure[i] assign(idx.dummy,as.numeric(dummyList[idx.dummy])) } } # we use Lewis' acceptance/rejection method #if(grep("^[dexp|dnorm|dgamma|dconst]", sdeModel@measure$df$expr)){ ##:: e.g. dnorm(z,1,1) -> rnorm(mu.size*N_sharp,1,1) #gsub("^d(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", sdeModel@measure$df$expr, perl=TRUE) #} else{ #stop("Sorry. CP only supports dconst, dexp, dnorm and dgamma yet.") #} if(!is(sdeModel@measure$df,"yuima.law")){ dumStringMeas <- toString(sdeModel@measure$df$expr) dumStringMeas1 <- substr(x=dumStringMeas, start=2,stop=nchar(x = dumStringMeas)) dumStringMeas2 <- paste0("r",dumStringMeas1) tmpMeas2 <- strsplit(x=dumStringMeas2,split="") posMeas2 <- match("(" , tmpMeas2[[1]])[1] dumStringMeas3 <- substr(x=dumStringMeas2, start=1,stop=(posMeas2-1)) a<-deparse(args(eval(parse(text=dumStringMeas3))))[1] b<-gsub("^function (.+?)","(",a) b1 <- substr(x=b,start =1, stop=(nchar(b)-1)) FinalMeasRandn<-paste0(dumStringMeas3,b1) dummyvarMaes <- all.vars(parse(text=FinalMeasRandn)) posDum<- match(c([email protected],sdeModel@parameter@measure),dummyvarMaes) if(length(posDum)+1!=length(dummyvarMaes)){ yuima.stop("too input variables in the random number function") } deltaVar <- dummyvarMaes[-posDum] # ell <- optimize(f=.CPintensity, interval=c(Initial, Terminal), maximum = TRUE)$objective # ellMax <- ell * 1.01 F <- suppressWarnings(parse(text=gsub("^r(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", parse(text=FinalMeasRandn), perl=TRUE))) F.env <- new.env(parent=env) N_sharp <- unique(yuima@sampling@n) TrueDelta <- unique(yuima@sampling@delta) assign(deltaVar, TrueDelta, envir=F.env) assign("mu.size", mu.size, envir=F.env) assign("N_sharp", N_sharp, envir=F.env) randJ <- eval(F, envir=F.env) ## this expression is evaluated in the F.env randJ <- rbind(dummy.val, randJ) }else{ TrueDelta <- unique(yuima@sampling@delta) randJ<- env$dL } RANDLevy <- apply(randJ,2,cumsum) tsX <- zoo(x=RANDLevy) yuimaData <- setYuima(data=setData(tsX, delta=TrueDelta)) #yuimaData <- subsampling(yuimaData, sampling=yuima@sampling) return(yuimaData) } Multi.Euler<-function(xinit,yuima,dW,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] Terminal <- yuima@sampling@Terminal[1] n <- yuima@sampling@n[1] dL <- env$dL # dX <- xinit # 06/11 xinit is an expression: the structure is equal to that of V0 if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } # 06/11 we need a initial variable for X_0 dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } ##:: set time step delta <- Terminal/n ##:: check if DRIFT and/or DIFFUSION has values has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) #print(is.Poisson(sdeModel)) ##:: function to calculate coefficients of dW(including drift term) ##:: common used in Wiener and CP p.b <- function(t, X=numeric(d.size)){ ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) ##:: solve diffusion term if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { ##:: no drift term (faster) tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ # we do not need to evaluate diffusion for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } # for j } # foh i } # !is.Poisson } # else return(tmp) } X_mat <- matrix(0, d.size, n+1) X_mat[,1] <- dX if(has.drift){ ##:: consider drift term to be one of the diffusion term(dW=1) dW <- rbind( rep(1, n)*delta , dW) } if(!length([email protected])){ ##:: Wiener Proc ##:: using Euler-Maruyama method if(var.in.diff & (!is.Poisson(sdeModel))){ ##:: diffusions have state variables and it is not Poisson ##:: calcurate difference eq. for( i in 1:n){ dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] X_mat[,i+1] <- dX } }else{ ##:: diffusions have no state variables (not use p.b(). faster) sde.tics <- seq(0, Terminal, length=(n+1)) sde.tics <- sde.tics[2:length(sde.tics)] X_mat[, 1] <- dX ##:: assign names of variables for(i in 1:length(modelstate)){ assign(modelstate[i], dX[i]) } assign(modeltime, sde.tics) t.size <- length(sde.tics) ##:: solve diffusion term if(has.drift){ pbdata <- matrix(0, d.size*(r.size+1), t.size) for(i in 1:d.size){ pbdata[(i-1)*(r.size+1)+1, ] <- eval(V0[i], env) for(j in 1:r.size){ pbdata[(i-1)*(r.size+1)+j+1, ] <- eval(V[[i]][j], env) } } dim(pbdata)<-(c(r.size+1, d.size*t.size)) }else{ pbdata <- matrix(0, d.size*r.size, t.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ pbdata[(i-1)*r.size+j, ] <- eval(V[[i]][j], env) } # for j } # for i } # !is.Poisson dim(pbdata)<-(c(r.size, d.size*t.size)) } # else pbdata <- t(pbdata) ##:: calcurate difference eq. for( i in 1:n){ if(!is.Poisson(sdeModel)) dX <- dX + pbdata[((i-1)*d.size+1):(i*d.size), ] %*% dW[, i] X_mat[, i+1] <- dX } } tsX <- ts(data=t(X_mat), deltat=delta , start=0) }else{ ##:: Levy JP <- [email protected] mu.size <- length(JP) # cat("\n Levy\n") ##:: function to solve c(x,z) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) # tmp <- numeric(d.size) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) # cat("\n inside\n") #print(dim(tmp)) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } # tmp[i] <- eval(JP[i], env) } return(tmp) } # print(ls(env)) ### WHY I AM DOING THIS? # tmp <- matrix(0, d.size, r.size) # #for(i in 1:d.size){ # for(j in 1:r.size){ # cat("\n here\n") # tmp[i,j] <- eval(V[[i]][j],env) # } # for j # } ### # if([email protected] == "CP" ){ ##:: Compound-Poisson type # # ##:: delete 2010/09/13 for simulate func bug fix by s.h # ## eta0 <- eval(sdeModel@measure$intensity) # # ##:: add 2010/09/13 for simulate func bug fix by s.h # eta0 <- eval(sdeModel@measure$intensity, env) ## intensity param # # ##:: get lambda from nu() # tmp.expr <- function(my.x){ # assign([email protected],my.x) # return(eval(sdeModel@measure$df$expr)) # } # #lambda <- integrate(sdeModel@measure$df$func, 0, Inf)$value * eta0 # #lambda <- integrate(tmp.expr, 0, Inf)$value * eta0 ##bug:2013/10/28 # # dummyList<-as.list(env) # # print(str(dummyList)) # #print(str(idx.dummy)) # lgth.meas<-length(yuima@model@parameter@measure) # if(lgth.meas>1){ # for(i in c(2:lgth.meas)){ # idx.dummy<-yuima@model@parameter@measure[i] # #print(i) # #print(yuima@model@parameter@measure[i]) # assign(idx.dummy,as.numeric(dummyList[idx.dummy])) # } # } # # # #lambda <- integrate(tmp.expr, -Inf, Inf)$value * eta0 # # ##:: lambda = nu() (p6) # N_sharp <- rpois(1,Terminal*eta0) ##:: Po(Ne) # if(N_sharp == 0){ # JAMP <- FALSE # }else{ # JAMP <- TRUE # Uj <- sort( runif(N_sharp, 0, Terminal) ) # ij <- NULL # for(i in 1:length(Uj)){ # Min <- min(which(c(1:n)*delta > Uj[i])) # ij <- c(ij, Min) # } # } # # ##:: make expression to create iid rand J # if(grep("^[dexp|dnorm|dgamma|dconst]", sdeModel@measure$df$expr)){ # ##:: e.g. dnorm(z,1,1) -> rnorm(mu.size*N_sharp,1,1) # F <- suppressWarnings(parse(text=gsub("^d(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", sdeModel@measure$df$expr, perl=TRUE))) # }else{ # stop("Sorry. CP only supports dconst, dexp, dnorm and dgamma yet.") # } # # ##:: delete 2010/09/13 for simulate func bug fix by s.h # ## randJ <- eval(F) ## this expression is evaluated locally not in the yuimaEnv # # ##:: add 2010/09/13 for simulate func bug fix by s.h # F.env <- new.env(parent=env) # assign("mu.size", mu.size, envir=F.env) # assign("N_sharp", N_sharp, envir=F.env) # # randJ <- eval(F, F.env) ## this expression is evaluated in the F.env # # j <- 1 # for(i in 1:n){ # if(JAMP==FALSE || sum(i==ij)==0){ # Pi <- 0 # }else{ # if(is.null(dL)){ # J <- eta0*randJ[j]/lambda # j <- j+1 # ##cat(paste(J,"\n")) # ##Pi <- zeta(dX, J) # assign([email protected], J, env) # # if([email protected]){ # J <- 1 # } # # Pi <- p.b.j(t=i*delta,X=dX) * J # }else{# we add this part since we allow the user to specify the increment of CP LM 05/02/2015 # Pi <- p.b.j(t=i*delta,X=dX) %*% dL[, i] # } # ##Pi <- p.b.j(t=i*delta, X=dX) # } # dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] + Pi # X_mat[, i+1] <- dX # } # tsX <- ts(data=t(X_mat), deltat=delta, start=0) # ##::end CP # }else if([email protected]=="code"){ ##:: code type # ##:: Jump terms # code <- suppressWarnings(sub("^(.+?)\\(.+", "\\1", sdeModel@measure$df$expr, perl=TRUE)) # args <- unlist(strsplit(suppressWarnings(sub("^.+?\\((.+)\\)", "\\1", sdeModel@measure$df$expr, perl=TRUE)), ",")) # #print(args) # dZ <- switch(code, # rNIG=paste("rNIG(n, ", args[2], ", ", args[3], ", ", args[4], "*delta, ", args[5], "*delta, ", args[6],")"), # rIG=paste("rIG(n,", args[2], "*delta, ", args[3], ")"), # rgamma=paste("rgamma(n, ", args[2], "*delta, ", args[3], ")"), # rbgamma=paste("rbgamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], "*delta, ", args[5], ")"), # ## rngamma=paste("rngamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], ", ", args[5], "*delta, ", args[6], ")"), # rngamma=paste("rngamma(n, ", args[2], "*delta, ", args[3], ", ", args[4], ", ", args[5], "*delta,", args[6],")"), # ## rstable=paste("rstable(n, ", args[2], ", ", args[3], ", ", args[4], ", ", args[5], ", ", args[6], ")") # rstable=paste("rstable(n, ", args[2], ", ", args[3], ", ", args[4], "*delta^(1/",args[2],"), ", args[5], "*delta)") # ) # dummyList<-as.list(env) # #print(str(dummyList)) # lgth.meas<-length(yuima@model@parameter@measure) # #print(lgth.meas) # if(lgth.meas!=0){ # for(i in c(1:lgth.meas)){ # #print(i) # #print(yuima@model@parameter@measure[i]) # idx.dummy<-yuima@model@parameter@measure[i] # #print(str(idx.dummy)) # assign(idx.dummy,dummyList[[idx.dummy]]) # #print(str(idx.dummy)) # #print(str(dummyList[[idx.dummy]])) # #print(get(idx.dummy)) # } # } # if(is.null(dZ)){ ##:: "otherwise" # cat(paste("Code \"", code, "\" not supported yet.\n", sep="")) # return(NULL) # } # if(!is.null(dL)) dZ <- dL # else # dZ <- eval(parse(text=dZ)) ##:: calcurate difference eq. #print(str(dZ)) # if(is.null(dim(dZ))) # dZ <- matrix(dZ,nrow=1) # print(dim(dZ)) # print(str([email protected])) for(i in 1:n){ assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } # cat("\np.b.j call\n") tmp.j <- p.b.j(t=i*delta, X=dX) #print(str(tmp.j)) #cat("\np.b.j cback and dZ\n") # print(str(dZ[,i])) # print(sum(dim(tmp.j))) #print(str(tmp.j)) #print(str(p.b(t = i * delta, X = dX) %*% dW[, i])) dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] X_mat[, i+1] <- dX } tsX <- ts(data=t(X_mat), deltat=delta, start=0) ##::end code # }else{ # cat(paste("Type \"", [email protected], "\" not supported yet.\n", sep="")) # return(NULL) # } }##::end levy yuimaData <- setData(original.data=tsX) return(yuimaData) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/simulateMultiProcess.R
# library(KernSmooth) setMethod("show", "yuima.snr", function (object){ cat("\nCall:\n") print(object@call) cat("\nCoefficients:\n") print(object@coef) } ) snr<-function(yuima,start,lower,upper,withdrift=FALSE){ if(yuima@[email protected] == 1){ data <- get.zoo.data(yuima) s.size<-yuima@sampling@n modelstate<-yuima@[email protected] modeltime<-yuima@[email protected] DRIFT<-yuima@model@drift DIFFUSION<-yuima@model@diffusion PARLENGS<-length(yuima@model@parameter@drift)+length(yuima@model@parameter@diffusion) XINIT<-yuima@model@xinit X<-as.numeric(data[[1]]) dX <- abs(diff(X)) odX <- sort(dX, decreasing=TRUE) plot(yuima,main="Original path") abline(0,0,lty=5) pX<-X[1:(s.size-1)] sY<-as.numeric(data[[1]]) derDIFFUSION<-D(DIFFUSION[[1]],modelstate) tmp.env<-new.env() inc<-double(s.size-1) inc<-X[2:(s.size)]-pX preservedinc<-inc ainc<-abs(inc) oinc<-sort(ainc,decreasing=TRUE) yuima@[email protected] <- list() yuima@model@measure <- list() yuima@[email protected] <- character(0) yuima@[email protected] <- character(0) yuima@model@parameter@jump <- character(0) yuima@model@parameter@measure <- character(0) #yuima@model@drift<-expression((0)) qmle<-qmle(yuima, start = start, lower = lower, upper = upper) # initial estimation parameter<-yuima@model@parameter@all mp<-match(names(qmle@coef),parameter) esort <- qmle@coef[order(mp)] for(i in 1:length(qmle@coef)) { assign(parameter[i],esort[[i]],envir=tmp.env) } resi<-double(s.size-1) derv<-double(s.size-1) total<-c() j.size<-c() assign(modeltime,yuima@sampling@delta,envir=tmp.env) h<-yuima@sampling@delta assign(modelstate,pX,envir=tmp.env) diff.term<-eval(DIFFUSION[[1]],envir=tmp.env) drif.term<-eval(DRIFT,envir=tmp.env) if(length(diff.term)==1){ diff.term <- rep(diff.term, s.size) } if(length(drif.term)==1){ drif.term <- rep(drif.term, s.size) } # vectorization (note. if an expression type object does not include state.variable, the length of the item after "eval" operation is 1.) for(s in 1:(s.size-1)){ nova<-sqrt((diff.term)^2) # normalized variance resi[s]<-(1/(nova[s]*sqrt(h)))*(inc[s]-h*withdrift*drif.term[s]) } # assign(modelstate,pX,envir=tmp.env) # derv<-eval(derDIFFUSION,envir=tmp.env) # if(length(derv)==1){ # derv<-rep(derv,s.size) # vectorization # } mresi<-mean(resi) vresi<-mean((resi-mresi)^2) snr<-(resi-mresi)/sqrt(vresi) plot(snr,main="Raw self-normalized residual") # h <- dpih(snr) # bins <- seq(min(snr)-0.1, max(snr)+0.1+h, by=h) # hist(snr, prob=1, breaks=bins,xlim=c(-3,3),ylim=c(0,1)) hist(snr, freq = FALSE, breaks = "freedman-diaconis", xlim=c(min(snr),max(snr)),ylim=c(0,1)) xval <- seq(min(snr),max(snr),0.01) # to add plot the corresponding density lines(xval,dnorm(xval,0,1),xlim=c(min(snr),max(snr)),ylim=c(0,1),col="red",main="Jump removed self-normalized residual") call <- match.call() final_res <- new("yuima.snr", call = call, coef = qmle@coef[order(mp)], snr = snr, model = yuima@model) return(final_res) }else{ yuima.stop("This function currently works only for one-dimensional case.") } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/snr.R
## Local Method of Moments estimator lmm <- function(x, block = 20, freq = 50, freq.p = 10, K = 4, interval = c(0, 1), Sigma.p = NULL, noise.var = "AMZ", samp.adj = "direct", psd = TRUE){ Data <- get.zoo.data(x) d.size <- length(Data) N <- sapply(Data,"length") - 1 n <- min(N) interval <- as.numeric(interval) freq.p <- min(freq.p,freq) if(d.size > 1){ # Constructing the stpectral statistics and noise level estimates Spec <- array(0,dim=c(d.size,block,freq)) H <- matrix(0,d.size,block) cH <- array(0,dim=c(d.size^2,block,freq)) zmat <- diag(d.size^2) phi.br <- (block*pi*(1:freq))^2 for(p in 1:d.size){ dY <- diff(as.numeric(Data[[p]])) Time <- (as.numeric(time(Data[[p]])) - interval[1])/(interval[2] - interval[1]) if((min(Time) < 0) || (max(Time) > 1)){ print("lmm:invalid interval") return(NULL) } Time2 <- (Time[1:N[p]]+Time[-1])/2 k.idx <- findInterval(Time2,vec=seq(0,1,by=1/block)) # Noise variance if(is.numeric(noise.var)){ sq.eta <- noise.var[p] }else{ sq.eta <- switch(noise.var, "BR" = mean(dY^2)/2, # Bandi and Russel (2006) "O" = -sum(dY[-N[p]] * dY[-1])/N[p], # Oomen (2006) "AMZ" = {tmp <- arima0(dY,order=c(0,0,1),include.mean=FALSE); -tmp$coef * tmp$sigma2} # Ait-Sahalia et al. (2005) ) } # Effect of irregularity if(is.numeric(samp.adj)){ EOI <- samp.adj[p, ] }else{ EOI <- switch(samp.adj, "QVT" = block * rowsum(diff(Time)^2,group = findInterval(Time[-1],vec=seq(0,1,by=1/block), rightmost.closed = TRUE)), "direct" = block * rowsum((diff(Time,lag=2)/2)^2, group = k.idx[-N[p]])) } Spec[p,,] <- sqrt(2*block)* rowsum(sin(tcrossprod(pi*(block*Time2-(k.idx-1)),1:freq))*dY, group = k.idx) H[p, ] <- sq.eta * EOI cH[d.size*(p-1)+p,,] <- tcrossprod(H[p,],phi.br) for(q in 1:d.size){ tmp.mat <- diag(0, d.size) tmp.mat[p, q] <- 1 zmat <- zmat + tmp.mat %x% t(tmp.mat) } } #summand <- apply(Spec,c(2,3),FUN="tcrossprod") - cH summand <- array(.C("krprod", as.double(Spec), as.integer(d.size), as.integer(block*freq), result=double(d.size^2*block*freq))$result, dim=c(d.size^2,block,freq)) - cH if(is.null(Sigma.p)){ # Pilot estimation of Sigma # Using K adjacent blocks following Bibinger et al. (2014a) #Sigma.p <- rollmean(t(rowMeans(array(summand[,,1:freq.p], # dim=c(d.size^2,block,freq.p)), # dims = 2)),k = K, fill = "e") # Recent version of Bibinger et al. (2014b) Sigma.p <- rollapply(t(rowMeans(array(summand[,,1:freq.p], dim=c(d.size^2,block,freq.p)), dims = 2)), width = 2*K + 1, FUN="mean", partial = TRUE) } # Local method of moments Sigma <- matrix(0,d.size^2,block) inv.Ik <- array(0,dim=c(d.size^2,d.size^2,block)) for(k in 1:block){ tmp <- double(d.size^2) H.inv <- diag(1/H[,k]) tmp.eigen <- eigen(matrix(Sigma.p[k,], d.size, d.size) %*% H.inv, symmetric=FALSE) inv.V <- solve(tmp.eigen$vectors) iHV <- H.inv %*% tmp.eigen$vectors iHVxiHV <- iHV %x% iHV inv.VxV <- inv.V %x% inv.V #Lambda <- apply(1/outer(tmp.eigen$values, phi.br, FUN="+"), # 2,FUN="tcrossprod") Lambda <- matrix(.C("krprod", as.double(1/outer(tmp.eigen$values, phi.br, FUN="+")), as.integer(d.size), as.integer(freq), result=double(d.size^2*freq))$result,d.size^2,freq) #Lambda <- KhatriRao(1/outer(tmp.eigen$values, phi.br, FUN="+")) inv.Ik[,,k] <- solve(iHVxiHV %*% diag(rowSums(Lambda)) %*% inv.VxV) Sigma[,k] <- inv.Ik[,,k] %*% iHVxiHV %*% rowSums(Lambda * inv.VxV %*% summand[,k,]) } cmat <- matrix(rowMeans(Sigma), d.size, d.size) vcov <- rowMeans(inv.Ik, dims = 2) %*% zmat/block if(psd){ r <- eigen(cmat, symmetric = TRUE) cmat <- r$vectors %*% abs(diag(r$values)) %*% t(r$vectors) r <- eigen(vcov, symmetric = TRUE) vcov <- r$vectors %*% abs(diag(r$values)) %*% t(r$vectors) } result <- list(covmat = cmat, vcov = vcov, Sigma.p = Sigma.p) class(result) <- "yuima.specv" }else{ # Constructing the stpectral statistics and noise level estimates dY <- diff(as.numeric(Data[[1]])) Time <- (as.numeric(time(Data[[1]])) - interval[1])/(interval[2] - interval[1]) if((min(Time) < 0) || (max(Time) > 1)){ print("lmm:invalid interval") return(NULL) } Time2 <- (Time[1:N]+Time[-1])/2 k.idx <- findInterval(Time2,vec=seq(0,1,by=1/block)) # Noise variance if(is.numeric(noise.var)){ sq.eta <- noise.var }else{ sq.eta <- switch(noise.var, "BR" = mean(dY^2)/2, # Bandi and Russel (2006) "O" = -sum(dY[-N] * dY[-1])/N, # Oomen (2006) "AMZ" = {tmp <- arima0(dY,order=c(0,0,1),include.mean=FALSE); -tmp$coef * tmp$sigma2} # Ait-Sahalia et al. (2005) ) } phi.br <- (block*pi*(1:freq))^2 # Effect of irregularity if(is.numeric(samp.adj)){ EOI <- samp.adj }else{ EOI <- switch(samp.adj, "QVT" = block * rowsum(diff(Time)^2,group = findInterval(Time[-1],vec=seq(0,1,by=1/block), rightmost.closed = TRUE)), "direct" = block * rowsum((diff(Time,lag=2)/2)^2, group = k.idx[-N])) } Spec <- sqrt(2*block)* rowsum(sin(tcrossprod(pi*(block*Time2-(k.idx-1)),1:freq))*dY, group = k.idx) H <- sq.eta * EOI cH <- tcrossprod(H,phi.br) summand <- Spec^2 - cH if(is.null(Sigma.p)){ # Pilot estimation of Sigma # Using K adjacent blocks following Bibinger et al. (2014a) #Sigma.p <- rollmean(rowMeans(matrix(summand[,1:freq.p],block,freq.p)), # k = K, fill = "e") # Recent version of Bibinger et al. (2014b) Sigma.p <- rollapply(rowMeans(matrix(summand[,1:freq.p], block,freq.p)), width = 2*K + 1, FUN="mean", partial = TRUE) } Ijk <- 1/(Sigma.p + cH)^2 inv.Ik <- 1/rowSums(Ijk) if(psd){ cmat <- abs(sum(Ijk*inv.Ik*summand)/block) }else{ cmat <- sum(Ijk*inv.Ik*summand)/block } result <- list(covmat = as.matrix(cmat), vcov = as.matrix(2 * mean(inv.Ik)/block), Sigma.p = Sigma.p) class(result) <- "yuima.specv" } return(result) } # print method for yuima.specv-class print.yuima.specv <- function(x, ...){ cat("Estimated covariance matrix\n") print(x$covmat, ...) cat("Standard Error\n") print(matrix(sqrt(diag(x$vcov)), ncol = ncol(x$covmat)), ...) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/spectralcov.R
##:: function subsampling ##:: takes any yuima object with data or a yuima.data object and ##:: performs subsampling according to some method # poisson.random.sampling # returns sample of data using poisson sampling setGeneric("subsampling", function(x, sampling, ...) standardGeneric("subsampling") ) setMethod("subsampling","yuima", function(x, sampling, ...){ obj <- NULL if(missing(sampling)){ obj <- subsampling(x@data, setSampling(...)) } else { obj <- subsampling(x@data, sampling=sampling) } obj@model <- x@model return(obj) } ) setMethod("subsampling", "yuima.data", function(x, sampling=sampling){ #tmpsamp <- NULL #if(missing(sampling)){ # tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, # delta = delta, grid = grid, random = random, sdelta=sdelta, # sgrid=sgrid, interpolation=interpolation) #} else { tmpsamp <- sampling #} Data <- get.zoo.data(x) n.data <- length(Data) tmpgrid <- vector(n.data, mode="list") tmpsamp@grid <- rep(tmpsamp@grid, n.data)[1:n.data] # prepares a grid of times if(is.logical(tmpsamp@random)){ if(tmpsamp@random) stop("wrong random sampling specification") if(length(tmpsamp@delta) < n.data) tmpsamp@delta <- rep( tmpsamp@delta, n.data)[1:n.data] for(i in 1:n.data){ tmpgrid[[i]] <- tmpsamp@grid[[i]] #seq(start(Data[[i]]), end(Data[[i]]), by=tmpsamp@delta[i]) tmpsamp@regular[i] <- TRUE tmpsamp@random[i] <- FALSE } } # random sampling if(is.list(tmpsamp@random)){ rdist <- c(tmpsamp@random$rdist) if(is.null(rdist)) stop("provide at least `rdist' argument for random sampling") n.rdist <- length(rdist) r.gen <- rep( rdist, n.data) # eventually reciclying arguments r.gen <- r.gen[1:n.data] for(i in 1:n.data){ tmptime <- start(Data[[i]]) T <- end(Data[[i]]) while( sum( tmptime ) < T ) tmptime <- c(tmptime, r.gen[[i]](1)) tmpgrid[[i]] <- cumsum(tmptime) if(tail(tmpgrid[[i]],1)>T) tmpgrid[[i]] <- tmpgrid[[i]][-length(tmpgrid[[i]])] } } # prepares original index slot oindex <- vector(n.data, mode="list") # checks for interpolation method, if not in the list uses "pt" interpolation <- tmpsamp@interpolation int.methods <- c("previous", "pt", "next", "nt", "none", "exact", "lin", "linear") if(! (interpolation %in% int.methods) ) interpolation <- "pt" for(i in 1:n.data){ oindex[[i]] <- time(Data[[i]]) idx <- numeric(0) newData <- NULL lGrid <- length(tmpgrid[[i]]) if( interpolation %in% c("previous", "pt")){ idx <- as.numeric(sapply(tmpgrid[[i]], function(x) max(which(oindex[[i]] <= x)))) newData <- sapply(1:lGrid, function(x) as.numeric(Data[[i]][idx[x]])) oindex[[i]] <- sapply(1:lGrid, function(x) time(Data[[i]])[idx[x]]) } if( interpolation %in% c("next", "nt")){ idx <- as.numeric(sapply(tmpgrid[[i]], function(x) min(which(oindex[[i]] >= x)))) newData <- sapply(1:lGrid, function(x) as.numeric(Data[[i]][idx[x]])) oindex[[i]] <- sapply(1:lGrid, function(x) time(Data[[i]])[idx[x]]) } if( interpolation %in% c("none", "exact")){ idx <- match(tmpgrid[[i]], oindex[[i]]) newData <- sapply(1:lGrid, function(x) as.numeric(Data[[i]][idx[x]])) oindex[[i]] <- sapply(1:lGrid, function(x) time(Data[[i]])[idx[x]]) } if( interpolation %in% c("lin", "linear")){ idx.l <- as.numeric(sapply(tmpgrid[[i]], function(x) max(which(oindex[[i]] <= x)))) idx.r <- as.numeric(sapply(tmpgrid[[i]], function(x) min(which(oindex[[i]] >= x)))) f.int <- function(u) (as.numeric(Data[[i]][idx.r[u]])+as.numeric(Data[[i]][idx.l[u]]))/2 newData <- sapply(1:lGrid, f.int ) oindex[[i]] <- sapply(1:lGrid, function(u) time(Data[[i]])[idx.l[u]]) } Data[[i]] <- zoo(newData, order.by=tmpgrid[[i]]) tmpsamp@Terminal[i] <- end(Data[[i]]) tmpsamp@Initial[i] <- start(Data[[i]]) tmpsamp@n[i] <- length(Data[[i]]) } tmpsamp@oindex <- oindex tmpsamp@grid <- tmpgrid tmpsamp@regular <- sapply(1:n.data, function(x) sum(abs(diff(diff(tmpgrid[[x]]))))<1e-3) tmpsamp@delta <- sapply(1:n.data, function(x) ifelse(tmpsamp@regular[x], diff(tmpgrid[[x]])[1], numeric(0))) obj <- NULL tmpsamp@interpolation <- interpolation [email protected] <- Data obj <- setYuima(data=x, sampling=tmpsamp) return(obj) } ### end method )
/scratch/gouwar.j/cran-all/cranData/yuima/R/subsampling.R
toLatex.yuima <- function (object, ...) { mod <- NULL #if (class(object) == "yuima.model") if (inherits(object, "yuima.model")) # fixed by YK mod <- object #if (class(object) == "yuima.carma") if (inherits(object, "yuima.carma")) # fixed by YK mod <- object #if (class(object) == "yuima.cogarch") if (inherits(object, "yuima.cogarch")) # fixed by YK mod <- object #if (class(object) == "yuima") if (inherits(object, "yuima")) # fixed by YK mod <- object@model #if(class(mod) =="yuima.carma" && length(mod@[email protected])==0 ) #if((class(mod) =="yuima.carma") || (class(mod) =="yuima.cogarch") ) if(inherits(mod, "yuima.carma") || inherits(mod, "yuima.cogarch")) # fixed by YK { # yuima.warn("") mysymb <- c("*", "alpha", "beta", "gamma", "delta", "rho", "theta","sigma","mu", "sqrt") # myrepl <- c(" \\cdot ", "\\alpha ", "\\beta ", "\\gamma ", # "\\delta ", "\\rho ", "\\theta ", "\\sqrt ") myrepl <- c(" \\cdot ", "\\alpha ", "\\beta ", "\\gamma ", "\\delta ", "\\rho ", "\\theta ","\\sigma","\\mu", "\\sqrt ") ns <- length(mysymb) n.eq <- [email protected] info <- mod@info noise.var<-"W" # We construc the system that describes the CARMA(p,q) process if (!length([email protected])==0){noise.var <- [email protected]} dr <- paste("\\left\\{\\begin{array}{l} \n") main.con <- [email protected] #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK if(length([email protected])==0 && !length([email protected])==0){ main.con<-paste([email protected],"* \\ ", [email protected]) } if(!length([email protected])==0 && length([email protected])==0){ main.con<-paste([email protected],"+ \\ ", [email protected]) } if(!length([email protected])==0 && !length([email protected])==0){ main.con<-paste([email protected],"+ \\ ",[email protected],"* \\ ", [email protected]) } }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK main.con<-paste([email protected],"+ \\ ", [email protected]) } } #if((class(mod) =="yuima.carma")){ if(inherits(mod, "yuima.carma")){ # fixed by YK dr <- paste(dr, [email protected], "\\left(", sprintf("%s", [email protected]),"\\right) = ",main.con, "'" , [email protected],"\\left(", sprintf("%s", [email protected]),"\\right) \\\\ \n") }else{ #if((class(mod) =="yuima.cogarch")){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK dr <- paste(dr, sprintf("d%s", [email protected]), "\\left(", sprintf("%s", [email protected]),"\\right) = \\ sqrt{",[email protected], "\\left(", sprintf("%s", [email protected]),"\\right)} \\ ", sprintf("d%s", noise.var),"\\left(", sprintf("%s", [email protected]),"\\right) \\\\ \n") dr <- paste(dr, [email protected], "\\left(", sprintf("%s", [email protected]),"\\right) = ",main.con, "'" , [email protected],"\\left(", sprintf("%s", [email protected]),"\\right) \\\\ \n") } } #if((class(mod) =="yuima.carma")){ if(inherits(mod, "yuima.carma")){ # fixed by YK noise.latent.var <- noise.var }else{ #if((class(mod) =="yuima.cogarch")){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK noise.latent.var <- paste0("\\left[",noise.var,",",noise.var,"\\right]^{q}") } } dr <- paste(dr, sprintf("d%s", [email protected]), "\\left(", sprintf("%s", [email protected]),"\\right)", "=","A",[email protected], "\\left(", sprintf("%s", [email protected]),"\\right)", sprintf("d%s", [email protected]), "+ e",sprintf("d%s", noise.latent.var),"\\left(", [email protected], "\\right) \\\\ \n") dr<- paste(dr, "\\end{array}\\right.") #11/12 for (i in 1:ns) { dr <- gsub(mysymb[i], myrepl[i], dr, fixed = "TRUE") } body <- paste("%%% Copy and paste the following output in your LaTeX file") body <- c(body, paste("$$")) body <- c(body, dr) body <- c(body, paste("$$")) # Vector Latent Variable. body <- c(body, paste("$$")) #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK latent.lab0<-paste([email protected],0:(info@p-1),sep="_") }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK latent.lab0<-paste([email protected],1:info@q,sep="_") } } if(length(latent.lab0)==1){latent.lab<-latent.lab0} if(length(latent.lab0)==2){ latent.lab0[1]<-paste(latent.lab0[1],"(",[email protected],")",",\\ ",sep="") latent.lab0[2]<-paste(latent.lab0[2],"(",[email protected],")",sep="") latent.lab<-latent.lab0 } if(length(latent.lab0)>2){ latent.lab<-paste(latent.lab0[1],"(",[email protected],")", ",\\ ","\\ldots \\ ", ",\\ ",tail(latent.lab0,n=1), "(",[email protected],")") } latent.lab<-paste(latent.lab,collapse="") X<-paste([email protected],"(",[email protected],")", "=\\left[",latent.lab, "\\right]'") for (i in 1:ns) { X <- gsub(mysymb[i], myrepl[i], X, fixed = "TRUE") } body <- c(body, X) body <- c(body, paste("$$")) # Vector Moving Average Coefficient. body <- c(body, paste("$$")) #b.nozeros <-c(0:info@q) # ma.lab0<-paste(paste([email protected],0:(info@q),sep="_"),collapse=", \\ ") #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK ma.lab0<-paste([email protected],0:(info@q),sep="_") }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK ma.lab0<-paste([email protected],1:(info@p),sep="_") } } #if(length(ma.lab0)==1){ma.lab1<-ma.lab0} #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK if(info@q>=0 && info@q<=1){ ma.lab1<-paste(ma.lab0,collapse=", \\ ")} #if(length(ma.lab0)==2){ # if(info@q==1){ # ma.lab0[1]<-paste(ma.lab0[1],",\\ ",sep="") # # ma.lab0[2]<-paste(ma.lab0[2],"(",[email protected],")",sep="") # ma.lab1<-ma.lab0 # } #if(length(ma.lab0)>2){ if(info@q>1){ ma.lab1<-paste(ma.lab0[1], ",\\ ","\\ldots", " \\ , \\ ",tail(ma.lab0,n=1)) } }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK if(info@p>=0 && info@p<=2){ ma.lab1<-paste(ma.lab0,collapse=", \\ ") } if(info@p>2){ ma.lab1<-paste(ma.lab0[1], ",\\ ","\\ldots", " \\ , \\ ",tail(ma.lab0,n=1)) } } } #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK numb.zero<-(info@p-(info@q+1)) }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK numb.zero<-(info@q-info@p) } } if (numb.zero==0){ma.lab <- ma.lab1} if (numb.zero>0&&numb.zero<=2){ zeros<- 0*c(1:numb.zero) zero.el <- paste(zeros, collapse=", \\ ") ma.lab <- paste(ma.lab1," ,\\ ", zero.el) } if (numb.zero>2 ){ ma.lab <- paste(ma.lab1," ,\\ 0, \\ \\ldots \\ , \\ 0") } Vector.ma <- paste([email protected],"=","\\left[",ma.lab,"\\right]'") for (i in 1:ns) { Vector.ma <- gsub(mysymb[i], myrepl[i], Vector.ma, fixed = "TRUE") } body <- c(body, Vector.ma) body <- c(body, paste("$$")) # e vector body <- c(body, paste("$$")) noise.coef<-mod@diffusion vect.e0 <- substr(tail(noise.coef,n=1), 13, nchar(tail(noise.coef,n=1)) -2) vect.e1 <- substr(vect.e0, 2, nchar(vect.e0) -1) dummy.e0<-strsplit(vect.e1,split="+",fixed=TRUE) if (!length([email protected])==0){ noise.coef <- [email protected] #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK vect.e0 <- substr(tail(noise.coef,n=1), 18, nchar(tail(noise.coef,n=1)) -2) }else{ vect.e0 <- substr(tail(noise.coef,n=1), 18, nchar(tail(noise.coef,n=1)) -2) } #vect.e0 <- substr(tail(noise.coef,n=1), 2, nchar(tail(noise.coef,n=1)) -1) } else{ if(length([email protected]) != 0){ if ([email protected] != [email protected]){ dummy.e0<-c(dummy.e0[[1]][1], paste(dummy.e0[[1]][(2:length(dummy.e0[[1]]))], "(",[email protected],")",sep="")) dummy.e0<-gsub([email protected],paste0([email protected],"_",collapse=""),dummy.e0) dummy.e0<-gsub([email protected],paste0([email protected],"_",collapse=""),dummy.e0) if(length(dummy.e0)>3){ vect.e0<-paste(dummy.e0[1],"+",dummy.e0[2], "+ \\ldots +",tail(dummy.e0,n=1)) vect.e0<-paste("(",vect.e0,")") } else{vect.e0<-paste("(",paste(dummy.e0,collapse="+"),")")} } # else{ # yuima.warm("The case of loc.par and scale.par will be implemented as soon as possible") # return(NULL) # } } } #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK if (info@p==1){vect.e <- vect.e0} if (info@p==2){vect.e <- paste("0, \\ ",vect.e0)} if (info@p==3){vect.e <- paste("0, \\ 0, \\ ",vect.e0)} if (info@p>3){vect.e <- paste("0, \\ \\ldots \\ , \\ 0, \\ ",vect.e0)} }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK if (info@q==1){vect.e <- vect.e0} if (info@q==2){vect.e <- paste("0, \\ ",vect.e0)} if (info@q==3){vect.e <- paste("0, \\ 0, \\ ",vect.e0)} if (info@q>3){vect.e <- paste("0, \\ \\ldots \\ , \\ 0, \\ ",vect.e0)} } } coeff.e<- paste("e","=","\\left[", vect.e , "\\right]'") for (i in 1:ns) { coeff.e <- gsub(mysymb[i], myrepl[i], coeff.e, fixed = "TRUE") } body <- c(body, coeff.e) body <- c(body, paste("$$")) # Matrix A body <- c(body, paste("$$")) #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK Up.A<-NULL } #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK if(info@p==1){ cent.col<-"c" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@p:1,sep="_"),collapse=" &") } }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK if(info@q==1){ cent.col<-"c" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@q:1,sep="_"),collapse=" &") } } } #if(class(mod)=="yuima.carma"){ if(inherits(mod, "yuima.carma")){ # fixed by YK if(info@p==2){ cent.col<-"cc" Up.A <-" 0 & 1 \\\\ \n" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@p:1,sep="_"),collapse=" &") } if(info@p==3){ cent.col<-"ccc" Up.A <-" 0 & 1 & 0 \\\\ \n 0 & 0 & 1 \\\\ \n" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@p:1,sep="_"),collapse=" &") } if(info@p>3){ cent.col<-"cccc" Up.A <-" 0 & 1 & \\ldots & 0 \\\\ \n \\vdots & \\vdots & \\ddots & \\vdots \\\\ \n 0 & 0 & \\ldots & 1 \\\\ \n" dummy.ar<-paste(paste("",[email protected],sep=" -"),info@p:1,sep="_") last.A <- paste(dummy.ar[1]," & ", dummy.ar[2]," & \\ldots &", tail(dummy.ar,n=1) ) } }else{ #if(class(mod)=="yuima.cogarch"){ if(inherits(mod, "yuima.cogarch")){ # fixed by YK if(info@q==2){ cent.col<-"cc" Up.A <-" 0 & 1 \\\\ \n" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@q:1,sep="_"),collapse=" &") } if(info@q==3){ cent.col<-"ccc" Up.A <-" 0 & 1 & 0 \\\\ \n 0 & 0 & 1 \\\\ \n" last.A<-paste(paste(paste("",[email protected],sep=" -"),info@q:1,sep="_"),collapse=" &") } if(info@q>3){ cent.col<-"cccc" Up.A <-" 0 & 1 & \\ldots & 0 \\\\ \n \\vdots & \\vdots & \\ddots & \\vdots \\\\ \n 0 & 0 & \\ldots & 1 \\\\ \n" dummy.ar<-paste(paste("",[email protected],sep=" -"),info@q:1,sep="_") last.A <- paste(dummy.ar[1]," & ", dummy.ar[2]," & \\ldots &", tail(dummy.ar,n=1) ) } } } matrix.A <-paste(Up.A ,last.A," \\\\ \n",sep="") array.start<-paste0("\\begin{array}{",cent.col,"}\n",collapse="") MATR.A<-paste("A ","=","\\left[",array.start, matrix.A, "\\end{array}\\right]" ) for (i in 1:ns) { MATR.A <- gsub(mysymb[i], myrepl[i], MATR.A, fixed = "TRUE") } body <- c(body, MATR.A) body <- c(body, paste("$$")) body <- structure(body, class = "Latex") return(body) } else{ n.eq <- [email protected] dr <- NULL if(n.eq>1) dr <- paste("\\left(\\begin{array}{c}\n") for (i in 1:n.eq) { dr <- paste(dr, substr(mod@drift[i], 2, nchar(mod@drift[i]) -1)) if(n.eq>1) dr <- paste(dr, "\\\\ \n") # dr <- paste(dr, substr(mod@drift[i], 3, nchar(mod@drift[i]) - 2), "\\\\ \n") } # if(n.eq>1) dr <- paste(dr, "\\end{array}\\right)") dr <- paste(dr, sprintf("d%s", [email protected])) n.n <- [email protected] df <- NULL if(n.eq>1 & n.n>1) df <- paste(sprintf("\\left[\\begin{array}{%s}\n",paste(rep("c",n.n),sep="",collapse=""))) for (i in 1:n.eq) { #df <- paste(df, paste(mod@diffusion[[i]], collapse = "&")) if( n.eq>1 & n.n>1){ df <- paste(df, paste(substr(mod@diffusion[[i]], 2, nchar(mod@diffusion[[i]]) - 1) , collapse = "&")) df <- paste(df, "\\\\ \n") } else { df <- paste(df, paste(substr(mod@diffusion[[i]], 2, nchar(mod@diffusion[[i]]) - 1) , collapse = "")) } } if(n.eq>1 & n.n>1) df <- paste(df, "\\end{array}\\right]") # We consider the Jump 6/11 dj <- NULL if (length([email protected])>=1){ if(n.eq>1) dj<-paste("\\left(\\begin{array}{c}\n") for (i in 1:n.eq) { if(n.eq>1){ dj <- paste(dj, substr([email protected][[i]], 2, nchar([email protected][[i]]) - 1), "\\\\ \n") } else { dj <- paste(dj, substr([email protected][[i]], 2, nchar([email protected][[i]]) - 1)) } #dj <- paste(dj, [email protected][i], "\\\\ \n") } if(n.eq>1) dj <- paste(dj, "\\end{array}\\right)", sprintf("d %s", [email protected])) } wn <- NULL if( n.n>1){ wn <- paste("\\left(\\begin{array}{c}\n") } if(n.n>1){ wn <- paste(wn, paste(sprintf("dW%s", 1:n.n), sep = "", collapse = "\\\\ ")) } else { wn <- paste(wn, "dW1") } if( n.n>1){ wn <- paste(wn, "\n \\end{array}\\right)") } st <- NULL if(n.eq>1) st <- paste("\\left(\\begin{array}{c}\n") for(i in 1:n.eq){ st <- paste(st, sprintf("d%s", [email protected][i])) if(n.eq>1) st <- paste(st, " \\\\ ") } if(n.eq>1) st <- paste(st, "\n \\end{array}\\right)") mysymb <- c("*", "alpha", "beta", "gamma", "delta", "rho", "theta","sigma","mu", "sqrt") # myrepl <- c(" \\cdot ", "\\alpha ", "\\beta ", "\\gamma ", # "\\delta ", "\\rho ", "\\theta ", "\\sqrt ") myrepl <- c(" \\cdot ", "\\alpha ", "\\beta ", "\\gamma ", "\\delta ", "\\rho ", "\\theta ","\\sigma","\\mu", "\\sqrt ") ns <- length(mysymb) for (i in 1:ns) { dr <- gsub(mysymb[i], myrepl[i], dr, fixed = "TRUE") df <- gsub(mysymb[i], myrepl[i], df, fixed = "TRUE") # for Jump if (length([email protected])>=1){ dj <- gsub(mysymb[i], myrepl[i], dj, fixed = "TRUE") } } body <- paste("%%% Copy and paste the following output in your LaTeX file") body <- c(body, paste("$$")) body <- c(body, paste(st)) body <- c(body, paste(" = ")) body <- c(body, paste(dr)) body <- c(body, paste(" +")) body <- c(body, paste(df)) # body <- c(body, paste("")) body <- c(body, paste(wn)) # For Jump 6/11 if (length([email protected])>=1){ body <- c(body, paste(" +")) body <- c(body, paste(dj)) body <- c(body, "dZ") } body <- c(body, paste("$$")) body <- c(body, paste("$$")) # For Initial Conditions numb.solve.var <- length([email protected]) bodyaus <- NULL if(numb.solve.var >1){ bodyaus <- "\\left(\\begin{array}{c}\n" } for (i in 1:numb.solve.var) { bodyaus <- paste(bodyaus, paste(paste([email protected][i],"(0)",sep=""),substr(mod@xinit[i], 2, nchar(mod@xinit[i]) - 1),sep="=")) if(numb.solve.var>1) bodyaus <-paste(bodyaus, "\\\\ \n") # paste(bodyaus, paste(paste([email protected][i],"(0)",sep=""),substr(mod@xinit[i], 3, nchar(mod@xinit[i]) - 2),sep="="), "\\\\ \n") # paste(bodyaus, paste(paste([email protected][i],"(0)",sep=""),substr(mod@xinit[i], 2, nchar(mod@xinit[i]) - 1),sep="="), "\\\\ \n") } if(numb.solve.var >1){ bodyaus <- paste(bodyaus, "\\end{array}\\right)") } for (i in 1:ns) { bodyaus <- gsub(mysymb[i], myrepl[i], bodyaus, fixed = "TRUE") } body<-c(body,paste(bodyaus)) # body <- c(body, paste(sprintf("%s(0)=%f,\\quad", [email protected], # mod@xinit))) body <- c(body, paste("$$")) structure(body, class = "Latex") } } toLatex.yuima.model <- toLatex.yuima toLatex.yuima.carma <- toLatex.yuima toLatex.yuima.cogarch <- toLatex.yuima
/scratch/gouwar.j/cran-all/cranData/yuima/R/toLatex.R
# Scale-by-scale lead-lag estimation by wavelets ## function to compute Daubechies' extremal phase wavelet filter ## The function is based on implementation of wavethresh package daubechies.wavelet <- function(N){ switch (N, "1" = { H <- rep(0, 2) H[1] <- 1/sqrt(2) H[2] <- H[1] }, "2" = { H <- rep(0, 4) H[1] <- 0.482962913145 H[2] <- 0.836516303738 H[3] <- 0.224143868042 H[4] <- -0.129409522551 }, "3" = { H <- rep(0, 6) H[1] <- 0.33267055295 H[2] <- 0.806891509311 H[3] <- 0.459877502118 H[4] <- -0.13501102001 H[5] <- -0.085441273882 H[6] <- 0.035226291882 }, "4" = { H <- rep(0, 8) H[1] <- 0.230377813309 H[2] <- 0.714846570553 H[3] <- 0.63088076793 H[4] <- -0.027983769417 H[5] <- -0.187034811719 H[6] <- 0.030841381836 H[7] <- 0.032883011667 H[8] <- -0.010597401785 }, "5" = { H <- rep(0, 10) H[1] <- 0.160102397974 H[2] <- 0.603829269797 H[3] <- 0.724308528438 H[4] <- 0.138428145901 H[5] <- -0.242294887066 H[6] <- -0.032244869585 H[7] <- 0.07757149384 H[8] <- -0.006241490213 H[9] <- -0.012580752 H[10] <- 0.003335725285 }, "6" = { H <- rep(0, 12) H[1] <- 0.11154074335 H[2] <- 0.494623890398 H[3] <- 0.751133908021 H[4] <- 0.315250351709 H[5] <- -0.226264693965 H[6] <- -0.129766867567 H[7] <- 0.097501605587 H[8] <- 0.02752286553 H[9] <- -0.031582039318 H[10] <- 0.000553842201 H[11] <- 0.004777257511 H[12] <- -0.001077301085 }, "7" = { H <- rep(0, 14) H[1] <- 0.077852054085 H[2] <- 0.396539319482 H[3] <- 0.729132090846 H[4] <- 0.469782287405 H[5] <- -0.143906003929 H[6] <- -0.224036184994 H[7] <- 0.071309219267 H[8] <- 0.080612609151 H[9] <- -0.038029936935 H[10] <- -0.016574541631 H[11] <- 0.012550998556 H[12] <- 0.000429577973 H[13] <- -0.001801640704 H[14] <- 0.0003537138 }, "8" = { H <- rep(0, 16) H[1] <- 0.054415842243 H[2] <- 0.312871590914 H[3] <- 0.675630736297 H[4] <- 0.585354683654 H[5] <- -0.015829105256 H[6] <- -0.284015542962 H[7] <- 0.000472484574 H[8] <- 0.12874742662 H[9] <- -0.017369301002 H[10] <- -0.044088253931 H[11] <- 0.013981027917 H[12] <- 0.008746094047 H[13] <- -0.004870352993 H[14] <- -0.000391740373 H[15] <- 0.000675449406 H[16] <- -0.000117476784 }, "9" = { H <- rep(0, 18) H[1] <- 0.038077947364 H[2] <- 0.243834674613 H[3] <- 0.60482312369 H[4] <- 0.657288078051 H[5] <- 0.133197385825 H[6] <- -0.293273783279 H[7] <- -0.096840783223 H[8] <- 0.148540749338 H[9] <- 0.030725681479 H[10] <- -0.067632829061 H[11] <- 0.000250947115 H[12] <- 0.022361662124 H[13] <- -0.004723204758 H[14] <- -0.004281503682 H[15] <- 0.001847646883 H[16] <- 0.000230385764 H[17] <- -0.000251963189 H[18] <- 3.934732e-05 }, "10" = { H <- rep(0, 20) H[1] <- 0.026670057901 H[2] <- 0.188176800078 H[3] <- 0.527201188932 H[4] <- 0.688459039454 H[5] <- 0.281172343661 H[6] <- -0.249846424327 H[7] <- -0.195946274377 H[8] <- 0.127369340336 H[9] <- 0.093057364604 H[10] <- -0.071394147166 H[11] <- -0.029457536822 H[12] <- 0.033212674059 H[13] <- 0.003606553567 H[14] <- -0.010733175483 H[15] <- 0.001395351747 H[16] <- 0.001992405295 H[17] <- -0.000685856695 H[18] <- -0.000116466855 H[19] <- 9.358867e-05 H[20] <- -1.3264203e-05 } ) return(H) } ## function to compute autocorrelation wavelets autocorrelation.wavelet <- function(J, N){ h <- daubechies.wavelet(N) Phi1 <- convolve(h, h, type = "o") out <- vector(mode = "list", J) out[[1]] <- (-1)^((-2*N+1):(2*N-1)) * Phi1 if(J > 1){ Phi1 <- Phi1[seq(1,4*N-1,by=2)] for(j in 2:J){ Lj <- (2^j - 1) * (2 * N - 1) + 1 out[[j]] <- double(2*Lj - 1) out[[j]][seq(2*N,2*Lj-2*N,by=2)] <- out[[j-1]] out[[j]][seq(1,2*Lj-1,by=2)] <- convolve(out[[j-1]], Phi1, type = "o") } } return(out) } ## main function wllag <- function(x, y, J = 8, N = 10, #family = "DaubExPhase", tau = 1e-3, from = -to, to = 100, verbose = FALSE, in.tau = FALSE, tol = 1e-6){ time1 <- as.numeric(time(x)) time2 <- as.numeric(time(y)) grid <- seq(from, to, by = 1) * tau Lj <- (2^J - 1) * (2 * N - 1) + 1 #Lj <- (2^J - 1) * (length(wavethresh::filter.select(N, family)$H) - 1) + 1 grid2 <- seq(from - Lj + 1, to + Lj - 1, by = 1) * tau dx <- diff(as.numeric(x)) dy <- diff(as.numeric(y)) tmp <- .C("HYcrosscov2", as.integer(length(grid2)), as.integer(length(time2)), as.integer(length(time1)), as.double(grid2/tol), as.double(time2/tol), as.double(time1/tol), as.double(dy), as.double(dx), value=double(length(grid2)), PACKAGE = "yuima")$value #if(missing(J)) J <- floor(log2(length(grid))) #if(J < 2) stop("J must be larger than 1") #acw <- wavethresh::PsiJ(-J, filter.number = N, family = "DaubExPhase") #acw <- wavethresh::PsiJ(-J, filter.number = N, family = family) acw <- autocorrelation.wavelet(J, N) theta <- double(J) #covar <- double(J) #LLR <- double(J) corr <- double(J) crosscor <- vector("list", J) for(j in 1:J){ wcov <- try(stats::filter(tmp, filter = acw[[j]], method = "c", sides = 2)[Lj:(length(grid) + Lj - 1)], silent = TRUE) #Mj <- (2^J - 2^j) * (2 * N - 1) #wcov <- try(convolve(tmp, acw[[j]], conj = FALSE, type = "filter")[(Mj + 1):(length(grid) + Mj)], # silent = TRUE) if(inherits(wcov, "try-error")){ theta[j] <- NA crosscor[[j]] <- NA corr[j] <- NA }else{ #tmp.grid <- grid[-attr(wcov, "na.action")] crosscor[[j]] <- zoo(wcov, grid) obj <- abs(wcov) idx1 <- which(obj == max(obj, na.rm = TRUE)) idx <- idx1[which.max(abs(grid[idx1]))] # if there are multiple peaks, take the lag farthest from zero theta[j] <- grid[idx] corr[j] <- crosscor[[j]][idx] } } if(verbose == TRUE){ #obj0 <- tmp[(Lj + 1):(length(grid) + Lj)] obj0 <- tmp[Lj:(length(grid) + Lj - 1)]/sqrt(sum(dx^2)*sum(dy^2)) obj <- abs(obj0) idx1 <- which(obj == max(obj, na.rm = TRUE)) idx <- idx1[which.max(abs(grid[idx1]))] # if there are multiple peaks, the lag farthest from zero theta.hy <- grid[idx] corr.hy <- obj0[idx] if(in.tau == TRUE){ theta <- round(theta/tau) theta.hy <- round(theta.hy/tau) } result <- list(lagtheta = theta, obj.values = corr, obj.fun = crosscor, theta.hry = theta.hy, cor.hry = corr.hy, ccor.hry = zoo(obj0, grid)) class(result) <- "yuima.wllag" }else{ if(in.tau == TRUE){ result <- round(theta/tau) }else{ result <- theta } } return(result) } # print method for yuima.wllag-class print.yuima.wllag <- function(x, ...){ cat("Estimated scale-by-scale lead-lag parameters\n") print(x$lagtheta, ...) cat("Corresponding values of objective functions\n") print(x$obj.values, ...) cat("Estimated lead-lag parameter in the HRY sense\n") print(x$theta.hry, ...) cat("Corresponding correlation coefficient\n") print(x$cor.hry, ...) } # plot method for yuima.wllag class plot.yuima.wllag <- function(x, selectJ = NULL, xlab = expression(theta), ylab = "", ...){ J <- length(x$lagtheta) if(is.null(selectJ)) selectJ <- 1:J for(j in selectJ){ #plot(x$ccor[[j]], main=paste("j=",j), xlab=expression(theta), # ylab=expression(U[j](theta)), type = type, pch = pch, ...) plot(x$obj.fun[[j]], main = paste("j = ", j, sep =""), xlab = xlab, ylab = ylab, ...) abline(0, 0, lty = "dotted") } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/wllag.R
ybook <- function(chapter){ chapter <- as.integer(chapter[1]) if(chapter %in% 1:7){ file.show(file.path(.libPaths()[1],"yuima","ybook",sprintf("chapter%d.R",chapter))) } else { cat("\nPlease choose an integer number within 1 and 7") } } yuima.stop <- function(x) stop(sprintf("\nYUIMA: %s\n", x)) yuima.warn <- function(x) warning(sprintf("\nYUIMA: %s\n", x)) # 22/11/2013 # We introduce a new utility yuima.simplify that allows us to simplify # the expressions in the drift, diffusion and jump terms. # yuima.Simplify modified from the original code Simplify.R # by Andrew Clausen <[email protected]> in 2007. # http://economics.sas.upenn.edu/~clausen/computing/Simplify.R # This isn't a serious attempt at simplification code. It just does some # obvious things like 0 + x => x. It was written to support Deriv.R. yuima.Simplify <- function(expr, yuima.env){ ### Simplify_ <- function(expr) { if (is.symbol(expr)) { expr } else if (is.language(expr) && is.symbol(expr[[1]])) { # is there a rule in the table? sym.name <- as.character(expr[[1]]) # if (class(try(Simplify.rule <- # get(sym.name, envir=yuima.env, # inherits=FALSE), silent=TRUE)) # != "try-error") tmpOutTry <- try(Simplify.rule <- get(sym.name, envir=yuima.env, inherits=FALSE), silent=TRUE) if(!inherits(tmpOutTry,"try-error")) return(Simplify.rule(expr)) } expr } Simplify.function <- function(f, x=names(formals(f)), env=parent.frame()) { stopifnot(is.function(f)) as.function(c(as.list(formals(f)), Simplify_(body(f))), envir=env) } `Simplify.+` <- function(expr) { if (length(expr) == 2) { if (is.numeric(expr[[2]])) return(+expr[[2]]) return(expr) } a <- Simplify_(expr[[2]]) b <- Simplify_(expr[[3]]) if (is.numeric(a) && all(a == 0)) { b } else if (is.numeric(b) && all(b == 0)) { a } else if (is.numeric(a) && is.numeric(b)) { a + b } else { expr[[2]] <- a expr[[3]] <- b expr } } `Simplify.-` <- function(expr) { if (length(expr) == 2) { if (is.numeric(expr[[2]])) return(-expr[[2]]) return(expr) } a <- Simplify_(expr[[2]]) b <- Simplify_(expr[[3]]) if (is.numeric(a) && all(a == 0)) { -b } else if (is.numeric(b) && all(b == 0)) { a } else if (is.numeric(a) && is.numeric(b)) { a - b } else { expr[[2]] <- a expr[[3]] <- b expr } } `Simplify.(` <- function(expr) expr[[2]] `Simplify.*` <- function(expr) { a <- Simplify_(expr[[2]]) b <- Simplify_(expr[[3]]) if (is.numeric(a) && all(a == 0)) { 0 } else if (is.numeric(b) && all(b == 0)) { 0 } else if (is.numeric(a) && all(a == 1)) { b } else if (is.numeric(b) && all(b == 1)) { a } else if (is.numeric(a) && is.numeric(b)) { a * b } else { expr[[2]] <- a expr[[3]] <- b expr } } `Simplify.^` <- function(expr) { a <- Simplify_(expr[[2]]) b <- Simplify_(expr[[3]]) if (is.numeric(a) && all(a == 0)) { 0 } else if (is.numeric(b) && all(b == 0)) { 1 } else if (is.numeric(a) && all(a == 1)) { 1 } else if (is.numeric(b) && all(b == 1)) { a } else if (is.numeric(a) && is.numeric(b)) { a ^ b } else { expr[[2]] <- a expr[[3]] <- b expr } } `Simplify.c` <- function(expr) { args <- expr[-1] args.simplified <- lapply(args, Simplify_) if (all(lapply(args.simplified, is.numeric))) { as.numeric(args.simplified) } else { for (i in 1:length(args)) expr[[i + 1]] <- args.simplified[[i]] expr } } assign("+", `Simplify.+`, envir=yuima.env) assign("-", `Simplify.-`, envir=yuima.env) assign("*", `Simplify.*`, envir=yuima.env) assign("(", `Simplify.(`, envir=yuima.env) assign("c", `Simplify.c`, envir=yuima.env) assign("^", `Simplify.^`, envir=yuima.env) ### as.expression(Simplify_(expr[[1]])) } ## Constructor and Initializer of class 'yuima' # we convert objects to "zoo" internally # we should change it later to more flexible classes setMethod("initialize", "yuima", function(.Object, data=NULL, model=NULL, sampling=NULL, characteristic=NULL, functional=NULL){ eqn <- NULL if(!is.null(data)){ .Object@data <- data eqn <- dim(data) if(is.null(sampling)) sampling <- setSampling(grid=list(index(get.zoo.data(data)[[1]]))) } if(!is.null(model)){ if(!is.null(eqn)){ if([email protected]){ yuima.warn("Model's equation number missmatch.") return(NULL) } }else{ eqn <- [email protected] } .Object@model <- model } if(!is.null(sampling)){ if(!is.null(eqn)){ if(eqn!=length(sampling@Terminal)){ if(length(sampling@Terminal)==1){ sampling@Terminal <- rep(sampling@Terminal, eqn) sampling@n <- rep(sampling@n, eqn) }else{ yuima.warn("Sampling's equation number missmatch.") return(NULL) } } }else{ eqn <- length(sampling@Terminal) } .Object@sampling <- sampling } if(!is.null(characteristic)){ if(!is.null(eqn)){ if([email protected]){ yuima.warn("Characteristic's equation number missmatch.") return(NULL) } } .Object@characteristic <- characteristic }else if(!is.null(eqn)){ characteristic <- new("yuima.characteristic", equation.number=eqn, time.scale=1) .Object@characteristic <- characteristic } if(!is.null(functional)) .Object@functional <- functional return(.Object) }) # setter setYuima <- function(data=NULL, model=NULL, sampling=NULL, characteristic=NULL, functional=NULL){ if(is.CarmaHawkes(model) && !is.null(data)){ if(is(data,"zoo")){ data <- setData(original.data = data, t0 = index(data)[1]) } if(is.null(sampling)){ zooData <- get.zoo.data(data)[[1]] originalgrid <- index(zooData) samp <- setSampling(Initial=originalgrid[1], Terminal = tail(originalgrid,1L), n = as.integer((tail(originalgrid,1L)-originalgrid[1])/mean(diff(originalgrid)))) gridData <- na.approx(zooData, xout=samp@grid[[1]]) [email protected]<-model@[email protected] [email protected][[1]] <- gridData res <- new("yuima",data=NULL, model=model, sampling=NULL, characteristic=characteristic,functional=functional) res@data <- data res@sampling <- samp }else{ zooData <- get.zoo.data(data) samp <- sampling gridData <- na.approx(zooData, xout=samp@grid[[1]]) [email protected]<-model@[email protected] [email protected][[1]] <- gridData res <- new("yuima",data=NULL, model=model, sampling=NULL, characteristic=characteristic,functional=functional) res@data <- data res@sampling <- samp } return(res) } if(is.CARMA(model)&& !is.null(data)){ if(dim([email protected])[2]==1){ dum.matr<-matrix(0,length([email protected]), (model@info@p+1)) dum.matr[,1]<-as.numeric([email protected]) data<-setData(zoo(x=dum.matr, order.by=time([email protected][[1]]))) } } if(is.COGARCH(model)&& !is.null(data)){ if(dim([email protected])[2]==1){ # data<-setData(zoo(x=matrix(as.numeric([email protected]),length([email protected]), # (model@info@p+1)), order.by=time([email protected][[1]]))) dum.matr<-matrix(0,length([email protected]), (model@info@q+2)) dum.matr[,1]<-as.numeric([email protected]) data<-setData(zoo(x=dum.matr, order.by=time([email protected][[1]]))) } } # LM 25/04/15 return(new("yuima", data=data, model=model, sampling=sampling, characteristic=characteristic,functional=functional)) } setMethod("show", "yuima.functional", function(object){ str(object) } ) setMethod("show", "yuima.sampling", function(object){ str(object) } ) setMethod("show", "yuima.data", function(object){ show(setYuima(data=object)) } ) setMethod("show", "yuima.model", function(object){ show(setYuima(model=object)) } ) setMethod("show", "yuima", function(object){ myenv <- new.env() mod <- object@model has.drift <- FALSE has.diff <- FALSE has.fbm <- FALSE has.levy <- FALSE is.wienerdiff <- FALSE is.fracdiff <- FALSE is.jumpdiff <- FALSE is.carma <- FALSE is.cogarch <- FALSE is.poisson <- is.Poisson(mod) if(length(mod@drift)>0 & !all(as.character(mod@drift) %in% c("(0)","expression((0))"))) { has.drift <- TRUE } if(length(mod@diffusion)>0 & !all(as.character(mod@diffusion) %in% c("(0)", "expression((0))"))) { has.diff <- TRUE} if(length([email protected])>0){ has.levy <- TRUE} if(!is.null(mod@hurst)){ if(!is.na(mod@hurst)){ if(mod@hurst != 0.5){ has.fbm <- TRUE } } } if( has.diff ) is.wienerdiff <- TRUE #if( has.drift | has.diff ) is.wienerdiff <- TRUE if( has.fbm ) is.fracdiff <- TRUE if( has.levy ) is.jumpdiff <- TRUE ldif <- 0 if(length(mod@diffusion)>0) ldif <- length(mod@diffusion[[1]]) if(ldif==1 & (length(mod@diffusion)==0)){ if( as.character(mod@diffusion[[1]]) %in% c("(0)","expression(0)") ){ has.diff <- FALSE is.wienerdiff <- FALSE is.fracdiff <- FALSE } } #if( class(mod) == "yuima.carma") if( inherits(mod, "yuima.carma")) # YK, Mar. 22, 2022 is.carma <- TRUE #if( class(mod) == "yuima.cogarch"){ if( inherits(mod, "yuima.cogarch")){ # YK, Mar. 22, 2022 is.cogarch <- TRUE is.wienerdiff <- FALSE is.fracdiff <- FALSE } if( is.wienerdiff | is.fracdiff | is.jumpdiff ){ if( is.wienerdiff & ! is.carma & !is.poisson & !is.cogarch){ cat("\nDiffusion process") if(!has.drift) cat(", driftless") if( is.fracdiff ){ if(!is.na(mod@hurst)){ if(mod@hurst!=0.5){ cat(sprintf(" with Hurst index:%.2f", mod@hurst)) } } else { cat(" with unknown Hurst index") } } } if(is.carma) cat(sprintf("\nCarma process p=%d, q=%d", mod@info@p, mod@info@q)) if(is.cogarch) cat(sprintf("\nCogarch process p=%d, q=%d", mod@info@p, mod@info@q)) if(is.poisson) cat("\nCompound Poisson process") if( (is.jumpdiff & !is.cogarch) ){ if( (is.wienerdiff | is.carma) & !is.poisson ){ cat(" with Levy jumps") } else { if(!is.poisson) cat("Levy process") } }else{ if(is.jumpdiff) cat(" with Levy jumps") } cat(sprintf("\nNumber of equations: %d", [email protected])) if((is.wienerdiff | is.fracdiff) & !is.poisson) cat(sprintf("\nNumber of Wiener noises: %d", [email protected])) if(is.jumpdiff & !is.poisson) cat(sprintf("\nNumber of Levy noises: %d", 1)) if(is.cogarch) cat(sprintf("\nNumber of quadratic variation: %d", 1)) if(length(mod@parameter@all)>0){ cat(sprintf("\nParametric model with %d parameters",length(mod@parameter@all))) } } if(length(object@[email protected])>0){ n.series <- 1 if(!is.null(dim(object@[email protected]))){ n.series <- dim(object@[email protected])[2] n.length <- dim(object@[email protected])[1] } else { n.length <- length(object@[email protected]) } cat(sprintf("\n\nNumber of original time series: %d\nlength = %d, time range [%s ; %s]", n.series, n.length, min(time(object@[email protected])), max(time(object@[email protected])))) } if(length(object@[email protected])>0){ n.series <- length(object@[email protected]) n.length <- unlist(lapply(object@[email protected], length)) t.min <- unlist(lapply(object@[email protected], function(u) as.character(round(time(u)[which.min(time(u))],3)))) t.max <- unlist(lapply(object@[email protected], function(u) as.character(round(time(u)[which.max(time(u))],3)))) delta <- NULL is.max.delta <- rep("", n.series) have.max.delta <- FALSE for(i in 1:n.series){ tmp <- length(table(round(diff(time(object@[email protected][[i]])),5))) if(tmp>1){ tmp <- max(diff(time(object@[email protected][[i]])), na.rm=TRUE) is.max.delta[i] <- "*" have.max.delta <- TRUE #tmp <- NULL } else { tmp <- diff(time(object@[email protected][[i]]))[1] } if(is.null(tmp)){ delta <- c(delta, NA) } else { delta <- c(delta, tmp) } } cat(sprintf("\n\nNumber of zoo time series: %d\n", n.series)) tmp <- data.frame(length=n.length, time.min = t.min, time.max =t.max, delta=delta) if(have.max.delta) tmp <- data.frame(tmp, note=is.max.delta) nm <- names(object@[email protected]) if(is.null(nm)){ rownames(tmp) <- sprintf("Series %d",1:n.series) } else { rownames(tmp) <- nm } print(tmp) if(have.max.delta) cat("================\n* : maximal mesh") } })
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.R
setMethod("initialize", "yuima.characteristic", function(.Object, equation.number, time.scale){ if(equation.number==length(time.scale)){ [email protected] <- equation.number [email protected] <- time.scale }else if(length(time.scale)==1){ time.scale <- rep(time.scale, equation.number) [email protected] <- equation.number [email protected] <- time.scale }else{ yuima.warn("Dimension missmatch") return(NULL) } return(.Object) }) setCharacteristic <- function(equation.number=1, time.scale=1){ return(new("yuima.characteristic", equation.number, time.scale=time.scale)) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.characteristic.R
##Constructor and Initializer of class 'yuima.data' # we convert objects to "zoo" internally setMethod("initialize", "yuima.data", function(.Object, original.data, delta=NULL, t0=0){ [email protected] <- original.data if(is.list(original.data) && is.zoo(original.data[[1]])) { [email protected] <- original.data } else { [email protected] <- as.list(as.zoo([email protected])) } if(!is.null(delta)){ delta <- rep(delta, length([email protected])) for(i in 1:length([email protected])){ n <- length([email protected][[i]]) t <- t0 + (0:(n-1))*delta[i] # t<-seq(0, n*delta[i], length=n)+t0 ## L.M. Using this mod we get the same result on JSS index([email protected][[i]]) <- t } } return(.Object) }) # utils onezoo <- function(ydata) { dat <- get.zoo.data(ydata) dats <- dat[[1]] if(length(dat)>1) { for(i in 2:(length(dat))) { dats <- merge(dats,dat[[i]]) } } if(!is.null(dim(dats))){ #if(class(ydata)=="yuima") if(inherits(ydata, "yuima")) # YK, Mar. 22, 2022 colnames(dats) <- colnames(ydata@[email protected]) #if(class(ydata)=="yuima.data") if(inherits(ydata, "yuima.data")) # YK, Mar. 22, 2022 colnames(dats) <- colnames([email protected]) } return(dats) } # accessors setData <- function(original.data, delta=NULL, t0=0){ return(new("yuima.data", original.data=original.data, delta=delta, t0=t0 )) } setGeneric("get.zoo.data", function(x) standardGeneric("get.zoo.data") ) setMethod("get.zoo.data", signature(x="yuima.data"), function(x){ return([email protected]) }) # following funcs are basic generic funcs setGeneric("plot", function(x,y,...) standardGeneric("plot") ) setMethod("plot",signature(x="yuima.data"), function(x,y,main="",xlab="index",ylab=names([email protected]),...){ plot(onezoo(x),main=main,xlab=xlab,ylab=ylab,...) } ) #setGeneric("time", # function(x,...) # standardGeneric("time") # ) #setMethod("time", signature(x="yuima.data"), # function(x,...){ # return(time([email protected])) # }) #setGeneric("end", # def = function(x,...) standardGeneric("end") # ) #setMethod("end", signature(x="yuima.data"), # function(x,...){ # return(end([email protected])) # }) #setGeneric("start", # function(x,...) # standardGeneric("start") # ) #setMethod("start", signature(x="yuima.data"), # function(x,...){ # return(start([email protected])) # }) # length is primitive, so no standardGeneric should be defined setMethod("length", signature(x= "yuima.data"), function(x){ # if(is.null(dim([email protected]))) # return(length([email protected])) # else # return(dim([email protected])[1]) result <- numeric() for(i in 1:(length([email protected]))) result <- c(result,length([email protected][[i]])) return(result) } ) setMethod("dim", signature(x = "yuima.data"), function(x){ return(length([email protected])) } ) # same methods for 'yuima'. Depend on same methods for 'data' setMethod("get.zoo.data", "yuima", function(x){ return(get.zoo.data(x@data)) }) setMethod("length", "yuima", function(x){ return(length(x@data)) }) setMethod("dim", "yuima", function(x){ return(dim(x@data)) }) setMethod("plot","yuima", function(x,y,xlab=x@[email protected],ylab=x@[email protected],...){ if(length(x@[email protected])==0) { plot(x@data,...) } else { plot(x@data,xlab=xlab,ylab=ylab,...) } }) ##:: yuima.data obj cbind ( implementation 08/18 ) setGeneric("cbind.yuima", function(x, ...) standardGeneric("cbind.yuima") ) setMethod("cbind.yuima", signature(x="yuima"), function(x, ...){ ##:: init y.list <- list(x, ...) y.num <- length(y.list) ##:: bind yuima.data in yuima yd.tmp <- y.list[[1]]@data for(idx in 2:y.num){ ##:: error check ##if( class(y.list[[idx]])!="yuima"){ if( !inherits(y.list[[idx]],"yuima")){ stop("arg ", idx, " is not yuima-class") } ##:: bind yd.tmp <- cbind.yuima(yd.tmp, y.list[[idx]]@data) } ##:: substitute yuima.data x@data <- yd.tmp ##:: return result return(x) } ) setMethod("cbind.yuima", signature(x="yuima.data"), function(x, ...){ ##:: init yd.list <- list(x, ...) yd.num <- length(yd.list) ##:: bind yuima.data (original.data) od.tmp <- yd.list[[1]]@original.data for(idx in 2:yd.num){ ##:: error check ##if( class(yd.list[[idx]])!="yuima.data" ){ if( !inherits(yd.list[[idx]],"yuima.data") ){ stop("arg ", idx, " is not yuima.data-class.") } ##:: bind od.tmp <- cbind(od.tmp, yd.list[[idx]]@original.data) } ##:: return result return(new("yuima.data", original.data=od.tmp)) } ) ##:: END ( yuima.data obj cbind )
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.data.R
# constructor and initializer of class 'yuima.functional' setMethod("initialize", "yuima.functional", function(.Object, F, f, xinit, e){ .Object@F <- F .Object@f <- f .Object@xinit <- xinit #.Object@Terminal <- Terminal #.Object@division <- division .Object@e <- e return(.Object) }) # setter setGeneric("setFunctional", function(model, F, f, xinit, e) standardGeneric("setFunctional") ) setMethod("setFunctional", "yuima", function(model, F, f, xinit, e){ model@functional <- setFunctional(model@model,F,f,xinit,e)@functional return(model) }) setMethod("setFunctional", "yuima.model", function(model, F, f, xinit, e){ # error check if( missing(model)){ yuima.warn("yuima.model is missing.") return(NULL) } if( missing(xinit)){ yuima.warn("Initial value of state variable is missing.") return(NULL) } if( missing(f) || missing(F) || missing(e)){ yuima.warn("Functional specification is incomplete.") return(NULL) } r.size <- [email protected] d.size <- [email protected] k.size <- length(F) if( length(f) != (r.size + 1)){ yuima.warn("Functional needs r+1 f_alphas.") return(NULL) } if( length(f[[1]]) != k.size){ yuima.warn("Missmatch in dimension of functional.") return(NULL) } if( length(xinit) != d.size){ yuima.warn("Missmatch in dimension of functional and state variables.") return(NULL) } # instanciate return(setYuima(model = model,functional = new("yuima.functional", F=F, f=f, xinit=xinit, e=e ))) }) # getter of each variables setGeneric("getF", function(x) standardGeneric("getF") ) setMethod("getF", "yuima.functional", function(x){ return(x@F) }) setGeneric("getf", function(x) standardGeneric("getf") ) setMethod("getf", "yuima.functional", function(x){ return(x@f) }) setGeneric("getxinit", function(x) standardGeneric("getxinit") ) setMethod("getxinit", "yuima.functional", function(x){ return(x@xinit) }) setGeneric("gete", function(x) standardGeneric("gete") ) setMethod("gete", "yuima.functional", function(x){ return(x@e) })
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.functional.R
## Distribution Law setClass("yuima.law",representation(rng = "function", density = "function", cdf = "function", quantile = "function", characteristic = "function", param.measure = "character", time.var = "character", dim = "numLike") ) setMethod("initialize", "yuima.law", function(.Object, rng = function(n,...){}, density = function(x,...){}, cdf = function(q,...){}, quantile = function(p,...){}, characteristic = function(u,...){}, param.measure = character(), time.var = character(), dim = NA ){ .Object@rng <- rng .Object@density <- density .Object@cdf <- cdf .Object@quantile <- quantile .Object@characteristic <- characteristic [email protected] <- param.measure [email protected] <- time.var .Object@dim <- dim return(.Object) } ) setMethod("rand","yuima.law", function(object, n, param, ...){ res <- aux.rand(object, n, param, ...) return(res) } ) setMethod("dens","yuima.law", function(object, x, param, log = FALSE, ...){ res <- aux.dens(object, x, param, log, ...) return(res) } ) setMethod("cdf","yuima.law", function(object, q, param, ...){ res <- aux.cdf(object, q, param, log, ...) return(res) } ) setMethod("quant","yuima.law", function(object, p, param, ...){ res <- aux.quant(object, p, param, ...) return(res) } ) setMethod("char","yuima.law", function(object, u, param, ...){ res <- aux.char(object, u, param, ...) return(res) } ) # Constructor setLaw <- function(rng = function(n,...){NULL}, density = function(x,...){NULL}, cdf = function(q,...){NULL}, quant = function(p,...){NULL}, characteristic = function(u,...){NULL}, time.var="t", dim = NA){ param <- NULL param.rng <- extrapParam(myfun = rng, time.var = time.var, aux.var = "n" ) CondRng<- FALSE if(all(param.rng %in% "...")){ # yuima.warn("rng is not defined") }else{ CondRng <- TRUE param <- param.rng } param.dens <- extrapParam(myfun = density, time.var = time.var, aux.var = "x" ) CondDens<- FALSE if(all(param.dens %in% "...")){ # yuima.warn("density is not defined") }else{ CondDens <- TRUE param <- param.dens } if(CondDens){ if(CondRng){ if(!all(param.dens %in% param.rng)){ yuima.stop("dens and rng have different parameters") } } } param.cdf <- extrapParam(myfun = cdf, time.var = time.var, aux.var = "q" ) #Condcdf<- FALSE if(all(param.cdf %in% "...")){ #yuima.warn("cdf is not defined") }else{ # Condcdf <- TRUE if(is.null(param)){ param <- param.cdf }else{ if(!all(param %in% param.cdf)){ yuima.stop("cdf has different parameters") } } } param.quant <- extrapParam(myfun = quant, time.var = time.var, aux.var = "p" ) # Condquant<- FALSE if(all(param.quant %in% "...")){ #yuima.warn("cdf is not defined") }else{ # Condquant <- TRUE if(is.null(param)){ param <- param.quant }else{ if(!all(param %in% param.quant)){ yuima.stop("quantile has different parameters") } } } param.char <- extrapParam(myfun = characteristic, time.var = time.var, aux.var = "u" ) if(all(param.char %in% "...")){ # yuima.warn("char is not defined") }else{ if(is.null(param)){ param <- param.char }else{ if(!all(param %in% param.char)){ yuima.stop("quantile has different parameters") } } } if(is.null(param)){ param<-character() } res <- new("yuima.law", rng = rng, density = density, cdf = cdf, characteristic = characteristic, quantile = quant, param.measure = param, time.var = time.var, dim = NA) return(res) } extrapParam <- function(myfun, time.var, aux.var){ dummy <- names(as.list(args(myfun))) dummy <- dummy[-length(dummy)] if(dummy[1] != aux.var){ yuima.stop("Change rand.var or charac.var ...") } cond <- dummy %in% time.var # if(!any(cond)){ # yuima.warn("The yuima.law is the distribution # of the jump size, in a CP process") # } dummy.par <- dummy[!cond] dummy <- dummy.par[!dummy.par%in%aux.var] return(dummy) } ### From a Characteristic Function To yuima.law object InternalDensity <- function(x, param, mynames, time.names, time.var, up, low, N_grid, method , myfun, N_Fourier){ myenv <- new.env() for(i in c(1:length(param))){ assign(mynames[i], param[i] , envir =myenv ) } assign(time.names, time.var, envir =myenv) x_old <- x x_new <-unique(sort(c(low, x_old, up))) x_new <- unique(sort(c(seq(min(x_new)-0.1,max(x_new)+0.1, length.out =N_grid+1),x))) alim <- min(x_new) blim <- max(x_new) i <- 0:(N_Fourier - 1) dx <- (blim - alim)/N_Fourier x <- alim + i * dx dt <- 2 * pi/(N_Fourier * dx) c <- -N_Fourier/2 * dt d <- N_Fourier/2 * dt u <- c + i * dt assign("u",u,myenv) #dummyphy <- eval(parse(text=myfun)) #phi <- as.numeric(eval(parse(text=myfun), envir =myenv)) phi <- eval(parse(text=myfun), envir =myenv) #plot(u,phi, type="l") X <- exp(-(0 + (0+1i)) * i * dt * alim) * phi Y <- fft(X) density <- dt/(2 * pi) * exp(-(0 + (0+1i)) * c * x) * Y invFFT<-data.frame(i = i, u = u, characteristic_function = phi, x = x, density = Re(density)) #dens <- na.approx(zoo(x=invFFT$density, order.by= invFFT$x), xout=x_old) na <- is.na(invFFT$density) dens <- approx(x=invFFT$x[!na], y=invFFT$density[!na], xout=x_old)$y return(dens) } InternalCdf <- function(q, param, mynames, time.names, time.var, up, low, N_grid, method, myfun, N_Fourier){ x_old <- q x_new <-unique(sort(c(low, x_old, up))) x_new <- unique(sort(c(seq(min(x_new)-0.1,max(x_new)+0.1, length.out =N_grid+1),x_old))) dens <- InternalDensity(x_new, param, mynames, time.names, time.var, up, low, N_grid, method , myfun, N_Fourier) cdf <- c(0,cumsum(as.numeric(dens)[-1]*diff(x_new))) res <- na.approx(zoo(cdf, order.by=sort(x_new)), xout = q) return(res) } InternalRnd <- function(n, param, mynames, time.names, time.var, up, low, N_grid, method, myfun, N_Fourier){ x_new <- seq(low-0.1,up+0.1, length.out =N_grid+1) cdf<-as.numeric(InternalCdf(q=x_new, param, mynames, time.names,time.var, up, low, N_grid, method, myfun, N_Fourier)) cdf0 <- cdf[cdf>0 & cdf<1] x_new0 <- x_new[cdf>0 & cdf<1] rndUn0 <- runif(n, min = min(cdf0), max(cdf0)) res <- approx(y=x_new0, x = cdf0, xout=rndUn0, ties = mean, rule =2) if(length(res$y)==n){ return(as.numeric(res$y)) }else{ m <- n-length(res$y) rndUn1 <- runif(m, min = min(cdf0), max(cdf0)) res1 <- approx(y=x_new0, x = cdf0, xout=rndUn1) res_new <- c(res$y,res1$y) if(length(res_new)==n){ return(res_new) }else{ m<-n-length(res_new) return(c(res_new, sample(res_new, m))) } } } InternalQnt <- function(p, param, mynames, time.names, time.var, up, low, N_grid, method, myfun, N_Fourier){ x_new <- seq(low-0.1,up+0.1, length.out =N_grid+1) cdf<-as.numeric(InternalCdf(q=x_new, param, mynames, time.names,time.var, up, low, N_grid, method, myfun, N_Fourier)) cdf0 <- cdf[cdf>0 & cdf<1] x_new0 <- x_new[cdf>0 & cdf<1] res <- approx(y=x_new0, x = cdf0, xout=p) return(res$y) } FromCF2yuima_law <- function(myfun, time.names = "t", var_char = "u", up = 45, low = -45, N_grid = 50001, N_Fourier=2^10){ method <- "FFT" if(!myfun %in% names(globalenv())){ yuima.stop("the characteristi function is not defined in the global enviromnent: check arg myfun") } dumEval <- parse(text = paste0("dumFun <- ", myfun)) lawpar<-extrapParam(eval(dumEval),time.names, var_char) # if(!all(names(true.par) %in% lawpar)){ # stop("error massage") # } true.par<- lawpar mynames <- lawpar nametime <- time.names dumm1 <- paste0("(", paste0(c("u",lawpar,time.names), collapse=", "),")") mystring <- paste0(paste(paste0(lawpar, collapse=", "), time.names, sep =", " ),"){") mystring <- paste(mystring, paste0(" up <- ",up) ,sep="\n") mystring <- paste(mystring, paste0(" low <- ", low) ,sep="\n") mystring <- paste(mystring, paste0(" N_grid <- ", N_grid) ,sep="\n") mystring <- paste(mystring, paste0(" param <- c(", paste0(lawpar, collapse=" ,"), ")") ,sep="\n") mystring <- paste(mystring, paste0(" mynames <- c('", paste0(mynames, collapse="' ,'"), "')") ,sep="\n") mystring <- paste(mystring, paste0(" time.var <- c(", paste0(nametime, collapse=" ,"), ")") ,sep="\n") mystring <- paste(mystring, paste0(" time.names <- c('", paste0(nametime, collapse="' ,"), "')") ,sep="\n") mystring <- paste(mystring, paste0(" method <- c('", paste0(method, collapse="' ,"), "')") ,sep="\n") mystring <- paste(mystring, paste0(" myfun <- '", paste0(paste0(myfun, collapse="' ,"),dumm1), "'") ,sep="\n") mystring <- paste(mystring, paste0(" N_Fourier <- ", N_Fourier) ,sep="\n") mystring_dens_in <- "dmyLaw <- function(x, " mystring_dens_fin <- paste(mystring, paste(" res <- InternalDensity(x", "param", "mynames", "time.names", "time.var", "up", "low", "N_grid", "method ", "myfun", "N_Fourier", sep = ", " ) ,sep="\n") mystring_dens <- paste0(mystring_dens_in,mystring_dens_fin) mystring_dens <- paste(mystring_dens,")", sep="") mystring_dens <- paste(mystring_dens, " return(res)","}" ,sep="\n") mystring_cdf_in <- "pmyLaw <- function(q, " mystring_cdf_fin <- paste(mystring, paste(" res <- InternalCdf(q", "param", "mynames", "time.names", "time.var", "up", "low", "N_grid", "method ", "myfun", "N_Fourier", sep = ", " ) ,sep="\n") #cat(mystring) mystring_cdf <- paste0(mystring_cdf_in,mystring_cdf_fin) mystring_cdf <- paste(mystring_cdf,")", sep="") mystring_cdf <- paste(mystring_cdf, " return(res)","}" ,sep="\n") mystring_rnd_in <- "rmyLaw <- function(n, " mystring_rnd_fin <- paste(mystring, paste(" res <- InternalRnd(n", "param", "mynames", "time.names", "time.var", "up", "low", "N_grid", "method ", "myfun", "N_Fourier", sep = ", " ) ,sep="\n") #cat(mystring) mystring_rnd <- paste0(mystring_rnd_in,mystring_rnd_fin) mystring_rnd <- paste(mystring_rnd,")", sep="") mystring_rnd <- paste(mystring_rnd, " return(res)","}" ,sep="\n") mystring_qnt_in <- "qmyLaw <- function(p, " mystring_qnt_fin <- paste(mystring, paste(" res <- InternalQnt(p", "param", "mynames", "time.names", "time.var", "up", "low", "N_grid", "method ", "myfun", "N_Fourier", sep = ", " ) ,sep="\n") #cat(mystring) mystring_qnt <- paste0(mystring_qnt_in,mystring_qnt_fin) mystring_qnt <- paste(mystring_qnt,")", sep="") mystring_qnt <- paste(mystring_qnt, " return(res)","}" ,sep="\n") dmyLaw <- NULL pmyLaw <- NULL rmyLaw <- NULL qmyLaw <- NULL eval(parse(text=mystring_dens)) eval(parse(text=mystring_cdf)) eval(parse(text=mystring_rnd)) eval(parse(text=mystring_qnt)) res<-setLaw(density = dmyLaw) # res@characteristic<-myChar res@cdf <- pmyLaw res@rng <- rmyLaw res@quantile <- qmyLaw return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.law.r
# setMethod("initialize", "model.parameter", # function(.Object, # all, # common, # diffusion, # drift, # jump, # measure, # xinit){ # .Object@all <- all # .Object@common <- common # .Object@diffusion <- diffusion # .Object@drift <- drift # .Object@jump <- jump # .Object@measure <- measure # .Object@xinit <- xinit # return(.Object) # }) setMethod("initialize", "model.parameter", function(.Object, all = character(), common = character(), diffusion = character(), drift = character(), jump = character(), measure = character(), xinit = character()){ .Object@all <- all .Object@common <- common .Object@diffusion <- diffusion .Object@drift <- drift .Object@jump <- jump .Object@measure <- measure .Object@xinit <- xinit return(.Object) }) # setMethod("initialize", "yuima.model", # function(.Object, # drift , # diffusion, # hurst, # jump.coeff, # measure, # measure.type, # parameter, # state.variable, # jump.variable, # time.variable, # noise.number, # equation.number, # dimension, # solve.variable, # xinit, # J.flag){ # .Object@drift <- drift # .Object@diffusion <- diffusion # .Object@hurst <- hurst # [email protected] <- jump.coeff # .Object@measure <- measure # [email protected] <- measure.type # .Object@parameter <- parameter # [email protected] <- state.variable # [email protected] <- jump.variable # [email protected] <- time.variable # [email protected] <- noise.number # [email protected] <- equation.number # .Object@dimension <- dimension # [email protected] <- solve.variable # .Object@xinit <- xinit # [email protected] <- J.flag # return(.Object) # }) # 23/11 we need to provide the default values for the yuima.model object class # in order to construct a new class that inherits from yuima.model class setMethod("initialize", "yuima.model", function(.Object, drift = expression() , diffusion = list() , hurst = 0.5, jump.coeff = list(), #jump.coeff = expression(), measure=list(), measure.type=character(), parameter = new("model.parameter"), state.variable = "x", jump.variable = "z", time.variable = "t", noise.number = numeric(), equation.number = numeric(), dimension = numeric(), solve.variable = character(), xinit = expression(), J.flag = logical()){ .Object@drift <- drift .Object@diffusion <- diffusion .Object@hurst <- hurst [email protected] <- jump.coeff .Object@measure <- measure [email protected] <- measure.type .Object@parameter <- parameter [email protected] <- state.variable [email protected] <- jump.variable [email protected] <- time.variable [email protected] <- noise.number [email protected] <- equation.number .Object@dimension <- dimension [email protected] <- solve.variable .Object@xinit <- xinit [email protected] <- J.flag return(.Object) }) ## setModel ## setter of class 'yuima.model' ## set yuima model from SDE setModel <- function(drift=NULL, diffusion=NULL, hurst=0.5, jump.coeff=NULL, measure=list(), measure.type=character(), state.variable="x", jump.variable="z", time.variable="t", solve.variable, xinit=NULL){ ## we need a temp env for simplifications mylengdumMeas<-length(measure) if(mylengdumMeas>0){ for(i in c(1:mylengdumMeas)){ if(is(measure[[i]],"yuima.law")){ res<- aux.setModelLaw(drift,diffusion, hurst, jump.coeff, measure, measure.type, state.variable, jump.variable, time.variable, solve.variable, xinit, posyuimalaw=i) res@measure[[i]]<-measure[[i]] return(res) } } } yuimaENV <- new.env() ##::measure and jump term ##################################### ##::initialize objects ######## MEASURE <- list() ##::end initialize objects ######## ##::make type function list #### CPlist <- c("dnorm", "dgamma", "dexp", "dconst") codelist <- c("rIG", "rNIG", "rgamma", "rbgamma", "rvgamma", "rstable","rpts","rnts") ## added "rpts" and "rnts" by YU (2016/10/4) ##::end make type function list #### ## Multivariate YUIMA model if(!is.null(jump.coeff)){ if(is.matrix(jump.coeff)){ if(dim(jump.coeff)[2]!=1){ intensity <- NULL #if(is.null(names(measure)) || names(measure)=="df"){ if(is.null(names(measure)) || all(names(measure)%in%"df")){ names(measure) <- "df" } df <- as.list(measure[["df"]]) if(any(measure.type=="CP")){ intensity <- measure[["intensity"]] } my.cond <- TRUE tmp <- regexpr("\\(", measure$df)[1] measurefunc <- substring(measure$df, 1, tmp-1) if(!is.na(match(measurefunc, codelist))){ my.cond <- FALSE } if(my.cond){ res <- setMultiModel(drift = drift, diffusion = diffusion, hurst = hurst, jump.coeff = jump.coeff, intensity = intensity, df = df, measure.type = measure.type, state.variable = state.variable, jump.variable = jump.variable, time.variable = time.variable, solve.variable = solve.variable, xinit= xinit) return(res) } } } } if(!length(measure.type)){ if( length(jump.coeff) || length(measure) ){ yuima.warn("measure type does not match with jump term.") return(NULL) } jump.variable <- character() measure.par <- character() }else{ if( !length(jump.coeff) || !length(measure) ){ yuima.warn("measure type isn't matched with jump term.") return(NULL) # }else # if(length(jump.coeff)!=1){ # yuima.warn("multi dimentional jump term is not supported yet.") # # return(NULL) # } } else if(measure.type=="CP"){ ##::CP # if(length(measure)!=2){ # yuima.warn(paste("length of measure must be two on type", measure.type, ".")) # return(NULL) #} if(!is.list(measure)){ measure <- list(intensity=measure[1], df=measure[2],dimension=measure[3]) } else { #if(length(measure[[1]])!=1 || length(measure[[2]])!=1){ # yuima.warn("multi dimentional jump term is not supported yet.") # return(NULL) # } ##::naming measure list ######## tmpc <- names(measure) if(is.null(tmpc)){ names(measure) <- c("intensity", "df","dimension") }else{ whichint <- match("intensity", tmpc) whichdf <- match("df", tmpc) if(!is.na(whichint)){ if(names(measure)[-whichint]=="" || names(measure)[-whichint]=="df"){ names(measure)[-whichint] <- "df" }else{ yuima.warn("names of measure are incorrect.") return(NULL) } }else if(!is.na(whichdf)){ if(names(measure)[-whichdf]=="" || names(measure)[-whichdf]=="intensity"){ names(measure)[-whichdf] <- "intensity" }else{ yuima.warn("names of measure are incorrect.") return(NULL) } }else{ yuima.warn("names of measure are incorrect.") return(NULL) } } ##::end naming measure list ######## } ##::check df name #################### tmp <- regexpr("\\(", measure$df)[1] measurefunc <- substring(measure$df, 1, tmp-1) if(!is.na(match(measurefunc, codelist))){ yuima.warn(paste("distribution function", measurefunc, "should be defined as type code.")) return(NULL) }#else if(is.na(match(measurefunc, CPlist))){ # warning(paste("\ndistribution function", measurefunc, "is not officialy supported as type CP.\n")) #} MEASURE$df$func <- eval(parse(text=measurefunc)) #LM 15/05/2017 MEASURE$df$expr <- parse(text=measure$df) MEASURE$intensity <- parse(text=measure$intensity) measure.par <- unique( c( all.vars(MEASURE$intensity), all.vars(MEASURE$df$expr) ) ) ##measure.par$intensity <- unique(all.vars(MEASURE$intensity)) ##::end check df name #################### ##::end CP } else if(measure.type=="code"){ ##::code if(length(measure)!=1){ yuima.warn(paste("length of measure must be one on type", measure.type, ".")) return(NULL) } if(!is.list(measure)){ measure <- list(df=measure) }else{ if(length(measure[[1]])!=1){ yuima.warn("multi dimentional jump term is not supported yet.") return(NULL) } ##::naming measure list ############# if(is.null(names(measure)) || names(measure)=="df"){ names(measure) <- "df" }else{ yuima.warn("name of measure is incorrect.") return(NULL) } ##::end naming measure list ############# } ##::check df name #################### tmp <- regexpr("\\(", measure$df)[1] measurefunc <- substring(measure$df, 1, tmp-1) if(!is.na(match(measurefunc, CPlist))){ yuima.warn(paste("\ndistribution function", measurefunc, "should be defined as type CP.")) return(NULL) }else if(is.na(match(measurefunc, codelist))){ warning(paste("\ndistribution function", measurefunc, "is not officialy supported as type code.\n")) } ##MEASURE$df$func <- eval(parse(text=measurefunc)) MEASURE$df$expr <- parse(text=measure$df) measure.par <- unique(all.vars(MEASURE$df$expr)) ##::end check df name #################### ##::end code }else if(measure.type=="density"){ ##::density if(length(measure)!=1){ yuima.warn(paste("length of measure must be one on type", measure.type, ".")) return(NULL) } if(!is.list(measure)){ measure <- list(df=measure) }else{ if(length(measure[[1]])!=1){ yuima.warn("multi dimentional jump term is not supported yet.") return(NULL) } ##::naming measure list ############# if(is.null(names(measure))){ names(measure) <- "df" }else if(names(measure)!="density" && names(measure)!="df"){ yuima.warn("name of measure is incorrect.") return(NULL) } ##::end naming measure list ############# } ##::check df name #################### tmp <- regexpr("\\(", measure[[names(measure)]])[1] measurefunc <- substring(measure[[names(measure)]], 1, tmp-1) if(!is.na(match(measurefunc, CPlist))){ yuima.warn(paste("distribution function", measurefunc, "should be defined as type CP.")) return(NULL) }else if(!is.na(match(measurefunc, codelist))){ yuima.warn(paste("distribution function", measurefunc, "should be defined as type code.")) return(NULL) } MEASURE[[names(measure)]]$func <- eval(parse(text=measurefunc)) MEASURE[[names(measure)]]$expr <- parse(text=measure[[names(measure)]]) measure.par <- unique(all.vars(MEASURE[[names(measure)]]$expr)) ##::end check df name #################### ##::end density }else{ ##::else yuima.warn(paste("measure type", measure.type, "isn't supported.")) return(NULL) } n.eqn3 <- 1 n.jump <- 1 } ##::end measure and jump term ##################################### ##:: check for errors and reform values if(any(time.variable %in% state.variable)){ yuima.warn("time and state(s) variable must be different.") return(NULL) } if(is.null(dim(drift))){ # this is a vector n.eqn1 <- length(drift) n.drf <- 1 }else{ # it is a matrix n.eqn1 <- dim(drift)[1] n.drf <- dim(drift)[2] } if(is.null(dim(diffusion))){ # this is a vector n.eqn2 <- length(diffusion) n.noise <- 1 }else{ # it is a matrix n.eqn2 <- dim(diffusion)[1] n.noise <- dim(diffusion)[2] } if(is.null(diffusion)){ diffusion <- rep("0", n.eqn1) n.eqn2 <- n.eqn1 n.noise <- 1 } ## TBC n.eqn3 <- n.eqn1 if(!length(measure)){ n.eqn3 <- n.eqn1 } if(n.eqn1 != n.eqn2 || n.eqn1 != n.eqn3){ yuima.warn("Malformed model, number of equations in the drift and diffusion do not match.") return(NULL) } n.eqn <- n.eqn1 if(is.null(xinit)){ # xinit <- numeric(n.eqn) xinit <- character(n.eqn) }else if(length(xinit) != n.eqn){ if(length(xinit)==1){ xinit <- rep(xinit, n.eqn) }else{ yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } if(missing(solve.variable)){ yuima.warn("Solution variable (lhs) not specified. Trying to use state variables.") solve.variable <- state.variable } if(n.eqn != length(solve.variable)){ yuima.warn("Malformed model, number of solution variables (lhs) do no match number of equations (rhs).") return(NULL) } loc.drift <- matrix(drift, n.eqn, n.drf) loc.diffusion <- matrix(diffusion, n.eqn, n.noise) # Modification starting point 6/11 loc.xinit<-matrix(xinit,n.eqn,n.drf) ##:: allocate vectors DRIFT <- vector(n.eqn, mode="expression") DIFFUSION <- vector(n.eqn, mode="list") # Modification starting point 6/11 XINIT<-vector(n.eqn, mode = "expression") ##:: function to make expression from drift characters pre.proc <- function(x){ for(i in 1:length(x)){ if(length(parse(text=x[i]))==0){ x[i] <- "0" } } parse(text=paste(sprintf("(%s)", x), collapse="+")) } ##22/11:: function to simplify expression in drift, diffusion, jump and xinit characters yuima.Simplifyobj<-function(x){ dummy<-yuima.Simplify(x, yuima.env=yuimaENV) dummy1<-yuima.Simplify(dummy, yuima.env=yuimaENV) dummy2<-as.character(dummy1) res<-parse(text=paste0("(",dummy2,")",collapse=NULL)) return(res) } ##:: make expressions of drifts and diffusions and jump for(i in 1:n.eqn){ DRIFT[i] <- pre.proc(loc.drift[i,]) # 22/11 Simplify expressions DRIFT[i] <- yuima.Simplifyobj(DRIFT[i]) # Modification starting point 6/11 XINIT[i]<-pre.proc(loc.xinit[i, ]) XINIT[i]<- yuima.Simplifyobj(XINIT[i]) for(j in 1:n.noise){ expr <- parse(text=loc.diffusion[i,j]) if(length(expr)==0){ expr <- expression(0) # expr must have something } # DIFFUSION[[i]][j] <- expr #22/11 DIFFUSION[[i]][j] <- yuima.Simplifyobj(expr) } #22/11 #if (length(JUMP)>0){ # JUMP[i] <- parse(text=jump.coeff[i]) # JUMP[i] <- yuima.Simplifyobj(JUMP[i]) #} } #print(length(jump.coeff)) #if (length(jump.coeff)==0){ # JUMP <- list(parse(text=jump.coeff)) #}else{ # # JUMP <- vector(n.eqn, mode="expression") # JUMP <- vector(n.eqn, mode="list") #} if(length(jump.coeff)==0){ JUMP <- list() } else { if(length(jump.coeff)==1 & !is.matrix(jump.coeff)){ # is a scalar expr <- parse(text=jump.coeff) if(length(expr)==0){ expr <- expression(0) # expr must have something } JUMP <- list(yuima.Simplifyobj(expr)) } else { # must be matrix, n.col = dimension of Levy noise jump.coeff <- as.matrix(jump.coeff) c.j <- ncol(jump.coeff) r.j <- nrow(jump.coeff) #print(c.j) #print(r.j) #print(jump.coeff) JUMP <- vector(r.j, mode="list") for(i in 1:r.j){ for(j in 1:c.j){ #cat(sprintf("\ni=%d,j=%d\n",i,j)) expr <- parse(text=jump.coeff[i,j]) if(length(expr)==0){ expr <- expression(0) # expr must have something } JUMP[[i]][j] <- yuima.Simplifyobj(expr) } } } } #print(str(JUMP)) # ##:: get parameters in drift expression drift.par <- unique(all.vars(DRIFT)) # Modification starting point 6/11 xinit.par <- unique(all.vars(XINIT)) drift.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), drift.par))) if(length(drift.idx)>0){ drift.par <- drift.par[-drift.idx] } ##:: get parameters in diffusion expression diff.par <- unique(unlist(lapply(DIFFUSION, all.vars))) diff.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), diff.par))) if(length(diff.idx)>0){ diff.par <- diff.par[-diff.idx] } ##:: get parameters in jump expression J.flag <- FALSE # jump.par <- unique(all.vars(JUMP)) jump.par <- unlist(lapply(JUMP,all.vars)) if(is.null(jump.par)) jump.par <- character() if(length(na.omit(match(jump.par, jump.variable)))){ J.flag <- TRUE } jump.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), jump.par))) if(length(jump.idx)>0){ jump.par <- jump.par[-jump.idx] } ##:: get parameters in measure expression measure.idx <- as.numeric(na.omit(match(c(state.variable, time.variable, jump.variable, solve.variable), measure.par))) if(length(measure.idx)>0){ measure.par <- measure.par[-measure.idx] } ##:: order parameters for 'yuima.pars' ##id1 <- which(diff.par %in% drift.par) ##id2 <- which(drift.par %in% diff.par) ##common <- unique(c(diff.par[id1], drift.par[id2])) common <- c(drift.par, diff.par) common <- common[duplicated(common)] common1<-common # modification 06/11 common1 contains only # parameters that appear in both drift and diffusion terms. # Modification 06/11 common contains only parameters that appear # in drift, diff, Jump and xinit if (length(xinit)) { common <- c(common, xinit.par) common <- common[duplicated(common)] common <- c(common, xinit.par) common <- common[duplicated(common)] } if(length(measure)){ common <- c(common, jump.par) common <- common[duplicated(common)] common <- c(common, measure.par) common <- common[duplicated(common)] } # all.par <- unique(c(drift.par, diff.par, jump.par, measure.par)) all.par <- unique(c(drift.par, diff.par, jump.par, measure.par, xinit.par)) ##:: instanciate class tmppar <- new("model.parameter", all= all.par, # common= common, common= common1, diffusion= diff.par, drift= drift.par, jump= jump.par, measure= measure.par, xinit=xinit.par) tmp <- new("yuima.model", drift= DRIFT, diffusion= DIFFUSION, hurst=as.numeric(hurst), jump.coeff=JUMP, measure= MEASURE, measure.type= measure.type, parameter= tmppar, state.variable= state.variable, jump.variable= jump.variable, time.variable= time.variable, noise.number= n.noise, equation.number= n.eqn, dimension= c( length(tmppar@all), length(tmppar@common), length(tmppar@diffusion), length(tmppar@drift), length(tmppar@jump), length(tmppar@measure) ), solve.variable= solve.variable, xinit= XINIT, J.flag <- J.flag) return(tmp) } aux.setModelLaw <- function(drift,diffusion, hurst, jump.coeff, measure, measure.type, state.variable, jump.variable, time.variable, solve.variable, xinit, posyuimalaw){ dummyMeasure <- paste0(c("yuima.law(", paste0(measure[[posyuimalaw]]@param.measure,collapse=", ") ,")"), collapse="") auxmeasure <- measure auxmeasure[[posyuimalaw]]<-dummyMeasure names(auxmeasure[posyuimalaw]) <- "df" setModel(drift = drift,diffusion = diffusion, hurst = hurst, jump.coeff = jump.coeff, measure = auxmeasure, measure.type = measure.type, state.variable = state.variable, jump.variable = jump.variable, time.variable, solve.variable, xinit) } # yuima.model rbind # setGeneric("rbind.yuima", # function(x, ...) # standardGeneric("rbind.yuima") # ) # setMethod("cbind.yuima", signature(x="yuima"), # function(x, ...){ # ##:: init # y.list <- list(x, ...) # y.num <- length(y.list) # # ##:: bind yuima.data in yuima # # ##:: return result # return(NULL) # } # ) # setMethod("rbind.yuima", signature(x="yuima.model"), # function(x, ...){ # y.list <- list(x, ...) # y.num <- length(y.list) # res <- aux.rbind.model(y.list,y.num) # return(res) # } # ) rbind.yuima.model <- function(x, ...){ y.list <- list(x, ...) # y.list1 <- lapply(y.list, FUN = only.yuima.model) y.num <- length(y.list) new.list <- list() for(i in (1:y.num)){ if(is(y.list[[i]],"yuima.model")) new.list[i] <- y.list[[i]] } new.y.num <- length(new.list) res <- aux.rbind.model(y.list = new.list, y.num = new.y.num, mycall = y.list) return(res) } aux.rbind.model<-function(y.list,y.num, mycall=list()){ lapply(y.list, FUN = check.yuima.model) check.lev <- lapply(y.list, FUN = check.yuima.levy) check.lev <- unlist(check.lev) drift <- lapply(y.list, FUN = extract.model, type = "drift") diffusion <- lapply(y.list, FUN = extract.model, type = "diffusion") solve.variable <- lapply(y.list, FUN = extract.model, type = "solve.variable") state.variable <- lapply(y.list, FUN = extract.model, type = "state.variable") xinit <- lapply(y.list, FUN = extract.model, type = "xinit") noise.number <- lapply(y.list, FUN = extract.model, type = "noise.number") equation.number <- lapply(y.list, FUN = extract.model, type = "equation.number") #Until Here only diffusion process drift <- lapply(drift, FUN = ExpToString) drift <- unlist(drift) # drift nrow.diff <- sum(unlist(equation.number)) ncol.diff <- sum(unlist(noise.number)) matr.diff <- matrix("0", nrow = nrow.diff, ncol = ncol.diff) extrinf <- 1 extrsup <- noise.number[[1]] j <- 1 cond.eq <- equation.number[[1]] cond.eq1 <- 0 for(i in c(1:nrow.diff)){ if(i <= cond.eq){ dum <- ExpToString(diffusion[[j]][[i-cond.eq1]]) matr.diff[i,extrinf:extrsup] <- dum if(i == equation.number[[j]]){ extrinf <- extrsup+1 j <- j+1 if(j <= nrow.diff){ extrsup <- extrsup + equation.number[[j]] cond.eq1 <- i cond.eq <- cond.eq + equation.number[[j]] } } } } solve.variable <- lapply(solve.variable, FUN = ExpToString, cond = FALSE) solve.variable <- unlist(solve.variable) state.variable <- lapply(state.variable, FUN = ExpToString, cond = FALSE) state.variable <- unlist(state.variable) xinit <- lapply(xinit, FUN = ExpToString, cond = FALSE) xinit <- unlist(xinit) if(!any(check.lev)){ mod <- setModel(drift = drift, diffusion = matr.diff, solve.variable = solve.variable, state.variable = state.variable, xinit = xinit) }else{ MultiLevy <- y.list[check.lev] jump.coeff <- lapply(MultiLevy, FUN = extract.model, type = "jump.coeff") ncol.jump <- lapply(jump.coeff, FUN = numb.jump) dum.ncolj <- unlist(ncol.jump) ncol.jump <- sum(unlist(dum.ncolj)) jump.coeff <- lapply(y.list, FUN = extract.model, type = "jump.coeff") #ncol.jump1 <- lapply(jump.coeff, FUN = numb.jump) matr.jump <- matrix("0",nrow = nrow.diff, ncol = ncol.jump) j <- 1 h <- 0 cond.eqa <- equation.number[[j]] cond.eqb <- 0 extrinf <- 1 extrsup <- 1 if(check.lev[j]) extrsup <- dum.ncolj[j] else{ h <- h+1 } for(i in c(1:nrow.diff)){ if(i <= cond.eqa){ if(check.lev[j]){ dum <- ExpToString(jump.coeff[[j]][[i-cond.eqb]]) matr.jump[i, extrinf:extrsup] <- dum }else{ # matr.jump[i,] <- matr.jump[i,] } if(i == cond.eqa){ cond.eqb <- i j <- j+1 if(j<=length(equation.number)) cond.eqa <- cond.eqa + equation.number[[j]] if(check.lev[j-1]){ extrinf <- extrsup + 1 extrsup <- extrsup + dum.ncolj[j-h] }else{ extrinf <- extrinf extrsup <- extrsup h <- h+1 } } } } # mod <- matr.jump # measure <- lapply(y.list, # FUN = extract.model, type = "measure") # measure df <- NULL if("df" %in% names(mycall)) df <- mycall$df measure.type <- NULL if("measure.type" %in% names(mycall)) measure.type <- mycall$measure.type intensity <-NULL if("intensity" %in% names(mycall)) intensity <- mycall$intensity time.variable <- "t" if("time.variable" %in% names(mycall)) time.variable <- mycall$time.variable mod <- setMultiModel(drift=drift, diffusion = matr.diff, jump.coeff = matr.jump, solve.variable = solve.variable, xinit = xinit, time.variable = time.variable, df= df, intensity = intensity, measure.type = measure.type) } return(mod) } # only.yuima.model<- function(y.list){ # if(is(y.list,"yuima.model")){ # return(y.list) # }else{ # NULL # } # } numb.jump <- function(x){length(x[[1]])} check.yuima.levy <- function(x){ Levy <- FALSE if(length([email protected])>0){ if(!is(x, "yuima.model")){ yuima.stop("the Levy model have to belong to the yuima.multimodel class") } Levy <- TRUE } return(Levy) } ExpToString <- function(x, cond = TRUE){ dum <- unlist(strsplit(toString(x),split=", ")) if(cond) dum <- substr(dum, 2, nchar(dum)-1) return(dum) } extract.model <- function(x, type = "drift"){ res<- slot(x,type) return(res) } check.yuima.model <- function(x){ if(is.CARMA(x)){ yuima.warn("The cbind for CARMA will be implemented as soon as possible") return(NULL) } if(is.COGARCH(x)){ yuima.warn("The cbind for COGARCH will be implemented as soon as possible") return(NULL) } if(is.Poisson(x)){ yuima.warn("The cbind for Poisson will be implemented as soon as possible") return(NULL) } }
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.model.R
# general behaviour # if grid is specified, the following are derived from it # grid -> n, delta, Initial, Terminal, regular, random # grid is ALWAYS a list, possibly of dimension 1 # if it is not a list, we transform it to a list # if grid is 1-dim, no problem, but we can have more grids. # in this case it is better to have a listI replace grid # with alist ##Constructor and Initializer of class 'sampling' # we convert objects to "zoo" internally # to be fixed: the grid should always be prepared unless it is random sampling # which.delta: check is grid is regular. If regular returns the delta, otherwise NA which.delta <- function(x) ifelse(length(unique(round(diff(x),7)))==1, diff(x)[1], NA) setMethod("initialize", "yuima.sampling", function(.Object, Initial, Terminal, n, delta, grid, random, regular, sdelta, sgrid, oindex, interpolation){ .Object@sdelta <- as.numeric(NULL) .Object@sgrid <- as.numeric(NULL) .Object@oindex <- as.numeric(NULL) .Object@interpolation <- interpolation # grid given if(!is.null(grid)){ if(!is.list(grid)){ yuima.warn("attempting to coerce 'grid' to a list, unexpected results may occur!") grid <- list(grid) } grid <- lapply(grid, sort) # we make sure grids are ordered .Object@grid <- grid .Object@Initial <- sapply(grid, min) .Object@Terminal <- sapply(grid, max) .Object@n <- sapply(grid, function(x) length(x)) .Object@random <- FALSE .Object@delta <- as.numeric(sapply(grid, which.delta)) .Object@regular <- !any(is.na( .Object@delta ) ) return(.Object) } # grid is missing, but random sampling if(!is.logical(random)){ .Object@regular <- FALSE .Object@Terminal <- Terminal .Object@Initial <- Initial .Object@n <- numeric(0) .Object@delta <- numeric(0) .Object@random <- random return(.Object) } # grid is missing, but non random sampling nTerm <- 0 if(!missing(Terminal)) nTerm <- length(Terminal) nInit <- 0 if(!missing(Initial)) nInit <- length(Initial) nObs <- 0 if(!missing(n)) nObs <- length(n) nDelta <- 0 if(!any(is.na(delta))) nDelta <- length(delta) grid <- list() # Initial + delta + n (+ Terminal: ignored) => Terminal if(nInit>0 & nDelta>0 & nObs>0){ dims <- c(nInit, nDelta, nObs) ndim <- dims[ which.max(dims) ] Initial <- rep(Initial, ndim)[1:ndim] delta <- rep(delta, ndim)[1:ndim] n <- rep(n, ndim)[1:ndim] Terminal <- Initial + n*delta yuima.warn("'Terminal' (re)defined.") for(i in 1:ndim) grid[[i]] <- seq(Initial[i], Terminal[i], by=delta[i]) .Object@Terminal <- Terminal .Object@Initial <- Initial .Object@n <- n .Object@delta <- delta .Object@grid <- grid .Object@random <- FALSE .Object@regular <- TRUE return(.Object) } # Initial + Terminal + n (+ delta: ignored) => delta if(nInit>0 & nTerm>0 & nObs>0){ dims <- c(nInit, nTerm, nObs) ndim <- dims[ which.max(dims) ] Initial <- rep(Initial, ndim)[1:ndim] Terminal <- rep(Terminal, ndim)[1:ndim] if( any(Terminal < Initial)) stop("\nYUIMA: 'Terminal' < 'Initial'\n") n <- as.integer(n) n <- rep(n, ndim)[1:ndim] delta <- (Terminal-Initial)/n yuima.warn("'delta' (re)defined.") for(i in 1:ndim) grid[[i]] <- seq(Initial[i], Terminal[i], by=delta[i]) } # Initial + delta + Terminal ( ignored) => n if(nInit>0 & nTerm>0 & nDelta>0){ dims <- c(nInit, nTerm, nDelta) ndim <- dims[ which.max(dims) ] delta <- rep(delta, ndim)[1:ndim] Initial <- rep(Initial, ndim)[1:ndim] Terminal <- rep(Terminal, ndim)[1:ndim] if( any(Terminal < Initial)) stop("\nYUIMA: 'Terminal' < 'Initial'\n") n <- as.integer((Terminal-Initial)/delta) n <- rep(n, ndim)[1:ndim] yuima.warn("'n' (re)defined.") for(i in 1:ndim) grid[[i]] <- seq(Initial[i], Terminal[i], by=delta[i]) } .Object@Terminal <- Terminal .Object@Initial <- Initial .Object@n <- n .Object@delta <- delta .Object@grid <- grid .Object@random <- FALSE .Object@regular <- TRUE return(.Object) }) setSampling <- function(Initial=0, Terminal=1, n=100, delta, grid, random=FALSE, sdelta=as.numeric(NULL), sgrid=as.numeric(NULL), interpolation="pt" ){ if(missing(delta)) delta <- NA if(missing(grid)) grid <- NULL return(new("yuima.sampling", Initial=Initial, Terminal=Terminal, n=n, delta=delta, grid=grid, random=random, regular=TRUE, sdelta=sdelta, sgrid=sgrid, interpolation=interpolation)) } #setMethod("initialize", "yuima.sampling", #function(.Object, Initial, Terminal, n, delta, grid, random, #regular, sdelta, sgrid, oindex, interpolation){ # .Object@sdelta <- as.numeric(NULL) # .Object@sgrid <- as.numeric(NULL) # .Object@oindex <- as.numeric(NULL) # .Object@interpolation <- interpolation ## grid given # if(length(grid)>0){ # testInitial<-(min(grid)==Initial) # testTerminal<-(max(grid)==Terminal) # testn<-(abs(n-diff(range(grid))/mean(diff(grid))+1)<10^(-10)) # testdelta<-(abs(delta-mean(diff(grid)))<10^(-10)) # testregular<-all(abs(diff(diff(grid)))<10^(-10)) # # if(!testInitial){ # cat("\n Start time has been set with the grid \n") # } # if(!testTerminal){ # cat("\n Terminal time has been set with the grid \n") # } # if(!testn){ # cat("\n Division has been set with the grid \n") # } # if(!testdelta){ # cat("\n delta has been set with the grid \n") # } # if(testregular){ # .Object@n <- diff(range(grid))/mean(diff(grid))+1 # .Object@delta <- mean(diff(grid)) # .Object@regular <- TRUE # }else{ # .Object@n <- length(grid)-1 # .Object@delta <- as.numeric(NULL) # .Object@regular <- FALSE # } # .Object@grid <- grid # .Object@Initial <- min(grid) # .Object@Terminal <- max(grid) # .Object@random <- random # }else{ ## There is no grid # eqn <- length(Terminal) # if(length(Terminal)==length(n)){ # .Object@Initial <- Initial # .Object@Terminal <- Terminal # .Object@n <- n # .Object@delta <- (Terminal-Initial)/n # .Object@grid <- seq(Initial,Terminal,by=.Object@delta) # .Object@random <- FALSE # .Object@regular <- regular # }else if(length(Terminal)==1){ # .Object@Initial <- Initial # .Object@Terminal <- rep(Terminal, length(n)) # .Object@n <- n # .Object@delta <- (Terminal-Initial)/n # .Object@grid <- seq(Initial,Terminal,by=.Object@delta) # .Object@random <- FALSE # .Object@regular <- regular # }else if(length(n)==1){ # .Object@Initial <- Initial # .Object@Terminal <- Terminal # .Object@n <- rep(n, length(Terminal)) # .Object@delta <- (Terminal-Initial)/n # .Object@grid <- seq(Initial,Terminal,by=.Object@delta) # .Object@random <- FALSE # .Object@regular <- regular # }else{ # cat("\nDimension missmatch.\n") # return(NULL) # }} # return(.Object) #}) #
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima.sampling.R
setClass("yuima.th", slots=c(method = "character", up = "numeric", low = "numeric", N = "numeric", N_grid = "numeric", regular_par = "ANY", h = "numeric", Dof = "character"), contains= "yuima.law") setMethod("initialize", "yuima.th", function(.Object, h=1, method="LAG", up=7, low=-7, N=180, N_grid=1000, regular_par=NULL){ .Object@density<- dtLevy .Object@cdf<- ptLevy .Object@quantile<- qtLevy .Object@rng<- rtLevy .Object@method <- method .Object@up <- up .Object@low <- low .Object@N <- N .Object@N_grid <- N_grid .Object@regular_par <- regular_par .Object@h <- h .Object@Dof <- "nu" [email protected] <- "nu" # validObject(.Object) return(.Object) } ) setLaw_th <- function(h=1,method="LAG", up=7, low=-7, N=180, N_grid=1000, regular_par=NULL, ...) { initialize(new("yuima.th"), h=h, method=method, up=up, low=low, N=N, N_grid=N_grid, regular_par=regular_par, ...) } setMethod("dens", "yuima.th", function(object, x, param, log = FALSE, ...){ if(is.list(param)){ nu <- unlist(param)[[email protected]] }else{ nu <- param[[email protected]] } res <- object@density(x = x, nu = nu, h = object@h, method = object@method, up = object@up, low = object@low, N=object@N, N_grid = object@N_grid, regular_par = object@regular_par) if(log){ res <- log(res) } return(res) } ) setMethod("cdf", "yuima.th", function(object, q, param, ...){ if(is.list(param)){ nu <- unlist(param)[[email protected]] }else{ nu <- param[[email protected]] } res <- object@cdf(q, nu = nu, h = object@h, method = object@method, up = object@up, low = object@low, N=object@N, N_grid = object@N_grid, regular_par = object@regular_par) return(res) } ) setMethod("quant", "yuima.th", function(object, p, param, ...){ if(is.list(param)){ nu <- unlist(param)[[email protected]] }else{ nu <- param[[email protected]] } res <- object@quantile(p, nu = nu, h = object@h, method = object@method, up = object@up, low = object@low, N=object@N, N_grid = object@N_grid, regular_par = object@regular_par) return(res) } ) setMethod("rand", "yuima.th", function(object, n, param, ...){ if(is.list(param)){ nu <- unlist(param)[[email protected]] }else{ nu <- param[[email protected]] } res <- numeric(length = n) res <- object@rng(n, nu = nu, h = object@h, method = object@method, up = object@up, low = object@low, N=object@N, N_grid = object@N_grid, regular_par = object@regular_par) return(res) } ) setClass("yuima.LevyRM", slots=c(unit_Levy ="yuima.th", regressors ="character", LevyRM = "character", paramRM = "character", paramAll = "character", solve.varRM = "character", coeff = "character"), contains = "yuima") setMethod("initialize", "yuima.LevyRM", function(.Object, unit_Levy, yuima_regressors, LevyRM="Y", coeff=c("mu","sigma0"), data, sampling, characteristic, functional ){ .Object@coeff <- c(paste0(coeff[1],1:length([email protected])),coeff[2]) .Object@paramRM <- c(.Object@coeff,[email protected]) .Object@paramAll <- c(yuima_regressors@parameter@all, .Object@paramRM) [email protected] <- c([email protected],LevyRM) .Object@LevyRM <- LevyRM .Object@regressors <- [email protected] .Object@unit_Levy <- unit_Levy test <- new("yuima", data = data, model = yuima_regressors, sampling = sampling, characteristic = characteristic, functional = functional) .Object@data <- test@data .Object@sampling <- test@sampling .Object@model <- yuima_regressors .Object@characteristic <- test@characteristic .Object@functional <- test@functional #validObject(.Object) return(.Object) } ) setLRM <- function(unit_Levy, yuima_regressors, LevyRM="Y", coeff=c("mu","sigma0"), data=NULL, sampling = NULL, characteristic = NULL, functional = NULL, ...) { new("yuima.LevyRM", unit_Levy=unit_Levy, yuima_regressors=yuima_regressors, LevyRM = LevyRM, coeff = coeff, data = data, sampling = sampling, characteristic = characteristic, functional = functional) } #setMethod("simulate","yuima.LevyRM", aux.simulateLevyRM <- function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized = FALSE, increment.W = NULL, increment.L = NULL, method = "euler", hurst, methodfGn = "WoodChan", sampling=sampling, subsampling=subsampling, ...){ Samp <- sampling param <- true.parameter if(length(param[object@model@parameter@all])==0){ traj <- simulate(object = object@model, nsim=nsim, seed=seed, xinit=xinit, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst=hurst, methodfGn = methodfGn, sampling=Samp, subsampling=subsampling) }else{ traj <- simulate(object = object@model, nsim=nsim, seed=seed, true.parameter = param[object@model@parameter@all], xinit=xinit, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst=hurst, methodfGn = methodfGn, sampling=Samp, subsampling=subsampling) } myint <- object@unit_Levy myint@h <- sampling@delta param <- unlist(param) # defaultW <- getOption("warn") # options(warn = -1) deltaLt <- rand(myint,n=sampling@n,param[[email protected]]) process <- c(0,cumsum(deltaLt)) test<- traj@[email protected]%*%param[object@paramRM[1:length(object@regressors)]] test<- test+param[object@paramRM[length(object@regressors)+1]]*process/sqrt(param[[email protected]]) #plot(x=sampling@grid[[1]],y=as.numeric(test),type="l") res<-cbind(traj@[email protected],test) colnames(res) <- [email protected] mydata <- setData(as.matrix(res),delta=sampling@delta, t0=sampling@Initial) object@data <- mydata object@unit_Levy@h<-1 # res<-setLRM(object@unit_Levy, object@yuima_regressors, LevyRM="Y", coeff=c("mu","sigma0"), # data=mydata, sampling = Samp, characteristic = characteristic, # functional = functional) # res<-new("yuima.LevyRM", unit_Levy=object@unit_Levy, # yuima_regressors=object@yuima_regressors, # LevyRM = object@LevyRM, coeff = c("mu","sigma"), # data = mydata, sampling = Samp, # characteristic = object@characteristic, functional = object@functional) return(object) } #) estimation_LRM <- function(start, model, data, upper, lower, PT=500, n_obs1=NULL){ mydata <- data if(is.null(n_obs1)){ n_obs1 <- floor((dim([email protected])[1]-1)/diff(range(index([email protected])))) } Term <- tail(index([email protected][[1]]),1L) NofW <- n_obs1*Term # the number of the whole data m <- n_obs1*PT # the number of the data for the estimation of mu and sigma labY <- model@LevyRM Y <- as.numeric([email protected][,labY]) regrlab <- model@regressors X <- as.matrix([email protected][,regrlab]) dY <- Y[2:NofW] - Y[1:(NofW-1)] dX <- X[2:NofW,] - X[1:(NofW-1),] # first stage estimation # minus Cauchy quasi-likelihood h<-1/n_obs1 day <- n_obs1 Term <- floor((dim([email protected])[1]-1)*h) if(length(regrlab)==1){ mcql <- function(par, model, h, m){ mu <- par[model@paramRM[1:length(model@regressors)]] sigma <- par[model@paramRM[length(model@regressors)+1]] #sum(log(sigma) + log(1 + (dY[1:m] - mu1*dX1[1:m] - mu2*dX2[1:m])^2/(h*sigma)^2)) sum(log(sigma) + log(1 + (dY[1:m] - dX[1:m]*mu)^2/(h*sigma)^2)) } }else{ mcql <- function(par, model, h, m){ mu <- par[model@paramRM[1:length(model@regressors)]] sigma <- par[model@paramRM[length(model@regressors)+1]] #sum(log(sigma) + log(1 + (dY[1:m] - mu1*dX1[1:m] - mu2*dX2[1:m])^2/(h*sigma)^2)) sum(log(sigma) + log(1 + (dY[1:m] - dX[1:m,]%*%mu)^2/(h*sigma)^2)) } } # estimation of mu and sigma (partial data) fres <- optim(par = unlist(start), fn = mcql, lower = lower, upper = upper, method = "L-BFGS-B", model=model, h=h, m=m) esig <- fres$par[model@paramRM[length(model@regressors)+1]] emu <- fres$par[model@paramRM[1:length(model@regressors)]] # second stage estimation # unit-time increments # if(is.null(data)){ # Term <- floor(tail(index(model@[email protected][[1]]),1L)) # }else{ # Term <- floor(tail(index([email protected][[1]]),1L)) # } duY <- numeric(Term) duX <- matrix(NA, Term, length(model@regressors)) #duX2 <- numeric(Term) duY[1] <- Y[day] duX[1,] <- X[day,] for(i in 2:Term){ duY[i] <- Y[i*day] - Y[(i-1)*day + 1] duX[i,] <- X[i*day,] - X[(i-1)*day + 1,] } # unit-time residuals ures <- numeric(Term) for(i in 1:Term){ ures[i] <- esig^(-1)*(duY[i] - duX[i,]%*%emu ) } # hres <- numeric(m) # for(i in 1:m){ # hres[i] <- esig^(-1)/h*(dY[i] - dX[i,]%*%emu) # } # minus (scaled) student-t likelihood function (unit time) stl <- function(nu){ sum(-log(gamma((nu + 1)/2)) + log(gamma(nu/2)) + (nu + 1)/2*log(1 + (ures)^2)) #-sum(log(dt(ures, nu))) } #sres <- optimize(stl, c(0.01, 10)) sres<-optim(1,fn=stl,method="Brent",upper=100,lower=0.00001) enu <- sres$par names(enu)<-"nu" est<-c(emu, esig, enu) dFPos <- length(model@paramRM) # scalepos <- length(model@paramRM)-1 mycoef_a <- est[model@paramRM[-c(scalepos,dFPos)]] X_data <- [email protected][,model@regressors] if(length(model@regressors)==1){ VarX_data<- as.matrix(diff(X_data)) }else{ VarX_data<-apply(X_data,2,"diff") } #Nn <- dim(VarX_data)[1] Sn <- as.matrix(VarX_data[1,])%*%t(as.matrix(VarX_data[1,])) #m <- n_obs1*PT for(i in c(2:m)){ Sn <- Sn+as.matrix(VarX_data[i,])%*%t(as.matrix(VarX_data[i,])) } Sn <- 1/(h^2*m)*Sn esig <- est[model@paramRM[scalepos]] GAM_a <- matrix(0, dim(Sn)[1]+1,dim(Sn)[2]+1) GAM_a[1:dim(Sn)[1],1:dim(Sn)[1]]<-Sn/(2*esig^2) GAM_a[dim(Sn)[1]+1,dim(Sn)[2]+1] <- 1/(2*esig^2) Vcov1 <- 1/m*solve(GAM_a) enu <- est[model@paramRM[dFPos]] GAM_nu <- 1/4*(trigamma(enu/2)-trigamma((enu+1)/2)) Vcov2 <- 1/Term*solve(GAM_nu) Vcov <- matrix(0 , dim(Vcov1)[1]+1,dim(Vcov1)[2]+1) Vcov[1:dim(Vcov1)[1],1:dim(Vcov1)[1]]<- Vcov1 Vcov[dim(Vcov1)[1]+1,dim(Vcov1)[1]+1]<- Vcov2 call <- match.call() colnames(Vcov)<-names(est) rownames(Vcov)<-names(est) min <- c(fres$value,sres$value) final_res <- new("yuima.qmle", call = call, coef = est, fullcoef = est, vcov = Vcov, min = min, details = list(), minuslogl = function(){NULL}, method = "L-BFGS-B", nobs=as.integer(NofW), model=model@model) #return(list(est=est,vcov=Vcov)) return(final_res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima_t_regression_model_new_class.R
# Algorithms for the density of the increment of a L\'evy t - student process ## Internal functions: ### internal characteristic function phi_int <- function(t,lambda,v){ if(t==0){ return(1) }else{ t=1i*t my<-(sqrt(v)*abs(t))^lambda*besselK(sqrt(v)*abs(t),lambda)/(gamma(lambda)*2^(lambda-1)) return(my) } } phi <- Vectorize(phi_int, vectorize.args = "t") ### FFT internal function Inter_dens <-function (n, nu, h, alim, blim) { v=nu lambda = nu/2 i <- 0:(n - 1) dx <- (blim - alim)/n x <- alim + i * dx dt <- 2 * pi/(n * dx) c <- -n/2 * dt d <- n/2 * dt t <- c + i * dt phi_t <- phi(t,lambda,v)^h X <- exp(-(0 + (0+1i)) * i * dt * alim) * phi_t Y <- fft(X) density <- dt/(2 * pi) * exp(-(0 + (0+1i)) * c * x) * Y data.frame(i = i, t = t, characteristic_function = phi_t, x = x, density = Re(density)) } Internal_FTT_dens<-function (x, nu, h, N = 2^10) { # if (length(x) == 1) { # alim <- min((-abs(x) - 0.5), setInf) # blim <- max((abs(x) + 0.5), setSup) # } # else { # xdummy <- na.omit(x[is.finite(x)]) # alim <- min(min(xdummy) - 0.1, setInf) # blim <- max(max(xdummy) + 0.1, setSup) # } alim <- min(x) blim <- max(x) invFFT <-Inter_dens(n=N, nu=nu, h=h, alim = alim, blim = blim) dens <- spline(invFFT$x, invFFT$density, xout=x) return(dens$y) } ### COS internal function inter_fun_cos1 <- function(x,FK,k,low,Dt,w){ C_fun <- cos(k*pi*(x-low)/Dt) f <- sum(w*FK*C_fun) return(f) } inter_fun_cos_vect <- Vectorize(FUN=inter_fun_cos1,vectorize.args ="x") cos_method_dens_t <-function(pts, nu, h, N=100){ Dt <- diff(range(pts)) k <- c(0:N) w <- c(0.5,rep(1,N)) char_h <- phi(t=k*pi/Dt,lambda=nu/2,v=nu)^h low <- min(pts) FK <- 2/Dt*Re(char_h*exp(-1i*k*pi*low/Dt)) dens <- inter_fun_cos_vect(x=pts,FK=FK,k=k, low=low,Dt=Dt,w=w) return(dens) } ### Laguerre Internal_LAG_dens <-function(pts,nu,h=1, n=40){ # without tail approx #if(is.null(regular_par)){ x<- pts/sqrt(nu) alpha <- nu*h/2 out <- gauss.quad(n,"laguerre",alpha=alpha) nodes<-out$nodes myw_1<-out$weights*exp(out$nodes)*(besselK(out$nodes,nu/2))^h arg <- cos(as.matrix(nodes)%*%t(x)) dens <-((2^(1-nu/2)/gamma(nu/2))^h)/(pi)*t(myw_1)%*%arg dens <- as.numeric(dens)/sqrt(nu) return(dens) } intern_dens <- function(mydens,x,nu,sigma=1,h=1, n=40){ dens<-mydens pos_low<-tail(which(dens<0 & x<=0),1L)+1 pos_up<-which(dens<0 & x>0)[1]-1 if(is.na(pos_low)||is.infinite(pos_low)||length(pos_low)==0){ pos_low<-0 } if(is.na(pos_up)){ pos_up <- +Inf } B_nu <- h*gamma(0.5*nu+0.5)/(sqrt(pi)*gamma(0.5*nu)) expnu <- -1/2*(nu+1) if(pos_low>1&pos_up<length(x)){ dens_low <- B_nu*(1+x[1:pos_low]^2)^expnu #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) dens_up <- B_nu*(1+x[pos_up:length(x)]^2)^expnu # beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[pos_up:length(stddata)])^(1+beta)*pi) dens <- c(dens_low,dens[(pos_low+1):(pos_up-1)],dens_up) }else{ if(pos_low>1&!pos_up<length(x)){ dens_low <- B_nu*(1+x[1:pos_low]^2)^expnu #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) dens <- c(dens_low,dens[(pos_low+1):length(x)]) } if(!pos_low>1&pos_up<length(x)){ dens_up <- B_nu*(1+x[pos_up:length(x)]^2)^expnu dens <- c(dens[1:(pos_up-1)],dens_up) } if(!pos_low>1&!pos_up<length(x)){ dens<-dens } } return(dens) } mydtlevy_1vers <-function(x,nu,sigma=1,h=1, n=40){ # without tail approx #if(is.null(regular_par)){ alpha <- nu*h/2 out <- gauss.quad(n,"laguerre",alpha=alpha) nodes<-out$nodes myw_1<-out$weights*exp(out$nodes)*(besselK(out$nodes,nu/2))^h int <- as.matrix(nodes)%*%t(x/sigma) #arg <- matrix(0,dim(int)[1],dim(int)[2]) a <- cos(int) dens <-((2^(1-nu/2)/gamma(nu/2))^h)/(pi*sigma)*t(myw_1)%*%a dens <- as.numeric(dens) return(dens) } mydtlevy_4vers<- function(x,nu,sigma,h, n, regular_par,ImprovGibbs){ if(is.null(regular_par)){ L<-0 }else{ L<-regular_par } if(length(x)>1){ oldx <- x x<-sort(unique(x)) dens <- as.numeric(mydtlevy_1vers(x,nu,sigma,h, n)) pos_low<-max(tail(which(diff(dens)<0 & x[-1]<=0),1L), tail(which(dens<0 & x<=0),1L))+1 pos_up<-min(which(diff(dens)>0 & x[-1]>0)[1],which(dens<0 & x>0)[1])-1 if(is.na(pos_low)){ pos_low<-0 } if(is.na(pos_up)){ pos_up <- +Inf } if(pos_low>1&pos_up<length(x)){ x_dow <- x[1:pos_low] dens_low <- (as.numeric(mydtlevy_1vers(x_dow-L,nu,sigma,h, n))+as.numeric(mydtlevy_1vers(x_dow+L,nu,sigma,h, n)))/2 #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) x_up <- x[pos_up:length(x)] dens_up <- (as.numeric(mydtlevy_1vers(x_up-L,nu,sigma,h, n))+as.numeric(mydtlevy_1vers(x_up+L,nu,sigma,h, n)))/2 dens <- c(dens_low,dens[(pos_low+1):(pos_up-1)],dens_up) if(ImprovGibbs){ dens<-intern_dens(dens,x,nu,sigma,h, n) } }else{ if(pos_low>1&!pos_up<length(x)){ x_dow <- x[1:pos_low] dens_low <- (as.numeric(mydtlevy_1vers(x_dow-L,nu,sigma,h, n))+as.numeric(mydtlevy_1vers(x_dow+L,nu,sigma,h, n)))/2 #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) dens <- c(dens_low,dens[(pos_low+1):length(x)]) if(ImprovGibbs){ dens<-intern_dens(dens,x,nu,sigma,h, n) } } if(!pos_low>1&pos_up<length(x)){ x_up <- x[pos_up:length(x)] dens_up <- (as.numeric(mydtlevy_1vers(x_up-L,nu,sigma,h, n))+as.numeric(mydtlevy_1vers(x_up+L,nu,sigma,h, n)))/2 dens <- c(dens[1:(pos_up-1)],dens_up) if(ImprovGibbs){ dens<-intern_dens(dens,x,nu,sigma,h, n) } } if(!pos_low>1&!pos_up<length(x)){ dens<-dens } } pos <- match(oldx,x) dens <- dens[pos] }else{ dens <- as.numeric(mydtlevy_1vers(x,nu,sigma,h, n)) if(dens<0){ B_nu <- h*gamma(0.5*nu+0.5)/(sqrt(pi)*gamma(0.5*nu)) expnu <- -1/2*(nu+1) dens <- B_nu*(1+x^2)^expnu } } } rt_Levy<-function(n,nu=1,h=1,n_laguerre=180,up=7,low=-7, N_grid=500001, regular_par=NULL,ImprovGibbs=TRUE){ xin<- seq(low,up,length.out=N_grid) dens_g <- mydtlevy_4vers(xin/sqrt(nu),nu=nu,sigma=1,h=h, n=n_laguerre, regular_par=regular_par, ImprovGibbs=ImprovGibbs)/sqrt(nu) cond <- xin>=low & xin<=up cdf_g <- cumsum(dens_g*diff(xin)[1]) cdf_g0<-cdf_g[cond] cond_cdf<-(cdf_g0-cdf_g0[1])/(tail(cdf_g0,1L)-cdf_g0[1]) U=runif(n) # res<-as.numeric(approx(x=cond_cdf, # y=xin[cond],xout=U,method="constant",f=1)$y) res<-as.numeric(spline(x=cond_cdf, y=xin[cond],xout=U)$y) return(res) } ## NO_Approx tdens_noapprox <- function(x, nu, h, method="COS", N = 2^7){ #pts <- sort(unique(c(x,seq(low,up,length.out=N_grid)))) if(method=="COS"){ dens0<- cos_method_dens_t(pts=x, nu=nu, h=h, N=N) }else{ if(method=="FFT"){ dens0 <- Internal_FTT_dens(x=x, nu=nu, h=h, N = N) }else{ if(method=="LAG"){ dens0 <- Internal_LAG_dens(pts=x,nu=nu,h=h, n=N) }else{ yuima.stop("method must be either 'COS' or 'FFT' or 'LAG')") } } } #pos <- match(x,pts) #mydens <- dens0[pos] return(dens0) } ## Tail approx approx_dens1 <- function(mydens,x,nu,h){ dens<-mydens pos_low<-tail(which(dens<0 & x<=0),1L)+1 pos_up<-which(dens<0 & x>0)[1]-1 # pos_low<-max(tail(which(diff(dens)<0 & x[-1]<=0),1L), tail(which(dens<0 & x<=0),1L))+1 # pos_up<-min(which(diff(dens)>0 & x[-1]>0)[1],which(dens<0 & x>0)[1])-1 # if(is.na(pos_low)||is.infinite(pos_low)||length(pos_low)==0){ pos_low<-0 } if(is.na(pos_up)){ pos_up <- +Inf } B_nu <- h*gamma(0.5*nu+0.5)/(sqrt(pi)*gamma(0.5*nu)) expnu <- -1/2*(nu+1) if(pos_low>1&pos_up<length(x)){ dens_low <- B_nu*(1+x[1:pos_low]^2)^expnu #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) dens_up <- B_nu*(1+x[pos_up:length(x)]^2)^expnu # beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[pos_up:length(stddata)])^(1+beta)*pi) dens <- c(dens_low,dens[(pos_low+1):(pos_up-1)],dens_up) }else{ if(pos_low>1&!pos_up<length(x)){ dens_low <- B_nu*(1+x[1:pos_low]^2)^expnu #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) dens <- c(dens_low,dens[(pos_low+1):length(x)]) } if(!pos_low>1&pos_up<length(x)){ dens_up <- B_nu*(1+x[pos_up:length(x)]^2)^expnu dens <- c(dens[1:(pos_up-1)],dens_up) } if(!pos_low>1&!pos_up<length(x)){ dens<-dens } } return(dens) } # Inter_mytail2<-function(dens,x,pos, pos2,C_nu){ # t_low <- 1/(1+x[pos]^2) # t_low_inc <- 1/(1+x[pos2]^2) # f<- dens[pos] # delta_t_low <- t_low-t_low_inc # delta_f_low <- (f-dens[pos2])/(t_low-t_low_inc) # C_nu_low <- C_nu*t_low^(0.5*nu+.5) # Mat_low <- matrix(c(2*t_low,-1,-t_low^2,t_low),2,2)/(C_nu_low*t_low^2) # Coeff_low <- Mat_low%*%(c(f,delta_f_low)-c(C_nu_low,1/2*(nu+1)*t_low^(-1)*f)) # return(Coeff_low) # } # # # Inter_mytail<-function(dens,x,pos,C_nu){ # t_low <- 1/(1+x[pos]^2) # f<- dens[pos] # C_nu_low <- C_nu*t_low^(0.5*nu+.5) # Coeff_low <- (f/C_nu_low-1)/t_low # return(Coeff_low) # } # # # approx_dens2 <- function(mydens,x,nu,h){ # dens<-mydens # pos_low<-tail(which(dens<0 & x<=0),1L)+1 # pos_up<-which(dens<0 & x>0)[1]-1 # # pos_low<-max(tail(which(diff(dens)<0 & x[-1]<=0),1L), tail(which(dens<0 & x<=0),1L))+1 # # pos_up<-min(which(diff(dens)>0 & x[-1]>0)[1],which(dens<0 & x>0)[1])-1 # # if(is.na(pos_low)||is.infinite(pos_low)||length(pos_low)==0){ # pos_low<-0 # } # if(is.na(pos_up)){ # pos_up <- +Inf # } # C_nu<- h*gamma(0.5*nu+0.5)/(sqrt(pi)*gamma(0.5*nu)) # if(pos_low>1&pos_up<length(x)){ # #pos_low2<-pos_low+1 # #Coeff_low <- Inter_mytail(dens=dens,x=x,pos=pos_low, pos2=pos_low2,C_nu=C_nu) # Coeff_low <- Inter_mytail(dens=dens,x=x,pos=pos_low,C_nu=C_nu) # t_low <- 1/(1+x[1:pos_low]^2) # #dens_low<- C_nu*t_low^(0.5*nu+0.5)*(1+Coeff_low[1,1]*t_low+Coeff_low[2,1]*t_low^2) # dens_low<- C_nu*t_low^(0.5*nu+0.5)*(1+Coeff_low*t_low) # # # pos_up2<-pos_up-1 # # Coeff_up <- Inter_mytail(dens=dens,x=x,pos=pos_up, pos2=pos_up2,C_nu=C_nu) # Coeff_up <- Inter_mytail(dens=dens,x=x,pos=pos_up,C_nu=C_nu) # t_up <- 1/(1+x[pos_up:length(x)]^2) # #dens_up<- C_nu*t_up^(0.5*nu+0.5)*(1+Coeff_up[1,1]*t_up+Coeff_up[2,1]*t_up^2) # dens_up<- C_nu*t_up^(0.5*nu+0.5)*(1+Coeff_up*t_up) # dens <- c(dens_low,dens[(pos_low+1):(pos_up-1)],dens_up) # }else{ # if(pos_low>1&!pos_up<length(x)){ # #dens_low <- B_nu*(1+x[1:pos_low]^2)^expnu #beta*sin(beta*pi/(2))*gamma(beta)/(abs(stddata[1:pos_low])^(1+beta)*pi) # # pos_low2<-pos_low+1 # # Coeff_low <- Inter_mytail(dens=dens,x=x,pos=pos_low, pos2=pos_low2,C_nu=C_nu) # Coeff_low <- Inter_mytail(dens=dens,x=x,pos=pos_low, C_nu=C_nu) # t_low <- 1/(1+x[1:pos_low]^2) # #dens_low<- C_nu*t_low^(0.5*nu+0.5)*(1+Coeff_low[1,1]*t_low+Coeff_low[2,1]*t_low^2) # dens_low<- C_nu*t_low^(0.5*nu+0.5)*(1+Coeff_low*t_low) # dens <- c(dens_low,dens[(pos_low+1):length(x)]) # } # if(!pos_low>1&pos_up<length(x)){ # #dens_up <- B_nu*(1+x[pos_up:length(x)]^2)^expnu # #pos_up2<-pos_up-1 # #Coeff_up <- Inter_mytail(dens=dens,x=x,pos=pos_up, pos2=pos_up2,C_nu=C_nu) # Coeff_up <- Inter_mytail(dens=dens,x=x,pos=pos_up, C_nu=C_nu) # t_up <- 1/(1+x[pos_up:length(x)]^2) # #dens_up<- C_nu*t_up^(0.5*nu+0.5)*(1+Coeff_up[1,1]*t_up+Coeff_up[2,1]*t_up^2) # dens_up<- C_nu*t_up^(0.5*nu+0.5)*(1+Coeff_up*t_up) # dens <- c(dens[1:(pos_up-1)],dens_up) # } # if(!pos_low>1&!pos_up<length(x)){ # dens<-dens # } # } # # } # yuima density function dtLevy<-function(x, nu, h, method="COS", up = 7, low = -7, N = 2^7, N_grid=1000, regular_par=NULL){ pts <- sort(unique(c(x,seq(low,up,length.out=N_grid)))) if(method == "COS" | method == "FFT"){ approx_tail <- "NO" }else{ approx_tail <- "Tail_Approx1" } if(method=="LAG" & approx_tail=="Tail_Approx1"){ mydens <- mydtlevy_4vers(pts/sqrt(nu),nu=nu,sigma=1,h=h, n=N, regular_par=regular_par, ImprovGibbs=TRUE)/sqrt(nu) pos <- match(x,pts) mydens1 <-mydens[pos] return(mydens1) } dens0<-tdens_noapprox(x=pts, nu, h, method, N) #if(approx_tail=="NO"){ pos <- match(x,pts) mydens <- dens0[pos] return(mydens) #}else{ # if(approx_tail=="Tail_Approx1"){ # mydens <- approx_dens1(mydens=dens0,x=pts,nu=nu,h=h) # pos <- match(x,pts) # mydens1 <-mydens[pos] # return(mydens1) # } # if(approx_tail=="Tail_Approx2"){ # mydens <- approx_dens2(mydens=dens0,x=pts,nu=nu,h=h) # pos <- match(x,pts) # mydens1 <-mydens[pos] # return(mydens1) # } #} } # yuima cdf # cdf ptLevy<-function(x, nu, h, method="COS", up = 7, low = -7, N = 2^7, N_grid=1000,regular_par=NULL){ pts <- sort(unique(c(x,seq(low,up,length.out=N_grid)))) if(method == "COS" | method == "FFT"){ approx_tail <- "NO" }else{ approx_tail <- "Tail_Approx1" } if(method=="LAG" & approx_tail=="Tail_Approx1"){ dens_g <- mydtlevy_4vers(pts/sqrt(nu),nu=nu,sigma=1,h=h, n=N, regular_par=regular_par, ImprovGibbs=TRUE)/sqrt(nu) }else{ dens_g <- dtLevy(x=pts, nu=nu, h=h, method=method, up=max(pts), low=min(pts), N=N, N_grid=2) } cdf_g <- cumsum(dens_g*diff(pts)[1]) cond <- pts>=low & pts<=up cdf_g0<-cdf_g[cond] cond_cdf<-(cdf_g0-cdf_g0[1])/(tail(cdf_g0,1L)-cdf_g0[1]) res<-as.numeric(spline(x=pts[cond], y=cond_cdf,xout=x)$y) return(res) } # yuima quantile # quantile qtLevy<-function(p, nu, h, method="COS", up = 7, low = -7, N = 2^7, N_grid=1000,regular_par=NULL){ pts <- seq(low,up,length.out=N_grid) if(method == "COS" | method == "FFT"){ approx_tail <- "NO" }else{ approx_tail <- "Tail_Approx1" } if(method=="LAG" & approx_tail=="Tail_Approx1"){ dens_g <- mydtlevy_4vers(pts/sqrt(nu),nu=nu,sigma=1,h=h, n=N, regular_par=regular_par, ImprovGibbs=TRUE)/sqrt(nu) }else{ dens_g<-dtLevy(x=pts, nu=nu, h=h, method=method, up=max(pts), low=min(pts), N=N, N_grid=2) } cdf_g <- cumsum(dens_g*diff(pts)[1]) cond <- pts>=low & pts<=up cdf_g0<-cdf_g[cond] cond_cdf<-(cdf_g0-cdf_g0[1])/(tail(cdf_g0,1L)-cdf_g0[1]) res<-as.numeric(approx(x=cond_cdf, y=pts[cond],xout=p,method="constant",f=1)$y) # res<-as.numeric(spline(x=cond_cdf, # y=pts[cond],xout=p)$y) return(res) } # yuima rng # Random Number Generator rtLevy<-function(n, nu, h, method="COS", up = 7, low = -7, N = 2^7, N_grid=1000,regular_par=NULL){ if(method == "COS" | method == "FFT"){ approx_tail <- "NO" }else{ approx_tail <- "Tail_Approx1" } if(method=="LAG" & approx_tail=="Tail_Approx1"){ res<-rt_Levy(n=n,nu=nu,h=h,n_laguerre=N,up=up,low=low, N_grid=c(N_grid+1), regular_par=regular_par, ImprovGibbs=TRUE) return(res) } pts <- seq(low,up,length.out=N_grid) dens_g<-dtLevy(x=pts, nu=nu, h=h, method=method, up=max(pts), low=min(pts), N=N, N_grid=2) cdf_g <- cumsum(dens_g*diff(pts)[1]) cond <- pts>=low & pts<=up cdf_g0<-cdf_g[cond] cond_cdf<-(cdf_g0-cdf_g0[1])/(tail(cdf_g0,1L)-cdf_g0[1]) U <- runif(n) # res<-as.numeric(approx(x=cond_cdf, # y=pts[cond],xout=U,method="constant",f=1, ties = mean)$y) # if we use constant we have more zeros res<-as.numeric(approx(x=cond_cdf, y=pts[cond],xout=U,method="linear",f=1, ties = mean)$y) # if we use constant we have more zeros # res<-as.numeric(spline(x=cond_cdf, # y=pts[cond],xout=U)$y) return(res) # newpts <- seq(pts[which(cdf_g0>0.001)[1]], pts[which(cdf_g0>1-0.001)[1]-1],length.out=N_grid) # # dens_g<-dtLevy(x=newpts, nu=nu, h=h, method=method, # up=max(newpts), low=min(newpts), N=N, N_grid=2) # cdf_g0 <- cumsum(dens_g*diff(pts)[1]) # # cond_cdf<-(cdf_g0-cdf_g0[1])/(tail(cdf_g0,1L)-cdf_g0[1]) # U <- runif(n) # # res<-as.numeric(approx(x=cond_cdf, # # y=newpts,xout=U,method="constant",f=1)$y) # if we use constant we have more zeros # res<-as.numeric(spline(x=cond_cdf, # y=newpts,xout=U)$y) # # U <- runif(n) # # res<-as.numeric(approx(x=cdf_g, # # y=pts,xout=U,method="constant",f=1)$y) # # # return(res) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/yuima_t_student_Levy.R
#.First.lib <- function(lib, pkg) library.dynam("sde", pkg, lib) #.noGenerics <- TRUE .onAttach <- function(libname, pkgname) { # require(methods) # require(zoo) Pver <- read.dcf(file=system.file("DESCRIPTION", package=pkgname), fields="Version") packageStartupMessage(rep("#",40)) packageStartupMessage(sprintf("This is YUIMA Project package v.%s", Pver)) packageStartupMessage("Why don't you try yuimaGUI package?") packageStartupMessage("Visit: http://www.yuima-project.com") packageStartupMessage(rep("#",40)) # require(KernSmooth, quietly=TRUE) # library.dynam("yuima", pkgname, libname) }
/scratch/gouwar.j/cran-all/cranData/yuima/R/zzz.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) Rver <- paste(version$major,version$minor, collapse="",sep=".") YUIMAver <- as.character(read.dcf(file=system.file("DESCRIPTION", package="yuima"), fields="Version")) ## ----eval=FALSE---------------------------------------------------------- ## ybook(1) ## ----eval=FALSE---------------------------------------------------------- ## ybook(3) ## ------------------------------------------------------------------------ data(cars) class(cars) ## ------------------------------------------------------------------------ summary(cars) mod <- lm(dist~speed, data=cars) summary(mod) ## ------------------------------------------------------------------------ class(mod) ## ------------------------------------------------------------------------ methods(summary) ## ------------------------------------------------------------------------ x <- 1:4 x class(x) class(x) <- "lm" class(x) ## ------------------------------------------------------------------------ require(stats4) set.seed(123) y <- rnorm(100, mean=1.5) f <- function(theta=0) -sum(dnorm(x=y, mean=theta,log=TRUE)) fit <- mle(f) fit ## ----results='hide'------------------------------------------------------ str(fit) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(fit)),width=60)) ## ------------------------------------------------------------------------ fit@coef ## ------------------------------------------------------------------------ showMethods(summary) ## ----eval=FALSE---------------------------------------------------------- ## install.packages("yuima") ## ----eval=FALSE---------------------------------------------------------- ## install.packages("yuima",repos="http://R-Forge.R-project.org") ## ----eval=FALSE---------------------------------------------------------- ## install.packages("yuima",repos="http://R-Forge.R-project.org", ## type="source") ## ----echo=TRUE,eval=TRUE,results='markup',showWarnings=TRUE-------------- library(yuima) ## ----echo=TRUE,results='hide'-------------------------------------------- mod1 <- setModel(drift = "-3*x", diffusion = "1/(1+x^2)") ## ----results='hide'------------------------------------------------------ str(mod1) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(mod1)),width=60)) ## ------------------------------------------------------------------------ mod1 ## ----echo=TRUE,results='hide'-------------------------------------------- mod1b <- setModel(drift = "-3*s*y", diffusion = "1/(1+y^2)", state.var="y", time.var="s") ## ------------------------------------------------------------------------ tmp <- capture.output(str(mod1b)) writeLines(strwrap(tmp[c(2,3,4,17,19,23)],width=60)) ## ----echo=TRUE,results='hide'-------------------------------------------- mod2 <- setModel(drift = "-mu*x", diffusion = "1/(1+x^gamma)") ## ------------------------------------------------------------------------ tmp <- capture.output(str(mod2)) writeLines(strwrap(tmp[c(2,3,4,9:13,17,19,23)],width=60)) ## ------------------------------------------------------------------------ mod2 ## ----sim-mod1,echo=TRUE,results='hide'----------------------------------- set.seed(123) X <- simulate(mod1) ## ----plot-mod1,echo=TRUE,fig.keep='none',results='hide'------------------ plot(X) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ----plot-mod1bis,echo=TRUE,fig.keep='none',results='hide'--------------- x0 <- 1 set.seed(123) X <- simulate(mod1, xinit=x0) plot(X) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1bis.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ----results='hide'------------------------------------------------------ str(X@data,vec.len=2) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(X@data,vec.len=2)),width=60)) ## ------------------------------------------------------------------------ str(X@sampling,vec.len=2) ## ------------------------------------------------------------------------ tmp <- capture.output(str(X)) writeLines(strwrap(tmp[c(14:16,29,31,35,36)],width=60)) ## ------------------------------------------------------------------------ X ## ----plot-mod1ter,echo=TRUE,fig.keep='none',results='hide'--------------- x0 <- 1 set.seed(123) X <- simulate(mod1, xinit=x0, Initial=0.5, Terminal=1.2) X plot(X) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1ter.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ------------------------------------------------------------------------ str(X@sampling,vec.len=2) ## ----plot-mod1b,echo=TRUE,fig.keep='none',results='hide'----------------- set.seed(123) X <- simulate(mod1b, xinit=x0) X plot(X) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1b.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ----sim-mod2,echo=TRUE,fig.keep='none',results='hide'------------------- set.seed(123) X <- simulate(mod2,true.param=list(mu=1,gamma=3)) plot(X) ## ----plot-mod2,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-mod2.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ------------------------------------------------------------------------ sol <- c("x1","x2") # variable for numerical solution b <- c("-theta*x1","-x1-gamma*x2") # drift vector s <- matrix(c("1","x1","0","beta","x2","0"),2,3) # diff. mat. mymod <- setModel(drift = b, diffusion = s, solve.variable = sol) ## ------------------------------------------------------------------------ samp <- setSampling(Terminal=3, n=3000) ## ----results='hide'------------------------------------------------------ str(samp) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(samp)),width=60)) ## ------------------------------------------------------------------------ set.seed(123) X2 <- simulate(mymod, sampling=samp, true.param=list(theta=1,gamma=1,beta=1)) X2 ## ----results='hide'------------------------------------------------------ str(X2@sampling) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(X2@sampling)),width=60)) ## ----sub1---------------------------------------------------------------- newsamp <- setSampling( random=list(rdist=c( function(x) rexp(x, rate=10), function(x) rexp(x, rate=20))) ) ## ----results='hide'------------------------------------------------------ str(newsamp) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(newsamp)),width=60)) ## ----sub2,echo=TRUE, fig.keep='none'------------------------------------- newdata <- subsampling(X2, sampling=newsamp) newdata plot(X2,plot.type="single", lty=c(1,3),ylab="X2") points(get.zoo.data(newdata)[[1]],col="red") points(get.zoo.data(newdata)[[2]],col="green",pch=18) ## ----plot-sub2,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-sub2.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X2,plot.type="single", lty=c(1,3),ylab="X2") points(get.zoo.data(newdata)[[1]],col="red") points(get.zoo.data(newdata)[[2]],col="green",pch=18) dev.off() ## ----sub3,echo=TRUE, fig.keep='none'------------------------------------- newsamp <- setSampling(Terminal=3, delta=c(0.1,0.2), n=NULL) newsamp newdata <- subsampling(X2, sampling=newsamp) newdata plot(X2,plot.type="single", lty=c(1,3),ylab="X2") points(get.zoo.data(newdata)[[1]],col="red") points(get.zoo.data(newdata)[[2]],col="green", pch=18) ## ----plot-sub3,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-sub3.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X2,plot.type="single", lty=c(1,3),ylab="X2") points(get.zoo.data(newdata)[[1]],col="red") points(get.zoo.data(newdata)[[2]],col="green", pch=18) dev.off() ## ------------------------------------------------------------------------ str(newdata@sampling) ## ----sub4,fig.keep='none'------------------------------------------------ set.seed(123) Y.sub <- simulate(mymod,sampling=setSampling(delta=0.001,n=1000), subsampling=setSampling(delta=0.01,n=100), true.par=list(theta=1,beta=1,gamma=1)) set.seed(123) Y <- simulate(mymod, sampling=setSampling(delta=0.001,n=1000), true.par=list(theta=1,beta=1,gamma=1)) plot(Y, plot.type="single") points(get.zoo.data(Y.sub)[[1]],col="red") points(get.zoo.data(Y.sub)[[2]],col="green",pch=18) ## ----plot-sub4,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-sub4.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(Y, plot.type="single") points(get.zoo.data(Y.sub)[[1]],col="red") points(get.zoo.data(Y.sub)[[2]],col="green",pch=18) dev.off() ## ----sub5,fig.keep='none'------------------------------------------------ plot(Y.sub, plot.type="single") ## ----plot-sub5,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-sub5.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(Y.sub, plot.type="single") dev.off() ## ------------------------------------------------------------------------ Y Y.sub ## ----eval=FALSE---------------------------------------------------------- ## my.yuima <- setYuima(data=setData(X), model=mod) ## ----echo=TRUE,results='hide',tidy=TRUE---------------------------------- require(quantmod) getSymbols("IBM", to = "2017-07-31") ## ----echo=TRUE----------------------------------------------------------- str(IBM) ## ----echo=TRUE----------------------------------------------------------- head(IBM) ## ------------------------------------------------------------------------ x <- setYuima(data=setData(IBM$IBM.Close)) str(x@data) ## ------------------------------------------------------------------------ y <- setYuima(data=setData(IBM$IBM.Close, delta=1/252)) str(y@data) ## ----setData,fig.keep='none'--------------------------------------------- plot(x, main="data with the original time stamps") plot(y, main="time stamps of data rescaled") ## ----plot-setData,echo=FALSE, fig.keep='none',results='hide'------------- pdf("figures/plot-setData.pdf",width=9,height=6) par(mar=c(4,4,2,1), mfrow=c(2,1)) plot(x, main="data with the original time stamps") plot(y, main="time stamps of data rescaled") dev.off() ## ------------------------------------------------------------------------ x y ## ----quantmod,message=FALSE---------------------------------------------- library(quantmod) getSymbols("IBM", to = "2017-07-31") attr(IBM, "src") ## ------------------------------------------------------------------------ getSymbols("IBM", to = "2017-07-31", src="google") attr(IBM, "src") ## ------------------------------------------------------------------------ getSymbols("DEXUSEU",src="FRED") attr(DEXUSEU, "src") getSymbols("EUR/USD",src="oanda") attr(EURUSD, "src") str(EURUSD) ## ----results='hide'------------------------------------------------------ library(tseries) x <- get.hist.quote("IBM") str(x) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(x)),width=60)) ## ------------------------------------------------------------------------ mydat <- get.zoo.data(y)[[1]] str(mydat) ## ------------------------------------------------------------------------ head(y@[email protected]) ## ----results='hide'------------------------------------------------------ str(y@[email protected]) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(y@[email protected])),width=60)) ## ------------------------------------------------------------------------ set.seed(123) some.data <- rnorm(12) str(some.data) ## ------------------------------------------------------------------------ X <- ts(some.data, frequency = 4, start = c(1961, 2)) X ## ------------------------------------------------------------------------ set.seed(123) X <- ts(some.data, start = c(1964, 2), frequency = 12) X ## ------------------------------------------------------------------------ time(X)[1:12] deltat(X) start(X) end(X) frequency(X) ## ------------------------------------------------------------------------ window(X, frequency=4) ## ------------------------------------------------------------------------ require(zoo) X <- zoo( some.data ) X str(X) ## ------------------------------------------------------------------------ index(X) ## ------------------------------------------------------------------------ rtimes <- cumsum(rexp(12,rate=0.2)) rtimes ## ------------------------------------------------------------------------ X <- zoo( rnorm(12), order.by = rtimes) X str(X) ## ------------------------------------------------------------------------ Xreg <- zooreg(some.data, start = c(1964, 2), frequency = 12) time(Xreg) ## ------------------------------------------------------------------------ Y <- as.ts(X) time(X) time(Y) ## ------------------------------------------------------------------------ require(xts) my.time.stamps <- as.Date(rtimes) my.time.stamps X <- xts( some.data , order.by = my.time.stamps) X str(X) ## ------------------------------------------------------------------------ X.ts <- ts(some.data, start = c(1964, 2), frequency = 12) X.ts X.zoo <- as.zoo(X.ts) X.zoo X.xts <- as.xts(X.ts) X.xts ## ----xts,fig.keep='none'------------------------------------------------- plot(X) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-xts.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(X) dev.off() ## ------------------------------------------------------------------------ require(tseries) X <- irts( rtimes, some.data) X str(X) ## ------------------------------------------------------------------------ require(timeSeries) X <- timeSeries( some.data, my.time.stamps) X str(X) ## ------------------------------------------------------------------------ d <- ISOdate(2008,7,3) d ## ----results='hide'------------------------------------------------------ args(ISOdate) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(args(ISOdate)),width=60)) ## ------------------------------------------------------------------------ class(d) ## ------------------------------------------------------------------------ names(as.POSIXlt(d)) unlist(as.POSIXlt(d)) ## ------------------------------------------------------------------------ format(d,"%a") # week day format(d,"%A") format(d,"%b") # month format(d,"%B") format(d,"%c") # full date format(d,"%D") # yy/dd/mm format(d,"%T") # hh:mm:ss format(d,"%A %B %d %H:%M:%S %Y") format(d,"%A %d/%m/%Y") format(d,"%d/%m/%Y (%A)") ## ------------------------------------------------------------------------ x <- c("10jan1962", "2feb1970", "11jul2011", "27jun1968") strptime(x, "%d%b%Y") ## ------------------------------------------------------------------------ Sys.getlocale() Sys.setlocale("LC_ALL", "it_it") strptime(x, "%d%b%Y") Sys.setlocale("LC_ALL", "en_GB") strptime(x, "%d%b%Y") ## ------------------------------------------------------------------------ format(ISOdate(2006,6,9),"%H:%M:%S") format(as.POSIXct("2006-06-09"),"%H:%M:%S") ## ------------------------------------------------------------------------ holidayNYSE() holidayNERC() ## ------------------------------------------------------------------------ ISOdate(2006,7,10) - ISOdate(2005, 3, 1) ## ------------------------------------------------------------------------ my.dates <- timeDate(c("2001-01-09", "2001-02-25")) diff(my.dates) ## ------------------------------------------------------------------------ listFinCenter("America*")[1:50] ## ------------------------------------------------------------------------ dA <- timeDate("2011-02-05", Fin="Europe/Zurich") dB <- timeDate("2016-01-22", Fin="America/Chicago") dA dB ## ------------------------------------------------------------------------ set.seed(123) mydata <- rnorm(9) chardata <- sprintf("2010-0%s-01", 9:1) chardata ## ------------------------------------------------------------------------ X1 <- zoo(mydata, as.Date(chardata)) X2 <- xts(mydata, as.Date(chardata)) X3 <- timeSeries(mydata, chardata) ## ------------------------------------------------------------------------ X1 X2 X3 ## ------------------------------------------------------------------------ zA <- zoo(mydata, as.POSIXct(chardata)) zB <- zoo(mydata, ISOdatetime(2016, 9:1, 1, 0,0,0)) zC <- zoo(mydata, ISOdate(2016, 9:1, 1, 0)) zA zB zC ## ------------------------------------------------------------------------ set.seed(123) val1 <- rnorm(9) val2 <- rnorm(6) mydate1 <- ISOdate(2016,1:9,1) mydate2 <- ISOdate(2015,6:11,1) Z1 <- zoo(val1, mydate1) Z2 <- zoo(val2, mydate2) rbind(Z1,Z2) X1 <- xts(val1, mydate1) X2 <- xts(val2, mydate2) rbind(X1,X2) W1 <- timeSeries(val1, mydate1) W2 <- timeSeries(val2, mydate2) rbind(W1,W2) ## ------------------------------------------------------------------------ mydate2 <- ISOdate(2016,4:9,1) Z2 <- zoo(val2, mydate2) ## ----eval=FALSE---------------------------------------------------------- ## rbind(Z1,Z2) ## ----echo=FALSE---------------------------------------------------------- cat(unclass(try(rbind(Z1,Z2)))) ## ------------------------------------------------------------------------ X2 <- xts(val2, mydate2) rbind(X1,X2) W2 <- timeSeries(val2, mydate2) rbind(W1,W2) ## ------------------------------------------------------------------------ merge(Z1,Z2) merge(X1,X2) ## ------------------------------------------------------------------------ merge(W1,W2) ## ------------------------------------------------------------------------ W2 <- timeSeries(val2, mydate2, units="MyData") merge(W1,W2) ## ------------------------------------------------------------------------ mydate1 <- ISOdate(2016,1:9,1) mydate2 <- ISOdate(2015,6:11,1) W1 <- timeSeries(val1, mydate1) W2 <- timeSeries(val2, mydate2) ## ------------------------------------------------------------------------ rbind(W1,W2) ## ------------------------------------------------------------------------ rbind(W2,W1) ## ------------------------------------------------------------------------ sort( rbind(W2,W1) ) sort( rbind(W2,W1), decr=TRUE) ## ------------------------------------------------------------------------ W2 rev(W2) ## ----results="hide",message=FALSE---------------------------------------- require(sde) data(quotes) str(quotes) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(quotes)),width=60)) ## ------------------------------------------------------------------------ quotes[2,2:4] quotes[10:20,"INTEL"] ## ------------------------------------------------------------------------ quotes$INTEL[10:20] ## ------------------------------------------------------------------------ mydate <- as.Date(sprintf("2006-08-%.2d",20:10)) mydate quotes[mydate, 5:9] ## ------------------------------------------------------------------------ initial <- as.Date("2007-05-15") terminal <- as.Date("2007-05-21") quotes[ (time(quotes) >= initial) & (time(quotes)<= terminal), 4:9] ## ------------------------------------------------------------------------ getSymbols("IBM", from="2015-01-01", to = "2016-12-31") str(IBM) ## ------------------------------------------------------------------------ IBM["2015-01","IBM.Close"] ## ------------------------------------------------------------------------ IBM["2016-02-11/2016-03-05","IBM.Close"] ## ------------------------------------------------------------------------ IBM["/2015-02-11","IBM.Close"] ## ------------------------------------------------------------------------ mod2 <- setModel(drift = "-mu*x", diffusion = "1/(1+x^gamma)") mod2 ## ------------------------------------------------------------------------ toLatex(mod2) ## ----echo=FALSE, results='asis', include=TRUE---------------------------- toLatex(mod2) ## ------------------------------------------------------------------------ sol <- c("x1","x2") # variable for numerical solution b <- c("-theta*x1","-x1-gamma*x2") # drift vector s <- matrix(c("1","x1","0","delta","x2","0"),2,3) # diff. mat. mymod <- setModel(drift = b, diffusion = s, solve.variable = sol) ## ----echo=FALSE, results='asis', include=TRUE---------------------------- toLatex(mymod) ## ----eval=FALSE---------------------------------------------------------- ## install.packages("yuimaGUI") ## ----eval=FALSE---------------------------------------------------------- ## library(yuimaGUI) ## yuimaGUI()
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter1.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ----results='hide',tidy=FALSE,width.cutoff = 60------------------------- mod1 <- setModel(drift = "-3*x", diffusion = "1/(1+x^2)", xinit="rnorm(1)") str(mod1) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(mod1)),width=60)) ## ----plot-mod1diff,echo=TRUE,fig.keep='none',results='hide'-------------- set.seed(123) x1 <- simulate(mod1) x2 <- simulate(mod1) par(mfrow=c(1,2)) plot(x1) plot(x2) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1diff.pdf",width=9,height=4) par(mar=c(4,4,1,1)) set.seed(123) x1 <- simulate(mod1) x2 <- simulate(mod1) par(mfrow=c(1,2)) plot(x1) plot(x2) dev.off() ## ----results='hide'------------------------------------------------------ mod2 <- setModel(drift = "-3*x", diffusion = "1/(1+x^2)", xinit="rnorm(1, mean=mu)") mod2 str(mod2) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(mod2)),width=60)) ## ----eval=FALSE---------------------------------------------------------- ## x <- simulate(mod2, true.par=list(mu=1)) ## ----plot-mod1diff2,echo=TRUE,fig.keep='none',results='hide'------------- mod1 <- setModel(drift = "-3*x", diffusion = "1/(1+x^2)") set.seed(123) x1 <- simulate(mod1, xinit=1) x2 <- simulate(mod1, xinit=expression(rnorm(1))) x3 <- simulate(mod2, xinit=3) par(mfrow=c(1,3)) plot(x1, main="mod1, xinit=1") plot(x2, main="mod1, xinit=expression(rnorm(1))") plot(x3, main="mod2, xinit=3") par(mfrow=c(1,1)) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-mod1diff2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) mod1 <- setModel(drift = "-3*x", diffusion = "1/(1+x^2)") set.seed(123) x1 <- simulate(mod1, xinit=1) x2 <- simulate(mod1, xinit=expression(rnorm(1))) x3 <- simulate(mod2, xinit=3) par(mfrow=c(1,3)) plot(x1, main="mod1, xinit=1") plot(x2, main="mod1, xinit=expression(rnorm(1))") plot(x3, main="mod2, xinit=3") dev.off() ## ------------------------------------------------------------------------ ou <- setModel(drift="-theta*x", diffusion=1) ## ------------------------------------------------------------------------ gBm <- setModel(drift="mu*x", diffusion="sigma*x") ## ------------------------------------------------------------------------ vasicek <- setModel(drift="theta1-theta2*x", diffusion="theta3") ## ------------------------------------------------------------------------ cev <- setModel(drift="mu*x", diffusion="sigma*x^gamma") ## ------------------------------------------------------------------------ cir <- setModel(drift="theta1-theta2*x", diffusion="theta3*sqrt(x)") ## ------------------------------------------------------------------------ ckls <- setModel(drift="theta1-theta2*x", diffusion="theta3*x^theta4") ## ------------------------------------------------------------------------ hyper1 <- setModel( diff="sigma", drift="(sigma^2/2)*(beta-alpha*((x-mu)/(sqrt(delta^2+(x-mu)^2))))") ## ------------------------------------------------------------------------ hyper1 str(hyper1@parameter) ## ------------------------------------------------------------------------ hyper2 <- setModel(drift="0", diffusion = "sigma*exp(0.5*alpha*sqrt(delta^2+(x-mu)^2)- beta*(x-mu))") ## ------------------------------------------------------------------------ hyper2 str(hyper2@parameter) ## ------------------------------------------------------------------------ set.seed(123) modA <- setModel(drift="-0.3*x", diffusion=1) modB <- setModel(drift="0.3*x", diffusion=1) ## Set the model in an `yuima' object with a sampling scheme. Terminal <- 1 n <- 500 mod.sampling <- setSampling(Terminal=Terminal, n=n) yuima1 <- setYuima(model=modA, sampling=mod.sampling) yuima2 <- setYuima(model=modB, sampling=mod.sampling) ##use original increment delta <- Terminal/n my.dW <- matrix( rnorm(n , 0, sqrt(delta)), nrow=1, ncol=n) ## Solve SDEs using Euler-Maruyama method. y1 <- simulate(yuima1, xinit=1, increment.W=my.dW) y2 <- simulate(yuima2, xinit=1, increment.W=my.dW) ## ----plot-modAB,echo=TRUE,fig.keep='none',results='hide'----------------- plot(y1) lines(get.zoo.data(y2)[[1]], col="red",lty=3) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-modAB.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(y1) lines(get.zoo.data(y2)[[1]], col="red",lty=3) dev.off() ## ----echo=TRUE,results='hide'-------------------------------------------- sol <- c("x1","x2") # variable for numerical solution a <- c("-3*x1","-x1-2*x2") # drift vector b <- matrix(c("1","x1","0","3","x2","0"),2,3) # diffusion matrix mod3 <- setModel(drift = a, diffusion = b, solve.variable = sol) ## ----sim-mod3,echo=TRUE,fig.keep='none',results='hide'------------------- set.seed(123) X <- simulate(mod3) plot(X, plot.type="single",lty=1:2) ## ----plot-mod3,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-mod3.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(X, plot.type="single",lty=1:2) dev.off() ## ----echo=TRUE,results='hide'-------------------------------------------- mu <- 0.1 sig <- 0.2 rho <- -0.7 g <- function(t) {0.4 + (0.1 + 0.2*t)* exp(-2*t)} f1 <- function(t, x1, x2, x3) { ret <- 0 if(x1 > 0 && x2 > 0) ret <- x2*exp(log(x1)*2/3) return(ret) } f2 <- function(t, x1, x2, x3) { ret <- 0 if(x3 > 0) ret <- rho*sig*x3 return(ret) } f3 <- function(t, x1, x2, x3) { ret <- 0 if(x3 > 0) ret <- sqrt(1-rho^2)*sig*x3 return(ret) } diff.coef.matrix <- matrix(c("f1(t,x1,x2,x3)", "f2(t,x1,x2,x3) * g(t)", "f2(t,x1,x2,x3)", "0", "f3(t,x1,x2,x3)*g(t)", "f3(t,x1,x2,x3)"), 3, 2) sabr.mod <- setModel(drift = c("0", "mu*g(t)*x3", "mu*x3"), diffusion = diff.coef.matrix, state.variable = c("x1", "x2", "x3"), solve.variable = c("x1", "x2", "x3")) str(sabr.mod@parameter) ## ----echo=TRUE,results='hide'-------------------------------------------- f2 <- function(t, x1, x2, x3, rho, sig) { ret <- 0 if(x3 > 0) ret <- rho*sig*x3 return(ret) } f3 <- function(t, x1, x2, x3, rho, sig) { ret <- 0 if(x3 > 0) ret <- sqrt(1-rho^2)*sig*x3 return(ret) } diff.coef.matrix <- matrix(c("f1(t,x1,x2,x3)", "f2(t,x1,x2,x3,rho, sig) * g(t)", "f2(t,x1,x2,x3,rho,sig)", "0", "f3(t,x1,x2,x3,rho,sig)*g(t)", "f3(t,x1,x2,x3,rho,sig)"), 3, 2) sabr.mod <- setModel(drift = c("0", "mu*g(t)*x3", "mu*x3"), diffusion = diff.coef.matrix, state.variable = c("x1", "x2", "x3"), solve.variable = c("x1", "x2", "x3")) str(sabr.mod@parameter) ## ------------------------------------------------------------------------ Sigma <- matrix(c(0.5, 0.7, 0.7, 2), 2, 2) C <- chol(Sigma) C crossprod(C) Sigma ## ------------------------------------------------------------------------ set.seed(123) drift <- c("mu*x1", "kappa*(theta-x2)") diffusion <- matrix(c("c11*sqrt(x2)*x1", "0", "c12*sqrt(x2)*x1", "c22*epsilon*sqrt(x2)"),2,2) heston <- setModel(drift=drift, diffusion=diffusion, state.var=c("x1","x2")) X <- simulate(heston, true.par=list(theta=0.5, mu=1.2, kappa=2, epsilon=0.2, c11=C[1,1], c12=C[1,2], c22=C[2,2]), xinit=c(100,0.5)) ## ----plot-heston,echo=FALSE, fig.keep='none',results='hide'-------------- pdf("figures/plot-heston.pdf",width=9,height=6) set.seed(123) par(mar=c(4,4,1,1)) plot(X) dev.off() ## ----echo=TRUE,results='hide'-------------------------------------------- ymodel <- setModel(drift="(2-theta2*x)", diffusion="(1+x^2)^theta1") n <- 750 ysamp <- setSampling(Terminal = n^(1/3), n = n) yuima <- setYuima(model = ymodel, sampling = ysamp) set.seed(123) yuima <- simulate(yuima, xinit = 1, true.parameter = list(theta1 = 0.2, theta2 = 0.3)) ## ----echo=TRUE,results='hide'-------------------------------------------- param.init <- list(theta2=0.5,theta1=0.5) low.par <- list(theta1=0, theta2=0) upp.par <- list(theta1=1, theta2=1) mle1 <- qmle(yuima, start = param.init, lower = low.par, upper = upp.par) ## ----results='hide'------------------------------------------------------ summary(mle1) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(mle1)),width=60)) ## ----echo=TRUE----------------------------------------------------------- prior <- list(theta2=list(measure.type="code",df="dunif(theta2,0,1)"), theta1=list(measure.type="code",df="dunif(theta1,0,1)")) ## ----echo=TRUE, results='hide'------------------------------------------- lower <- list(theta1=0,theta2=0) upper <- list(theta1=1,theta2=1) bayes1 <- adaBayes(yuima, start=param.init, prior=prior, lower=lower,upper=upper, method="nomcmc") ## ----echo=TRUE----------------------------------------------------------- coef(summary(bayes1)) coef(summary(mle1)) ## ------------------------------------------------------------------------ n <- 500 ysamp <- setSampling(Terminal = n^(1/3), n = n) yuima <- setYuima(model = ymodel, sampling = ysamp) set.seed(123) yuima <- simulate(yuima, xinit = 1, true.parameter = list(theta1 = 0.2, theta2 = 0.3)) param.init <- list(theta2=0.5,theta1=0.5) lower <- list(theta1=0, theta2=0) upper <- list(theta1=1, theta2=1) mle2 <- qmle(yuima, start =param.init , lower = lower, upper = upper) bayes2 <- adaBayes(yuima, start=param.init, prior=prior, lower=lower,upper=upper) ## ------------------------------------------------------------------------ coef(summary(bayes2)) coef(summary(mle2)) ## ------------------------------------------------------------------------ ymodel <- setModel(drift="(2-theta2*x)", diffusion="(1+x^2)^theta1") n <- 100000 ysamp <- setSampling(delta=0.001, n = n) mod <- setYuima(model = ymodel, sampling=ysamp) set.seed(123) yuima <- simulate(mod, xinit = 1, true.parameter = list(theta1 = 0.2, theta2 = 0.3)) param.init <- list(theta2=0.5,theta1=0.5) yuima0.01 <- subsampling(yuima, sampling=setSampling(delta=0.01,n=NULL,Terminal=100)) yuima0.1 <- subsampling(yuima, sampling=setSampling(delta=0.1,n=NULL,Terminal=100)) yuima1.0 <- subsampling(yuima, sampling=setSampling(delta=1,n=NULL,Terminal=100)) ## ----echo=TRUE, fig.keep='none',results='hide'--------------------------- par(mfrow=c(2,2)) plot(yuima,main="delta=0.001, n=100000") plot(yuima0.01,main="delta=0.01, n=10000") plot(yuima0.1,main="delta=0.1, n=1000") plot(yuima1.0,main="delta=1.0, n=100") ## ----plot-delta,echo=FALSE, fig.keep='none',results='hide'--------------- pdf("figures/plot-delta.pdf",width=9,height=6) par(mar=c(4,4,3,1)) par(mfrow=c(2,2)) plot(yuima,main="delta=0.001, n=100000") plot(yuima0.01,main="delta=0.01, n=10000") plot(yuima0.1,main="delta=0.1, n=1000") plot(yuima1.0,main="delta=1.0, n=100") dev.off() ## ------------------------------------------------------------------------ low <- list(theta1=0, theta2=0) up <- list(theta1=1, theta2=1) mle0.001 <- qmle(yuima, start = param.init, lower = low, upper = up) summary(mle0.001)@coef mle0.01 <- qmle(yuima0.01, start = param.init, lower = low, upper = up) summary(mle0.01)@coef mle0.1 <- qmle(yuima0.1, start = param.init, lower = low, upper = up) summary(mle0.1)@coef mle1.0 <- qmle(yuima1.0, start = param.init, lower = low, upper = up) summary(mle1.0)@coef ## ----echo=FALSE---------------------------------------------------------- est <- rbind( t(summary(mle0.001)@coef), t(summary(mle0.01)@coef), t(summary(mle0.1)@coef), t(summary(mle1.0)@coef)) ## ----message=FALSE------------------------------------------------------- library(quantmod) getSymbols("AAPL",to="2016-12-31") head(AAPL) S <- AAPL$AAPL.Adjusted ## ------------------------------------------------------------------------ Delta <- 1/252 gBm <- setModel(drift="mu*x", diffusion="sigma*x") mod <- setYuima(model=gBm, data=setData(S, delta=Delta)) ## ----appl,echo=TRUE,fig.keep='none',results='hide'----------------------- set.seed(123) plot(S) ## ----plot-aapl,echo=FALSE, fig.keep='none',results='hide'---------------- pdf("figures/plot-aapl.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(S) dev.off() ## ----results='hide'------------------------------------------------------ fit <- qmle(mod, start=list(mu=1, sigma=1), lower=list(mu=0.1, sigma=0.1), upper=list(mu=100, sigma=10)) summary(fit) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit)),width=60)) ## ------------------------------------------------------------------------ X <- diff(log(S)) X <- as.numeric(na.omit(diff(log(S)))) alpha <- mean(X)/Delta sigma <- sqrt(var(X)/Delta) mu <- alpha +0.5*sigma^2 mu sigma coef(fit) ## ------------------------------------------------------------------------ getSymbols("DEXUSEU", src="FRED") DEXUSEU <- DEXUSEU["/2016"] head(DEXUSEU) meanCIR <- mean(DEXUSEU, na.rm=TRUE) meanCIR ## ----dexuseu,echo=TRUE,fig.keep='none',results='hide'-------------------- set.seed(123) plot(DEXUSEU) ## ----plot-dexuseu,echo=FALSE, fig.keep='none',results='hide'------------- pdf("figures/plot-dexuseu.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(DEXUSEU) dev.off() ## ------------------------------------------------------------------------ cir1 <- setModel(drift="theta1-theta2*x", diffusion="sigma*sqrt(x)") cir2 <- setModel(drift="kappa*(mu-x)", diffusion="sigma*sqrt(x)") mod1 <- setYuima(model=cir1, data=setData(na.omit(DEXUSEU), delta=Delta)) mod2 <- setYuima(model=cir2, data=setData(na.omit(DEXUSEU), delta=Delta)) ## ----results='hide'------------------------------------------------------ fit1 <- qmle(mod1, start=list(theta1=1, theta2=1, sigma=0.5), lower=list(theta1=0.1, theta2=0.1, sigma=0.1), upper=list(theta1=10, theta2=10, sigma=100), method="L-BFGS-B") summary(fit1) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit1)),width=60)) ## ----results='hide'------------------------------------------------------ fit2 <- qmle(mod2, start=list(kappa=1, mu=meanCIR, sigma=0.5), lower=list(kappa=0.1, mu=0.1, sigma=0.1), upper=list(kappa=10, mu=10, sigma=100), method="L-BFGS-B") summary(fit2) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit2)),width=60)) ## ------------------------------------------------------------------------ theta1 <- as.numeric( coef(fit2)["kappa"] * coef(fit2)["mu"] ) theta1 coef(fit1)["theta1"] ## ------------------------------------------------------------------------ mu <- as.numeric( coef(fit1)["theta1"] / coef(fit1)["theta2"] ) mu coef(fit2)["mu"] ## ------------------------------------------------------------------------ model<- setModel(drift="t1*(t2-x)",diffusion="t3") ## ------------------------------------------------------------------------ T<-300 n<-3000 sampling <- setSampling(Terminal=T, n=n) yuima<-setYuima(model=model, sampling=sampling) h00 <- list(t1=0.3, t2=1, t3=0.25) h01 <- list(t1=0.3, t2=0.2, t3=0.1) set.seed(123) X <- simulate(yuima, xinit=1, true.par=h00) ## ------------------------------------------------------------------------ phi1 <- function(x) 1-x+x*log(x) ## ------------------------------------------------------------------------ phi.test(X, H0=h00, phi=phi1, start=h00, lower=list(t1=0.1, t2=0.1, t3=0.1), upper=list(t1=2,t2=2,t3=2),method="L-BFGS-B") ## ----echo=FALSE,results='hide'------------------------------------------- pval <- phi.test(X, H0=h00, phi=phi1, start=h00, lower=list(t1=0.1, t2=0.1, t3=0.1), upper=list(t1=2,t2=2,t3=2),method="L-BFGS-B")$pvalue ## ------------------------------------------------------------------------ phi.test(X, H0=h01, phi=phi1, start=h00, lower=list(t1=0.1, t2=0.1, t3=0.1), upper=list(t1=2,t2=2,t3=2),method="L-BFGS-B") ## ------------------------------------------------------------------------ library(quantmod) Delta <- 1/252 getSymbols("DEXUSEU", src="FRED") DEXUSEU <- DEXUSEU["/2016"] USEU <- setData(na.omit(DEXUSEU), delta=Delta) meanCIR <- mean(get.zoo.data(USEU)[[1]]) gBm <- setModel(drift="mu*x", diffusion="sigma*x") mod <- setYuima(model=gBm, data=USEU) cir1 <- setModel(drift="theta1-theta2*x", diffusion="sigma*sqrt(x)") cir2 <- setModel(drift="kappa*(mu-x)", diffusion="sigma*sqrt(x)") ckls <- setModel(drift="theta1-theta2*x", diffusion="sigma*x^gamma") mod1 <- setYuima(model=cir1, data=USEU) mod2 <- setYuima(model=cir2, data=USEU) mod3 <- setYuima(model=ckls, data=USEU) gBm.fit <- qmle(mod, start=list(mu=1, sigma=1), lower=list(mu=0.1, sigma=0.1), upper=list(mu=100, sigma=10)) cir1.fit <- qmle(mod1, start=list(theta1=1, theta2=1, sigma=0.5), lower=list(theta1=0.1, theta2=0.1, sigma=0.1), upper=list(theta1=10, theta2=10, sigma=100), method="L-BFGS-B") cir2.fit <- qmle(mod2, start=list(kappa=1, mu=meanCIR, sigma=0.5), lower=list(kappa=0.1, mu=0.1, sigma=0.1), upper=list(kappa=10, mu=10, sigma=100), method="L-BFGS-B") ckls.fit <- qmle(mod3, start=list(theta1=1, theta2=1, sigma=0.5, gamma=0.5), lower=list(theta1=0.1, theta2=0.1, sigma=0.1, gamma=0.1), upper=list(theta1=10, theta2=10, sigma=10, gamma=2), method="L-BFGS-B") ## ------------------------------------------------------------------------ AIC(gBm.fit,cir1.fit,cir2.fit,ckls.fit) ## ----echo=FALSE---------------------------------------------------------- tmp <- AIC(gBm.fit,cir1.fit,cir2.fit,ckls.fit) ## ------------------------------------------------------------------------ set.seed(123) S <- simulate(gBm, true.par=list(mu=1, sigma=0.25), sampling=setSampling(T=1, n=1000), xinit=100) mod <- setYuima(model=gBm, data=S@data) mod1 <- setYuima(model=cir1, data=S@data) mod2 <- setYuima(model=cir2, data=S@data) mod3 <- setYuima(model=ckls, data=S@data) gBm.fit <- qmle(mod, start=list(mu=1, sigma=1), lower=list(mu=0.1, sigma=0.1), upper=list(mu=100, sigma=10)) cir1.fit <- qmle(mod1, start=list(theta1=1, theta2=1, sigma=0.5), lower=list(theta1=0.1, theta2=0.1, sigma=0.1), upper=list(theta1=10, theta2=10, sigma=100), method="L-BFGS-B") cir2.fit <- qmle(mod2, start=list(kappa=1, mu=meanCIR, sigma=0.5), lower=list(kappa=0.1, mu=0.1, sigma=0.1), upper=list(kappa=10, mu=10, sigma=100), method="L-BFGS-B") ckls.fit <- qmle(mod3, start=list(theta1=1, theta2=1, sigma=0.5, gamma=0.5), lower=list(theta1=0.1, theta2=0.1, sigma=0.1, gamma=0.1), upper=list(theta1=10, theta2=10, sigma=10, gamma=2), method="L-BFGS-B") ## ------------------------------------------------------------------------ AIC(gBm.fit,cir1.fit,cir2.fit,ckls.fit) ## ----echo=FALSE---------------------------------------------------------- tmp <- AIC(gBm.fit,cir1.fit,cir2.fit,ckls.fit) ## ------------------------------------------------------------------------ a <- c("1-mu11*X1+mu12*X2","2+mu21*X1-mu22*X2") b <- matrix(c("s1*X1","s2*X1", "-s3*X2","s4*X2"),2,2) mod.est <- setModel(drift=a, diffusion=b, solve.var=c("X1","X2"),state.variable=c("X1","X2")) truep <- list(mu11=.9, mu12=0, mu21=0, mu22=0.7, s1=.3, s2=0,s3=0,s4=.2) low <- list(mu11=1e-5, mu12=1e-5, mu21=1e-5, mu22=1e-5, s1=1e-5, s2=1e-5, s3=1e-5,s4=1e-5) upp <- list(mu11=2, mu12=2, mu21=1, mu22=1, s1=1, s2=1, s3=1,s4=1) set.seed(123) n <- 1000 X <- simulate(mod.est, T=n^(1/3), n=n, xinit=c(1,1), true.parameter=truep) ## ----results='hide'------------------------------------------------------ myest <- lasso(X, delta=2, start=truep, lower=low, upper=upp, method="L-BFGS-B") myest ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(myest),width=60)) ## ------------------------------------------------------------------------ fit1 <- qmle(X, start=truep, lower=low, upper=upp, method="L-BFGS-B") ## ------------------------------------------------------------------------ a <- c("1-mu11*X1","2-mu22*X2") b <- matrix(c("s1*X1","0", "0","s4*X2"),2,2) mod.est2 <- setModel(drift=a, diffusion=b, solve.var=c("X1","X2"),state.variable=c("X1","X2")) truep <- list(mu11=.9, mu22=0.7, s1=.3,s4=.2) low <- list(mu11=1e-5, mu22=1e-5, s1=1e-5, s4=1e-5) upp <- list(mu11=2, mu22=2, s1=1, s4=1) Y <- setYuima(model=mod.est2, data=X@data) fit2 <- qmle(Y, start=truep, lower=low, upper=upp, method="L-BFGS-B") summary(fit1) summary(fit2) AIC(fit1, fit2) ## ----results='hide',fig.keep='none',message=FALSE------------------------ library("Ecdat") data("Irates") rates <- Irates[,"r1"] plot(rates) X <- window(rates, start=1964.471, end=1989.333) mod <- setModel(drift="alpha+beta*x", diffusion="sigma*x^gamma") yuima <- setYuima(data=setData(X,delta=1/12), model=mod) start <- list(alpha=1, beta =-.1, sigma =.1, gamma =1) low <- list(alpha=-5, beta =-5, sigma =-5, gamma =-5) upp <- list(alpha=8, beta =8, sigma =8, gamma =8) ## ----plot-irates,echo=FALSE, fig.keep='none',results='hide'-------------- pdf("figures/plot-irates.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(rates) dev.off() ## ----echo=TRUE,results='hide'-------------------------------------------- lasso.est <- lasso(yuima, start=start, lower=low, upper=upp, method="L-BFGS-B", delta=2) lasso.est ## ----results='hide'------------------------------------------------------ mod1 <- setModel(drift="alpha", diffusion="sigma*x^gamma") yuima1 <- setYuima(data=setData(X,delta=1/12), model=mod1) start1 <- list(alpha=1, sigma =.1, gamma =1) low1 <- list(alpha=-5, sigma =-5, gamma =-5) upp1 <- list(alpha=8, sigma =8, gamma =8) fit <- qmle(yuima, start=start, lower=low, upper=upp, method="L-BFGS-B") fit1 <- qmle(yuima1, start=start1, lower=low1, upper=upp1, method="L-BFGS-B") summary(fit) summary(fit1) AIC(fit, fit1) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit)),width=60)) writeLines(strwrap(capture.output(summary(fit1)),width=60)) writeLines(strwrap(capture.output(AIC(fit, fit1)),width=60)) ## ----cpoint1------------------------------------------------------------- diff.matrix <- matrix(c("theta1.k*x1","0*x2","0*x1","theta2.k*x2"), 2, 2) drift.c <- c("sin(x1)", "3-x2") drift.matrix <- matrix(drift.c, 2, 1) ymodel <- setModel(drift=drift.matrix, diffusion=diff.matrix, time.variable="t", state.variable=c("x1", "x2"), solve.variable=c("x1", "x2")) ymodel ## ----cpoint3,results='hide'---------------------------------------------- n <- 1000 set.seed(123) t0 <- list(theta1.k=0.5, theta2.k=0.3) T <- 10 tau <- 4 pobs <- tau/T ysamp1 <- setSampling(n=n*pobs, Initial=0, delta=0.01) yuima1 <- setYuima(model=ymodel, sampling=ysamp1) yuima1 <- simulate(yuima1, xinit=c(3, 3), true.parameter=t0) v11 <- get.zoo.data(yuima1)[[1]] x1 <- as.numeric(v11[length(v11)]) # terminal value v21 <- get.zoo.data(yuima1)[[2]] x2 <- as.numeric(v21[length(v21)]) # terminal value ## ----cpoint3b,results='hide'--------------------------------------------- t1 <- list(theta1.k=0.2, theta2.k=0.4) ysamp2 <- setSampling(Initial=n*pobs*0.01, n=n*(1-pobs), delta=0.01) yuima2 <- setYuima(model=ymodel, sampling=ysamp2) yuima2 <- simulate(yuima2, xinit=c(x1, x2), true.parameter=t1) ## ----cpoint3c,results='hide'--------------------------------------------- v12 <- get.zoo.data(yuima2)[[1]] v22 <- get.zoo.data(yuima2)[[2]] v1 <- c(v11,v12[-1]) v2 <- c(v21,v22[-1]) new.data <- setData(zoo(cbind(v1,v2)),delta=0.01) yuima <- setYuima(model=ymodel, data=new.data) ## ----cpoint4,fig.keep='none'--------------------------------------------- plot(yuima) ## ----plot-cpoint4,echo=FALSE, fig.keep='none',results='hide'------------- pdf("figures/plot-cpoint4.pdf",width=9,height=5) par(mar=c(4,4,1,1)) plot(yuima) dev.off() ## ----cpoint4b------------------------------------------------------------ noDriftModel <- setModel(drift=c(0,0), diffusion=diff.matrix, time.variable="t", state.variable=c("x1", "x2"), solve.variable=c("x1", "x2")) noDriftModel <- setYuima(noDriftModel, data=new.data) noDriftModel@model@drift noDriftModel ## ----cpoint5------------------------------------------------------------- t.est <- CPoint(yuima,param1=t0,param2=t1) t.est$tau t.est2 <- CPoint(noDriftModel,param1=t0,param2=t1) t.est2$tau ## ------------------------------------------------------------------------ qmleL(noDriftModel, t=1.5, start=list(theta1.k=0.1, theta2.k=0.1), lower=list(theta1.k=0, theta2.k=0), upper=list(theta1.k=1, theta2.k=1), method="L-BFGS-B") -> estL qmleR(noDriftModel, t=8.5, start=list(theta1.k=0.1, theta2.k=0.1), lower=list(theta1.k=0, theta2.k=0), upper=list(theta1.k=1, theta2.k=1), method="L-BFGS-B") -> estR t0.est <- coef(estL) t1.est <- coef(estR) ## ------------------------------------------------------------------------ t.est3 <- CPoint(noDriftModel,param1=t0.est,param2=t1.est) t.est3 ## ----eval=FALSE---------------------------------------------------------- ## CPoint(noDriftModel,param1=t0.est,param2=t1.est, plot=TRUE) ## ----plot-cpoint-stat,echo=FALSE,results='hide'-------------------------- pdf("figures/plot-cpoint-stat.pdf",width=9,height=4) par(mar=c(4,4,2,1)) CPoint(noDriftModel,param1=t0.est,param2=t1.est, plot=TRUE) dev.off() ## ------------------------------------------------------------------------ qmleL(noDriftModel, t=t.est3$tau, start=list(theta1.k=0.1, theta2.k=0.1), lower=list(theta1.k=0, theta2.k=0), upper=list(theta1.k=1, theta2.k=1), method="L-BFGS-B") -> estL qmleR(noDriftModel, t=t.est3$tau, start=list(theta1.k=0.1, theta2.k=0.1), lower=list(theta1.k=0, theta2.k=0), upper=list(theta1.k=1, theta2.k=1), method="L-BFGS-B") -> estR t02s.est <- coef(estL) t12s.est <- coef(estR) t2s.est3 <- CPoint(noDriftModel,param1=t02s.est,param2=t12s.est) t2s.est3 ## ------------------------------------------------------------------------ library(quantmod) getSymbols("AAPL", to="2016-12-31") S <- AAPL$AAPL.Adjusted Delta <- 1/252 gBm <- setModel(drift="mu*x", diffusion="sigma*x") mod <- setYuima(model=gBm, data=setData(S, delta=Delta)) lower <- list(mu=0.1, sigma=0.1) upper <- list(mu=100, sigma=10) start <- list(mu=1, sigma=1) fit <- qmle(mod, start= start, upper=upper, lower=lower) summary(fit) ## ------------------------------------------------------------------------ fit1 <- qmleL(mod, t=1, start= list(mu=1,sigma=1)) fit2 <- qmleR(mod, t=6, start= list(mu=1,sigma=1)) fit1 fit2 ## ------------------------------------------------------------------------ cp <- CPoint(mod,param1=coef(fit1),param2=coef(fit2)) cp ## ----fig.keep='none'----------------------------------------------------- X <- diff(log(get.zoo.data(mod)[[1]])) plot(X) abline(v=cp$tau, lty=3,lwd=2,col="red") ## ----plot-returns,echo=FALSE, fig.keep='none',results='hide'------------- pdf("figures/plot-returns.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(X,main="log returns of AAPL") abline(v=cp$tau, lty=3,lwd=2,col="red") dev.off() ## ----plot-cpoint-aapl,echo=FALSE,results='hide'-------------------------- pdf("figures/plot-cpoint-aapl.pdf",width=9,height=4) par(mar=c(4,4,2,1)) CPoint(mod,param1=coef(fit1),param2=coef(fit2),plot=TRUE) dev.off() ## ----echo=TRUE----------------------------------------------------------- # diffusion coefficient for process 1 diff.coef.1 <- function(t,x1=0, x2=0) sqrt(1+t) # diffusion coefficient for process 2 diff.coef.2 <- function(t,x1=0, x2=0) sqrt(1+t^2) # correlation cor.rho <- function(t,x1=0, x2=0) sqrt(1/2) # coefficient matrix for diffusion term diff.coef.matrix <- matrix( c( "diff.coef.1(t,x1,x2)", "diff.coef.2(t,x1,x2) * cor.rho(t,x1,x2)", "", "diff.coef.2(t,x1,x2) * sqrt(1-cor.rho(t,x1,x2)^2)"),2,2) # Model SDE using yuima.model cor.mod <- setModel(drift = c("",""), diffusion = diff.coef.matrix, solve.variable=c("x1","x2")) ## ----echo=TRUE----------------------------------------------------------- CC.theta <- function( T, sigma1, sigma2, rho){ tmp <- function(t) return( sigma1(t) * sigma2(t) * rho(t) ) integrate(tmp,0,T) } ## ------------------------------------------------------------------------ set.seed(123) Terminal <- 1 n <- 1000 # Cumulative Covariance theta <- CC.theta(T=Terminal, sigma1=diff.coef.1, sigma2=diff.coef.2, rho=cor.rho)$value cat(sprintf("theta=%5.3f\n",theta)) ## ----results='hide'------------------------------------------------------ yuima.samp <- setSampling(Terminal=Terminal,n=n) yuima <- setYuima(model=cor.mod, sampling=yuima.samp) X <- simulate(yuima) ## ------------------------------------------------------------------------ cce(X) ## ----cceplot1,fig.keep='none'-------------------------------------------- plot(X,main="complete data") ## ----plot-cceplot1,echo=FALSE, fig.keep='none',results='hide'------------ pdf("figures/plot-cceplot1.pdf",width=9,height=5) par(mar=c(4,4,1,1)) plot(X,main="complete data") dev.off() ## ------------------------------------------------------------------------ p1 <- 0.2 p2 <- 0.3 newsamp <- setSampling(random=list(rdist=c( function(x) rexp(x, rate=p1*n/Terminal), function(x) rexp(x, rate=p2*n/Terminal))) ) ## ------------------------------------------------------------------------ Y <- subsampling(X, sampling=newsamp) ## ----cceplot2,fig.keep='none'-------------------------------------------- plot(Y,main="asynchronous data") ## ----plot-cceplot2,echo=FALSE, fig.keep='none',results='hide'------------ pdf("figures/plot-cceplot2.pdf",width=9,height=5) par(mar=c(4,4,1,1)) plot(Y,main="asynchronous data") dev.off() ## ------------------------------------------------------------------------ cce(Y)$covmat # asynch data cce(X)$covmat # full data ## ------------------------------------------------------------------------ b1 <- function(x,y) y b2 <- function(x,y) -x s1 <- function(t,x,y) sqrt(abs(x)*(1+t)) s2 <- function(t,x,y) sqrt(abs(y)) cor.rho <- function(t,x,y) 1/(1+x^2) diff.mat <- matrix(c("s1(t,x,y)", "s2(t,x,y) * cor.rho(t,x,y)","", "s2(t,x,y) * sqrt(1-cor.rho(t,x,y)^2)"), 2, 2) cor.mod <- setModel(drift = c("b1","b2"), diffusion = diff.mat, solve.variable = c("x", "y"),state.var=c("x","y")) ## Generate a path of the process set.seed(111) Terminal <- 1 n <- 10000 yuima.samp <- setSampling(Terminal = Terminal, n = n) yuima <- setYuima(model = cor.mod, sampling = yuima.samp) yuima <- simulate(yuima, xinit=c(2,3)) ## ------------------------------------------------------------------------ p1 <- 0.2 p2 <- 0.3 newsamp <- setSampling(random=list(rdist=c( function(x) rexp(x, rate=p1*n/Terminal), function(x) rexp(x, rate=p2*n/Terminal))) ) Y <- subsampling(yuima, sampling = newsamp) ## ----cceplot3,fig.keep='none'-------------------------------------------- plot(Y,main="asynchronous data (non linear case)") ## ----plot-cceplot3,echo=FALSE, fig.keep='none',results='hide'------------ pdf("figures/plot-cceplot3.pdf",width=9,height=5) par(mar=c(4,4,1,1)) plot(Y,main="asynchronous data (non linear case)") dev.off() ## ------------------------------------------------------------------------ cce(yuima)$covmat # full data cce(Y)$covmat # asynch data ## ------------------------------------------------------------------------ diff.coef.matrix <- matrix(c("sqrt(x1)", "3/5*sqrt(x2)", "1/3*sqrt(x3)", "", "4/5*sqrt(x2)","2/3*sqrt(x3)","","", "2/3*sqrt(x3)"), 3, 3) drift <- c("1-x1","2*(10-x2)","3*(4-x3)") cor.mod <- setModel(drift = drift, diffusion = diff.coef.matrix, solve.variable = c("x1", "x2","x3")) set.seed(111) Terminal <- 1 yuima.samp <- setSampling(Terminal = Terminal, n = 1200) yuima <- setYuima(model = cor.mod, sampling = yuima.samp) yuima <- simulate(yuima, xinit=c(1,7,5)) # intentionally displace the second time series data1 <- get.zoo.data(yuima)[[1]] data2 <- get.zoo.data(yuima)[[2]] time2 <- time( data2 ) theta2 <- 0.05 # the lag of x2 behind x1 stime2 <- time2 + theta2 time(data2) <- stime2 data3 <- get.zoo.data(yuima)[[3]] time3 <- time( data3 ) theta3 <- 0.12 # the lag of x3 behind x1 stime3 <- time3 + theta3 time(data3) <- stime3 syuima <- setYuima(data=setData(merge(data1, data2, data3))) yuima syuima ## ----shifted,fig.keep='none'--------------------------------------------- plot(syuima,main="time shifted data") ## ----plot-shifted,echo=FALSE, fig.keep='none',results='hide'------------- pdf("figures/plot-shifted.pdf",width=9,height=5) par(mar=c(4,4,2,1)) plot(syuima,main="time shifted data") dev.off() ## ------------------------------------------------------------------------ llag(yuima) llag(syuima) ## ----plot-shifted-ci,echo=FALSE, fig.keep='none',results='hide'---------- pdf("figures/plot-shifted-ci.pdf",width=9,height=5) par(mar=c(4,5,2,1)) par(mfrow=c(1,3)) llag(syuima,plot=TRUE,ci=TRUE) dev.off() ## ------------------------------------------------------------------------ data2 <- get.zoo.data(yuima)[[2]] time2 <- time( data2 ) theta2 <- 0.05 # the lag of x2 behind x1 stime2 <- time2 + theta2 time(data2) <- stime2 data3 <- get.zoo.data(yuima)[[3]] time3 <- time( data3 ) theta3 <- 0.12 # the lag of x3 behind x1 stime3 <- time3 + theta3 time(data3) <- stime3 data1 <- data1[which(time(data1)>0.5 & time(data1)<1)] data2 <- data2[which(time(data2)>0.5 & time(data2)<1)] data3 <- data3[which(time(data3)>0.5 & time(data3)<1)] syuima2 <- setYuima(data=setData(merge(data1, data2, data3))) syuima2 llag(syuima2) ## ------------------------------------------------------------------------ p1 <- 0.2 p2 <- 0.3 p3 <- 0.4 n <- 1000 newsamp <- setSampling( random=list(rdist=c( function(x) rexp(x, rate=p1*n/Terminal), function(x) rexp(x, rate=p2*n/Terminal), function(x) rexp(x, rate=p3*n/Terminal))) ) psample <- subsampling(syuima, sampling = newsamp) psample llag(psample) ## ----results='hide'------------------------------------------------------ library(quantmod) getSymbols("AAPL", from="2013-01-01", to="2013-12-31") getSymbols("IBM", from="2013-01-01", to="2013-12-31") getSymbols("AMZN", from="2013-01-01", to="2013-12-31") getSymbols("EBAY", from="2013-01-01", to="2013-12-31") getSymbols("FB", from="2013-01-01", to="2013-12-31") getSymbols("MSFT", from="2013-01-01", to="2013-12-31") data1 <- AAPL$AAPL.Close data2 <- IBM$IBM.Close data3 <- AMZN$AMZN.Close data4 <- EBAY$EBAY.Close data5 <- FB$FB.Close data6 <- MSFT$MSFT.Close market.data <- merge(data1, data2, data3, data4,data5,data6) colnames(market.data) <- c("AAPL", "IBM", "AMZN", "EBAY", "FB", "MSFT") mkt <- setYuima(data=setData(market.data, delta=1/252)) ## ------------------------------------------------------------------------ mkt round(cce(mkt)$cormat,2) # correlation matrix ## ----market,fig.keep='none'---------------------------------------------- plot(mkt) ## ----plot-market,echo=FALSE, fig.keep='none',results='hide'-------------- pdf("figures/plot-market.pdf",width=9,height=5) par(mar=c(4,4,1,1)) plot(mkt,main="") dev.off() ## ------------------------------------------------------------------------ round(llag(mkt),4) ## ----corrplot,fig.keep='none',message=FALSE------------------------------ require(corrplot) cols <- colorRampPalette(c("#7F0000", "red", "#FF7F00", "yellow", "white", "cyan", "#007FFF", "blue", "#00007F")) corrplot(cce(mkt)$cormat,method="ellipse", cl.pos = "b", tl.pos = "d", tl.srt = 60, col=cols(100), outline=TRUE) corrplot(llag(mkt),method="ellipse",is.corr=FALSE, cl.pos = "b", tl.pos = "d", tl.srt = 60, col=cols(100), outline=TRUE) ## ----plot-corrplot,echo=FALSE, fig.keep='none',results='hide'------------ pdf("figures/plot-corrplot1.pdf",width=6,height=6) require(corrplot) corrplot(cce(mkt)$cormat,method="ellipse", cl.pos = "b", tl.pos = "d", tl.srt = 60, col=cols(100), outline=TRUE) dev.off() pdf("figures/plot-corrplot2.pdf",width=6,height=6) corrplot(llag(mkt),method="ellipse",is.corr=FALSE, cl.pos = "b", tl.pos = "d", tl.srt = 60, col=cols(100), outline=TRUE) dev.off() ## ----echo=TRUE, results='hide'------------------------------------------- model <- setModel(drift = "x", diffusion = matrix( "x*e", 1,1)) T <- 1 xinit <- 150 K <- 100 f <- list( expression(x/T), expression(0)) F <- 0 e <- 0.5 yuima <- setYuima(model = model, sampling = setSampling(Terminal=T, n=1000)) yuima <- setFunctional( yuima, f=f,F=F, xinit=xinit,e=e) ## ----echo=TRUE----------------------------------------------------------- str(yuima@functional) ## ----echo=TRUE----------------------------------------------------------- F0 <- F0(yuima) F0 ## ----echo=TRUE,results='hide'-------------------------------------------- rho <- expression(0) epsilon <- e # noise level g <- function(x) { tmp <- (F0 - K) + (epsilon * x) tmp[(epsilon * x) < (K-F0)] <- 0 tmp } ## ----echo=TRUE,results='hide'-------------------------------------------- asymp <- asymptotic_term(yuima, block=10, rho, g) asymp ## ----echo=TRUE----------------------------------------------------------- asy1 <- asymp$d0 + e * asymp$d1 # 1st order asymp. exp. of asian call price asy1 asy2 <- asymp$d0 + e * asymp$d1 + e^2* asymp$d2 # 2nd order asymp. exp. of asian call price asy2 ## ----message=FALSE------------------------------------------------------- library("fExoticOptions") levy <- LevyAsianApproxOption(TypeFlag = "c", S = xinit, SA = xinit, X = K, Time = 1, time = 1, r = 0.0, b = 1, sigma = e)@price levy ## ------------------------------------------------------------------------ a <- 0.9 e <- 0.4 Terminal <- 3 xinit <- 1 K <- 10 drift <- "a * x" diffusion <- "e * sqrt(x)" model <- setModel(drift=drift,diffusion=diffusion) n <- 1000*Terminal yuima <- setYuima(model = model, sampling = setSampling(Terminal=Terminal,n=n)) f <- list(c(expression(0)),c(expression(0))) F <- expression(x) yuima.ae <- setFunctional(yuima,f=f,F=F,xinit=xinit,e=e) rho <- expression(0) F1 <- F0(yuima.ae) get_ge <- function(x,epsilon,K,F0){ tmp <- (F0 - K) + (epsilon * x[1]) tmp[(epsilon * x[1]) > (K - F0)] <- 0 return( - tmp ) } g <- function(x){ return(get_ge(x,e,K,F1)) } time1 <- proc.time() asymp <- asymptotic_term(yuima.ae,block=100,rho,g) time2 <- proc.time() ## ------------------------------------------------------------------------ ae.value0 <- asymp$d0 ae.value0 ae.value1 <- asymp$d0 + e * asymp$d1 ae.value1 ae.value2 <- as.numeric(asymp$d0 + e * asymp$d1 + e^2 * asymp$d2) ae.value2 ae.time <- time2 - time1 ae.time
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter2.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ----mod1---------------------------------------------------------------- mod1 <- setPoisson(intensity="lambda", df=list("dconst(z,1)")) mod1 ## ----poi1,fig.keep='none'------------------------------------------------ Terminal <- 30 samp <- setSampling(T=Terminal,n=3000) set.seed(123) poisson1 <- simulate(mod1, true.par=list(lambda=1),sampling=samp) poisson1 plot(poisson1) ## ----plot-poi1,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi1.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson1,type="S") dev.off() ## ----eval=FALSE---------------------------------------------------------- ## setPoisson(intensity="lambda", df=list("dconst(z,1)"), scale=5) ## setPoisson(intensity="lambda", df=list("dconst(z,5)")) ## ----mod2,fig.keep='none'------------------------------------------------ mod2 <- setPoisson(intensity="lambda", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson2 <- simulate(mod2, sampling=samp, true.par=list(lambda=1,mu=0, sigma=2)) poisson2 plot(poisson2) ## ----plot-poi2,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi2.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson2,type="S") dev.off() ## ----fig.keep='none'----------------------------------------------------- mod3 <- setPoisson(intensity="lambda", df=list("dNIG(z,alpha,beta,gamma,mu)")) poisson3 <- simulate(mod3, sampling=samp, true.par=list(lambda=10,alpha=2,beta=0.3,gamma=1,mu=0)) poisson3 ## ----message=FALSE------------------------------------------------------- require(fBasics) mod4 <- setPoisson(intensity="lambda", df=list("dnig(z,alpha,beta,gamma)")) poisson4 <- simulate(mod4, sampling=samp, true.par=list(lambda=10,alpha=2,beta=0.3,gamma=1)) poisson4 ## ----mod5,fig.keep='none'------------------------------------------------ mod5 <- setPoisson(intensity="alpha+beta*t", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson5 <- simulate(mod5, sampling=samp, true.par=list(alpha=2,beta=.5,mu=0, sigma=2)) plot(poisson5) f <- function(t,alpha,beta) alpha + beta*t curve(f(x,alpha=2,beta=0.5)-20,0,30,add=TRUE,col="red",lty=3,lwd=2) ## ----plot-poi5,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi5.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson5,type="S") curve(f(x,alpha=2,beta=0.5)-20,0,30,add=TRUE,col="red",lty=3,lwd=2) dev.off() ## ----mod6,fig.keep='none'------------------------------------------------ mod6 <- setPoisson(intensity="theta*t^(theta-1)", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson6 <- simulate(mod6, sampling=samp, true.par=list(theta=1.5,mu=0, sigma=2)) plot(poisson6) f <- function(t,theta) theta*t^(theta-1) curve(f(x,theta=1.5),0,30,add=TRUE,col="red",lty=3,lwd=2) ## ----plot-poi6,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi6.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson6,type="S") curve(f(x,theta=1.5),0,30,add=TRUE,col="red",lty=3,lwd=2) dev.off() ## ----mod7,fig.keep='none'------------------------------------------------ mod7 <- setPoisson(intensity="beta*exp(-lambda*t)", df=list("dexp(z,gamma)")) set.seed(123) poisson7 <- simulate(mod7, sampling=samp, true.par=list(lambda=.2,beta=10,gamma=1)) plot(poisson7) f <- function(t,beta,lambda) beta*exp(-lambda*t) curve(f(x,beta=10,lambda=0.2),0,30,add=TRUE,col="red",lty=3,lwd=2) ## ----plot-poi7,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi7.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson7,type="S") curve(f(x,beta=10,lambda=0.2),0,30,add=TRUE,col="red",lty=3,lwd=2) dev.off() ## ----mod8,fig.keep='none'------------------------------------------------ mod8 <- setPoisson(intensity="0.5*a*(1+cos(omega*t+phi))+lambda", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson8 <- simulate(mod8, sampling=samp, true.par=list(a=2,omega=0.5,phi=3.14,lambda=5,mu=0,sigma=1)) plot(poisson8) f <- function(t,a,omega,phi,lambda) 0.5*a*(1+cos(omega*t+phi))+lambda curve(f(x,a=2,omega=0.5,phi=3.14,lambda=5),0,30,add=TRUE, col="red",lty=3,lwd=2) ## ----plot-poi8,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi8.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson8,type="S") curve(f(x,a=2,omega=0.5,phi=3.14,lambda=5),0,30,add=TRUE, col="red",lty=3,lwd=2) dev.off() ## ----fig.keep='none'----------------------------------------------------- mod9 <- setPoisson(intensity="a*cos(theta*t)+lambda", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson9 <- simulate(mod9, sampling=samp, true.par=list(a=1,theta=0.5,lambda=5,mu=0,sigma=1)) plot(poisson9) f <- function(t,a,theta,lambda) a*cos(theta*t)+lambda curve(f(x,a=1,theta=0.5,lambda=5),0,30,add=TRUE,col="red",lty=3,lwd=2) ## ----plot-poi9,echo=FALSE,results='hide'--------------------------------- pdf("figures/plot-poi9.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson9,type="S") curve(f(x,a=1,theta=0.5,lambda=5),0,30,add=TRUE,col="red",lty=3,lwd=2) dev.off() ## ----mod10,fig.keep='none'----------------------------------------------- mod10 <- setPoisson(intensity="lambda*t", df=list("dmvnorm(z,c(0.15,-0.1),matrix(c(2,-1.9,-1.9,4.3),2,2))"), dimension=2) set.seed(123) poisson10 <- simulate(mod10, true.par=list(lambda=5), sampling=samp) poisson10 plot(poisson10) ## ----plot-poi10,echo=FALSE,results='hide'-------------------------------- pdf("figures/plot-poi10.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson10,type="S") dev.off() ## ----mod111,fig.keep='none'---------------------------------------------- mod11 <- setPoisson(intensity="lambda*t", df=list("dmvnorm(z,c(0.01,-0.01,.05), matrix(c(1,.5,0,.5,1,0,0,0,1),3,3))"), dimension=3) set.seed(123) poisson11 <- simulate(mod11, true.par=list(lambda=5), sampling=samp,xinit=c(-100,200,300)) plot(poisson11) ## ----plot-poi11,echo=FALSE,results='hide'-------------------------------- pdf("figures/plot-poi11.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(poisson11,type="S") dev.off() ## ------------------------------------------------------------------------ r2DNIG <- function(n,alpha){ alpha <- 2 beta <- c(0,0) delta0 <- 0.55 mu <- c(0,0) Lambda <- matrix(c(1,0,0,1),2,2) t(rNIG(n,alpha=alpha,beta=beta,delta=delta0,mu=mu,Lambda=Lambda)) } # the next fake density plays no role in simulation # but it is needed for model specification d2DNIG <- function(n,alpha){ rep(0,2) } ## ------------------------------------------------------------------------ mod12 <- setPoisson(intensity="lambda", df=list("d2DNIG(z,)"), dim=2) set.seed(123) poisson12 <- simulate(mod12, true.par= list(lambda=1), sampling=samp) poisson12 ## ------------------------------------------------------------------------ rMydis <- function(n,a=1){ cbind(rnorm(n), rexp(n), rNIG(n,1,1,1,1)) } dMydis <- function(n,a=1){ rep(0,3) } mod13 <- setPoisson(intensity="lambda*t", df=list("dMydis(z,1)"), dimension=3) set.seed(123) poisson13 <- simulate(mod13, true.par=list(lambda=5), sampling=samp) poisson13 ## ------------------------------------------------------------------------ mod14 <- setPoisson(intensity="alpha+lambda*t", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson14 <- simulate(mod14, sampling=samp, true.par=list(alpha=1,lambda=.5,mu=0, sigma=2)) poisson14 fit14 <- qmle(poisson14, start=list(alpha=2,lambda=1,mu=0,sigma=1), lower=list(alpha=0.1, lambda=0.1,mu=-1,sigma=0.1), upper=list(alpha=10,lambda=10,mu=3,sigma=4), method="L-BFGS-B") coef(fit14) ## ------------------------------------------------------------------------ summary(fit14) ## ----results='hide'------------------------------------------------------ mod15 <- setPoisson(intensity="lambda", df=list("dNIG(z,alpha,beta,gamma,mu)")) set.seed(123) poisson15 <- simulate(mod15,sampling=samp, true.par=list(lambda=10,alpha=2,beta=0.3,gamma=1,mu=0)) poisson15 fit15 <- qmle(poisson15, start=list(beta=5,lambda=2,gamma=0.5,alpha=1,mu=0), lower=list(alpha=1,beta=0.1,lambda=0.1,gamma=0.1,mu=-1), upper=list(alpha=5,beta=0.99,lambda=20,gamma=2,mu=2), method="L-BFGS-B") summary(fit15) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit15)),width=60)) ## ------------------------------------------------------------------------ mod16 <- setPoisson(intensity="beta*exp(-lambda*t)", df=list("dexp(z,lambda)")) set.seed(123) poisson16 <- simulate(mod16, true.par=list(lambda=.2,beta=10), sampling=samp) poisson16 fit16 <- qmle(poisson16, start=list(beta=.5,lambda=2), lower=list(beta=0.1,lambda=0.1), upper=list(beta=20,lambda=10), method="L-BFGS-B") summary(fit16) ## ----results='hide'------------------------------------------------------ mod17 <- setPoisson(intensity="lambda*t^(lambda-1)", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson17 <- simulate(mod17, true.par=list(lambda=2,mu=0, sigma=2), sampling=samp) poisson17 fit17 <- qmle(poisson17, start=list(lambda=5,mu=0,sigma=1), lower=list(lambda=0.1,mu=-1,sigma=0.1), upper=list(lambda=10,mu=3,sigma=4), method="L-BFGS-B") summary(fit17) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit17)),width=60)) ## ----results='hide'------------------------------------------------------ mod18 <- setPoisson(intensity="0.5*a*(1+cos(omega*t+phi))+lambda", df=list("dnorm(z,mu,sigma)")) set.seed(123) poisson18 <- simulate(mod18, sampling=samp, true.par=list(a=2,omega=0.5,phi=3.14,lambda=5,mu=0,sigma=1)) fit18 <- qmle(poisson18, start=list(a=1, omega=0.2, phi=1, lambda=2, mu=1, sigma=2), lower=list(a=0.1, omega=0.1, phi=0.1, lambda=0.1, mu=-2, sigma=0.1), upper=list(a=5, omega=1, phi=5, lambda=10, mu=2, sigma=3), method="L-BFGS-B") summary(fit18) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(summary(fit18)),width=60))
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter3.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ------------------------------------------------------------------------ set.seed(123) mu <- 0 sigma <- 1 lambda <- 10 samp <- setSampling(Terminal=10, n=1000) mod10b <- setPoisson(intensity="lambda", df=list("dnorm(z,mu,sigma)")) y10b <- simulate(mod10b,sampling=samp, true.par=list(lambda=lambda,mu=0.1, sigma=2)) y10b ## ----fig.keep='none'----------------------------------------------------- BGmodel <- setModel(drift="0", xinit="0", jump.coeff="1", measure.type="code", measure=list(df="rbgamma(z, delta.plus=1.4, gamma.plus=0.3, delta.minus=2, gamma.minus=0.6)")) n <- 1000 samp <- setSampling(Terminal=1, n=n) BGyuima <- setYuima(model=BGmodel, sampling=samp) set.seed(127) for (i in 1:5) { result <- simulate(BGyuima) plot(result,xlim=c(0,1),ylim=c(-6,6), main="Paths of bilateral gamma process",col=i,par(new=T)) } ## ----plot-BGprocess,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-BGprocess.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(127) for (i in 1:5) { result <- simulate(BGyuima) plot(result,xlim=c(0,1),ylim=c(-6,6), main="Paths of bilateral gamma process",col=i,par(new=T)) } dev.off() ## ----fig.keep='none'----------------------------------------------------- VGmodel <- setModel(drift="0", xinit="0", jump.coeff="1", measure.type="code", measure=list(df="rbgamma(z, delta.minus=2, gamma.minus=0.6, delta.plus=2, gamma.plus=0.3)")) VGyuima <- setYuima(model=VGmodel, sampling=samp) set.seed(127) for (i in 1:5) { result <- simulate(VGyuima) plot(result,xlim=c(0,1),ylim=c(-4,12), main="Paths of variance gamma process",col=i,par(new=T)) } ## ----plot-VGprocess,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-VGprocess.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(127) for (i in 1:5) { result <- simulate(VGyuima) plot(result,xlim=c(0,1),ylim=c(-4,12), main="Paths of variance gamma process",col=i,par(new=T)) } dev.off() ## ----eval=FALSE---------------------------------------------------------- ## Gmodel <- setModel(drift="0", xinit="0", jump.coeff="1", ## measure.type="code", measure=list(df="rgamma(z, ## shape=0.7, scale=1)")) ## n <- 10000 ## samp <- setSampling(Terminal=1, n=n) ## Gyuima <- setYuima(model=Gmodel, sampling=samp) ## set.seed(129) ## for (i in 1:5){ ## result <- simulate(Gyuima) ## plot(result,xlim=c(0,1),ylim=c(-0.1,1.2), ## main="Paths of gamma process",col=i,par(new=T)) ## } ## ----plot-Gprocess,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-Gprocess.pdf",width=9,height=4) par(mar=c(4,4,2,1)) Gmodel <- setModel(drift="0", xinit="0", jump.coeff="1", measure.type="code", measure=list(df="rgamma(z, shape=0.7, scale=1)")) n <- 10000 samp <- setSampling(Terminal=1, n=n) Gyuima <- setYuima(model=Gmodel, sampling=samp) set.seed(129) for (i in 1:5){ result <- simulate(Gyuima) plot(result,xlim=c(0,1),ylim=c(-0.1,1.2), main="Paths of gamma process",col=i,par(new=T)) } dev.off() ## ----eval=FALSE---------------------------------------------------------- ## n <- 5 ## sampling <- setSampling(Terminal=1, n=n) ## Gmodel <- setModel(drift="0", xinit="0", jump.coeff="1", ## measure.type="code", measure=list(df="rgamma(z, ## shape=0.7, scale=1)")) ## Gyuima <- setYuima(model=Gmodel, sampling=samp) ## simdata <- NULL ## set.seed(127) ## for (i in 1:3000){ ## result <- simulate(Gyuima) ## x1 <- result@[email protected][n+1,1] ## simdata <- c(simdata,as.numeric(x1)) ## } ## hist(simdata, xlim=c(0,2), ylim=c(0,3), breaks=100, freq=FALSE, ## main=expression(paste("Distribution of ", X[1], ## " and Density of Gamma(0.7,1)"))) ## curve(dgamma(x,0.7,1),add=TRUE,col="red") ## ----plot-dgamma,echo=FALSE,results='hide'------------------------------- pdf("figures/plot-dgamma.pdf",width=9,height=4) par(mar=c(4,4,2,1)) n <- 5 samp <- setSampling(Terminal=1, n=n) Gmodel <- setModel(drift="0", xinit="0", jump.coeff="1", measure.type="code", measure=list(df="rgamma(z, shape=0.7, scale=1)")) Gyuima <- setYuima(model=Gmodel, sampling=samp) simdata <- NULL set.seed(127) for (i in 1:3000){ result <- simulate(Gyuima) x1 <- result@[email protected][n+1,1] simdata <- c(simdata,as.numeric(x1)) } hist(simdata, xlim=c(0,2), ylim=c(0,3), breaks=100, freq=FALSE, main=expression(paste("Distribution of ", X[1], " and Density of Gamma(0.7,1)"))) curve(dgamma(x,0.7,1),add=TRUE,col="red") dev.off() ## ----fig.keep='none'----------------------------------------------------- delta <- 1 gamma <- 2 set.seed(127) x <- rIG(100000,delta,gamma) hist(x,xlim=c(0,2),ylim=c(0,2),breaks=100,freq=FALSE) curve(dIG(x,delta,gamma),add=TRUE,col="red", from=min(x), to=max(x), n=500) mean(x) var(x) ## ----plot-dIG,echo=FALSE,results='hide'---------------------------------- pdf("figures/plot-dIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) hist(x,xlim=c(0,2),ylim=c(0,2),breaks=100,freq=FALSE) curve(dIG(x,delta,gamma),add=TRUE,col="red", from=min(x), to=max(x), n=500) dev.off() ## ----fig.keep='none'----------------------------------------------------- IGmodel <- setModel(drift=0, xinit=0, jump.coeff=1, measure.type="code", measure=list(df="rIG(z, delta=1, gamma=2)")) n <- 1000 samp <- setSampling(Terminal=1, n=n) IGyuima <- setYuima(model=IGmodel, sampling=samp) set.seed(127) for (i in 1:5){ result <- simulate(IGyuima,xinit=0) plot(result, xlim=c(0,1), ylim=c(0,1), main="Paths of IG process (delta=1, gamma=2)",par(new=T),col=i) } ## ----plot-dIGproc,echo=FALSE,results='hide'------------------------------ pdf("figures/plot-dIGproc.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(127) for (i in 1:5){ result <- simulate(IGyuima,xinit=0) plot(result, xlim=c(0,1), ylim=c(0,1), main="Paths of IG process (delta=1, gamma=2)",par(new=T),col=i) } dev.off() ## ----eval=FALSE---------------------------------------------------------- ## n <- 5 ## samp <- setSampling(Terminal=1, n=n) ## IGyuima <- setYuima(model=IGmodel, sampling=samp) ## IGsimdata <- NULL ## for (i in 1:3000){ ## result <- simulate(IGyuima) ## x1 <- result@[email protected][n+1,1] ## IGsimdata <- c(IGsimdata,as.numeric(x1)) ## } ## hist(IGsimdata,xlim=c(0,2), ylim=c(0,2), breaks=100, freq=FALSE, ## main=expression(paste("Distribution of ",X[1], ## " and Density of IG(1,2)"))) ## curve(dIG(x,delta,gamma),add=TRUE,col="red", ## from = 0.001, to = 5, n=500) ## ----plot-IGprocd,echo=FALSE,results='hide'------------------------------ pdf("figures/plot-IGprocd.pdf",width=9,height=4) par(mar=c(4,4,2,1)) n <- 5 samp <- setSampling(Terminal=1, n=n) IGyuima <- setYuima(model=IGmodel, sampling=samp) IGsimdata <- NULL for (i in 1:3000){ result <- simulate(IGyuima) x1 <- result@[email protected][n+1,1] IGsimdata <- c(IGsimdata,as.numeric(x1)) } hist(IGsimdata,xlim=c(0,2), ylim=c(0,2), breaks=100, freq=FALSE, main=expression(paste("Distribution of ",X[1]," and Density of IG(1,2)"))) curve(dIG(x,delta,gamma),add=TRUE,col="red", from = 0.001, to = 5, n=500) dev.off() ## ----fig.keep='none'----------------------------------------------------- rep <- 3000000 set.seed(129) X1 <- rpts(rep,0.5,0.2,1) hist(X1,xlim=c(0,3),ylim=c(0,3),breaks=100, main=expression(X[1]),probability=TRUE) X05 <- rpts(rep,0.5,0.1,1) X05.prime <- rpts(rep,0.5,0.1,1) Xsum <- X05+X05.prime summary(X1) summary(Xsum) ks.test(X1,Xsum) ## ----plot-X1pts,echo=FALSE,results='hide'-------------------------------- pdf("figures/plot-X1pts.pdf",width=9,height=4) par(mar=c(4,4,2,1)) hist(X1,xlim=c(0,3),ylim=c(0,3),breaks=100,main=expression(paste(X[1]," positive tempered stable distribution")),probability=TRUE) dev.off() rm(X1) rm(Xsum) rm(X05) rm(X05.prime) ## ----fig.keep='none'----------------------------------------------------- lambda <- 2 alpha <- 1.5 beta <- -0.7 mu <- 3 xinit <- 0 gamma <- sqrt(alpha^2-beta^2) n <- 1000 T <- 1.8 VGPmodel <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rvgamma(z,lambda,alpha,beta,mu)")) samp <- setSampling(Terminal=T, n=n) VGPyuima <- setYuima(model=VGPmodel, sampling=samp) # simulation set.seed(127) for (i in 1:7) { result <- simulate(VGPyuima, xinit=xinit, true.par=list(lambda=lambda,alpha=alpha,beta=beta,mu=mu)) plot(result,xlim=c(0,T),ylim=c(-5,6),col=i, main="Paths of variance gamma process",par(new=T)) } ## ----plot-VGprocess2,echo=FALSE,results='hide'--------------------------- pdf("figures/plot-VGprocess2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(127) for (i in 1:7) { result <- simulate(VGPyuima, xinit=xinit, true.par=list(lambda=lambda,alpha=alpha,beta=beta,mu=mu)) plot(result,xlim=c(0,T),ylim=c(-5,6),col=i, main="Paths of variance gamma process",par(new=T)) } dev.off() ## ----eval=FALSE---------------------------------------------------------- ## n <- 5 ## samp <- setSampling(Terminal=T, n=n) ## VGPyuima <- setYuima(model=VGPmodel, sampling=samp) ## VGPsimdata <- NULL ## for (i in 1:5000){ ## result <- simulate(VGPyuima, xinit=xinit, ## true.par=list(lambda=lambda,alpha=alpha,beta=beta,mu=mu)) ## x1 <- result@[email protected][n+1,1] ## VGPsimdata <- c(VGPsimdata,as.numeric(x1[1])) ## } ## hist(VGPsimdata,xlim=c(-7,10),ylim=c(0,0.22),breaks=100,freq=FALSE, ## main=expression(paste("Distribution of ",X[1.8], ## " and Density of VG"))) ## curve(dvgamma(x,lambda*T,alpha,beta,mu*T),add=TRUE,col="red") ## ----plot-VGPproc2,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-VGPproc2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) n <- 5 samp <- setSampling(Terminal=T, n=n) VGPyuima <- setYuima(model=VGPmodel, sampling=samp) VGPsimdata <- NULL for (i in 1:5000){ result <- simulate(VGPyuima, xinit=xinit, true.par=list(lambda=lambda,alpha=alpha,beta=beta,mu=mu)) x1 <- result@[email protected][n+1,1] VGPsimdata <- c(VGPsimdata,as.numeric(x1[1])) } hist(VGPsimdata,xlim=c(-7,10),ylim=c(0,0.22),breaks=100,freq=FALSE, main=expression(paste("Distribution of ",X[1.8], " and Density of VG"))) curve(dvgamma(x,lambda*T,alpha,beta,mu*T),add=TRUE,col="red") dev.off() ## ----fig.keep='none'----------------------------------------------------- delta <- 0.5 alpha <- 1.5 beta <- -0.7 mu <- 3 gamma <- sqrt(alpha^2-beta^2) n <- 10000 T <- 1.8 set.seed(127) normal.rn <- rnorm(n,0,1) iv.rn <- rIG(n,delta*T,gamma) z <- mu*T+beta*iv.rn+sqrt(iv.rn)*normal.rn title <- expression(paste(NIGP[1.8], " built by subordination (green) and rNIG (white)")) nig.rn <- rNIG(n,alpha,beta,delta*T,mu*T) hist(z,xlim=c(-1,10),ylim=c(0,0.61),breaks=100, freq=FALSE, col="green", main=title, xlab=expression(X[1.8]) ) curve(dNIG(x,alpha,beta,delta*T,mu*T),add=TRUE,col="red") par(new=T) hist(nig.rn,xlim=c(-1,10),ylim=c(0,0.61),breaks=100, freq=FALSE, main="", xlab="") ## ----plot-NIGproc2,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-NIGproc2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) hist(z,xlim=c(-1,10),ylim=c(0,0.61),breaks=100, freq=FALSE, col="green", main=title, xlab=expression(X[1.8]) ) curve(dNIG(x,alpha,beta,delta*T,mu*T),add=TRUE,col="red") par(new=T) hist(nig.rn,xlim=c(-1,10),ylim=c(0,0.61),breaks=100, freq=FALSE, main="", xlab="") dev.off() ## ----eval=FALSE---------------------------------------------------------- ## delta1 <- 0.5 ## alpha <- 1.5 ## beta <- -0.7 ## mu <- 3 ## xinit <- 0 ## gamma <- sqrt(alpha^2-beta^2) ## n <- 1000 ## T <- 1.8 ## NIG2model <- setModel(drift=0, jump.coeff=1, measure.type="code", ## measure=list(df="rNIG(z,alpha,beta,delta1,mu)")) ## samp <- setSampling(Terminal=T, n=n) ## NIG2yuima <- setYuima(model=NIG2model, sampling=samp) ## set.seed(127) ## for (i in 1:10) { ## result <- simulate(NIG2yuima, xinit=xinit, ## true.par=list(delta1=delta1, alpha=alpha, beta=beta, ## mu=mu, gamma=gamma)) ## plot(result,xlim=c(0,T),ylim=c(-1,10),col=i, ## main="Paths of NIG process",par(new=T)) ## } ## ----plot-NIGproc3,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-NIGproc3.pdf",width=9,height=4) par(mar=c(4,4,2,1)) delta1 <- 0.5 alpha <- 1.5 beta <- -0.7 mu <- 3 xinit <- 0 gamma <- sqrt(alpha^2-beta^2) n <- 1000 T <- 1.8 NIG2model <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rNIG(z,alpha,beta,delta1,mu)")) samp <- setSampling(Terminal=T, n=n) NIG2yuima <- setYuima(model=NIG2model, sampling=samp) set.seed(127) for (i in 1:10) { result <- simulate(NIG2yuima, xinit=xinit, true.par=list(delta1=delta1, alpha=alpha, beta=beta, mu=mu, gamma=gamma)) plot(result,xlim=c(0,T),ylim=c(-1,10),col=i, main="Paths of NIG process",par(new=T)) } dev.off() ## ----fig.keep='none'----------------------------------------------------- n <- 5 samp <- setSampling(Terminal=T, n=n) NIG2yuima <- setYuima(model=NIG2model, sampling=samp) NIG2data <- NULL for (i in 1:3000){ result <- simulate(NIG2yuima, xinit=xinit, true.par=list(delta1=delta1, alpha=alpha, beta=beta, mu=mu, gamma=gamma)) x1 <- result@[email protected][n+1,1] NIG2data <- c(NIG2data,as.numeric(x1[1])) } hist(NIG2data,xlim=c(2,8),ylim=c(0,0.8),breaks=100, freq=FALSE, main=expression(paste("Distribution of ",X[1.8], " and Density of NIG"))) curve(dNIG(x,alpha,beta,delta*T,mu*T),add=TRUE,col="red") ## ----plot-NIGproc4,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-NIGproc4.pdf",width=9,height=4) par(mar=c(4,4,2,1)) hist(NIG2data,xlim=c(2,8),ylim=c(0,0.8),breaks=100, freq=FALSE, main=expression(paste("Distribution of ",X[1.8], " and Density of NIG"))) curve(dNIG(x,alpha,beta,delta*T,mu*T),add=TRUE,col="red") dev.off() ## ----fig.keep='none'----------------------------------------------------- nrep <- 100000 alpha <- 0.5 delta <- 0.2 gamma <- 1 beta <- 1 mu <- -0.7 Lambda <- matrix(1,1,1) t <- 1.5 par(mfrow=c(2,2)) set.seed(127) x <- rnts(nrep,alpha,delta*t,gamma,beta,mu*t,Lambda) s <- rpts(nrep,alpha,delta*t,gamma) w <- rnorm(nrep,0,1) y <- rep(mu*t,nrep) + beta*s + sqrt(s)*w hist(x,xlim=c(-3,3),ylim=c(0,1.2),breaks=200, main=expression(X[t]),probability=TRUE) hist(y,xlim=c(-3,3),ylim=c(0,1.2),breaks=200, main=expression(Y[t]),probability=TRUE,col="red") ## experiment by convolution nrep <- 3000000 Xt <- rnts(nrep,alpha,delta*t,gamma,beta,mu*t,Lambda) X05 <- rnts(nrep,alpha,delta*t/2,gamma,beta,mu*t/2,Lambda) X05.prime <- rnts(nrep,alpha,delta*t/2,gamma,beta,mu*t/2,Lambda) Xsum <- X05+X05.prime hist(Xt,xlim=c(-3,3),ylim=c(0,1.2),breaks=300, main=expression(X[t]),probability=TRUE) hist(Xsum,xlim=c(-3,3),ylim=c(0,1.2),breaks=300, main=expression(paste(X[t/2]+X[t/2],"'")), probability=TRUE,col="red") ks.test(Xt,Xsum) ## ----plot-NTSPproc,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-NTSPproc.pdf",width=9,height=4) par(mar=c(4,4,2,1)) par(mfrow=c(2,2)) hist(x,xlim=c(-3,3),ylim=c(0,1.2),breaks=200, main=expression(X[t]),probability=TRUE) hist(y,xlim=c(-3,3),ylim=c(0,1.2),breaks=200, main=expression(Y[t]),probability=TRUE,col="red") hist(Xt,xlim=c(-3,3),ylim=c(0,1.2),breaks=300, main=expression(X[t]),probability=TRUE) hist(Xsum,xlim=c(-3,3),ylim=c(0,1.2),breaks=300, main=expression(paste(X[t/2]+X[t/2],"'")), probability=TRUE,col="red") dev.off() rm(Xt) rm(X05) rm(X05.prime) rm(Xsum) ## ----eval=FALSE---------------------------------------------------------- ## alpha <- 0.5 ## beta <- -0.4 ## sigma <- 0.7 ## gamma <- 0.5 ## n <- 1000 ## T <- 1.8 ## ASmodel <- setModel(drift=0, jump.coeff=1, measure.type="code", ## measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) ## samp <- setSampling(Terminal=T, n=n) ## ASyuima <- setYuima(model=ASmodel, sampling=samp) ## set.seed(129) ## for (i in 1:10) { ## result <- simulate(ASyuima, true.par=list(alpha=alpha, ## beta=beta,sigma=sigma,gamma=gamma)) ## plot(result,xlim=c(0,T),ylim=c(-40,10),col=i, ## main=expression(paste("Paths of stable process (", ## alpha==0.5,",",beta==-0.4,")")),par(new=T)) ## } ## ## #param2 ## alpha <- 1 ## beta <- -0.4 ## sigma <- 0.7 ## gamma <- 0.5 ## AS2model <- setModel(drift=0, jump.coeff=1, measure.type="code", ## measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) ## AS2yuima <- setYuima(model=AS2model, sampling=samp) ## for (i in 1:10) { ## result <- simulate(AS2yuima, true.par=list(alpha=alpha, ## beta=beta,sigma=sigma,gamma=gamma)) ## plot(result,xlim=c(0,T),ylim=c(-5,5),col=i, ## main=expression(paste("Paths of stable process (", ## alpha==1,",",beta==-0.4,")")),par(new=T)) ## } ## ## #param3 ## alpha <- 1 ## beta <- 0.4 ## sigma <- 0.7 ## gamma <- 0.5 ## AS3model <- setModel(drift=0, jump.coeff=1, measure.type="code", ## measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) ## AS3yuima <- setYuima(model=AS3model, sampling=samp) ## for (i in 1:10) { ## result <- simulate(AS3yuima, true.par=list(alpha=alpha, ## beta=beta,sigma=sigma,gamma=gamma)) ## plot(result,xlim=c(0,T),ylim=c(-5,5),col=i, ## main=expression(paste("Paths of stable process (", ## alpha==1,",",beta==0.4,")")),par(new=T)) ## } ## ## #param4 ## alpha <- 1.5 ## beta <- 0.4 ## sigma <- 0.7 ## gamma <- 0.5 ## AS4model <- setModel(drift=0, jump.coeff=1, measure.type="code", ## measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) ## AS4yuima <- setYuima(model=AS4model, sampling=samp) ## for (i in 1:10) { ## result <- simulate(AS4yuima, true.par=list(alpha=alpha, ## beta=beta, sigma=sigma,gamma=gamma)) ## plot(result,xlim=c(0,T),ylim=c(-3,5),col=i, ## main=expression(paste("Paths of stable process (", ## alpha==1.5,",",beta==0.4,")")),par(new=T)) ## } ## ----plot-ASproc,echo=FALSE,results='hide'------------------------------- pdf("figures/plot-ASproc1.pdf",width=9,height=4) par(mar=c(4,4,2,1)) alpha <- 0.5 beta <- -0.4 sigma <- 0.7 gamma <- 0.5 n <- 1000 T <- 1.8 ASmodel <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) samp <- setSampling(Terminal=T, n=n) ASyuima <- setYuima(model=ASmodel, sampling=samp) set.seed(129) for (i in 1:10) { result <- simulate(ASyuima, true.par=list(alpha=alpha, beta=beta,sigma=sigma,gamma=gamma)) plot(result,xlim=c(0,T),ylim=c(-40,10),col=i, main=expression(paste("Paths of stable process (", alpha==0.5,",",beta==-0.4,")")),par(new=T)) } dev.off() pdf("figures/plot-ASproc2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) #param2 alpha <- 1 beta <- -0.4 sigma <- 0.7 gamma <- 0.5 AS2model <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) AS2yuima <- setYuima(model=AS2model, sampling=samp) for (i in 1:10) { result <- simulate(AS2yuima, true.par=list(alpha=alpha, beta=beta,sigma=sigma,gamma=gamma)) plot(result,xlim=c(0,T),ylim=c(-5,5),col=i, main=expression(paste("Paths of stable process (", alpha==1,",",beta==-0.4,")")),par(new=T)) } dev.off() pdf("figures/plot-ASproc3.pdf",width=9,height=4) par(mar=c(4,4,2,1)) #param3 alpha <- 1 beta <- 0.4 sigma <- 0.7 gamma <- 0.5 AS3model <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) AS3yuima <- setYuima(model=AS3model, sampling=samp) for (i in 1:10) { result <- simulate(AS3yuima, true.par=list(alpha=alpha, beta=beta,sigma=sigma,gamma=gamma)) plot(result,xlim=c(0,T),ylim=c(-5,5),col=i, main=expression(paste("Paths of stable process (", alpha==1,",",beta==0.4,")")),par(new=T)) } dev.off() pdf("figures/plot-ASproc4.pdf",width=9,height=4) par(mar=c(4,4,2,1)) #param4 alpha <- 1.5 beta <- 0.4 sigma <- 0.7 gamma <- 0.5 AS4model <- setModel(drift=0, jump.coeff=1, measure.type="code", measure=list(df="rstable(z,alpha,beta,sigma,gamma)")) AS4yuima <- setYuima(model=AS4model, sampling=samp) for (i in 1:10) { result <- simulate(AS4yuima, true.par=list(alpha=alpha,beta=beta, sigma=sigma,gamma=gamma)) plot(result,xlim=c(0,T),ylim=c(-3,5),col=i, main=expression(paste("Paths of stable process (", alpha==1.5,",",beta==0.4,")")),par(new=T)) } dev.off() ## ----fig.keep='none'----------------------------------------------------- modJump <- setModel(drift = c("-theta*x"), diffusion = "sigma", jump.coeff=c("gamma+x/sqrt(1+x^2)"), measure = list(intensity="lambda",df=list("dnorm(z, -3, 1)")), measure.type="CP", solve.variable="x") modJump samp <- setSampling(n=10000,Terminal=10) set.seed(125) X <- simulate(modJump, xinit=2, sampling=samp, true.par= list(theta=2, sigma=0.5,gamma=0.3,lambda=0.5)) plot(X) ## ----plot-modelJump,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-modelJump.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(X) dev.off() ## ----fig.keep='none'----------------------------------------------------- x0 <- 2 a <- 0.1 c <- -1 model.ig <- setModel(drift="a*x", xinit=x0, jump.coeff=c, measure.type="code", measure=list(df="rIG(z, delta0, gamma)")) model.ig sampling.ig <- setSampling(Terminal=10, n=10000) yuima.ig <- setYuima(model=model.ig, sampling=sampling.ig) set.seed(128) result.ig <- simulate(yuima.ig,true.par=list(delta0=0.55,gamma=2)) plot(result.ig) ## ----plot-modelIG,echo=FALSE,results='hide'------------------------------ pdf("figures/plot-modelIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(128) result.ig <- simulate(yuima.ig,true.par=list(delta0=0.55,gamma=2)) plot(result.ig) dev.off() ## ----fig.keep='none'----------------------------------------------------- x0 <- 2 a <- 0.1 c <- -1 model.nig <- setModel(drift="a*x", xinit=x0, jump.coeff=c, measure.type="code",measure=list(df="rNIG(z, alpha, beta, delta0, mu)")) sampling.nig <- setSampling(Terminal=10, n=10000) yuima.nig <- setYuima(model=model.nig, sampling=sampling.ig) set.seed(128) result.nig <- simulate(yuima.nig,true.par=list(alpha=2, beta=0, delta0=0.55, mu=0)) plot(result.nig) ## ----plot-modelNIG,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-modelNIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(128) result.nig <- simulate(yuima.nig,true.par=list(alpha=2, beta=0, delta0=0.55, mu=0)) plot(result.nig) dev.off() ## ----fig.keep='none'----------------------------------------------------- x0 <- 2 a <- 0.1 c <- -1 Lambda <- matrix(1,1,1) model.nig <- setModel(drift="a*x", xinit=x0, jump.coeff=c, measure.type="code",measure=list(df="rNIG(z, alpha, beta, delta0, mu, Lambda)")) sampling.nig <- setSampling(Terminal=10, n=10000) yuima.nig <- setYuima(model=model.nig, sampling=sampling.ig) set.seed(128) result.nig <- simulate(yuima.nig,true.par=list(alpha=2, beta=0, delta0=0.55, mu=0, Lambda=Lambda)) plot(result.nig) ## ----plot-modelNIG2,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-modelNIG2.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(128) result.nig <- simulate(yuima.nig,true.par=list(alpha=2, beta=0, delta0=0.55, mu=0, Lambda=Lambda)) plot(result.nig) dev.off() ## ----fig.keep='none'----------------------------------------------------- x0 <- c(2,3) a1 <- function(t,x1,x2){ x1*cos(2*pi*t)-x2*sin(2*pi*t) } a2 <- function(t,x1,x2){ x1*sin(2*pi*t)+x2*cos(2*pi*t) } a <- c("a1(t,x1,x2)","a2(t,x1,x2)") b <- matrix(c("t*x2","1","0","x1"),2,2) c <- matrix(c("cos(2*pi*t)", "(5-t)*x1","sin(2*pi*t)",1),2,2) alpha <- 2 beta <- c(0,0) delta0 <- 0.55 mu <- c(0,0) Lambda <- matrix(c(1,0,0,1),2,2) model.mnig <- setModel(drift=a, xinit=x0, diffusion=b, jump.coeff=c, measure.type="code", measure=list(df="rNIG(z, alpha, beta, delta0, mu, Lambda)"), state.variable=c("x1","x2"),solve.variable=c("x1","x2") ) model.mnig sampling.mnig <- setSampling(Terminal=1, n=10000) yuima.mnig <- setYuima(model=model.mnig, sampling=sampling.mnig) set.seed(128) result.mnig <- simulate(yuima.mnig,true.par=list(alpha=alpha, beta=beta, delta0=delta0, mu=mu, Lambda=Lambda)) plot(result.mnig) ## ----plot-modelMNIG,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-modelMNIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) set.seed(128) result.mnig <- simulate(yuima.mnig,true.par=list(alpha=alpha, beta=beta, delta0=delta0, mu=mu, Lambda=Lambda)) plot(result.mnig) dev.off() ## ----fig.keep='none', results='hide'------------------------------------- mod5 <- setModel(drift = c("-theta*x"), diffusion = "sigma", jump.coeff=c("gamma+x/sqrt(1+x^2)"), measure = list(intensity="lambda",df=list("dnorm(z, 2, 0.1)")), measure.type="CP", solve.variable="x") theta <- 2 sigma <- 0.5 gamma <- 0.3 lambda <- 2.5 T <- 10 N <- 10000 delta <- T/N h <- T/N true <- list(theta=theta, sigma=sigma,gamma=gamma,lambda=lambda) set.seed(125) X <- simulate(mod5, true.p=true,xinit=2, sampling=setSampling(n=N,Terminal=T)) plot(X) r <- h^0.4 est.qmle <- qmle(yuima=X, start=true, lower=list(theta=1,sigma=0,gamma=0.1,lambda=0.1), upper=list(theta=3,sigma=2,gamma=0.8,lambda=20), method="L-BFGS-B", threshold=r) unlist(true) summary(est.qmle) ## ----echo=FALSE---------------------------------------------------------- unlist(true) writeLines(strwrap(capture.output(summary(est.qmle)),width=60)) ## ----plot-modelSDEJ,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-modelSDEJ.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(X) dev.off() ## ------------------------------------------------------------------------ est.qmle1 <- qmle(yuima=X, start=true, lower=list(theta=1,sigma=0,gamma=0.1,lambda=0.1), upper=list(theta=3,sigma=2,gamma=0.8,lambda=20), method="L-BFGS-B", threshold=2) # too large coef(est.qmle1) est.qmle2 <- qmle(yuima=X, start=true, lower=list(theta=1,sigma=0,gamma=0.1,lambda=0.1), upper=list(theta=3,sigma=2,gamma=10,lambda=1000), method="L-BFGS-B", threshold=0.03) ## too low coef(est.qmle2) ## ----fig.keep='none',message=FALSE--------------------------------------- require(quantmod) getSymbols("ENI.MI",to="2016-12-31") S <- ENI.MI$ENI.MI.Adjusted Z <- na.omit(diff(log(S))) Dt <- 1/252 # geometric Brownian motion estimation model1 <- setModel(drift="mu*x", diff="sigma*x") gBm <- setYuima(model=model1, data=setData(S,delta=Dt)) gBm.fit <- qmle(gBm, start=list(mu=0,sigma=1),method="BFGS") gBm.cf <- coef(gBm.fit) zMin <- min(Z) zMax <- max(Z) # Gaussian-Levy estimation model3 <- setPoisson( df="dnorm(z,mu,sigma)") Norm <- setYuima(model=model3, data=setData(cumsum(Z),delta=Dt)) Norm.fit <- qmle(Norm,start=list(mu=1, sigma=1), lower=list(mu=1e-7,sigma=0.01),method="L-BFGS-B") Norm.cf <- coef(Norm.fit) # NIG-Levy estimation model2 <- setPoisson( df="dNIG(z,alpha,beta,delta1,mu)") NIG <- setYuima(model=model2, data=setData(cumsum(Z),delta=Dt)) NIG.fit <- qmle(NIG,start=list(alpha=10, beta=1, delta1=1,mu=1), lower=list(alpha=1,beta=-2, delta1=0.001,mu=0.0001), method="L-BFGS-B") NIG.cf <- coef(NIG.fit) myfgBm <- function(u) dnorm(u, mean=gBm.cf["mu"], sd=gBm.cf["sigma"]) myfNorm <- function(u) dnorm(u, mean=Norm.cf["mu"],sd=Norm.cf["sigma"]) myfNIG <- function(u) dNIG(u, alpha=NIG.cf["alpha"],beta=NIG.cf["beta"], delta=NIG.cf["delta1"], mu=NIG.cf["mu"]) plot(density(Z,na.rm=TRUE),main="Gaussian versus NIG") curve(myfgBm, zMin, zMax, add=TRUE, lty=2) curve(myfNorm, zMin, zMax, col="red", add=TRUE, lty=4) curve(myfNIG, zMin, zMax, col="blue", add=TRUE,lty=3) ## ----plot-modelExpLevy,echo=FALSE,results='hide'------------------------- pdf("figures/plot-modelExpLevy.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(density(Z,na.rm=TRUE),main="Gaussian versus NIG") curve(myfgBm, zMin, zMax, add=TRUE, lty=2) curve(myfNorm, zMin, zMax, col="red", add=TRUE, lty=4) curve(myfNIG, zMin, zMax, col="blue", add=TRUE,lty=3) dev.off() ## ------------------------------------------------------------------------ AIC(gBm.fit) AIC(Norm.fit) AIC(NIG.fit)
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter4.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ----sim-mod4AB, echo=TRUE,fig.keep='none'------------------------------- mod4A <- setModel(drift="3*y", diffusion=1, hurst=0.3, solve.var="y") mod4A mod4B <- setModel(drift="3*y", diffusion=1, hurst=0.7, solve.var="y") mod4B set.seed(123) X1 <- simulate(mod4A,sampling=setSampling(n=1000)) X2 <- simulate(mod4B,sampling=setSampling(n=1000)) par(mfrow=c(2,1)) par(mar=c(2,3,1,1)) plot(X1,main="H=0.3") plot(X2,main="H=0.7") ## ----results='hide'------------------------------------------------------ str(mod4A) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(mod4A)),width=60)) ## ----plot-mod4AB,echo=FALSE,results='hide'------------------------------- pdf("figures/plot-mod4AB.pdf",width=9,height=4) par(mfrow=c(2,1)) par(mar=c(2,3,1,1)) plot(X1,main="H=0.3") plot(X2,main="H=0.7") dev.off() ## ------------------------------------------------------------------------ set.seed(123) samp <- setSampling(Terminal=100, n=10000) mod <- setModel(drift="-lambda*x", diffusion="sigma", hurst=NA) ou <- setYuima(model=mod, sampling=samp) fou <- simulate(ou, xinit=1, true.param=list(lambda=2, sigma=1), hurst=0.7) fou ## ------------------------------------------------------------------------ qgv(fou) ## ------------------------------------------------------------------------ mmfrac(fou) ## ----results='hide'------------------------------------------------------ data(MWK151) str(MWK151) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(MWK151)),width=60)) ## ----MWK151, echo=TRUE,fig.keep='none'----------------------------------- par(mfrow=c(1,2)) plot(MWK151, main="Methuselah Walk ring widths", xlab="year") plot(acf(MWK151)) ## ----plot-MWK151,echo=FALSE,results='hide'------------------------------- pdf("figures/plot-MWK151.pdf",width=9,height=6) par(mar=c(4,4,2,1)) par(mfrow=c(1,2)) plot(MWK151, main="Methuselah Walk ring widths", xlab="year") plot(acf(MWK151)) dev.off() ## ------------------------------------------------------------------------ mod <- setModel(drift="-lambda *x", diffusion="sigma", hurst=NA) mwk <- setYuima(model=mod, data=setData(MWK151)) mwk mmfrac(mwk)
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter5.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ----carma.brown,echo=TRUE,eval=TRUE------------------------------------- carma.mod<-setCarma(p=3,q=1,loc.par="c0",Carma.var="y",Latent.var="X") carma.mod ## ----carma.brown.str,results='hide'-------------------------------------- str(carma.mod) ## ----echo=FALSE---------------------------------------------------------- writeLines(strwrap(capture.output(str(carma.mod)),width=60)) ## ----carma.brown.par,echo=TRUE,eval=TRUE--------------------------------- par.carma<-list(a1=4,a2=4.75,a3=1.5,b0=1,b1=0.23,c0=0) samp<-setSampling(Terminal=100, n=3000) set.seed(123) carma <-simulate(carma.mod, true.parameter=par.carma, sampling=samp) ## ----plot-carma,echo=TRUE,fig.keep='none',results='hide'----------------- plot(carma) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-carma.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(carma) dev.off() ## ----eval=FALSE---------------------------------------------------------- ## CarmaNoise(yuima, param, data=NULL) ## ----carma.brown.qmle,echo=TRUE,eval=TRUE-------------------------------- fit <- qmle(carma, start=par.carma) fit ## ----Carm21Comp0, echo=TRUE---------------------------------------------- modCP<-setCarma(p=2,q=1,Carma.var="y", measure=list(intensity="Lamb",df=list("dnorm(z, mu, sig)")), measure.type="CP") true.parmCP <-list(a1=1.39631,a2=0.05029,b0=1,b1=2, Lamb=1,mu=0,sig=1) ## ----sim_Carm21Comp0, echo=TRUE------------------------------------------ samp.L<-setSampling(Terminal=200,n=4000) set.seed(123) simCP<-simulate(modCP,true.parameter=true.parmCP,sampling=samp.L) ## ----plot-simCP,echo=TRUE,fig.keep='none',results='hide'----------------- plot(simCP,main="CP CARMA(2,1) model") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-simCP.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(simCP,main="CP CARMA(2,1) model") dev.off() ## ----plot_Carm21Comp0,echo=TRUE,fig.width=14,fig.height=7---------------- carmaoptCP <- qmle(simCP, start=true.parmCP, Est.Incr="Incr") summary(carmaoptCP) ## ----plot-carmaoptCP,echo=TRUE,fig.keep='none',results='hide'------------ plot(carmaoptCP,ylab="Incr.",type="l", main="Compound Poisson with normal jump size") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-carmaoptCP.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(carmaoptCP,main="Compound Poisson with normal jump size",ylab="Incr.",type="l") dev.off() ## ----Carm21vg, echo=TRUE------------------------------------------------- modVG<-setCarma(p=2,q=1,Carma.var="y", measure=list("rvgamma(z,lambda,alpha,beta,mu)"), measure.type="code") true.parmVG <-list(a1=1.39631, a2=0.05029, b0=1, b1=2, lambda=1, alpha=1, beta=0, mu=0) ## ----PlotCarm21vg, echo=TRUE,fig.width=14,fig.height=7,fig.keep='none',results='hide'---- set.seed(100) simVG<-simulate(modVG, true.parameter=true.parmVG, sampling=samp.L) plot(simVG,main="VG CARMA(2,1) model") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-simVG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(simVG,main="VG CARMA(2,1) model") dev.off() ## ----EstPlotCarm21vg,echo=TRUE, fig.keep='none',results='hide'----------- carmaoptVG <- qmle(simVG, start=true.parmVG, Est.Incr="Incr") summary(carmaoptVG) plot(carmaoptVG,xlab="Time", main="Variance Gamma increments",ylab="Incr.",type="l") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-carmaoptVG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(carmaoptVG,main="Variance Gamma increments",ylab="Incr.",xlab="Time",type="l") dev.off() ## ----Carm21Comp3, echo=TRUE---------------------------------------------- modNIG<-setCarma(p=2,q=1,Carma.var="y", measure=list("rNIG(z,alpha,beta,delta1,mu)"), measure.type="code") IncMod<-setModel(drift="0",diffusion="0",jump.coeff="1", measure=list("rNIG(z,1,0,1,0)"),measure.type="code") set.seed(100) simLev<-simulate(IncMod,sampling=samp.L) incrLevy<-diff(as.numeric(get.zoo.data(simLev)[[1]])) ## ----plot-incrLevy,echo=TRUE,fig.keep='none',results='hide'-------------- plot(incrLevy,main="simulated noise increments",type="l") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-incrLevy.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(incrLevy,main="simulated noise increments",type="l") dev.off() ## ----Carm21sim3, echo=TRUE----------------------------------------------- true.parmNIG <-list(a1=1.39631,a2=0.05029,b0=1,b1=2, alpha=1,beta=0,delta1=1,mu=0) simNIG<-simulate(modNIG,true.parameter=true.parmNIG,sampling=samp.L) ## ----plot-simNIG,echo=TRUE,fig.keep='none',results='hide'---------------- plot(simNIG,main="NIG CARMA(2,1) model") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-simNIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(simNIG,main="NIG CARMA(2,1) model") dev.off() ## ----plot_Carm21Comp3 ,echo=TRUE,fig.width=14,fig.height=7--------------- carmaoptNIG <- qmle(simNIG, start=true.parmNIG, Est.Incr="Incr") summary(carmaoptNIG) ## ----plot-carmaoptNIG,echo=TRUE,fig.keep='none',results='hide'----------- plot(carmaoptNIG,main="Normal Inverse Gaussian",ylab="Incr.",type="l") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-carmaoptNIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(carmaoptNIG,main="Normal Inverse Gaussian",ylab="Incr.",type="l") dev.off() ## ----Incrtime1Levy3a, echo=TRUE------------------------------------------ NIG.Inc<-as.numeric(coredata([email protected])) NIG.freq<-frequency([email protected]) ## ----Incrtime1Levy3b, echo=TRUE------------------------------------------ t.idx <- seq(from=1, to=length(NIG.Inc), by=NIG.freq) Unitary.NIG.Inc<-diff(cumsum(NIG.Inc)[t.idx]) ## ----Incrtime1Levy3est, echo=TRUE---------------------------------------- library(GeneralizedHyperbolic) FitInc.NIG.Lev<-nigFit(Unitary.NIG.Inc) summary(FitInc.NIG.Lev, hessian = TRUE, hessianMethod = "tsHessian") ## ----plot-fitNIG,echo=TRUE,fig.keep='none',results='hide'---------------- par(mfrow = c(1, 2)) plot(FitInc.NIG.Lev, which = 2:3, plotTitles = paste(c("Histogram of NIG ", "Log-Histogram of NIG ", "Q-Q Plot of NIG "), "Incr.", sep = "")) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-fitNIG.pdf",width=9,height=4) par(mar=c(4,4,2,1)) par(mfrow = c(1, 2)) plot(FitInc.NIG.Lev, which = 2:3, plotTitles = paste(c("Histogram of NIG ", "Log-Histogram of NIG ", "Q-Q Plot of NIG "), "Incr.", sep = "")) dev.off() ## ----message=FALSE,fig.keep='none'--------------------------------------- library(quantmod) getSymbols("^VIX", to="2016-12-31") X <- VIX$VIX.Close VIX.returns <- log(X) plot(VIX.returns, main="VIX daily log-Returns") ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-VIXret.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(VIX.returns, main="VIX daily log-Returns") dev.off() ## ----fig.keep='none'----------------------------------------------------- acf(VIX.returns) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-acfVIX.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(acf(VIX.returns)) dev.off() ## ----message=FALSE,fig.keep='none'--------------------------------------- library(TSA) eacf(VIX.returns,ar.max = 3, ma.max = 4) Delta <- 1/252 VIX.Data<-setData(VIX.returns,delta=Delta) Normal.model<-setCarma(p=2, q=1,loc.par="mu") Normal.CARMA<-setYuima(data=VIX.Data, model=Normal.model) Normal.start <- list(a1=36,a2=56,b0=21,b1=1,mu=0) Normal.est <- qmle(yuima=Normal.CARMA, start=Normal.start, Est.Incr="Incr") summary(Normal.est ) ## ------------------------------------------------------------------------ inc <[email protected] shapiro.test(as.numeric(inc)) ## ----fig.keep='none'----------------------------------------------------- plot(acf(as.numeric(inc))) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-acf2VIX.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(acf(as.numeric(inc))) dev.off() ## ------------------------------------------------------------------------ Box.test(x=as.numeric(inc), lag = 10, type ="Ljung-Box") Box.test(x=as.numeric(inc), lag = 10, type ="Box-Pierce") ## ------------------------------------------------------------------------ VG.model <- setCarma(p=2, q=1,loc.par="mu", measure=list("rvgamma(z,lambda,alpha,beta,mu0)"), measure.type="code") NIG.model <- setCarma(p=2, q=1,loc.par="mu", measure=list(df=list("rNIG(z, alpha, beta, delta1, mu0)")), measure.type="code") VG.CARMA<-setYuima(data=VIX.Data, model=VG.model) NIG.CARMA<-setYuima(data=VIX.Data, model=NIG.model) VG.start <- list(a1=36,a2=56,b0=21,b1=1,mu=0, lambda=1,alpha=1,beta=0,mu0=0) NIG.start <- list(a1=36,a2=56,b0=21,b1=1,mu=0, alpha=2,beta=1,delta1=1,mu0=0) fit.VG <- qmle(yuima=VG.CARMA,start=VG.start, Est.Incr="IncrPar",aggregation=FALSE) fit.NIG <- qmle(yuima=NIG.CARMA,start=NIG.start, Est.Incr="IncrPar",aggregation=FALSE) cf.VG <- coef(fit.VG ) cf.NIG <- coef(fit.NIG ) summary(fit.VG) summary(fit.NIG) ## ----fig.keep='none'----------------------------------------------------- d.N <- function(u) log( 1+dnorm(u, mean=mean(inc), sd=sd(inc)) ) d.VG <- function(u) { log(1+dvgamma(u, lambda=cf.VG["lambda"]*Delta, alpha=cf.VG["alpha"], beta=cf.VG["beta"], mu=cf.VG["mu0"]*Delta)) } d.NIG <- function(u) { log(1+dNIG(u,alpha=cf.NIG["alpha"], beta=cf.NIG["beta"], delta=cf.NIG["delta1"]*Delta, mu=cf.NIG["mu0"]*Delta)) } d.Emp <- density(inc) plot(d.Emp$x, log(1+d.Emp$y),type="l", main="Rescaled log-densities") curve(d.N, min(d.Emp$x), max(d.Emp$x), col="blue",add=TRUE, lty=3) curve(d.VG, min(d.Emp$x), max(d.Emp$x), col="red",add=TRUE,lty=4) curve(d.NIG, min(d.Emp$x), max(d.Emp$x), col="green",add=TRUE,lty=2) ## ----echo=FALSE,results='hide'------------------------------------------- pdf("figures/plot-densVIX.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(d.Emp$x, log(1+d.Emp$y),type="l", main="Rescaled log-densities") curve(d.N, min(d.Emp$x), max(d.Emp$x), col="blue",add=TRUE,lty=3, n=500) curve(d.VG, min(d.Emp$x), max(d.Emp$x), col="red",add=TRUE,lty=4, n=500) curve(d.NIG, min(d.Emp$x), max(d.Emp$x), col="green",add=TRUE,lty=2, n=500) dev.off()
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter6.R
## ----include=FALSE------------------------------------------------------- library(knitr) opts_chunk$set( tidy=FALSE, width.cutoff = 60, strip.white=TRUE, warning=FALSE ) ## ----include=FALSE------------------------------------------------------- options(width=55) options(continue=" ") require(yuima) ## ----setCogarch,echo=TRUE,eval=TRUE-------------------------------------- # COGARCH(1,1) driven by CP Cog11 <- setCogarch(p = 1, q=1, measure = list(intensity="1", df="dnorm(z, 0, 1)"), measure.type = "CP", XinExpr = TRUE) Cog11 # COGARCH(2,2) driven by CP Cog22 <- setCogarch(p=2, q=2, measure = list(intensity="1", df="dnorm(z, 0, 1)"), measure.type = "CP", XinExpr = TRUE) Cog22 ## ----str-cog,echo=TRUE,eval=TRUE----------------------------------------- class(Cog11) slotNames(Cog11) str(Cog11@info,2) ## ------------------------------------------------------------------------ # Param of the COGARCH(1,1) paramCP11 <- list(a1 = 0.038, b1= 0.053, a0 = 0.04/0.053, y01 = 50.31) check11 <- Diagnostic.Cogarch(Cog11, param=paramCP11) str(check11) # Param of the COGARCH(2,2) paramCP22 <- list(a1 = 0.04, a2 = 0.001, b1 = 0.705, b2 = 0.1, a0 = 0.1, y01=01, y02 = 0) check22 <- Diagnostic.Cogarch(Cog22, param=paramCP22) str(check22) ## ----cogarch-euler,echo=TRUE--------------------------------------------- model1 <- setCogarch(p = 1, q = 1, measure=list("rvgamma(z, 1, sqrt(2), 0, 0)"), measure.type = "code", Cogarch.var = "G", V.var = "v", Latent.var="x", XinExpr=TRUE) ## ----cogarch-euler-bad--------------------------------------------------- param1 <- list(a1 = 0.038, b1 = 301, a0 =0.01, x01 = 0) Diagnostic.Cogarch(model1, param=param1) Terminal1 <- 5 n1 <- 750 samp1 <- setSampling(Terminal=Terminal1, n=n1) set.seed(123) sim1 <- simulate(model1, sampling = samp1, true.parameter = param1, method="euler") ## ----plot-cogarch,echo=TRUE,fig.keep='none',results='hide'--------------- plot(sim1, main="VG-COGARCH(1,1) model with Euler scheme") ## ----plot-cogarch1,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-cogarch1.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(sim1, main="VG-COGARCH(1,1) model with Euler scheme") dev.off() ## ----sim-cogarch2,eval=TRUE,echo=TRUE------------------------------------ set.seed(123) sim2 <- simulate(model1, sampling = samp1, true.parameter = param1, method="mixed") ## ----plot-cogach2,echo=TRUE,fig.keep='none',results='hide'--------------- plot(sim2, main="VG-COGARCH(1,1) model with mixed scheme") ## ----plot-cogarch2,echo=FALSE,results='hide'----------------------------- pdf("figures/plot-cogarch2.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(sim2, main="VG-COGARCH(1,1) model with mixed scheme") dev.off() ## ------------------------------------------------------------------------ sampCP <- setSampling(0, 1000, 5000) simCog11 <- simulate(Cog11, true.par=paramCP11, sampling=sampCP) simCog22 <- simulate(Cog22, true.par=paramCP22, sampling=sampCP) ## ----plot-cogachs,echo=TRUE,fig.keep='none',results='hide'--------------- plot(simCog11, main="CP-COGARCH(1,1) with Gaussian noise") plot(simCog22, main="CP-COGARCH(2,2) with Gaussian noise") ## ----plot-cogarchs2,echo=FALSE,results='hide'---------------------------- pdf("figures/plot-cogarchs1.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(simCog11, main="CP-COGARCH(1,1) with Gaussian noise") dev.off() pdf("figures/plot-cogarchs2.pdf",width=9,height=4) par(mar=c(4,4,1,1)) plot(simCog22, main="CP-COGARCH(2,2) with Gaussian noise") dev.off() ## ----gmm-cogarch,eval=TRUE,echo=TRUE------------------------------------- set.seed(123) sampCP <- setSampling(0, 5000, 15000) simCog11 <- simulate(Cog11, true.par=paramCP11, sampling=sampCP) fit11 <- gmm(simCog11, start=paramCP11) summary(fit11) mat <- rbind(coef(fit11), unlist(paramCP11[names(coef(fit11))])) rownames(mat) <- c("gmm", "true") mat ## ----est-cogarch3,eval=TRUE,echo=TRUE------------------------------------ param.VG <- list(a1 = 0.038, b1 = 0.053, a0 = 0.04 / 0.053, y01 = 50.33) cog.VG <- setCogarch(p = 1, q = 1, work = FALSE, measure=list("rvgamma(z, 1, sqrt(2), 0, 0)"), measure.type = "code", XinExpr = TRUE) samp.VG <- setSampling(Terminal = 1000, n = 15000) set.seed(123) sim.VG <- simulate(cog.VG, true.parameter = param.VG, sampling = samp.VG, method = "mixed") fit.gmm <- gmm(sim.VG, start=param.VG) fit.qmle <- qmle(sim.VG, start=param.VG, grideq=TRUE) nm <- names(coef(fit.gmm)) mat <- rbind(coef(fit.gmm), coef(fit.qmle)[nm], unlist(param.VG[nm])) rownames(mat) <- c("gmm", "qmle", "true") round(mat,5) ## ----message=FALSE,fig.keep='none'--------------------------------------- require(quantmod) getSymbols("NXT.L", to="2016-12-31") S <- NXT.L$NXT.L.Close X <- na.omit(diff(log(S))) mX <- mean(X) X <- X - mX plot(X, main="Log-returns of NEXT Plc") require(rugarch) spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0, 0), include.mean = FALSE)) fitGARCH <- ugarchfit(data = X, spec = spec) GARCH11param <- coef(fitGARCH) GARCH11param ## ----plot-nextplc,echo=FALSE,results='hide'------------------------------ pdf("figures/plot-nextplc.pdf",width=9,height=4) par(mar=c(4,4,2,1)) plot(X, main="Log-returns of NEXT Plc") dev.off() ## ------------------------------------------------------------------------ Delta <- 1/252 ParGarToCog<- function(GARCH11param, dt, names=NULL){ if(is.null(names)) names <- names(GARCH11param) my.omega <- GARCH11param["omega"] my.alpha <- GARCH11param["alpha1"] my.beta <- GARCH11param["beta1"] a1 <- my.alpha/dt b1 <- -log(my.beta)/dt a0 <- my.omega/(b1*dt^2) qmleparInGARCH <- c(a0, a1, b1) names(qmleparInGARCH) <- c("a0", "a1", "b1") return(qmleparInGARCH) } ## ------------------------------------------------------------------------ ParGarToCog(GARCH11param, Delta) start <- as.list(ParGarToCog(GARCH11param, Delta)) modCog11 <- setCogarch(p=1, q=1, measure = list(intensity="1", df=list("dnorm(z, 0, 1)")), measure.type="CP") NXT.data <- setData(cumsum(X), delta = Delta) Cog11 <- setYuima(data = NXT.data, model = modCog11) Cog11.fit <- qmle(yuima = Cog11, grideq=TRUE, start = c(start, y1 = 0.1), aggregation = FALSE, method = "Nelder-Mead") COGARCH11par <- coef(Cog11.fit) COGARCH11par ## ------------------------------------------------------------------------ ParCogToGar<- function(COGARCH11param, dt, names=NULL){ a0 <- COGARCH11param["a0"] a1 <- COGARCH11param["a1"] b1 <- COGARCH11param["b1"] my.omega <- a0*b1*dt^2 my.alpha <- a1*dt my.beta <- exp(-b1*dt) qmleparInGARCH <- c(my.omega, my.alpha, my.beta) names(qmleparInGARCH) <- c("omega", "alpha1", "beta1") return(qmleparInGARCH) } ParCogToGar(COGARCH11par, Delta) GARCH11param
/scratch/gouwar.j/cran-all/cranData/yuima/inst/ybook/chapter7.R
#' User-friendly Interface for the yuima package #' #' Runs yuima Graphical User Interface #' #' @param theme GUI theme: "black" or "white". #' #' @return Starts yuima GUI #' #' @author The YUIMA Project Team #' #' @examples #' \dontrun{ #' yuimaGUI() #' } #' #' @export #' yuimaGUI <- function(theme = "black") { if(!(theme %in% c("black", "white"))) stop ("Theme not supported. Only 'black' or 'white' themes are available.") print("Please wait while loading...") options(yuimaGUItheme = theme) utils::capture.output( suppressWarnings( shiny::runApp(system.file("yuimaGUI", package = "yuimaGUI")) ) ) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/R/sourceCodeYuimaGUI.R
suppressMessages(require(DT)) suppressMessages(require(shinyjs)) suppressMessages(require(yuima)) suppressMessages(require(shiny)) suppressMessages(require(sde)) suppressMessages(require(quantmod)) suppressMessages(require(shinydashboard)) suppressMessages(require(shinyBS)) suppressMessages(require(ggplot2)) suppressMessages(require(plotly)) suppressMessages(require(ghyp)) ### comment this for web app version ### if(!exists("yuimaGUIdata")) yuimaGUIdata <- reactiveValues(series=list(), model=list(), multimodel=list(), usr_model = list(), usr_multimodel = list(), simulation=list(), multisimulation=list(), usr_simulation = list(), usr_multisimulation = list(), cp=list(), cpYuima=list(), llag = list(), cluster = list(), hedging = list()) ### comment this for web app version ### if(is.null(getOption("yuimaGUItheme"))) options(yuimaGUItheme = "black") #NIG distribution dNIG.gui <- function(x, alpha, delta, beta, mu){ g <- NIG.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) dghyp(x = x, object = g) } rNIG.gui <- function(n, alpha, delta, beta, mu){ g <- NIG.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) rghyp(n = n, object = g) } pNIG.gui <- function(q, alpha, delta, beta, mu){ g <- NIG.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) pghyp(q = q, object = g) } #hyp distribution dhyp.gui <- function(x, alpha, delta, beta, mu){ g <- hyp.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) dghyp(x = x, object = g) } rhyp.gui <- function(n, alpha, delta, beta, mu){ g <- hyp.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) rghyp(n = n, object = g) } phyp.gui <- function(q, alpha, delta, beta, mu){ g <- hyp.ad(alpha = alpha, delta = delta, beta = beta, mu = mu) pghyp(q = q, object = g) } #VG distribution dVG.gui <- function(x, lambda, alpha, beta, mu){ g <- VG.ad(lambda = lambda, alpha = alpha, beta = beta, mu = mu) dghyp(x = x, object = g) } rVG.gui <- function(n, lambda, alpha, beta, mu){ g <- VG.ad(lambda = lambda, alpha = alpha, beta = beta, mu = mu) rghyp(n = n, object = g) } pVG.gui <- function(q, lambda, alpha, beta, mu){ g <- VG.ad(lambda = lambda, alpha = alpha, beta = beta, mu = mu) pghyp(q = q, object = g) } #ghyp distribution dghyp.gui <- function(x, lambda, alpha, delta, beta, mu){ g <- ghyp.ad(lambda = lambda, alpha = alpha, delta = delta, beta = beta, mu = mu) dghyp(x = x, object = g) } rghyp.gui <- function(n, lambda, alpha, delta, beta, mu){ g <- ghyp.ad(lambda = lambda, alpha = alpha, delta = delta, beta = beta, mu = mu) rghyp(n = n, object = g) } pghyp.gui <- function(q, lambda, alpha, delta, beta, mu){ g <- ghyp.ad(lambda = lambda, alpha = alpha, delta = delta, beta = beta, mu = mu) pghyp(q = q, object = g) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/global.R
###Display available data output$changepoint_table_select <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to change point seriesToChangePoint <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$changepoint_button_select, priority = 1, { seriesToChangePoint$table <<- rbind(seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$changepoint_table_select_rows_selected]) & !(rownames(yuimaGUItable$series) %in% rownames(seriesToChangePoint$table)),]) }) ###SelectAll Button observeEvent(input$changepoint_button_selectAll, priority = 1, { seriesToChangePoint$table <<- rbind(seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$changepoint_table_select_rows_all]) & !(rownames(yuimaGUItable$series) %in% rownames(seriesToChangePoint$table)),]) }) ###Display Selected Data output$changepoint_table_selected <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (length(rownames(seriesToChangePoint$table))==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (seriesToChangePoint$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(seriesToChangePoint$table)!=0){ if (length(yuimaGUItable$series)==0) seriesToChangePoint$table <<- data.frame() else seriesToChangePoint$table <<- seriesToChangePoint$table[which(as.character(seriesToChangePoint$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$changepoint_button_delete, priority = 1,{ if (!is.null(input$changepoint_table_selected_rows_selected)) seriesToChangePoint$table <<- seriesToChangePoint$table[-input$changepoint_table_selected_rows_selected,] }) ###DeleteAll Button observeEvent(input$changepoint_button_deleteAll, priority = 1,{ if (!is.null(input$changepoint_table_selected_rows_all)) seriesToChangePoint$table <<- seriesToChangePoint$table[-input$changepoint_table_selected_rows_all,] }) observe({ shinyjs::toggle("changepoint_charts", condition = (length(names(yuimaGUIdata$cp))!=0)) }) observe({ shinyjs::toggle("parametric_changepoint_charts", condition = (length(names(yuimaGUIdata$cpYuima))!=0)) }) output$changepoint_symb <- renderUI({ n <- names(yuimaGUIdata$cp) if(length(n)!=0) selectInput("changepoint_symb", "Symbol", choices = sort(n), selected = last(n)) }) observeEvent(input$changepoint_button_startEstimation, { if (length(rownames(seriesToChangePoint$table))!=0) withProgress(message = 'Analyzing: ', value = 0, { errors <- c() for (i in rownames(seriesToChangePoint$table)){ incProgress(1/length(rownames(seriesToChangePoint$table)), detail = i) errors <- c(errors, addCPoint_distribution(symb = i, method = input$changepoint_method, pvalue = input$changepoint_pvalue)$error) } if(!is.null(errors)) createAlert(session = session, anchorId = "nonparametric_changepoint_alert", content = paste("Unable to estimate change points of:", paste(errors, collapse = " ")), dismiss = T, style = "error") }) }) range_changePoint <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$changePoint_brush) & !is.null(input$changepoint_symb)){ data <- yuimaGUIdata$cp[[input$changepoint_symb]]$series test <- (length(index(window(data, start = input$changePoint_brush$xmin, end = input$changePoint_brush$xmax))) > 3) if (test==TRUE){ range_changePoint$x <- c(as.Date(input$changePoint_brush$xmin), as.Date(input$changePoint_brush$xmax)) range_changePoint$y <- c(input$changePoint_brush$ymin, input$changePoint_brush$ymax) } } }) observeEvent(input$changePoint_dbclick,{ range_changePoint$x <- c(NULL, NULL) }) observeEvent(input$changepoint_symb, { range_changePoint$x <- c(NULL, NULL) output$changepoint_plot_series <- renderPlot({ if(!is.null(input$changepoint_symb)) { cp <- isolate({yuimaGUIdata$cp[[input$changepoint_symb]]}) par(bg="black") plot(window(cp$series, start = range_changePoint$x[1], end = range_changePoint$x[2]), main=cp$symb, xlab="Index", ylab=NA, log=switch(input$changepoint_scale,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") abline(v=cp$tau, col = "red") grid(col="grey") } }) output$changepoint_plot_incr <- renderPlot({ if(!is.null(input$changepoint_symb)) { cp <- isolate({yuimaGUIdata$cp[[input$changepoint_symb]]}) if(cp$method=="KSdiff") { x <- diff(cp$series) title <- " - Increments" } else { x <- Delt(cp$series) title <- " - Percentage Increments" } x <- x[x[,1]!="Inf"] par(bg="black") plot(window(x, start = range_changePoint$x[1], end = range_changePoint$x[2]), main=paste(cp$symb, title), xlab="Index", ylab=NA, log=switch(input$changepoint_scale,"Linear"="","Logarithmic (Y)"="", "Logarithmic (X)"="x", "Logarithmic (XY)"="x"), col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") abline(v=cp$tau, col = "red") grid(col="grey") } }) }) output$text_ChangePointInfo <- renderUI({ if(!is.null(input$changepoint_symb)){ info <- yuimaGUIdata$cp[[input$changepoint_symb]] div( h3(input$changepoint_symb, class = "hModal"), h4( em(switch(info$method, "KSdiff"="Increments Distriution", "KSperc"="Percentage Increments Distriution")), br(), class = "hModal" ), align="center" ) } }) output$table_ChangePointInfo <- renderTable(digits = 4, { table <- data.frame(Time = as.character(yuimaGUIdata$cp[[input$changepoint_symb]]$tau), "p.value" = yuimaGUIdata$cp[[input$changepoint_symb]]$pvalue, check.names = FALSE, row.names = yuimaGUIdata$cp[[input$changepoint_symb]]$tau) return(table[order(rownames(table), decreasing = TRUE),]) }) observeEvent(input$changepoint_button_delete_estimated, { yuimaGUIdata$cp[[input$changepoint_symb]] <<- NULL }) observeEvent(input$changepoint_button_deleteAll_estimated, { yuimaGUIdata$cp <<- list() })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/eda/changepoint_non_parametric.R
###Display available data output$parametric_changepoint_table_select <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to change point parametric_seriesToChangePoint <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$parametric_changepoint_button_select, priority = 1, { parametric_seriesToChangePoint$table <<- rbind(parametric_seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$parametric_changepoint_table_select_rows_selected]) & !(rownames(yuimaGUItable$series) %in% rownames(parametric_seriesToChangePoint$table)),]) }) ###SelectAll Button observeEvent(input$parametric_changepoint_button_selectAll, priority = 1, { parametric_seriesToChangePoint$table <<- rbind(parametric_seriesToChangePoint$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$parametric_changepoint_table_select_rows_all]) & !(rownames(yuimaGUItable$series) %in% rownames(parametric_seriesToChangePoint$table)),]) }) ###Display Selected Data output$parametric_changepoint_table_selected <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (length(rownames(parametric_seriesToChangePoint$table))==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (parametric_seriesToChangePoint$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(parametric_seriesToChangePoint$table)!=0){ if (length(yuimaGUItable$series)==0) parametric_seriesToChangePoint$table <<- data.frame() else parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[which(as.character(parametric_seriesToChangePoint$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$parametric_changepoint_button_delete, priority = 1,{ if (!is.null(input$parametric_changepoint_table_selected_rows_selected)) parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[-input$parametric_changepoint_table_selected_rows_selected,] }) ###DeleteAll Button observeEvent(input$parametric_changepoint_button_deleteAll, priority = 1,{ if (!is.null(input$parametric_changepoint_table_selected_rows_all)) parametric_seriesToChangePoint$table <<- parametric_seriesToChangePoint$table[-input$parametric_changepoint_table_selected_rows_all,] }) output$parametric_changepoint_model <- renderUI({ choices <- as.vector(defaultModels[names(defaultModels)=="Diffusion process"]) sel <- choices[1] for(i in names(yuimaGUIdata$usr_model)) if (yuimaGUIdata$usr_model[[i]]$class=="Diffusion process") choices <- c(i, choices) selectInput("parametric_changepoint_model", label = "Model", choices = choices, multiple = FALSE, selected = sel) }) ###Interactive range of selectRange chart parametric_range_selectRange <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$parametric_selectRange_brush) & !is.null(input$parametric_plotsRangeSeries)){ data <- getData(input$parametric_plotsRangeSeries) test <- (length(index(window(data, start = input$parametric_selectRange_brush$xmin, end = input$parametric_selectRange_brush$xmax))) > 3) if (test==TRUE){ parametric_range_selectRange$x <- c(as.Date(input$parametric_selectRange_brush$xmin), as.Date(input$parametric_selectRange_brush$xmax)) parametric_range_selectRange$y <- c(input$parametric_selectRange_brush$ymin, input$parametric_selectRange_brush$ymax) } } }) observe({ shinyjs::toggle(id="parametric_plotsRangeErrorMessage", condition = nrow(parametric_seriesToChangePoint$table)==0) shinyjs::toggle(id="parametric_plotsRangeAll", condition = nrow(parametric_seriesToChangePoint$table)!=0) }) ###Display charts: series and its increments observe({ symb <- input$parametric_plotsRangeSeries if(!is.null(symb)) if (symb %in% rownames(yuimaGUItable$series)){ data <- getData(symb) incr <- na.omit(Delt(data, type = "arithmetic")) condition <- all(is.finite(incr)) shinyjs::toggle("parametric_selectRangeReturns", condition = condition) parametric_range_selectRange$x <- NULL parametric_range_selectRange$y <- NULL start <- as.character(parametric_seriesToChangePoint$table[input$parametric_plotsRangeSeries,"From"]) end <- as.character(parametric_seriesToChangePoint$table[input$parametric_plotsRangeSeries,"To"]) if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } output$parametric_selectRange <- renderPlot({ if ((symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(parametric_seriesToChangePoint$table)))){ par(bg="black") plot.zoo(window(data, start = parametric_range_selectRange$x[1], end = parametric_range_selectRange$x[2]), main=symb, xlab="Index", ylab=NA, log=switch(input$parametric_scale_selectRange,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(data, start = start, end = end), col = "green") grid(col="grey") } }) output$parametric_selectRangeReturns <- renderPlot({ if (symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(parametric_seriesToChangePoint$table)) & condition){ par(bg="black") plot.zoo( window(incr, start = parametric_range_selectRange$x[1], end = parametric_range_selectRange$x[2]), main=paste(symb, " - Percentage Increments"), xlab="Index", ylab=NA, log=switch(input$parametric_scale_selectRange,"Linear"="","Logarithmic (Y)"="", "Logarithmic (X)"="x", "Logarithmic (XY)"="x"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(incr, start = start, end = end), col = "green") grid(col="grey") } }) } }) output$parametric_plotsRangeSeries <- renderUI({ selectInput("parametric_plotsRangeSeries", label = "Series", choices = rownames(parametric_seriesToChangePoint$table), selected = input$parametric_plotsRangeSeries) }) ###Choose Range input set to "Select range from charts" if charts have been brushed output$parametric_chooseRange <- renderUI({ sel <- "full" if (!is.null(parametric_range_selectRange$x)) sel <- "selected" selectInput("parametric_chooseRange", label = "Range", choices = c("Full Range" = "full", "Select Range from Charts" = "selected", "Specify Range" = "specify"), selected = sel) }) output$parametric_chooseRange_specify <- renderUI({ if(!is.null(input$parametric_plotsRangeSeries)) { data <- getData(input$parametric_plotsRangeSeries) if(class(index(data))=="numeric") return(div( column(6,numericInput("parametric_chooseRange_specify_t0", label = "From", min = start(data), max = end(data), value = start(data))), column(6,numericInput("parametric_chooseRange_specify_t1", label = "To", min = start(data), max = end(data), value = end(data))) )) if(class(index(data))=="Date") return(dateRangeInput("parametric_chooseRange_specify_date", start = start(data), end = end(data), label = "Specify Range")) } }) observe({ shinyjs::toggle(id = "parametric_chooseRange_specify", condition = (input$parametric_chooseRange)=="specify") }) ###Function to update data range to use to estimate models updateRange_parametric_seriesToChangePoint <- function(symb, range = c("full","selected","specify"), type = c("Date", "numeric")){ for (i in symb){ data <- getData(i) if (range == "full"){ levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start(data))) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end(data))) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start(data)) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end(data)) } if (range == "selected"){ if(!is.null(parametric_range_selectRange$x) & class(index(data))==type){ start <- parametric_range_selectRange$x[1] end <- parametric_range_selectRange$x[2] if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } start <- max(start(data),start) end <- min(end(data), end) levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start)) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end)) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end) } } if (range == "specify"){ if(class(index(data))==type){ if(class(index(data))=="Date"){ start <- input$parametric_chooseRange_specify_date[1] end <- input$parametric_chooseRange_specify_date[2] } if(class(index(data))=="numeric"){ start <- input$parametric_chooseRange_specify_t0 end <- input$parametric_chooseRange_specify_t1 } start <- max(start(data),start) end <- min(end(data), end) levels(parametric_seriesToChangePoint$table[,"From"]) <- c(levels(parametric_seriesToChangePoint$table[,"From"]), as.character(start)) levels(parametric_seriesToChangePoint$table[,"To"]) <- c(levels(parametric_seriesToChangePoint$table[,"To"]), as.character(end)) parametric_seriesToChangePoint$table[i,"From"] <<- as.character(start) parametric_seriesToChangePoint$table[i,"To"] <<- as.character(end) } } } } ###Apply selected range by double click observeEvent(input$parametric_selectRange_dbclick, priority = 1, { updateRange_parametric_seriesToChangePoint(input$parametric_plotsRangeSeries, range = "selected", type = class(index(getData(input$parametric_plotsRangeSeries)))) }) ###Apply selected range observeEvent(input$parametric_buttonApplyRange, priority = 1, { updateRange_parametric_seriesToChangePoint(input$parametric_plotsRangeSeries, range = input$parametric_chooseRange, type = class(index(getData(input$parametric_plotsRangeSeries)))) }) ###ApplyAll selected range observeEvent(input$parametric_buttonApplyAllRange, priority = 1, { updateRange_parametric_seriesToChangePoint(rownames(parametric_seriesToChangePoint$table), range = input$parametric_chooseRange, type = class(index(getData(input$parametric_plotsRangeSeries)))) }) ### Estimation Settings parametric_modal_prev_buttonDelta <- 0 parametric_modal_prev_buttonAllDelta <- 0 observe({ for (symb in rownames(parametric_seriesToChangePoint$table)){ if (is.null(yuimaGUIsettings$delta[[symb]])) yuimaGUIsettings$delta[[symb]] <<- 0.01 if (is.null(yuimaGUIsettings$toLog[[symb]])) yuimaGUIsettings$toLog[[symb]] <<- FALSE data <- getData(symb) if (yuimaGUIsettings$toLog[[symb]]==TRUE) data <- log(data) for (modName in input$parametric_changepoint_model){ if (class(try(setModelByName(modName, jumps = NA, AR_C = NA, MA_C = NA)))!="try-error"){ if (is.null(yuimaGUIsettings$estimation[[modName]])) yuimaGUIsettings$estimation[[modName]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]])) yuimaGUIsettings$estimation[[modName]][[symb]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["start"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["start"]] <<- list() startMinMax <- defaultBounds(name = modName, jumps = NA, AR_C = NA, MA_C = NA, strict = FALSE, data = data, delta = yuimaGUIsettings$delta[[symb]]) upperLower <- defaultBounds(name = modName, jumps = NA, AR_C = NA, MA_C = NA, strict = TRUE, data = data, delta = yuimaGUIsettings$delta[[symb]]) if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]] <<- startMinMax$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]] <<- startMinMax$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]] <<- upperLower$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]]) | parametric_modal_prev_buttonDelta!=input$parametric_modal_button_applyDelta | parametric_modal_prev_buttonAllDelta!=input$parametric_modal_button_applyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]] <<- upperLower$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["method"]])){ yuimaGUIsettings$estimation[[modName]][[symb]][["method"]] <<- "L-BFGS-B" } if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]] <<- 1 if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]] <<- NA if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]] <<- FALSE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]] <<- TRUE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]] <<- NA } } } parametric_modal_prev_buttonDelta <<- input$advancedSettingsButtonApplyDelta parametric_modal_prev_buttonAllDelta <<- input$advancedSettingsButtonApplyAllDelta }) observe({ shinyjs::toggle(id="parametric_modal_body", condition = nrow(parametric_seriesToChangePoint$table)!=0) shinyjs::toggle(id="parametric_modal_errorMessage", condition = nrow(parametric_seriesToChangePoint$table)==0) }) output$parametric_modal_series <- renderUI({ if (nrow(parametric_seriesToChangePoint$table)!=0) selectInput(inputId = "parametric_modal_series", label = "Series", choices = rownames(parametric_seriesToChangePoint$table)) }) output$parametric_modal_delta <- renderUI({ if (!is.null(input$parametric_modal_series)) return (numericInput("parametric_modal_delta", label = paste("delta", input$parametric_modal_series), value = yuimaGUIsettings$delta[[input$parametric_modal_series]])) }) output$parametric_modal_toLog <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)){ choices <- FALSE if (all(getData(input$parametric_modal_series)>0)) choices <- c(FALSE, TRUE) return (selectInput("parametric_modal_toLog", label = "Convert to log", choices = choices, selected = yuimaGUIsettings$toLog[[input$parametric_modal_series]])) } }) output$parametric_modal_model <- renderUI({ if(!is.null(input$parametric_changepoint_model)) selectInput(inputId = "parametric_modal_model", label = "Model", choices = input$parametric_changepoint_model) }) output$parametric_modal_parameter <- renderUI({ if (!is.null(input$parametric_modal_model)){ mod <- setModelByName(input$parametric_modal_model, jumps = NA, AR_C = NA, MA_C = NA) par <- getAllParams(mod, 'Diffusion process') selectInput(inputId = "parametric_modal_parameter", label = "Parameter", choices = par) } }) output$parametric_modal_start <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) numericInput(inputId = "parametric_modal_start", label = "start", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["start"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_startMin <- renderUI({ input$parametric_modal_button_applyDelta input$parametric_modal_button_applyAllDelta if (!is.null(input$parametric_modal_start) & !is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (is.na(input$parametric_modal_start)) numericInput(inputId = "parametric_modal_startMin", label = "start: Min", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMin"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_startMax <- renderUI({ input$parametric_modal_button_applyDelta input$parametric_modal_button_applyAllDelta if (!is.null(input$parametric_modal_start) & !is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (is.na(input$parametric_modal_start)) numericInput(inputId = "parametric_modal_startMax", label = "start: Max", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMax"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_lower <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (input$parametric_modal_method=="L-BFGS-B" | input$parametric_modal_method=="Brent") numericInput("parametric_modal_lower", label = "lower", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["lower"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_upper <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_parameter)) if (input$parametric_modal_method=="L-BFGS-B" | input$parametric_modal_method=="Brent") numericInput("parametric_modal_upper", label = "upper", value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["upper"]][[input$parametric_modal_parameter]]) }) output$parametric_modal_method <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)) selectInput("parametric_modal_method", label = "method", choices = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", "Brent"), selected = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]]) }) output$parametric_modal_trials <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series) & !is.null(input$parametric_modal_method)) numericInput("parametric_modal_trials", label = "trials", min = 1, value = ifelse(input$parametric_modal_method=="SANN" & yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]]!="SANN",1,yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["trials"]])) }) output$parametric_modal_seed <- renderUI({ if (!is.null(input$parametric_modal_model) & !is.null(input$parametric_modal_series)) numericInput("parametric_modal_seed", label = "seed", min = 1, value = yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["seed"]]) }) observeEvent(input$parametric_modal_button_applyDelta, { yuimaGUIsettings$delta[[input$parametric_modal_series]] <<- input$parametric_modal_delta yuimaGUIsettings$toLog[[input$parametric_modal_series]] <<- input$parametric_modal_toLog }) observeEvent(input$parametric_modal_button_applyAllDelta, { for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$delta[[symb]] <<- input$parametric_modal_delta if (input$parametric_modal_toLog==FALSE) yuimaGUIsettings$toLog[[symb]] <<- input$parametric_modal_toLog else if (all(getData(symb)>0)) yuimaGUIsettings$toLog[[symb]] <<- input$parametric_modal_toLog } }) observeEvent(input$parametric_modal_button_applyModel,{ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["start"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_start yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMin"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMin yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["startMax"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMax yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["lower"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_lower yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["upper"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_upper }) observeEvent(input$parametric_modal_button_applyAllModel,{ for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["start"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_start yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["startMin"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMin yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["startMax"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_startMax yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["lower"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_lower yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["upper"]][[input$parametric_modal_parameter]] <<- input$parametric_modal_upper } }) observeEvent(input$parametric_modal_button_applyGeneral,{ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["method"]] <<- input$parametric_modal_method yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["trials"]] <<- input$parametric_modal_trials yuimaGUIsettings$estimation[[input$parametric_modal_model]][[input$parametric_modal_series]][["seed"]] <<- input$parametric_modal_seed }) observeEvent(input$parametric_modal_button_applyAllModelGeneral,{ for (symb in rownames(parametric_seriesToChangePoint$table)){ yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["method"]] <<- input$parametric_modal_method yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["trials"]] <<- input$parametric_modal_trials yuimaGUIsettings$estimation[[input$parametric_modal_model]][[symb]][["seed"]] <<- input$parametric_modal_seed } }) output$parametric_changepoint_symb <- renderUI({ n <- names(yuimaGUIdata$cpYuima) if(length(n)!=0) selectInput("parametric_changepoint_symb", "Symbol", choices = sort(n), selected = last(n)) }) ### Start Estimation observeEvent(input$parametric_changepoint_button_startEstimation, { if (length(rownames(parametric_seriesToChangePoint$table))!=0) closeAlert(session = session, alertId = "parametric_changepoint_alert_err") withProgress(message = 'Analyzing: ', value = 0, { errors <- c() for (symb in rownames(parametric_seriesToChangePoint$table)){ incProgress(1/length(rownames(parametric_seriesToChangePoint$table)), detail = symb) test <- try(addCPoint(modelName = input$parametric_changepoint_model, symb = symb, fracL = input$parametric_modal_rangeFraction[1]/100, fracR = input$parametric_modal_rangeFraction[2]/100, from = as.character(parametric_seriesToChangePoint$table[symb, "From"]), to = as.character(parametric_seriesToChangePoint$table[symb, "To"]), delta = yuimaGUIsettings$delta[[symb]], toLog = yuimaGUIsettings$toLog[[symb]], start = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["start"]], startMin = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["startMin"]], startMax = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["startMax"]], method = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["method"]], trials = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["trials"]], seed = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["seed"]], lower = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["lower"]], upper = yuimaGUIsettings$estimation[[input$parametric_changepoint_model]][[symb]][["upper"]])) if(class(test)=="try-error") errors <- c(errors, symb) } if (!is.null(errors)) createAlert(session = session, anchorId = "parametric_changepoint_alert", alertId = "parametric_changepoint_alert_err", style = "error", dismiss = TRUE, content = paste("Unable to estimate Change Point of:", paste(errors, collapse = " "))) }) }) parametric_range_changePoint <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$parametric_changePoint_brush) & !is.null(input$parametric_changepoint_symb)){ data <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$series test <- (length(index(window(data, start = input$parametric_changePoint_brush$xmin, end = input$parametric_changePoint_brush$xmax))) > 3) if (test==TRUE){ parametric_range_changePoint$x <- c(as.Date(input$parametric_changePoint_brush$xmin), as.Date(input$parametric_changePoint_brush$xmax)) parametric_range_changePoint$y <- c(input$parametric_changePoint_brush$ymin, input$parametric_changePoint_brush$ymax) } } }) observeEvent(input$parametric_changePoint_dbclick,{ parametric_range_changePoint$x <- c(NULL, NULL) }) observeEvent(input$parametric_changepoint_symb, { parametric_range_changePoint$x <- c(NULL, NULL) output$parametric_changepoint_plot_series <- renderPlot({ if(!is.null(input$parametric_changepoint_symb)) { cp <- isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]}) data <- cp$series toLog <- cp$info$toLog symb <- cp$info$symb par(bg="black") plot(window(data, start = parametric_range_changePoint$x[1], end = parametric_range_changePoint$x[2]), main=ifelse(toLog==TRUE, paste("log(",symb,")", sep = ""), symb), xlab="Index", ylab=NA, log=switch(input$parametric_changepoint_scale,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") abline(v=cp$tau, col = "red") grid(col="grey") } }) }) output$parametric_changepoint_info <- renderUI({ if(!is.null(input$parametric_changepoint_symb)){ info <- isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$info}) div( h3(info$model), withMathJax(printModelLatex(names = info$model, process = "Diffusion process")), br(), h4( em(paste("Change Point:", as.character(isolate({yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$tau})))) ), align="center" ) } }) output$parametric_changepoint_modal_info_text <- renderUI({ info <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]]$info div( h3(input$parametric_changepoint_symb, " - " , info$model, class = "hModal"), h4( em("series to log:"), info$toLog, br(), em("method:"), info$method, br(), em("trials:"), info$trials, br(), em("seed:"), info$seed, br(), class = "hModal" ), align="center") }) output$parametric_changepoint_modal_info_tableL <- renderTable(rownames = T, { cp <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] tL <- summary(cp$qmleL)@coef for (i in 1:nrow(tL)){ tL[i,"Estimate"] <- signifDigits(value = tL[i,"Estimate"], sd = tL[i,"Std. Error"]) tL[i,"Std. Error"] <- signifDigits(value = tL[i,"Std. Error"], sd = tL[i,"Std. Error"]) } return(tL) }) output$parametric_changepoint_modal_info_tableR <- renderTable(rownames = T, { cp <- yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] tR <- summary(cp$qmleR)@coef for (i in 1:nrow(tR)){ tR[i,"Estimate"] <- signifDigits(value = tR[i,"Estimate"], sd = tR[i,"Std. Error"]) tR[i,"Std. Error"] <- signifDigits(value = tR[i,"Std. Error"], sd = tR[i,"Std. Error"]) } return(tR) }) observeEvent(input$parametric_changepoint_button_delete_estimated, { yuimaGUIdata$cpYuima[[input$parametric_changepoint_symb]] <<- NULL }) observeEvent(input$parametric_changepoint_button_deleteAll_estimated, { yuimaGUIdata$cpYuima <<- list() })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/eda/changepoint_parametric.R
###Display available data output$cluster_table_select <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to cluster seriesToCluster <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$cluster_button_select, priority = 1, { if (length(input$cluster_table_select_rows_selected)!=0){ closeAlert(session, "cluster_alert_indexes") if (nrow(seriesToCluster$table)==0) seriesToCluster$table <<- rbind(seriesToCluster$table, yuimaGUItable$series[rownames(yuimaGUItable$series)[input$cluster_table_select_rows_selected[1]],]) for (symb in rownames(yuimaGUItable$series)[input$cluster_table_select_rows_selected]){ if (class(index(yuimaGUIdata$series[[symb]]))==class(index(yuimaGUIdata$series[[rownames(seriesToCluster$table)[1]]]))){ if (!(symb %in% rownames(seriesToCluster$table))) seriesToCluster$table <<- rbind(seriesToCluster$table, yuimaGUItable$series[symb,]) } else { createAlert(session, anchorId = "cluster_alert", alertId = "cluster_alert_indexes", append = FALSE, content = "Cannot cluster series with different type of index (numeric/date)", style = "warning") } } } }) ###SelectAll Button observeEvent(input$cluster_button_selectAll, priority = 1, { if (length(input$cluster_table_select_rows_all)!=0){ closeAlert(session, "cluster_alert_indexes") if (nrow(seriesToCluster$table)==0) seriesToCluster$table <<- rbind(seriesToCluster$table, yuimaGUItable$series[rownames(yuimaGUItable$series)[input$cluster_table_select_rows_all[1]],]) for (symb in rownames(yuimaGUItable$series)[input$cluster_table_select_rows_all]){ if (class(index(yuimaGUIdata$series[[symb]]))==class(index(yuimaGUIdata$series[[rownames(seriesToCluster$table)[1]]]))){ if (!(symb %in% rownames(seriesToCluster$table))) seriesToCluster$table <<- rbind(seriesToCluster$table, yuimaGUItable$series[symb,]) } else { createAlert(session, anchorId = "cluster_alert", alertId = "cluster_alert_indexes", append = FALSE, content = "Cannot cluster series with different type of index (numeric/date)", style = "warning") } } } }) ###Display Selected Data output$cluster_table_selected <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (length(rownames(seriesToCluster$table))==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (seriesToCluster$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(seriesToCluster$table)!=0){ if (length(yuimaGUItable$series)==0) seriesToCluster$table <<- data.frame() else seriesToCluster$table <<- seriesToCluster$table[which(as.character(seriesToCluster$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$cluster_button_delete, priority = 1,{ if (!is.null(input$cluster_table_selected_rows_selected)) seriesToCluster$table <<- seriesToCluster$table[-input$cluster_table_selected_rows_selected,] }) ###DeleteAll Button observeEvent(input$cluster_button_deleteAll, priority = 1,{ if (!is.null(input$cluster_table_selected_rows_all)) seriesToCluster$table <<- seriesToCluster$table[-input$cluster_table_selected_rows_all,] }) observe({ shinyjs::toggle("cluster_distance_minkowskiPower", condition = (input$cluster_distance=="minkowski")) }) observeEvent(input$cluster_button_startCluster, { closeAlert(session, "cluster_alert_dist") if (length(rownames(seriesToCluster$table))<=2) createAlert(session, anchorId = "cluster_alert", alertId = "cluster_alert_dist", content = "Select at least 3 series", style = "error") if (length(rownames(seriesToCluster$table))>2){ withProgress(value = 1, message = "Calculating...", { names_list <- rownames(seriesToCluster$table) x <- yuimaGUIdata$series[[names_list[1]]] for(i in names_list[-1]) x <- merge(x, yuimaGUIdata$series[[i]]) colnames(x) <- names_list d <- switch( input$cluster_distance, "MOdist" = try(sde::MOdist(na.omit(x))), "MYdist_perc" = try(MYdist(x, percentage = TRUE)), "MYdist_ass" = try(MYdist(x, percentage = FALSE)), "euclidean" = try(dist(t(as.data.frame(x)), method = "euclidean")), "maximum" = try(dist(t(as.data.frame(x)), method = "maximum")), "manhattan" = try(dist(t(as.data.frame(x)), method = "manhattan")), "canberra" = try(dist(t(as.data.frame(x)), method = "canberra")), "minkowski" = try(dist(t(as.data.frame(x)), method = "minkowski", p = input$cluster_distance_minkowskiPower)) ) if (class(d)=="try-error") createAlert(session, anchorId = "cluster_alert", alertId = "cluster_alert_dist", content = "Error in clustering", style = "error") else{ hc <- hclust(d, method = input$cluster_linkage) i <- 1 id <- "Clustering" repeat { if(id %in% names(yuimaGUIdata$cluster)){ id <- paste("Clustering", i) i <- i+1 } else break } yuimaGUIdata$cluster[[id]] <<- list(d = d, linkage = input$cluster_linkage, distance = input$cluster_distance, power = input$cluster_distance_minkowskiPower) } })} }) output$cluster_analysis_id <- renderUI({ n <- names(yuimaGUIdata$cluster) if(length(n)!=0) selectInput("cluster_analysis_id", label = "Clustering ID", choices = sort(n), selected = last(n)) }) observeEvent(input$cluster_analysis_id, { if(!is.null(input$cluster_analysis_id)) if (input$cluster_analysis_id %in% names(yuimaGUIdata$cluster)){ d <- yuimaGUIdata$cluster[[input$cluster_analysis_id]]$d hc <- hclust(d, method = yuimaGUIdata$cluster[[input$cluster_analysis_id]]$linkage) labelColors <- c("#CDB380", "#FF0000", "#036564", "#FF00FF", "#EB6841", "#7FFFD4", "#EDC951","#FF8000", "#FFE4E1", "#A2CD5A", "#71C671", "#AAAAAA", "#555555", "#FFA07A", "#8B6508", "#FFC125", "#FFFACD", "#808000", "#458B00", "#54FF9F", "#43CD80", "#008B8B", "#53868B", "#B0E2FF", "#0000FF", "#F8F8FF", "#551A8B", "#AB82FF", "#BF3EFF", "#FF83FA", "#8B1C62", "#CD6839", "#8E8E38", "#1E1E1E") dendrClick <- reactiveValues(y = NULL) output$cluster_dendogram <- renderPlot({ if(!is.null(input$cluster_dendrogram_click$y)) dendrClick$y <- input$cluster_dendrogram_click$y if(!is.null(dendrClick$y)){ clusMember = cutree(hc, h = dendrClick$y) colLab <- function(n) { if (is.leaf(n)) { a <- attributes(n) labCol <- labelColors[clusMember[which(names(clusMember) == a$label)]] attr(n, "nodePar") <- c(a$nodePar, lab.col = labCol) } n } hc <- dendrapply(as.dendrogram(hc), colLab) } if(is.null(dendrClick$y)){ colDefault <- function(n){ if (is.leaf(n)) attr(n, "nodePar") <- c(attributes(n)$nodePar, lab.col = labelColors[1]) return(n) } hc <- dendrapply(as.dendrogram(hc), colDefault) } output$cluster_button_saveDendogram <- downloadHandler( filename = "Dendrogram.png", content = function(file) { png(file, width = 960) par(bg="black", xaxt = "n", mar= c(10, 4, 4, 2)+0.1) plot(hc, ylab = "", xlab = "", main = "Dendrogram", edgePar=list(col="grey50"), col.main = "#FFF68F", col.axis="grey") dev.off() } ) par(bg="black", xaxt = "n", mar= c(10, 4, 4, 2)+0.1) plot(hc, ylab = "", xlab = "", main = "Dendrogram", edgePar=list(col="grey50"), col.main = "#FFF68F", col.axis="grey") }) output$cluster_scaling2D <- renderPlot({ points <- cmdscale(d) if(!is.null(dendrClick$y)) g1 <- cutree(hclust(d), h = dendrClick$y) else g1 <- 1 output$cluster_button_saveScaling2D <- downloadHandler( filename = "Multidimensional scaling.png", content = function(file) { png(file) par(bg="black", xaxt = "n", yaxt = "n", bty="n") plot(points, col=labelColors[g1], pch=16, cex=2, main = "Multidimensional scaling", col.main = "#FFF68F", xlab="", ylab="") dev.off() } ) par(bg="black", xaxt = "n", yaxt = "n", bty="n") plot(points, col=labelColors[g1], pch=16, cex=2, main = "Multidimensional scaling", col.main = "#FFF68F", xlab="", ylab="") }) } }) output$cluster_moreInfo <- renderUI({ if(!is.null(input$cluster_analysis_id)) if (input$cluster_analysis_id %in% names(isolate({yuimaGUIdata$cluster}))){ info <- isolate({yuimaGUIdata$cluster[[input$cluster_analysis_id]]}) dist <- switch(info$distance, "MOdist"="Markov Operator", "MYdist_perc"="Percentage Increments Distribution", "MYdist_ass"="Increments Distribution", "euclidean"="Euclidean", "maximum"="Maximum", "manhattan"="Manhattan", "canberra"="Canberra", "minkowski"="Minkowski") linkage <- switch(info$linkage, "complete"="Complete", "single"="Single", "average"="Average", "ward.D"="Ward", "ward.D2"="Ward squared", "mcquitty"="McQuitty", "Median"="median", "centroid"="Centroid") if (dist=="Minkowski") dist <- paste(dist, " (", info$power,")", sep = "") return(HTML(paste("<div><h4>&nbsp &nbsp Linkage:",linkage, " &nbsp &nbsp &nbsp &nbsp Distance:", dist, "</h4></div>"))) } }) observeEvent(input$cluster_button_delete_analysis, { yuimaGUIdata$cluster[[input$cluster_analysis_id]] <<- NULL }) observeEvent(input$cluster_button_deleteAll_analysis, { yuimaGUIdata$cluster <<- list() }) observe({ shinyjs::toggle("cluster_charts", condition = length(names(yuimaGUIdata$cluster))!=0) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/eda/clustering.R
###Display available data output$llag_table_select <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to change point seriesToLeadLag <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$llag_button_select, priority = 1, { if (length(input$llag_table_select_rows_selected)!=0){ closeAlert(session, "llag_alert_select") if (nrow(seriesToLeadLag$table)==0) seriesToLeadLag$table <<- rbind(seriesToLeadLag$table, yuimaGUItable$series[rownames(yuimaGUItable$series)[input$llag_table_select_rows_selected[1]],]) for (symb in rownames(yuimaGUItable$series)[input$llag_table_select_rows_selected]){ if (class(index(yuimaGUIdata$series[[symb]]))==class(index(yuimaGUIdata$series[[rownames(seriesToLeadLag$table)[1]]]))){ if (!(symb %in% rownames(seriesToLeadLag$table))) seriesToLeadLag$table <<- rbind(seriesToLeadLag$table, yuimaGUItable$series[symb,]) } else { createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", append = FALSE, content = "Cannot analyze Lead-Lag for series with different type of index (numeric/date)", style = "warning") } } } }) ###SelectAll Button observeEvent(input$llag_button_selectAll, priority = 1, { if (length(input$llag_table_select_rows_all)!=0){ closeAlert(session, "llag_alert_select") if (nrow(seriesToLeadLag$table)==0) seriesToLeadLag$table <<- rbind(seriesToLeadLag$table, yuimaGUItable$series[rownames(yuimaGUItable$series)[input$llag_table_select_rows_all[1]],]) for (symb in rownames(yuimaGUItable$series)[input$llag_table_select_rows_all]){ if (class(index(yuimaGUIdata$series[[symb]]))==class(index(yuimaGUIdata$series[[rownames(seriesToLeadLag$table)[1]]]))){ if (!(symb %in% rownames(seriesToLeadLag$table))) seriesToLeadLag$table <<- rbind(seriesToLeadLag$table, yuimaGUItable$series[symb,]) } else { createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", append = FALSE, content = "Cannot analyze Lead-Lag for series with different type of index (numeric/date)", style = "warning") } } } }) ###Display Selected Data output$llag_table_selected <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (length(rownames(seriesToLeadLag$table))==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (seriesToLeadLag$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(seriesToLeadLag$table)!=0){ if (length(yuimaGUItable$series)==0) seriesToLeadLag$table <<- data.frame() else seriesToLeadLag$table <<- seriesToLeadLag$table[which(as.character(seriesToLeadLag$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$llag_button_delete, priority = 1,{ if (!is.null(input$llag_table_selected_rows_selected)) seriesToLeadLag$table <<- seriesToLeadLag$table[-input$llag_table_selected_rows_selected,] }) ###DeleteAll Button observeEvent(input$llag_button_deleteAll, priority = 1,{ if (!is.null(input$llag_table_selected_rows_all)) seriesToLeadLag$table <<- seriesToLeadLag$table[-input$llag_table_selected_rows_all,] }) observe({ if (length(rownames(seriesToLeadLag$table))!=0){ type <- try(class(index(yuimaGUIdata$series[[rownames(seriesToLeadLag$table)[1]]])[1])) if(type!="try-error"){ shinyjs::toggle(id = "llag_range_date", condition = type=="Date") shinyjs::toggle(id = "llag_range_numeric", condition = type!="Date") } } else { shinyjs::show(id = "llag_range_date") shinyjs::hide(id = "llag_range_numeric") } }) observe({ shinyjs::toggle("llag_maxLag", condition = input$llag_type=="llag") shinyjs::toggle("llag_corr_method", condition = input$llag_type=="corr") }) observeEvent(input$llag_button_startEstimation, { closeAlert(session, alertId = "llag_alert_select") if (is.na(input$llag_maxLag) | input$llag_maxLag <= 0) createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", content = "Lag max must be greater than zero", style = "warning") else { series <- rownames(seriesToLeadLag$table) if (length(series)<=1) createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", content = "Select at least two series", style = "warning") else { withProgress(message = "Calculating...", value = 1, { data <- yuimaGUIdata$series[[series[1]]] type <- class(index(data)[1]) for (i in 2:length(series)) data <- merge(data, yuimaGUIdata$series[[series[i]]]) colnames(data) <- series if(type=="Date") { start <- input$llag_range_date[1] end <- input$llag_range_date[2] } else { start <- input$llag_range_numeric1 end <- input$llag_range_numeric2 } data <- window(data, start = start, end = end) if(is.regular(data)){ delta <- mode(na.omit(diff(index(data)))) yuimaData <- setDataGUI(data, delta = delta) if(input$llag_type=="llag"){ res <- try(llag(yuimaData, ci=TRUE, plot=FALSE, grid = seq(from = -input$llag_maxLag, to = input$llag_maxLag, by = delta))) if (class(res)=="try-error") createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", content = "Error in computing lead-lag", style = "error") else { i <- 1 id <- "Lead-Lag Analysis" repeat { if(id %in% names(yuimaGUIdata$llag)){ id <- paste("Lead-Lag Analysis", i) i <- i+1 } else break } yuimaGUIdata$llag[[id]] <<- list(type = "llag", maxLag = input$llag_maxLag, delta = delta, llag = res$lagcce, cor = res$cormat, p.values = res$p.values, start = start, end = end) } } if(input$llag_type=="corr"){ if(input$llag_corr_method %in% c("pearson", "kendall", "spearman")){ x <- as.matrix([email protected]) res <- try(cor(x, method = input$llag_corr_method, use = "pairwise.complete.obs")) } else res <- try(cce(x = yuimaData, method = input$llag_corr_method)$cormat) if (class(res)=="try-error") createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", content = "Error in computing the correlation matrix", style = "error") else { i <- 1 id <- "Correlation Analysis" repeat { if(id %in% names(yuimaGUIdata$llag)){ id <- paste("Correlation Analysis", i) i <- i+1 } else break } yuimaGUIdata$llag[[id]] <<- list(type = "corr", cormat = res, method = input$llag_corr_method, start = start, end = end) } } } else{ createAlert(session, anchorId = "llag_alert", alertId = "llag_alert_select", content = "Cannot analyze non-regular grid of observations", style = "error") } }) } } }) observe({ shinyjs::toggle("llag_plot_body", condition = length(names(yuimaGUIdata$llag))!=0) }) output$llag_analysis_id <- renderUI({ n <- names(yuimaGUIdata$llag) if(length(n)!=0) selectInput("llag_analysis_id", label = "Analysis ID", choices = sort(n), selected = last(n)) }) output$llag_plot_corr_method <- renderUI({ if(!is.null(input$llag_analysis_id)) if (input$llag_analysis_id %in% names(isolate({yuimaGUIdata$llag}))){ info <- isolate({yuimaGUIdata$llag})[[input$llag_analysis_id]] if (info$type=="corr"){ method <- switch(info$method, "HY"="Hayashi-Yoshida", "PHY"="Pre-averaged Hayashi-Yoshida", "MRC"="Modulated Realized Covariance", "TSCV"="Two Scales realized CoVariance", "GME"="Generalized Multiscale Estimator", "RK"="Realized Kernel", "QMLE"="Quasi Maximum Likelihood Estimator", "SIML"="Separating Information Maximum Likelihood", "THY"="Truncated Hayashi-Yoshida", "PTHY"="Pre-averaged Truncated Hayashi-Yoshida", "SRC"="Subsampled Realized Covariance", "SBPC"="Subsampled realized BiPower Covariation") return(HTML(paste("<div><h4>&nbsp &nbsp Method:", method, "</h4></div>"))) } } }) observe({ if(!is.null(input$llag_analysis_id)) if (input$llag_analysis_id %in% isolate({names(yuimaGUIdata$llag)})) { type <- isolate({yuimaGUIdata$llag})[[input$llag_analysis_id]]$type shinyjs::toggle("llag_plot_confidence", condition = type=="llag") shinyjs::toggle("llag_plot_corr_method", condition = type=="corr") shinyjs::toggle("llag_plot_howToRead", condition = type=="llag") } }) output$llag_plot <- renderPlot({ if(!is.null(input$llag_analysis_id) & !is.null(input$llag_plot_confidence)) if (input$llag_analysis_id %in% isolate({names(yuimaGUIdata$llag)})) { info <- isolate({yuimaGUIdata$llag[[input$llag_analysis_id]]}) if(info$type=="llag"){ co <- ifelse(info$p.values > input$llag_plot_confidence | is.na(info$p.values), 0, info$llag) co <- melt(t(co)) co$label <- paste( round(co$value, 1+as.integer(abs(log10(info$delta)))), '\n', '(', apply(co, MARGIN = 1, function(x) {round(info$cor[x[1], x[2]], 2)}), ')', sep = '') } if(info$type=="corr"){ co <- info$cormat co <- melt(t(co)) co$label <- round(co$value, 2) } fillColor <- switch(getOption("yuimaGUItheme"), "black"="#282828", "white"="#f0f4f5") textColor <- switch(getOption("yuimaGUItheme"), "black"="#CDCECD", "white"="black") ggplot(co, aes(Var1, Var2)) + # x and y axes => Var1 and Var2 geom_tile(aes(fill = value)) + # background colours are mapped according to the value column geom_text(aes(label = co$label)) + # write the values scale_fill_gradient2(low = "#ffa500", mid = switch(getOption("yuimaGUItheme"), "black"="gray30", "white"="#C7E2DF"), high = "#74d600", midpoint = 0) + # determine the colour theme(panel.grid.major.x=element_blank(), #no gridlines panel.grid.minor.x=element_blank(), panel.grid.major.y=element_blank(), panel.grid.minor.y=element_blank(), panel.background=element_rect(fill=fillColor), # background=white plot.background = element_rect(fill = fillColor, linetype = 0, color = fillColor), axis.text.x = element_text(angle=90,hjust = 1, size = 12,face = "bold", colour = textColor), plot.title = element_text(size=20,face="bold", colour = textColor, hjust = 0.5), axis.text.y = element_text(size = 12,face = "bold", colour = textColor)) + ggtitle(paste("Analyzed data from", info$start, "to", info$end)) + theme(legend.title=element_text(face="bold", size=14)) + scale_x_discrete(name="") + scale_y_discrete(name="") + labs(fill="") } }) observeEvent(input$llag_delete_analysis, { yuimaGUIdata$llag[[input$llag_analysis_id]] <<- NULL }) observeEvent(input$llag_deleteAll_analysis, { yuimaGUIdata$llag <<- list() })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/eda/llag_and_corr.R
hedging_databaseModels_table <- data.frame() output$hedging_databaseModels <- DT::renderDataTable(options=list(scrollY = 200, scrollX = TRUE, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$model)==0){ NoData <- data.frame("Symb"=NA,"Please estimate some models first"=NA, check.names = FALSE) return(NoData[-1,]) } date_indexed <- c() for (row in rownames(yuimaGUItable$model)){ id <- unlist(strsplit(row, split = " ")) if (class(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date") date_indexed <- c(date_indexed,row) } hedging_databaseModels_table <<- yuimaGUItable$model[rownames(yuimaGUItable$model) %in% date_indexed,] return (hedging_databaseModels_table) }) output$hedging_assMarketPrice <- renderUI({ if (is.null(input$hedging_databaseModels_rows_selected)) numericInput("hedging_assMarketPrice", label="Asset Market Price:", value=NA, min = 0) else { if(input$hedging_databaseModels_row_last_clicked %in% input$hedging_databaseModels_rows_selected){ id <- unlist(strsplit(rownames(hedging_databaseModels_table)[input$hedging_databaseModels_row_last_clicked], split = " ")) numericInput("hedging_assMarketPrice", label="Asset Market Price:", value=as.numeric(tail(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected],1)), min = 0) } else numericInput("hedging_assMarketPrice", label="Asset Market Price:", value=NA, min = 0) } }) output$hedging_strike <- renderUI({ if (is.null(input$hedging_databaseModels_rows_selected)) numericInput("hedging_strike", label="Strike Price:", value=0, min = 0, max = NA, step = NA, width = NULL) else { if(input$hedging_databaseModels_row_last_clicked %in% input$hedging_databaseModels_rows_selected){ id <- unlist(strsplit(rownames(hedging_databaseModels_table)[input$hedging_databaseModels_row_last_clicked], split = " ")) numericInput("hedging_strike", label="Strike Price:", value=as.numeric(tail(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected],1)), min = 0, max = NA, step = NA, width = NULL) } else numericInput("hedging_assMarketPrice", label="Asset Market Price:", value=NA, min = 0) } }) observeEvent(input$hedging_button_startComputation, { closeAlert(session, "hedging_alert_selectRow") if (is.na(input$hedging_optMarketPrice)){ createAlert(session, anchorId = "hedging_alert", alertId = "hedging_alert_selectRow", content = "Option market price is missing", style = "error") return() } if (input$hedging_optMarketPrice<=0){ createAlert(session, anchorId = "hedging_alert", alertId = "hedging_alert_selectRow", content = "Option market price must be positive", style = "error") return() } if (!is.null(input$hedging_databaseModels_rows_selected) & !is.null(input$hedging_databaseModels_row_last_clicked)){ if(input$hedging_databaseModels_row_last_clicked %in% input$hedging_databaseModels_rows_selected){ modID <- rownames(hedging_databaseModels_table)[input$hedging_databaseModels_row_last_clicked] id <- unlist(strsplit(modID, split = " ")) info = list( "maturity"= input$hedging_maturity, "strike"=input$hedging_strike, "type"=input$hedging_type, "optPrice"=input$hedging_optMarketPrice, "optLotMult"=input$hedging_lotMult, "optLotCost"= ifelse(is.na(input$hedging_lotCostOpt), 0, input$hedging_lotCostOpt), "assPrice"=input$hedging_assMarketPrice, "assPercCost"= ifelse(is.na(input$hedging_percCostAss), 0, input$hedging_percCostAss/100), "assMinCost"= ifelse(is.na(input$hedging_minCostAss), 0, input$hedging_minCostAss), "assRateShortSelling"= ifelse(is.na(input$hedging_rateShort), 0, input$hedging_rateShort/100)) addHedging( symbName = id[1], modelYuimaGUI = yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]], info = info, xinit = input$hedging_assMarketPrice, nsim = input$hedging_nSim, nstep = NA, simulate.from = end(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]), simulate.to = input$hedging_maturity, session = session, anchorId = "hedging_alert" ) updateTabsetPanel(session = session, inputId = "panel_hedging", selected = "Profit&Loss") } else createAlert(session, anchorId = "hedging_alert", alertId = "hedging_alert_selectRow" , content = "Please select a model to simulate the evolution of the underlying asset", style = "error") } else createAlert(session, anchorId = "hedging_alert", alertId = "hedging_alert_selectRow", content = "Please select a model to simulate the evolution of the underlying asset", style = "error") }) output$hedging_table_results <- DT::renderDataTable(options=list(scrollX=TRUE, scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$hedging)==0){ NoData <- data.frame("Symb"=NA, "Here will be stored simulations you run in the previous tab"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$hedging) }) hedging_values <- reactiveValues(profits=NULL, symb=NULL, model=NULL, return = NA) hedging_values2 <- reactiveValues(number_of_ids = 0) na_zero <- function(x){ifelse(is.na(x), 0, x)} observe({ hedging_values2$number_of_ids <<- length(yuimaGUIdata$hedging) shinyjs::toggle(id = "hedging_button_show", condition = hedging_values2$number_of_ids>0) }) output$hedging_modal_id <- renderUI({ if(hedging_values2$number_of_ids>0) selectInput("hedging_modal_id", label = "ID", choices = seq(1, hedging_values2$number_of_ids)) }) output$hedging_modal_id_hidden <- renderUI({ selectInput("hedging_modal_id_hidden", label = "ID", choices = input$hedging_modal_id, selected = input$hedging_modal_id) }) output$hedging_nAss_hedge <- renderUI({ if (!is.null(input$hedging_modal_id)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ info <- yuimaGUIdata$hedging[[id]]$info val <- switch (info$type, "call" = info$sell, "put" = info$buy) lab <- paste("Number of Assets to", ifelse(info$type=="call", "Sell", "Buy")) numericInput("hedging_nAss_hedge", label = lab, min = 0, value = val, step = 1) } } }) output$hedging_nOptLot_hedge <- renderUI({ if (!is.null(input$hedging_modal_id)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ info <- yuimaGUIdata$hedging[[id]]$info nOpt <- info$LotsToBuy numericInput("hedging_nOptLot_hedge", label = "Option - number of Lots", min = 0, value = nOpt, step = 1) } } }) output$hedging_type2 <- renderUI({ if (!is.null(input$hedging_modal_id)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ type <- yuimaGUIdata$hedging[[id]]$info$type selectInput("hedging_type2", width = "75%", label="Modify Type", c(Call="call", Put="put"), selected = type) } } }) output$hedging_strike2 <- renderUI({ if (!is.null(input$hedging_modal_id)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ strike <- yuimaGUIdata$hedging[[id]]$info$strike numericInput("hedging_strike2", width = "75%", label = "Modify Strike", min = 0, value = strike) } } }) output$hedging_optMarketPrice2 <- renderUI({ if (!is.null(input$hedging_modal_id)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ optPrice <- yuimaGUIdata$hedging[[id]]$info$optPrice numericInput("hedging_optMarketPrice2", width = "75%", label = "Modify Market Price", min = 0, value = optPrice) } } }) observe({ id <- input$hedging_modal_id_hidden if (!is.null(id) & !is.null(input$hedging_strike2) & !is.null(input$hedging_nAss_hedge)){ id <- as.integer(id) if(hedging_values2$number_of_ids>=id){ info <- yuimaGUIdata$hedging[[id]]$info profits <- profit_distribution(nOpt= na_zero(input$hedging_nOptLot_hedge)*info$optLotMult, nAss= na_zero(input$hedging_nAss_hedge), type=input$hedging_type2, strike=ifelse(is.na(input$hedging_strike2), info$strike, input$hedging_strike2), priceAtMaturity=yuimaGUIdata$hedging[[id]]$hist, optMarketPrice=ifelse(is.na(input$hedging_optMarketPrice2), info$optPrice, input$hedging_optMarketPrice2), assMarketPrice=info$assPrice, percCostAss=na_zero(input$hedging_percCostAss)/100, minCostAss=na_zero(input$hedging_minCostAss), lotCostOpt=na_zero(input$hedging_lotCostOpt), lotMultiplier=info$optLotMult, shortCostPerYear=na_zero(input$hedging_rateShort)/100, t0=info$today, maturity=info$maturity) hedging_values$profits <- profits hedging_values$symb <- yuimaGUIdata$hedging[[id]]$symb hedging_values$model <- yuimaGUIdata$hedging[[id]]$model$info$modName } } }) output$hedging_plot_distribution <- renderPlot({ par(bg="black") if (!is.null(hedging_values$profits) & !is.null(hedging_values$model) & !is.null(hedging_values$symb)) hist(hedging_values$profits, main = paste(hedging_values$symb,"-",hedging_values$model), xlab = "Profit & Loss", breaks = input$hedging_slider_nBin, col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black", right = FALSE) grid() }) output$hedging_quantiles_text <- renderUI({ if(!is.null(input$hedging_slider_rangeHist) & !is.null(hedging_values$profits)){ val <- hedging_values$profits qq <- quantile(val, probs = input$hedging_slider_rangeHist/100) HTML(paste("<div>", "Lower:", round(qq[1],0),"<br/>", "Upper: ", round(qq[2],0), "<br/>", "Mean: ", round(mean(val[val>=qq[1] & val<=qq[2]]),0), "</div>")) } }) output$hedging_capital_text <- renderUI({ if (!is.null(input$hedging_modal_id) & !is.null(hedging_values$profits)){ id <- as.integer(input$hedging_modal_id) if (hedging_values2$number_of_ids>=id){ info <- isolate({yuimaGUIdata$hedging[[id]]$info}) optPrice <- ifelse(is.na(input$hedging_optMarketPrice2), info$optPrice, input$hedging_optMarketPrice2) percCostAss <- na_zero(input$hedging_percCostAss)/100 minCostAss <- na_zero(input$hedging_minCostAss) lotCostOpt <- na_zero(input$hedging_lotCostOpt) nOptLot <- na_zero(input$hedging_nOptLot_hedge) nAss <- na_zero(input$hedging_nAss_hedge) cap <- nOptLot*(info$optLotMult*optPrice+lotCostOpt)+nAss*info$assPrice + ifelse(nAss>0,max(nAss*info$assPrice*percCostAss,minCostAss),0) val <- hedging_values$profits ret <- mean(val)/cap hedging_values$return <- ret HTML(paste("Invested Capital: ", round(cap,0), "<br/>", "Average Return: ", round(ret*100,2), "%")) } } }) observeEvent(input$hedging_button_saveHedging, { id <- as.integer(input$hedging_modal_id) yuimaGUIdata$hedging[[id]]$info$assPercCost <<- ifelse(is.na(input$hedging_percCostAss), 0, input$hedging_percCostAss/100) yuimaGUIdata$hedging[[id]]$info$assMinCost <<- ifelse(is.na(input$hedging_minCostAss), 0, input$hedging_minCostAss) yuimaGUIdata$hedging[[id]]$info$assRateShortSelling <<- ifelse(is.na(input$hedging_rateShort), 0, input$hedging_rateShort/100) yuimaGUIdata$hedging[[id]]$info$optLotCost <<- ifelse(is.na(input$hedging_lotCostOpt), 0, input$hedging_lotCostOpt) yuimaGUIdata$hedging[[id]]$info$type <<- input$hedging_type2 if (yuimaGUIdata$hedging[[id]]$info$type=="put"){ yuimaGUIdata$hedging[[id]]$info$buy <<- na_zero(input$hedging_nAss_hedge) yuimaGUIdata$hedging[[id]]$info$sell <<- NA } if (yuimaGUIdata$hedging[[id]]$info$type=="call"){ yuimaGUIdata$hedging[[id]]$info$sell <<- na_zero(input$hedging_nAss_hedge) yuimaGUIdata$hedging[[id]]$info$buy <<- NA } yuimaGUIdata$hedging[[id]]$info$LotsToBuy <<- na_zero(input$hedging_nOptLot_hedge) if (!is.na(input$hedging_strike2)) yuimaGUIdata$hedging[[id]]$info$strike <<- input$hedging_strike2 if (!is.na(input$hedging_optMarketPrice2)) yuimaGUIdata$hedging[[id]]$info$optPrice <<- input$hedging_optMarketPrice2 yuimaGUIdata$hedging[[id]]$info$profit <<- hedging_values$return }) observe({ shinyjs::toggle("hedging_alert_selectRow", condition = (input$panel_hedging=="Start simulations")) }) ###Delete Hedging observeEvent(input$hedging_button_delete, priority = 1, { if(!is.null(input$hedging_table_results_rows_selected) & !is.null(input$hedging_modal_id)){ if(input$hedging_table_results_row_last_clicked %in% input$hedging_table_results_rows_selected){ delHedging(n=input$hedging_table_results_row_last_clicked) } } }) ###DeleteAll Hedging observeEvent(input$hedging_button_deleteAll, priority = 1, { if(!is.null(input$hedging_table_results_rows_all)) delHedging(n=input$hedging_table_results_rows_all) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/finance/profit_and_loss.R
rbind.fill <- function(..., rep = NA){ dots <- list(...) names <- c() for (i in length(dots):1){ if (length(rownames(dots[[i]]))==0) dots[i] <- NULL else names <- unique(c(names, colnames(dots[[i]]))) } for (symb in names) for (i in 1:length(dots)) if (!(symb %in% colnames(dots[[i]]))) dots[[i]][,symb] <- rep return (do.call("rbind", dots)) } melt <- function(x){ V1 <- rep(rownames(x), ncol(x)) V2 <- sort(V1) xx <- data.frame(Var1 = V1, Var2 = V2, value = NA) for (i in 1:nrow(xx)) xx[i,"value"] <- x[as.character(xx[i,"Var1"]), as.character(xx[i,"Var2"])] return(xx) } mode <- function(x) { ux <- unique(na.omit(x)) ux[which.max(tabulate(match(x, ux)))] } isUserDefined <- function(name){ n <- names(isolate({yuimaGUIdata$usr_model})) if (length(n)!=0) return (name %in% n) return (FALSE) } setDataGUI <- function(original.data, delta){ original.data <- na.omit(original.data) delta <- max(delta) t <- index(original.data) t0 <- 0 if(is.numeric(t)){ delta.original.data <- mode(diff(t)) t0 <- min(t, na.rm = TRUE)*delta/delta.original.data } setData(original.data = original.data, delta = delta, t0 = t0) } addData <- function(x, typeIndex){ x <- data.frame(x, check.names = TRUE) err <- c() alreadyIn <- c() for (symb in colnames(x)){ if (symb %in% names(yuimaGUIdata$series)) alreadyIn <- c(alreadyIn, symb) else{ temp <- data.frame("Index" = rownames(x), "symb" = as.numeric(gsub(as.character(x[,symb]), pattern = ",", replacement = "."))) temp <- temp[complete.cases(temp), ] rownames(temp) <- temp[,"Index"] colnames(temp) <- c("Index", symb) if (all(is.na(temp[,2]))) err <- c(err, symb) else if (typeIndex=="numeric"){ test <- try(read.zoo(temp, FUN=as.numeric, drop = FALSE)) if (class(test)!="try-error") yuimaGUIdata$series[[symb]] <<- test else err <- c(err, symb) } else{ test <- try(read.zoo(temp, FUN=as.Date, format = typeIndex, drop = FALSE)) if (class(test)!="try-error") yuimaGUIdata$series[[symb]] <<- test else err <- c(err, symb) } } } return(list(err = err, already_in = alreadyIn)) } getData <- function(symb){ return(isolate({yuimaGUIdata$series[[symb]]})) } delData <- function(symb){ for (i in symb) yuimaGUIdata$series <<- yuimaGUIdata$series[-which(names(yuimaGUIdata$series)==i)] } defaultBounds <- function(name, delta, strict, jumps = NA, AR_C = NA, MA_C = NA, data, intensity = NULL, threshold = NULL){ lastPrice = as.numeric(last(data)) if ( isUserDefined(name) ){ mod <- setModelByName(name = name, jumps = jumps, AR_C = AR_C, MA_C = MA_C) par <- getAllParams(mod, yuimaGUIdata$usr_model[[name]]$class) if(strict==TRUE){ lower <- rep(NA, length(par)) upper <- rep(NA, length(par)) } else { if (yuimaGUIdata$usr_model[[name]]$class=="Compound Poisson"){ lower <- rep(0, length(par)) upper <- rep(1, length(par)) } else { lower <- rep(-100, length(par)) upper <- rep(100, length(par)) } } names(lower) <- par names(upper) <- par if (!is.na(jumps)){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) for (i in par[par %in% names(boundsJump$lower)]){ lower[[i]] <- boundsJump$lower[[i]] upper[[i]] <- boundsJump$upper[[i]] } } return(list(lower=as.list(lower), upper=as.list(upper))) } if (name == "Hawkes"){ if (strict==TRUE) return (list(lower=list("nu1"=0, "c11"=0, "a11"=0), upper=list("nu1"=NA, "c11"=100, "a11"=NA))) else { x <- as.numeric(diff(data)) t1 <- tail(time(data),n=1) t0 <- time(data)[1] n <- length(x[x!=0]) nu1 <- n/as.numeric(t1-t0) c11 <- 0 a11 <- 1 return (list(lower=list("nu1"=nu1, "c11"=c11, "a11"=a11), upper=list("nu1"=nu1, "c11"=c11, "a11"=a11))) } } if (name == "Hawkes Power Law Kernel"){ if (strict==TRUE) return (list(lower=list("nu"=0, "k"=NA, "beta"=NA, 'gamma'=NA), upper=list("nu"=NA, "k"=NA, "beta"=NA, 'gamma'=NA))) else { x <- as.numeric(diff(data)) t1 <- tail(time(data),n=1) t0 <- time(data)[1] n <- length(x[x!=0]) nu <- n/as.numeric(t1-t0) return (list(lower=list("nu"=nu, "k"=0, "beta"=0, 'gamma'=-1), upper=list("nu"=nu, "k"=0, "beta"=0, 'gamma'=1))) } } if (name %in% defaultModels[names(defaultModels) == "COGARCH"]){ mod <- setModelByName(name = name, jumps = jumps, AR_C = AR_C, MA_C = MA_C) par <- getAllParams(mod, "COGARCH") if(strict==TRUE){ lower <- rep(NA, length(par)) upper <- rep(NA, length(par)) } else { lower <- rep(0, length(par)) upper <- rep(10, length(par)) } names(lower) <- par names(upper) <- par return(list(lower=as.list(lower), upper=as.list(upper))) } if (name %in% defaultModels[names(defaultModels) == "CARMA"]){ mod <- setModelByName(name = name, jumps = jumps, AR_C = AR_C, MA_C = MA_C) par <- getAllParams(mod, "CARMA") if(strict==TRUE){ lower <- rep(NA, length(par)) upper <- rep(NA, length(par)) names(lower) <- par names(upper) <- par } else { lower <- rep(0, length(par)) upper <- rep(1, length(par)) names(lower) <- par names(upper) <- par lower["MA0"] <- min(lastPrice*0.5, lastPrice*1.5) upper["MA0"] <- max(lastPrice*0.5, lastPrice*1.5) } return(list(lower=as.list(lower), upper=as.list(upper))) } if (name == "Brownian Motion" | name == "Bm"){ if (strict==TRUE) return (list(lower=list("sigma"=0, "mu"=NA), upper=list("sigma"=NA, "mu"=NA))) else { x <- as.numeric(diff(data)) mu <- mean(x) sigma <- sd(x) return (list(lower=list("sigma"=sigma/sqrt(delta), "mu"=mu/delta), upper=list("sigma"=sigma/sqrt(delta), "mu"=mu/delta))) } } if (name == "Geometric Brownian Motion" | name == "gBm") { if (strict==TRUE) return (list(lower=list("sigma"=0, "mu"=NA), upper=list("sigma"=NA, "mu"=NA))) else { x <- as.numeric(na.omit(Delt(data))) mu <- mean(x) sigma <- sd(x) return (list(lower=list("sigma"=sigma/sqrt(delta), "mu"=mu/delta), upper=list("sigma"=sigma/sqrt(delta), "mu"=mu/delta))) } } if (name == "Ornstein-Uhlenbeck (OU)" | name == "OU"){ if (strict==TRUE) return(list(lower=list("theta"=0, "sigma"=0),upper=list("theta"=NA, "sigma"=NA))) else return(list(lower=list("theta"=0, "sigma"=0),upper=list("theta"=1/delta, "sigma"=1/sqrt(delta)))) } if (name == "Vasicek model (VAS)" | name == "VAS"){ if (strict==TRUE) return(list(lower=list("theta3"=0, "theta1"=NA, "theta2"=NA), upper=list("theta3"=NA, "theta1"=NA, "theta2"=NA))) else { mu <- abs(mean(as.numeric(data), na.rm = TRUE)) return(list(lower=list("theta3"=0, "theta1"=-0.1*mu/delta, "theta2"=-0.1/delta), upper=list("theta3"=1/sqrt(delta), "theta1"=0.1*mu/delta, "theta2"=0.1/delta))) } } if (name == "Constant elasticity of variance (CEV)" | name == "CEV"){ if (strict==TRUE) return(list(lower=list("mu"=NA, "sigma"=0, "gamma"=0), upper=list("mu"=NA, "sigma"=NA, "gamma"=NA))) else return(list(lower=list("mu"=-1/delta, "sigma"=0, "gamma"=0), upper=list("mu"=1/delta, "sigma"=1/sqrt(delta), "gamma"=3))) } if (name == "Cox-Ingersoll-Ross (CIR)" | name == "CIR"){ if (strict==TRUE) return(list(lower=list("theta1"=0,"theta2"=0,"theta3"=0),upper=list("theta1"=NA,"theta2"=NA,"theta3"=NA))) else return(list(lower=list("theta1"=0,"theta2"=0,"theta3"=0),upper=list("theta1"=1/delta,"theta2"=1/delta,"theta3"=1/sqrt(delta)))) } if (name == "Chan-Karolyi-Longstaff-Sanders (CKLS)" | name == "CKLS"){ if (strict==TRUE) return(list(lower=list("theta1"=NA, "theta2"=NA, "theta3"=0, "theta4"=0), upper=list("theta1"=NA, "theta2"=NA, "theta3"=NA, "theta4"=NA))) else return(list(lower=list("theta1"=-1/delta, "theta2"=-1/delta, "theta3"=0, "theta4"=0), upper=list("theta1"=1/delta, "theta2"=1/delta, "theta3"=1/sqrt(delta), "theta4"=3))) } if (name == "Hyperbolic (Barndorff-Nielsen)" | name == "hyp1"){ if (strict==TRUE) return(list(lower=list("delta"=0, "alpha"=0, "beta"=0, "sigma"=0, "mu"=0), upper=list("delta"=NA, "alpha"=NA, "beta"=NA, "sigma"=NA, "mu"=NA))) else return(list(lower=list("delta"=0, "alpha"=0, "beta"=0, "sigma"=0, "mu"=0), upper=list("delta"=100, "alpha"=10, "beta"=10, "sigma"=1/sqrt(delta), "mu"=mean(as.numeric(data), na.rm = TRUE)))) } if (name == "Hyperbolic (Bibby and Sorensen)" | name == "hyp2"){ if (strict==TRUE) return(list(lower=list("delta"=0, "alpha"=0, "beta"=0, "sigma"=0, "mu"=0), upper=list("delta"=NA, "alpha"=NA, "beta"=NA, "sigma"=NA, "mu"=NA))) else return(list(lower=list("delta"=0, "alpha"=0, "beta"=0, "sigma"=0, "mu"=0),upper=list("delta"=10, "alpha"=1, "beta"=10, "sigma"=1/sqrt(delta), "mu"=mean(as.numeric(data), na.rm = TRUE)))) } if (name == "Constant Intensity"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) if (strict==TRUE) return(list(lower=c(list("lambda"=0), boundsJump$lower),upper=c(list("lambda"=NA), boundsJump$upper))) else { x <- as.numeric(diff(data)) counts <- length(x[x!=0 & !is.na(x)]) lambda <- counts/(length(x)*delta) return(list(lower=c(list("lambda"=lambda), boundsJump$lower),upper=c(list("lambda"=lambda), boundsJump$upper))) } } if (name == "Power Low Intensity"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) if (strict==TRUE) return(list(lower=c(list("alpha"=0, "beta"=NA), boundsJump$lower),upper=c(list("alpha"=NA, "beta"=NA), boundsJump$upper))) else { x <- as.numeric(diff(data)) counts <- length(x[x!=0 & !is.na(x)]) alpha <- counts/(length(x)*delta) return(list(lower=c(list("alpha"=0, "beta"=0), boundsJump$lower),upper=c(list("alpha"=alpha, "beta"=0), boundsJump$upper))) } } if (name == "Linear Intensity"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) if (strict==TRUE) return(list(lower=c(list("alpha"=0, "beta"=0), boundsJump$lower),upper=c(list("alpha"=NA, "beta"=NA), boundsJump$upper))) else { x <- as.numeric(diff(data)) counts <- length(x[x!=0 & !is.na(x)]) alpha <- counts/(length(x)*delta) return(list(lower=c(list("alpha"=0, "beta"=0), boundsJump$lower),upper=c(list("alpha"=alpha, "beta"=0), boundsJump$upper))) } } if (name == "Exponentially Decaying Intensity"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) if (strict==TRUE) return(list(lower=c(list("alpha"=0, "beta"=0), boundsJump$lower),upper=c(list("alpha"=NA, "beta"=NA), boundsJump$upper))) else { x <- as.numeric(diff(data)) counts <- length(x[x!=0 & !is.na(x)]) alpha <- counts/(length(x)*delta) return(list(lower=c(list("alpha"=0, "beta"=0), boundsJump$lower),upper=c(list("alpha"=alpha, "beta"=0), boundsJump$upper))) } } if (name == "Periodic Intensity"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data) if (strict==TRUE) return(list(lower=c(list("a"=0, "b"=0, "omega"=0, "phi"=0), boundsJump$lower),upper=c(list("a"=NA, "b"=NA, "omega"=NA, "phi"=2*pi), boundsJump$upper))) else return(list(lower=c(list("a"=0, "b"=0, "omega"=0, "phi"=0), boundsJump$lower),upper=c(list("a"=1/delta, "b"=1/delta, "omega"=1/delta, "phi"=2*pi), boundsJump$upper))) } if (name == "Geometric Brownian Motion with Jumps"){ boundsJump <- jumpBounds(jumps = jumps, strict = strict, data = data, threshold = threshold) boundsIntensity <- intensityBounds(intensity = intensity, strict = strict, delta = delta) if (strict==TRUE) return(list(lower=c(list("mu"=NA, "sigma"=0), boundsJump$lower, boundsIntensity$lower),upper=c(list("mu"=NA, "sigma"=NA), boundsJump$upper, boundsIntensity$upper))) else return(list(lower=c(list("mu"=-1, "sigma"=0), boundsJump$lower, boundsIntensity$lower),upper=c(list("mu"=1, "sigma"=1), boundsJump$upper, boundsIntensity$upper))) } if (name == "Correlated Brownian Motion"){ mod <- setModelByName(name = name, jumps = jumps, AR_C = AR_C, MA_C = MA_C, dimension = ncol(data)) par <- getAllParams(mod, "Diffusion process", FALSE) drift <- rep(NA, length(par@drift)) diffusion <- rep(NA, length(par@diffusion)) names(drift) <- par@drift names(diffusion) <- par@diffusion if (strict==TRUE) { diffusion[] <- 0; lower_diffusion <- diffusion diffusion[] <- NA; upper_diffusion <- diffusion drift[] <- NA; lower_drift <- drift drift[] <- NA; upper_drift <- drift return (list(lower=as.list(c(lower_drift, lower_diffusion)), upper=as.list(c(upper_drift, upper_diffusion)))) } else { x <- na.omit(diff(data)) mu <- colMeans(x) sigma <- sapply(x, sd) drift[] <- mu/delta; lower_drift <- drift; upper_drift <- drift diffusion[] <- 0; diffusion[paste("s",seq(1,ncol(data)),seq(1,ncol(data)), sep = "")] <- sigma/sqrt(delta); lower_diffusion <- diffusion; upper_diffusion <- diffusion return (list(lower=as.list(c(lower_drift, lower_diffusion)), upper=as.list(c(upper_drift, upper_diffusion)))) } } } setThreshold <- function(class, data){ if(class!="Levy process") return(NA) else { return(0) } } setJumps <- function(jumps){ if(is.na(jumps)) return("") if(jumps=='Gaussian') { return(list("dnorm(z, mean = mu_jump, sd = sigma_jump)")) } if(jumps=='Constant') { return(list("dconst(z, k = k_jump)")) } if(jumps=='Uniform') { return(list("dunif(z, min = a_jump, max = b_jump)")) } if(jumps=='Inverse Gaussian') { return(list("dIG(z, delta = delta_jump, gamma = gamma_jump)")) } if(jumps=='Normal Inverse Gaussian') { return(list("dNIG.gui(z, alpha = alpha_jump, beta = beta_jump, delta = delta_jump, mu = mu_jump)")) } if(jumps=='Hyperbolic') { return(list("dhyp.gui(z, alpha = alpha_jump, beta = beta_jump, delta = delta_jump, mu = mu_jump)")) } if(jumps=='Student t') { return(list("dt(z, df = nu_jump, ncp = mu_jump)")) } if(jumps=='Variance Gamma') { return(list("dVG.gui(z, lambda = lambda_jump, alpha = alpha_jump, beta = beta_jump, mu = mu_jump)")) } if(jumps=='Generalized Hyperbolic') { return(list("dghyp.gui(z, lambda = lambda_jump, alpha = alpha_jump, delta = delta_jump, beta = beta_jump, mu = mu_jump)")) } } jumpBounds <- function(jumps, data, strict, threshold = 0){ x <- na.omit(as.numeric(diff(data))) x <- x[abs(x)>threshold] x <- x-sign(x)*threshold switch(jumps, "Gaussian" = { if(strict==TRUE) return(list(lower=list("mu_jump"=NA, "sigma_jump"=0), upper=list("mu_jump"=NA, "sigma_jump"=NA))) else { mu <- mean(x) s <- sd(x) return(list(lower=list("mu_jump"=mu, "sigma_jump"=s), upper=list("mu_jump"=mu, "sigma_jump"=s))) } }, "Uniform" = { if(strict==TRUE) return(list(lower=list("a_jump"=NA, "b_jump"=NA), upper=list("a_jump"=NA, "b_jump"=NA))) else { a <- min(x) b <- max(x) return(list(lower=list("a_jump"=a, "b_jump"=b), upper=list("a_jump"=a, "b_jump"=b))) } }, "Constant" = { if(strict==TRUE) return(list(lower=list("k_jump"=NA), upper=list("k_jump"=NA))) else { k <- median(x) return(list(lower=list("k_jump"=k), upper=list("k_jump"=k))) } }, "Inverse Gaussian" = { if(strict==TRUE) return(list(lower=list("delta_jump"=NA, "gamma_jump"=NA), upper=list("delta_jump"=NA, "gamma_jump"=NA))) else { x <- x[x>0] delta <- mean(x) gamma <- delta^3/var(x) return(list(lower=list("delta_jump"=delta, "gamma_jump"=gamma), upper=list("delta_jump"=delta, "gamma_jump"=gamma))) } }, "Normal Inverse Gaussian" = { if(strict==TRUE) return(list(lower=list("alpha_jump"=0, "beta_jump"=NA, "delta_jump"=0, "mu_jump"=NA), upper=list("alpha_jump"=NA, "beta_jump"=NA, "delta_jump"=NA, "mu_jump"=NA))) else { fit <- try(coef(fit.NIGuv(x), type = 'alpha.delta')) if(class(fit)!='try-error'){ alpha <- fit$alpha beta <- fit$beta delta <- fit$delta mu <- fit$mu } else { alpha <- 1.5 beta <- 0 delta <- 1 mu <- mean(x) } return(list(lower=list("alpha_jump"=alpha, "beta_jump"=beta, "delta_jump"=delta, "mu_jump" = mu), upper=list("alpha_jump"=alpha, "beta_jump"=beta, "delta_jump"=delta, "mu_jump" = mu))) } }, "Hyperbolic" = { if(strict==TRUE) return(list(lower=list("alpha_jump"=NA, "beta_jump"=NA, "delta_jump"=NA, "mu_jump"=NA), upper=list("alpha_jump"=NA, "beta_jump"=NA, "delta_jump"=NA, "mu_jump"=NA))) else { fit <- try(coef(fit.hypuv(x), type = 'alpha.delta')) if(class(fit)!='try-error'){ alpha <- fit$alpha beta <- fit$beta delta <- fit$delta mu <- fit$mu } else { alpha <- 1.5 beta <- 0 delta <- 1 mu <- mean(x) } return(list(lower=list("alpha_jump"=alpha, "beta_jump"=beta, "delta_jump"=delta, "mu_jump" = mu), upper=list("alpha_jump"=alpha, "beta_jump"=beta, "delta_jump"=delta, "mu_jump" = mu))) } }, "Student t" = { if(strict==TRUE) return(list(lower=list("nu_jump"=0, "mu_jump"=NA), upper=list("nu_jump"=NA, "mu_jump"=NA))) else { mu <- mean(x) nu <- 1 return(list(lower=list("nu_jump"=nu, "mu_jump" = mu), upper=list("nu_jump"=nu, "mu_jump" = mu))) } }, "Variance Gamma" = { if(strict==TRUE) return(list(lower=list("lambda_jump"=0, "alpha_jump"=NA, "beta_jump"=NA, "mu_jump"=NA), upper=list("lambda_jump"=NA, "alpha_jump"=NA, "beta_jump"=NA, "mu_jump"=NA))) else { fit <- try(coef(fit.VGuv(x), type = 'alpha.delta')) if(class(fit)!='try-error'){ lambda <- fit$lambda alpha <- fit$alpha beta <- fit$beta mu <- fit$mu } else { lambda <- 1 alpha <- 1.5 beta <- 0 mu <- mean(x) } return(list(lower=list("lambda_jump"=lambda, "alpha_jump"=alpha, "beta_jump"=beta, "mu_jump" = mu), upper=list("lambda_jump"=lambda, "alpha_jump"=alpha, "beta_jump"=beta, "mu_jump" = mu))) } }, "Generalized Hyperbolic" = { if(strict==TRUE) return(list(lower=list("lambda_jump"=NA, "alpha_jump"=NA, "delta_jump"=NA, "beta_jump"=NA, "mu_jump"=NA), upper=list("lambda_jump"=NA, "alpha_jump"=NA, "delta_jump"=NA, "beta_jump"=NA, "mu_jump"=NA))) else { fit <- try(coef(fit.ghypuv(x), type = 'alpha.delta')) if(class(fit)!='try-error'){ lambda <- fit$lambda alpha <- fit$alpha delta <- fit$delta beta <- fit$beta mu <- fit$mu } else { lambda <- 0.5 alpha <- 1.5 delta <- 1 beta <- 0 mu <- mean(x) } return(list(lower=list("lambda_jump"=lambda, "alpha_jump"=alpha, "delta_jump"=delta, "beta_jump"=beta, "mu_jump" = mu), upper=list("lambda_jump"=lambda, "alpha_jump"=alpha, "delta_jump"=delta, "beta_jump"=beta, "mu_jump" = mu))) } } ) } latexJumps <- function(jumps){ if (!is.null(jumps)){ switch (jumps, "Gaussian" = "Y_i \\sim N(\\mu_{jump}, \\; \\sigma_{jump})", "Constant" = "Y_i = k_{jump}", "Uniform" = "Y_i \\sim Unif(a_{jump}, \\; b_{jump})", "Inverse Gaussian" = "Y_i \\sim IG(\\delta_{jump}, \\; \\gamma_{jump})", "Normal Inverse Gaussian" = "Y_i \\sim NIG( \\alpha_{jump}, \\; \\beta_{jump}, \\; \\delta_{jump}, \\; \\mu_{jump})", "Hyperbolic" = "Y_i \\sim HYP( \\alpha_{jump}, \\; \\beta_{jump}, \\; \\delta_{jump}, \\; \\mu_{jump})", "Student t" = "Y_i \\sim t( \\nu_{jump}, \\; \\mu_{jump} )", "Variance Gamma" = "Y_i \\sim VG( \\lambda_{jump}, \\; \\alpha_{jump}, \\; \\beta_{jump}, \\; \\mu_{jump})", "Generalized Hyperbolic" = "Y_i \\sim GH( \\lambda_{jump}, \\; \\alpha_{jump}, \\; \\beta_{jump}, \\; \\delta_{jump}, \\; \\mu_{jump})" ) } } intensityBounds <- function(intensity, strict, delta){ switch(intensity, "lambda" = { if(strict==TRUE) return(list(lower=list("lambda"=0), upper=list("lambda"=NA))) else return(list(lower=list("lambda"=0), upper=list("lambda"=1/delta))) } ) } setModelByName <- function(name, jumps = NA, AR_C = NA, MA_C = NA, XinExpr = FALSE, intensity = NA, dimension = 1){ dimension <- max(1, dimension) if ( isUserDefined(name) ){ if (isolate({yuimaGUIdata$usr_model[[name]]$class=="Diffusion process" | yuimaGUIdata$usr_model[[name]]$class=="Fractional process"})) return(isolate({yuimaGUIdata$usr_model[[name]]$object})) if (isolate({yuimaGUIdata$usr_model[[name]]$class=="Compound Poisson"})) return(setPoisson(intensity = isolate({yuimaGUIdata$usr_model[[name]]$intensity}), df = setJumps(jumps = jumps), solve.variable = "x")) } if (name == "Brownian Motion" | name == "Bm") return(yuima::setModel(drift="mu", diffusion="sigma", solve.variable = "x")) if (name == "Geometric Brownian Motion" | name == "gBm") return(yuima::setModel(drift="mu*x", diffusion="sigma*x", solve.variable = "x")) if (name == "Ornstein-Uhlenbeck (OU)" | name == "OU") return(yuima::setModel(drift="-theta*x", diffusion="sigma", solve.variable = "x")) if (name == "Vasicek model (VAS)" | name == "VAS") return(yuima::setModel(drift="theta1-theta2*x", diffusion="theta3", solve.variable = "x")) if (name == "Constant elasticity of variance (CEV)" | name == "CEV") return(yuima::setModel(drift="mu*x", diffusion="sigma*x^gamma", solve.variable = "x")) if (name == "Cox-Ingersoll-Ross (CIR)" | name == "CIR") return(yuima::setModel(drift="theta1-theta2*x", diffusion="theta3*sqrt(x)", solve.variable = "x")) if (name == "Chan-Karolyi-Longstaff-Sanders (CKLS)" | name == "CKLS") return(yuima::setModel(drift="theta1+theta2*x", diffusion="theta3*x^theta4", solve.variable = "x")) if (name == "Hyperbolic (Barndorff-Nielsen)" | name == "hyp1") return(yuima::setModel(drift="(sigma/2)^2*(beta-alpha*((x-mu)/(sqrt(delta^2+(x-mu)^2))))", diffusion="sigma", solve.variable = "x")) if (name == "Hyperbolic (Bibby and Sorensen)" | name == "hyp2") return(yuima::setModel(drift="0", diffusion="sigma*exp(0.5*(alpha*sqrt(delta^2+(x-mu)^2)-beta*(x-mu)))", solve.variable = "x")) if (name == "Frac. Brownian Motion" | name == "Bm") return(yuima::setModel(drift="mu", diffusion="sigma", solve.variable = "x", hurst = NA)) if (name == "Frac. Geometric Brownian Motion" | name == "gBm") return(yuima::setModel(drift="mu*x", diffusion="sigma*x", solve.variable = "x", hurst = NA)) if (name == "Frac. Ornstein-Uhlenbeck (OU)" | name == "OU") return(yuima::setModel(drift="-theta*x", diffusion="sigma", solve.variable = "x", hurst = NA)) if (name == "Hawkes") return(yuima::setHawkes()) if (name == "Hawkes Power Law Kernel") { df <- setLaw(rng = function(n){as.matrix(rep(1,n))}, dim = 1) countMod <- setModel(drift = c("0"), diffusion = matrix("0",1,1), jump.coeff = matrix(c("1"),1,1), measure = list(df = df), measure.type = "code", solve.variable = c("N"), xinit=c("0")) return(yuima::setPPR(yuima = countMod, counting.var="N", gFun="nu", Kernel = as.matrix("k/(beta+(t-s))^gamma"), lambda.var = "lambda", var.dx = "N", lower.var="0", upper.var = "t")) } if (name == "Power Low Intensity") return(yuima::setPoisson(intensity="alpha*t^(beta)", df=setJumps(jumps = jumps), solve.variable = "x")) if (name == "Constant Intensity") return(yuima::setPoisson(intensity="lambda", df=setJumps(jumps = jumps), solve.variable = "x")) if (name == "Linear Intensity") return(yuima::setPoisson(intensity="alpha+beta*t", df=setJumps(jumps = jumps), solve.variable = "x")) if (name == "Exponentially Decaying Intensity") return(yuima::setPoisson(intensity="alpha*exp(-beta*t)", df=setJumps(jumps = jumps), solve.variable = "x")) if (name == "Periodic Intensity") return(yuima::setPoisson(intensity="a/2*(1+cos(omega*t+phi))+b", df=setJumps(jumps = jumps), solve.variable = "x")) if (name == "Cogarch(p,q)") return(yuima::setCogarch(p = MA_C, q = AR_C, measure.type = "CP", measure = list(intensity = "lambda", df = setJumps(jumps = "Gaussian")), XinExpr = XinExpr, Cogarch.var="y", V.var="v", Latent.var="x", ma.par="MA", ar.par="AR")) if (name == "Carma(p,q)") return(yuima::setCarma(p = AR_C, q = MA_C, ma.par="MA", ar.par="AR", XinExpr = XinExpr)) if (name == "Geometric Brownian Motion with Jumps") { if(intensity=="None") return(yuima::setModel(drift="mu*x", diffusion="sigma*x", jump.coeff="x", measure.type = "code", measure = list(df = setJumps(jumps = jumps)), solve.variable = "x")) else return(yuima::setModel(drift="mu*x", diffusion="sigma*x", jump.coeff="x", measure.type = "CP", measure = list(intensity = intensity, df = setJumps(jumps = jumps)), solve.variable = "x")) } if (name == "Correlated Brownian Motion") { mat <- matrix(rep(1:dimension, dimension),dimension,dimension) diff <- matrix(paste("s",mat,t(mat),sep=""), dimension, dimension) diff[lower.tri(diff, diag = FALSE)] <- 0 return(yuima::setModel(drift=paste("mu", seq(1,dimension), sep = ""), diffusion=diff, solve.variable = paste("x", seq(1,dimension)))) } } getAllParams <- function(mod, class, all = TRUE){ if(is(mod)=='yuima' & class!="Point Process") mod <- mod@model if(all==TRUE){ if (class=="Point Process") return(mod@PPR@allparamPPR) else if (class=="Fractional process") return(c(mod@parameter@all, "hurst")) else if (class=="COGARCH") return(c(mod@parameter@drift, mod@parameter@xinit)) else if (class=="CARMA") return(mod@parameter@drift) else return(mod@parameter@all) } else { if (class=="Point Process") return(mod@PPR) else return(mod@parameter) } } printModelLatex <- function(names, process, jumps = NA, multi = FALSE, dimension = 1, symb = character(0)){ dimension <- max(dimension, 1) if(length(symb)>0) dimension <- length(symb) if (multi==TRUE){ if (process=="Diffusion process"){ text <- toLatex(setModelByName(names, dimension = dimension)) x <- paste(text[-1], collapse = "") if(length(symb)>0) for (i in 1:dimension) { x <- gsub(x, pattern = paste("x", i), replacement = paste("X_{", symb[i], "}", sep = "")) } else x <- gsub(x, pattern = "x ", replacement = "X_") x <- gsub(x, pattern = "dW", replacement = "dW_") x <- gsub(x, pattern = "\\$\\$\\$\\$.*", replacement = "$$") return(x) } } else { if (process=="Diffusion process"){ mod <- "" for (name in names){ if ( isUserDefined(name) ){ text <- toLatex(setModelByName(name)) x <- paste(text[2:9], collapse = "") x <- substr(x,3,nchar(x)) x <- gsub(x, pattern = "'", replacement = "") x <- gsub(x, pattern = "x", replacement = "X_t") x <- gsub(x, pattern = "W1", replacement = "W_t") x <- gsub(x, pattern = "\\$", replacement = "") mod <- paste(mod, ifelse(mod=="","","\\\\"), x) } if (name == "Brownian Motion" | name == "Bm") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = \\mu \\; dt + \\sigma \\; dW_t") if (name == "Geometric Brownian Motion" | name == "gBm") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = \\mu X_t \\; dt + \\sigma X_t \\; dW_t") if (name == "Ornstein-Uhlenbeck (OU)" | name == "OU") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = -\\theta X_t \\; dt + \\sigma \\; dW_t") if (name == "Vasicek model (VAS)" | name == "VAS") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = (\\theta_1 - \\theta_2 X_t) \\;dt + \\theta_3 \\; dW_t") if (name == "Constant elasticity of variance (CEV)" | name == "CEV") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = \\mu X_t \\;dt + \\sigma X_t^\\gamma \\; dW_t") if (name == "Cox-Ingersoll-Ross (CIR)" | name == "CIR") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = (\\theta_1-\\theta_2 X_t) \\; dt + \\theta_3 \\sqrt{X_t} \\; dW_t") if (name == "Chan-Karolyi-Longstaff-Sanders (CKLS)" | name == "CKLS") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = (\\theta_1+\\theta_2 X_t) \\; dt + \\theta_3 X_t^{\\theta_4} \\; dW_t") if (name == "Hyperbolic (Barndorff-Nielsen)" | name == "hyp1") mod <- paste(mod, ifelse(mod=="","","\\\\"),"dX_t = \\frac{\\sigma}{2}^2 \\Bigl (\\beta-\\alpha \\frac{X_t-\\mu}{\\sqrt{\\delta^2+(X_t-\\mu)^2}} \\Bigl ) \\; dt + \\sigma \\; dW_t") if (name == "Hyperbolic (Bibby and Sorensen)" | name == "hyp2") mod <- paste(mod, ifelse(mod=="","","\\\\"),"dX_t = \\sigma \\; exp\\Bigl[\\frac{1}{2} \\Bigl( \\alpha \\sqrt{\\delta^2+(X_t-\\mu)^2}-\\beta (X_t-\\mu)\\Bigl)\\Bigl] \\; dW_t") } return(paste("$$",mod,"$$")) } if (process=="Fractional process"){ mod <- "" for (name in names){ if ( isUserDefined(name) ){ text <- toLatex(setModelByName(name)) x <- paste(text[2:9], collapse = "") x <- substr(x,3,nchar(x)) x <- gsub(x, pattern = "'", replacement = "") x <- gsub(x, pattern = "x", replacement = "X_t") x <- gsub(x, pattern = "W1", replacement = "W_t^H") x <- gsub(x, pattern = "\\$", replacement = "") mod <- paste(mod, ifelse(mod=="","","\\\\"), x) } if (name == "Frac. Brownian Motion" | name == "Bm") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = \\mu \\; dt + \\sigma \\; dW_t^H") if (name == "Frac. Geometric Brownian Motion" | name == "gBm") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = \\mu X_t \\; dt + \\sigma X_t \\; dW_t^H") if (name == "Frac. Ornstein-Uhlenbeck (OU)" | name == "OU") mod <- paste(mod, ifelse(mod=="","","\\\\"), "dX_t = -\\theta X_t \\; dt + \\sigma \\; dW_t^H") } return(paste("$$",mod,"$$")) } if (process=="Point Process"){ mod <- "\\lambda_t = \\nu_1+\\int_{0}^{t_-}kern(t-s)\\mbox{d}N_s" for (name in names){ if ( isUserDefined(name) ){ } if (name == "Hawkes") mod <- paste(mod, ifelse(mod=="","","\\\\"), "kern(t-s) = c_{11}\\exp\\left[-a_{11}\\left(t-s\\right)\\right]") if( name == "Hawkes Power Law Kernel") mod <- paste(mod, ifelse(mod=="","","\\\\"), "kern(t-s) = \\frac{k}{\\left[\\beta+(t-s)\\right]^{\\gamma}}") } return(paste("$$",mod,"$$")) } if (process=="Compound Poisson"){ mod <- paste("X_t = X_0+\\sum_{i=0}^{N_t} Y_i \\; : \\;\\;\\; N_t \\sim Poi\\Bigl(\\int_0^t \\lambda(t)dt\\Bigl)", ifelse(!is.null(jumps), paste(", \\;\\;\\;\\; ", latexJumps(jumps)),"")) for (name in names){ if ( isUserDefined(name) ){ text <- paste("\\lambda(t)=",yuimaGUIdata$usr_model[[name]]$intensity) mod <- paste(mod, ifelse(mod=="","","\\\\"), text) } if (name == "Power Low Intensity") mod <- paste(mod, ifelse(mod=="","","\\\\"), "\\lambda(t)=\\alpha \\; t^{\\beta}") if (name == "Constant Intensity") mod <- paste(mod, ifelse(mod=="","","\\\\"), "\\lambda(t)=\\lambda") if (name == "Linear Intensity") mod <- paste(mod, ifelse(mod=="","","\\\\"), "\\lambda(t)=\\alpha+\\beta \\; t") if (name == "Exponentially Decaying Intensity") mod <- paste(mod, ifelse(mod=="","","\\\\"), "\\lambda(t)=\\alpha \\; e^{-\\beta t}") if (name == "Periodic Intensity") mod <- paste(mod, ifelse(mod=="","","\\\\"), "\\lambda(t)=\\frac{a}{2}\\bigl(1+cos(\\omega t + \\phi)\\bigl)+b") } return(paste("$$",mod,"$$")) } if (process=="COGARCH"){ return(paste("$$","COGARCH(p,q)","$$")) } if (process=="CARMA"){ return(paste("$$","CARMA(p,q)","$$")) } if (process=="Levy process"){ return(paste("$$","dX_t = \\mu X_t \\; dt + \\sigma X_t \\; dW_t + X_t \\; dZ_t","$$")) } } } ###Function to convert unit of measure of the estimates changeBaseP <- function(param, StdErr, delta, original.data, paramName, modelName, newBase, allParam){ msg <- NULL if (newBase == "delta") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) if(class(index(original.data))=="Date"){ seriesLength <- as.numeric(difftime(end(original.data),start(original.data)),units="days") if (newBase == "Yearly") dt1 <- seriesLength/365/(length(original.data)-1) if (newBase == "Semestral") dt1 <- seriesLength/182.50/(length(original.data)-1) if (newBase == "Quarterly") dt1 <- seriesLength/120/(length(original.data)-1) if (newBase == "Trimestral") dt1 <- seriesLength/90/(length(original.data)-1) if (newBase == "Bimestral") dt1 <- seriesLength/60/(length(original.data)-1) if (newBase == "Monthly") dt1 <- seriesLength/30/(length(original.data)-1) if (newBase == "Weekly") dt1 <- seriesLength/7/(length(original.data)-1) if (newBase == "Daily") dt1 <- seriesLength/(length(original.data)-1) } if(class(index(original.data))=="numeric"){ dt1 <- as.numeric(end(original.data) - start(original.data))/(length(index(original.data))-1) msg <- "Parameters are in the same unit of measure of input data" } if (modelName %in% c("Brownian Motion","Bm","Geometric Brownian Motion","gBm")){ if(paramName == "mu") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "sigma") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) } if (modelName %in% c("Ornstein-Uhlenbeck (OU)","OU")){ if(paramName == "theta") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "sigma") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) } if (modelName %in% c("Vasicek model (VAS)","VAS")){ if(paramName == "theta1") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta2") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta3") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) } if (modelName %in% c("Constant elasticity of variance (CEV)","CEV")){ if(paramName == "mu") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "sigma") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) if(paramName == "gamma") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Cox-Ingersoll-Ross (CIR)","CIR")){ if(paramName == "theta1") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta2") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta3") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) } if (modelName %in% c("Chan-Karolyi-Longstaff-Sanders (CKLS)","CKLS")){ if(paramName == "theta1") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta2") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "theta3") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) if(paramName == "theta4") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Hyperbolic (Barndorff-Nielsen)", "Hyperbolic (Bibby and Sorensen)")){ if(paramName == "sigma") return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) if(paramName == "beta") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) if(paramName == "alpha") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) if(paramName == "mu") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) if(paramName == "delta") return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Constant Intensity")){ if(paramName == "lambda") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName %in% c("mu_jump", "sigma_jump", "a_jump", "b_jump")) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Linear Intensity")){ if(paramName == "alpha") return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName == "beta") return(list("Estimate"= param*(delta/dt1)^2, "Std. Error"=StdErr*(delta/dt1)^2, "msg"=msg)) if(paramName %in% c("mu_jump", "sigma_jump", "a_jump", "b_jump")) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Power Low Intensity")){ beta <- as.numeric(allParam["beta"]) if(paramName == "alpha") return(list("Estimate"= param*(delta/dt1)^(beta+1), "Std. Error"=StdErr*(delta/dt1)^(beta+1), "msg"=msg)) if(paramName %in% c("beta", "mu_jump", "sigma_jump", "a_jump", "b_jump")) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Exponentially Decaying Intensity")){ if(paramName %in% c("alpha", "beta")) return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName %in% c("mu_jump", "sigma_jump", "a_jump", "b_jump")) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Periodic Intensity")){ if(paramName %in% c("a", "b", "omega")) return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(paramName %in% c("phi", "mu_jump", "sigma_jump", "a_jump", "b_jump")) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg)) } if (modelName %in% c("Correlated Brownian Motion")){ if(startsWith(paramName, "mu")) return(list("Estimate"= param*delta/dt1, "Std. Error"=StdErr*delta/dt1, "msg"=msg)) if(startsWith(paramName, "s")) return(list("Estimate"= param*sqrt(delta/dt1), "Std. Error"=StdErr*sqrt(delta/dt1), "msg"=msg)) } msg <- paste("No parameters conversion available for this model. Parameters have been obtained using delta = ", delta) return(list("Estimate"= param, "Std. Error"=StdErr, "msg"=msg, "conversion"=FALSE)) } ###Function to manipulate digits signifDigits <- function(value, sd){ if (is.na(sd) | sd=="NaN" | sd==0) return (value) else{ pow <- 10^(1-as.integer(log10(as.numeric(sd)))) return(round(as.numeric(value)*pow)/pow) } } changeBase <- function(table, yuimaGUI, newBase, session = session, choicesUI, anchorId, alertId){ closeAlert(session, alertId) shinyjs::toggle(id = choicesUI, condition = (class(index(yuimaGUI$model@[email protected]))=="Date")) outputTable <- data.frame() for (param in unique(colnames(table))){ temp <- changeBaseP(param = as.numeric(table["Estimate",param]), StdErr = as.numeric(table["Std. Error",param]), delta = yuimaGUI$model@sampling@delta, original.data = yuimaGUI$model@[email protected], paramName = param, modelName = yuimaGUI$info$modName, newBase = newBase, allParam = table["Estimate",]) outputTable["Estimate",param] <- as.character(signifDigits(temp[["Estimate"]],temp[["Std. Error"]])) outputTable["Std. Error",param] <- as.character(signifDigits(temp[["Std. Error"]],temp[["Std. Error"]])) } colnames(outputTable) <- unique(colnames(table)) style <- "info" msg <- NULL if (any(outputTable["Std. Error",] %in% c(0, "NA", "NaN", "<NA>", NA, NaN))){ msg <- "The estimated model does not satisfy theoretical properties." style <- "warning" } if (!is.null(temp$conversion)) if (temp$conversion==FALSE) shinyjs::hide(choicesUI) if (yuimaGUI$info$class=="COGARCH") { capture.output(test <- try(Diagnostic.Cogarch(yuimaGUI$model, param = as.list(coef(yuimaGUI$qmle))))) if (class(test)=="try-error") createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("The estimated model does not satisfy theoretical properties.", temp$msg), style = "warning") else if(test$stationary==FALSE | test$positivity==FALSE) createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("The estimated model does not satisfy theoretical properties.", temp$msg), style = "warning") else createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste(msg, temp$msg), style = style) } else if (yuimaGUI$info$class=="CARMA") { test <- try(Diagnostic.Carma(yuimaGUI$qmle)) if (class(test)=="try-error") createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("The estimated model does not satisfy theoretical properties.", temp$msg), style = "warning") else if(test==FALSE) createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("The estimated model does not satisfy theoretical properties.", temp$msg), style = "warning") else createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste(msg, temp$msg), style = style) } else if (!is.null(temp$msg) | !is.null(msg)) createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste(msg, temp$msg), style = style) return(outputTable) } qmleGUI <- function(upper, lower, ...){ if(length(upper)!=0 & length(lower)!=0) return (qmle(upper = upper, lower = lower, ...)) if(length(upper)!=0 & length(lower)==0) return (qmle(upper = upper, ...)) if(length(upper)==0 & length(lower)!=0) return (qmle(lower = lower, ...)) if(length(upper)==0 & length(lower)==0) return (qmle(...)) } clearNA <- function(List){ for (i in names(List)) if (is.na(List[[i]])) List[[i]] <- NULL return (List) } addModel <- function(timeout = Inf, modName, multi = FALSE, intensity_levy, modClass, AR_C, MA_C, jumps, symbName, data, toLog, delta, start, startMin, startMax, trials, seed, method="BFGS", fixed = list(), lower, upper, joint=FALSE, aggregation=TRUE, threshold=NULL, session, anchorId, alertId){ info <- list( symb = names(data), class = modClass, modName = modName, AR = AR_C, MA = MA_C, jumps = ifelse(is.null(jumps),NA,jumps), method=method, delta = delta, toLog = toLog, start = start, startMin = startMin, startMax = startMax, trials = trials, seed = seed, fixed = fixed, lower = lower, upper = upper, joint = joint, aggregation = aggregation, threshold = threshold ) if(!is.na(seed)) set.seed(seed) if(is.na(seed)) set.seed(NULL) start <- clearNA(start) fixed <- clearNA(fixed) lower <- clearNA(lower) upper <- clearNA(upper) for (i in 1:length(toLog)) if(toLog[i]==TRUE) { tmp <- try(log(data[,i])) if(class(data)!="try-error") data[,i] <- tmp else { createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("Cannot convert series ", symbName, "to log. Try to use 'Advanced Settings' and customize estimation.", sep = ""), style = "error") return() } } if(modClass=='Point Process'){ model <- setModelByName(name = modName, dimension = ncol(data), intensity = intensity_levy, jumps = jumps, MA_C = MA_C, AR_C = AR_C) t1 <- tail(time(data),n=1) t0 <- time(data)[1] if(!is.numeric(t0) | !is.numeric(t1)){ t0 <- 0 t1 <- as.numeric(t1-t0)/365 } samp <- setSampling(t0, t1, n = as.integer(as.numeric(t1-t0)/delta)+1) colnames(data) <- model@[email protected] model <- DataPPR(CountVar = data, yuimaPPR = model, samp = samp) } else { model <- try(setYuima(data = setDataGUI(data, delta = delta), model=setModelByName(name = modName, dimension = ncol(data), intensity = intensity_levy, jumps = jumps, MA_C = MA_C, AR_C = AR_C))) } if (class(model)=="try-error"){ createAlert(session = session, anchorId = anchorId, alertId = alertId, content = "Unable to construct a synchronous grid for the data provided", style = "error") return() } #index(model@[email protected]) <- index(na.omit(data)) parameters <- getAllParams(model, modClass) if (modClass == "Fractional process"){ QMLEtemp <- try(mmfrac(model)) if(class(QMLEtemp)!="try-error") { estimates <- QMLEtemp[[1]] dev <- diag(QMLEtemp[[2]]) QMLE <- rbind(estimates, dev) col <- gsub(colnames(QMLE), pattern = "\\(", replacement = "") col <- gsub(col, pattern = "\\)", replacement = "") colnames(QMLE) <- col rownames(QMLE) <- c("Estimate", "Std. Error") } } else if (modClass=="CARMA") { if (all(parameters %in% c(names(start),names(fixed)))) QMLE <- try(qmleGUI(model, start = start, method = method, lower = lower, upper = upper)) else { miss <- parameters[!(parameters %in% c(names(start),names(fixed)))] m2logL_prec <- NA na_prec <- NA withProgress(message = 'Step: ', value = 0, { for(iter in 1:trials){ setTimeLimit(cpu = timeout, transient = TRUE) incProgress(1/trials, detail = paste(iter,"(/", trials ,")")) for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtemp <- try(qmleGUI(model, start = start, method = method, lower = lower, upper = upper)) if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))) break } if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtemp)@m2logL coefTable <- summary(QMLEtemp)@coef for (param in rownames(coefTable)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtemp <- try(qmleGUI(model, start = start, method = method, lower = lower, upper = upper)) if (class(QMLEtemp)=="try-error") break else if(summary(QMLEtemp)@m2logL>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtemp)!="try-error"){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtemp)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtemp)@m2logL if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLE <- QMLEtemp m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } }) } } else if (modClass=="COGARCH") { if (all(parameters %in% c(names(start),names(fixed)))) QMLE <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #REMOVE# joint = joint, aggregation = aggregation, threshold = threshold, grideq = TRUE, rcpp = TRUE)) else { miss <- parameters[!(parameters %in% c(names(start),names(fixed)))] m2logL_prec <- NA na_prec <- NA withProgress(message = 'Step: ', value = 0, { for(iter in 1:trials){ setTimeLimit(cpu = timeout, transient = TRUE) incProgress(1/trials, detail = paste(iter,"(/", trials ,")")) for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold, grideq = TRUE, rcpp = TRUE)) if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))) break } if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtemp)@objFunVal coefTable <- summary(QMLEtemp)@coef for (param in rownames(coefTable)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold, grideq = TRUE, rcpp = TRUE)) if (class(QMLEtemp)=="try-error") break else if(summary(QMLEtemp)@objFunVal>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtemp)!="try-error"){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@objFunVal na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtemp)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@objFunVal na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtemp)@objFunVal if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLE <- QMLEtemp m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } }) } } else if (modClass == "Compound Poisson") { if (all(parameters %in% c(names(start),names(fixed)))) QMLE <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #REMOVE# joint = joint, aggregation = aggregation, threshold = threshold)) else { miss <- parameters[!(parameters %in% c(names(start),names(fixed)))] m2logL_prec <- NA na_prec <- NA withProgress(message = 'Step: ', value = 0, { for(iter in 1:trials){ setTimeLimit(cpu = timeout, transient = TRUE) incProgress(1/trials, detail = paste(iter,"(/", trials ,")")) for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold)) if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))) break } if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtemp)@m2logL coefTable <- summary(QMLEtemp)@coef for (param in names(start)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold)) if (class(QMLEtemp)=="try-error") break else if (summary(QMLEtemp)@m2logL>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtemp)!="try-error"){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtemp)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtemp)@m2logL if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLE <- QMLEtemp m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } }) } } else if (modClass == "Levy process") { if (all(parameters %in% c(names(start),names(fixed)))) QMLE <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #REMOVE# joint = joint, aggregation = aggregation, threshold = threshold)) else { miss <- parameters[!(parameters %in% c(names(start),names(fixed)))] m2logL_prec <- NA na_prec <- NA withProgress(message = 'Step: ', value = 0, { for(iter in 1:trials){ setTimeLimit(cpu = timeout, transient = TRUE) incProgress(1/trials, detail = paste(iter,"(/", trials ,")")) for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold)) if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))) break } if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtemp)@m2logL coefTable <- summary(QMLEtemp)@coef for (param in names(start)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold)) if (class(QMLEtemp)=="try-error") break else if (summary(QMLEtemp)@m2logL>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtemp)!="try-error"){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtemp)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtemp)@m2logL if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLE <- QMLEtemp m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } }) } } else { if (all(parameters %in% c(names(start),names(fixed)))) QMLE <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #REMOVE# joint = joint, aggregation = aggregation, threshold = threshold, rcpp = TRUE)) else { miss <- parameters[!(parameters %in% c(names(start),names(fixed)))] m2logL_prec <- NA na_prec <- NA withProgress(message = 'Step: ', value = 0, { for(iter in 1:trials){ setTimeLimit(cpu = timeout, transient = TRUE) incProgress(1/trials, detail = paste(iter,"(/", trials ,")")) for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold, rcpp = TRUE)) if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))) break } if (class(QMLEtemp)!="try-error") if (all(!is.na(summary(QMLEtemp)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtemp)@m2logL coefTable <- summary(QMLEtemp)@coef for (param in names(start)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtemp <- try(qmle(model, start = start, fixed = fixed, method = method, lower = lower, upper = upper, #joint = joint, aggregation = aggregation, threshold = threshold, rcpp = TRUE)) if (class(QMLEtemp)=="try-error") break else if (summary(QMLEtemp)@m2logL>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtemp)!="try-error"){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtemp)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLE <- QMLEtemp m2logL_prec <- summary(QMLE)@m2logL na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtemp)@m2logL if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLE <- QMLEtemp m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } }) } } if (!exists("QMLE")){ createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("Unable to estimate ", modName," on ", symbName, ". Try to use 'Advanced Settings' and customize estimation.", sep = ""), style = "error") return() } if(multi==FALSE) yuimaGUIdata$model[[symbName]][[ifelse(is.null(length(yuimaGUIdata$model[[symbName]])),1,length(yuimaGUIdata$model[[symbName]])+1)]] <<- list( model = model, qmle = QMLE, aic = ifelse(!(modClass %in% c("CARMA","COGARCH","Fractional process")), AIC(QMLE), NA), bic = ifelse(!(modClass %in% c("CARMA","COGARCH","Fractional process")), BIC(QMLE), NA), info = info ) else yuimaGUIdata$multimodel[[symbName]][[ifelse(is.null(length(yuimaGUIdata$multimodel[[symbName]])),1,length(yuimaGUIdata$multimodel[[symbName]])+1)]] <<- list( model = model, qmle = QMLE, aic = ifelse(!(modClass %in% c("CARMA","COGARCH","Fractional process")), AIC(QMLE), NA), bic = ifelse(!(modClass %in% c("CARMA","COGARCH","Fractional process")), BIC(QMLE), NA), info = info ) } addCPoint <- function(modelName, symb, from, to, delta, toLog, start, startMin, startMax, method, trials, seed, lower, upper, fracL, fracR){ series <- getData(symb) if(class(index(series)[1])=="Date") series <- window(series, start = as.Date(from), end = as.Date(to)) else series <- window(series, start = as.numeric(from), end = as.numeric(to)) mod <- setModelByName(name = modelName) if(!is.na(seed)) set.seed(seed) if(is.na(seed)) set.seed(NULL) start <- clearNA(start) lower <- clearNA(lower) upper <- clearNA(upper) if(toLog==TRUE) series <- try(log(series)) if(class(series)=="try-error") stop() info <- list( symb = symb, seed = seed, model = modelName, toLog = toLog, trials = trials, method = method ) yuima <- setYuima(data = setDataGUI(series, delta = delta), model = mod) t0 <- start(yuima@[email protected][[1]]) par <- getAllParams(mod, "Diffusion process") miss <- par[!(par %in% names(start))] m2logL_prec <- NA na_prec <- NA qmleL <- function(yuima, t, start, method, lower , upper , rcpp){ yuima@[email protected][[1]] <- window(yuima@[email protected][[1]], end = t) qmle(yuima = yuima, start = start, method = method, upper = upper, lower = lower, rcpp = rcpp) } qmleR <- function(yuima, t, start, method, lower , upper , rcpp){ yuima@[email protected][[1]] <- window(yuima@[email protected][[1]], start = t) qmle(yuima = yuima, start = start, method = method, upper = upper, lower = lower, rcpp = rcpp) } for(iter in 1:trials){ for(j in 1:3){ for (i in miss) start[[i]] <- runif(1, min = max(lower[[i]],startMin[[i]], na.rm = TRUE), max = min(upper[[i]],startMax[[i]],na.rm = TRUE)) QMLEtempL <- try(qmleL(yuima = yuima, t = t0 + fracL*length(series)*delta, start = start, method=method, lower = lower, upper = upper, rcpp = TRUE)) if (class(QMLEtempL)!="try-error") if (all(!is.na(summary(QMLEtempL)@coef[,"Estimate"]))) break } if (class(QMLEtempL)!="try-error") if (all(!is.na(summary(QMLEtempL)@coef[,"Estimate"]))){ repeat{ m2logL <- summary(QMLEtempL)@m2logL coefTable <- summary(QMLEtempL)@coef for (param in names(start)) start[[param]] <- as.numeric(coefTable[param,"Estimate"]) QMLEtempL <- try(qmleL(yuima = yuima, t = t0 + fracL*length(series)*delta, start = start, method=method, lower = lower, upper = upper, rcpp = TRUE)) if (class(QMLEtempL)=="try-error") break else if (summary(QMLEtempL)@m2logL>=m2logL*abs(sign(m2logL)-0.001)) break } if(is.na(m2logL_prec) & class(QMLEtempL)!="try-error"){ QMLEL <- QMLEtempL m2logL_prec <- summary(QMLEL)@m2logL na_prec <- sum(is.na(coefTable)) } else if (class(QMLEtempL)!="try-error"){ if (sum(is.na(coefTable)) < na_prec){ QMLEL <- QMLEtempL m2logL_prec <- summary(QMLEL)@m2logL na_prec <- sum(is.na(coefTable)) } else { test <- summary(QMLEtempL)@m2logL if(test < m2logL_prec & sum(is.na(coefTable))==na_prec){ QMLEL <- QMLEtempL m2logL_prec <- test na_prec <- sum(is.na(coefTable)) } } } } } if (!exists("QMLEL")) stop() tmpL <- QMLEL tmpR <- try(qmleR(yuima = yuima, t = t0 + fracR*length(series)*delta, start = as.list(coef(tmpL)), method=method, lower = lower, upper = upper, rcpp = TRUE)) if (class(tmpR)=="try-error") stop() cp_prec <- try(CPoint(yuima = yuima, param1=coef(tmpL), param2=coef(tmpR))) if(class(cp_prec)=="try-error") stop() diff_prec <- delta*nrow(series) repeat{ tmpL <- try(qmleL(yuima, start=as.list(coef(tmpL)), t = cp_prec$tau, lower=lower, upper = upper, method=method, rcpp = TRUE)) if(class(tmpL)=="try-error") stop() tmpR <- try(qmleR(yuima, start=as.list(coef(tmpR)), t = cp_prec$tau, lower=lower, upper = upper, method=method, rcpp = TRUE)) if(class(tmpR)=="try-error") stop() cp <- try(CPoint(yuima = yuima, param1=coef(tmpL), param2=coef(tmpR))) if(class(cp)=="try-error") stop() if (abs(cp$tau - cp_prec$tau)<delta) break else if (abs(cp$tau - cp_prec$tau)>=diff_prec) stop() else { cp_prec <- cp diff_prec <- abs(cp$tau - cp_prec$tau) } } i <- 1 symb_id <- symb repeat { if(symb_id %in% names(yuimaGUIdata$cpYuima)){ symb_id <- paste(symb, i) i <- i+1 } else break } yuimaGUIdata$cpYuima[[symb_id]] <<- list(tau = index(series)[as.integer((cp$tau-t0)/delta)], info = info, series = series, qmleR = tmpR, qmleL = tmpL) } getModelNames <- function(){ return(isolate({yuimaGUItable$model})) } getModel <- function(symb){ return(isolate({yuimaGUIdata$model[[symb]]})) } delModel <- function(symb, n=1){ for(i in length(symb):1){ yuimaGUIdata$model[[symb[i]]][as.numeric(n[i])] <<- NULL if (length(yuimaGUIdata$model[[symb[i]]])==0) yuimaGUIdata$model[[symb[i]]] <<- NULL } } delMultiModel <- function(symb, n=1){ for(i in length(symb):1){ yuimaGUIdata$multimodel[[symb[i]]][as.numeric(n[i])] <<- NULL if (length(yuimaGUIdata$multimodel[[symb[i]]])==0) yuimaGUIdata$multimodel[[symb[i]]] <<- NULL } } simulateGUI <- function(symbName, modelYuimaGUI, xinit, nsim, nstep, simulate.from, simulate.to, saveTraj, space.discretized, method, session, anchorId, alertId = NULL, true.parameter = NULL){ modelYuima <- modelYuimaGUI$model model <- modelYuima@model if(is.null(modelYuimaGUI$info$toLog)) toLog <- FALSE else toLog <- modelYuimaGUI$info$toLog if(simulate.from >= simulate.to){ createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("Unable to simulate ", symbName," by ", modelYuimaGUI$info$modName, ": ending time before starting time.", sep = ""), style = "danger") return() } if(!is.null(names(xinit))) seriesnames <- names(xinit) else seriesnames <- [email protected] xinit <- as.numeric(xinit) xinit[toLog==TRUE] <- log(xinit[toLog==TRUE]) if(is.null(true.parameter)){ convert <- TRUE if (modelYuimaGUI$info$class=="Fractional process") true.parameter <- as.list(modelYuimaGUI$qmle["Estimate",]) else true.parameter <- as.list(modelYuimaGUI$qmle@coef) data <- modelYuima@[email protected] data_index <- index(data) real_delta <- as.numeric(last(data_index)-data_index[1])/(length(data_index)-1) used_delta <- modelYuima@sampling@delta if(is.numeric(data_index)){ Initial <- round(digits = 0, simulate.from/real_delta)*used_delta Terminal <- round(digits = 0, simulate.to/real_delta)*used_delta } else { Initial <- round(digits = 0, as.numeric(simulate.from-start(data))/real_delta)*used_delta Terminal <- round(digits = 0, as.numeric(simulate.to-start(data))/real_delta)*used_delta } if (modelYuimaGUI$info$class %in% c("COGARCH", "CARMA") | !is.numeric(nstep)) nstep <- (Terminal-Initial)/used_delta sampling <- setSampling(Initial = Initial, Terminal = Terminal, n = nstep) } else { convert <- FALSE sampling <- setSampling(Initial = simulate.from, Terminal = simulate.to, n = nstep) } if(nsim*sampling@n*length(xinit) > 1000*252*2) saveTraj <- FALSE is.valid <- TRUE if (modelYuimaGUI$info$class=="COGARCH") { noise <- cogarchNoise(yuima = modelYuima, param = true.parameter) xinit <- c(xinit, as.numeric(last(yuima:::onezoo(noise$Cogarch)))[-1]) increments <- noise$incr.L } if (modelYuimaGUI$info$class=="CARMA") { increments <- CarmaNoise(yuima = modelYuima, param = true.parameter) x <- try(yuima::simulate(object = model, increment.W = t(increments), xinit = as.numeric(first(modelYuima@[email protected])), true.parameter = true.parameter, sampling = setSampling(Initial = modelYuima@sampling@Initial, delta = used_delta, n = length(increments)), space.discretized = space.discretized, method = method)) if (class(x)=="try-error"){ createAlert(session = session, anchorId = anchorId, alertId = alertId, content = paste("Unable to simulate ", symbName," by ", modelYuimaGUI$info$modName, ". Probably something wrong with the estimation of this model", sep = ""), style = "danger") return() } xinit <- c(xinit, as.numeric(last(yuima:::onezoo(x)))[-1]) } if (modelYuimaGUI$info$class=="Fractional process") if (true.parameter[["hurst"]]>=1 | true.parameter[["hurst"]]<=0) { createAlert(session = session, anchorId = anchorId, alertId = alertId, content = "Hurst coefficient must greater than 0 and less than 1", style = "danger") return() } withProgress(message = 'Simulating: ', value = 0, { for (i in 1:nsim){ incProgress(1/nsim, detail = paste("Simulating:",i,"(/",nsim,")")) if (modelYuimaGUI$info$class=="COGARCH") simulation <- try(yuima::simulate(object = model, increment.L = sample(x = increments, size = sampling@n, replace = TRUE), xinit = xinit, true.parameter = true.parameter, sampling = sampling, space.discretized = space.discretized, method = method)) else if (modelYuimaGUI$info$class=="CARMA") simulation <- try(yuima::simulate(object = model, increment.W = t(sample(x = increments, size = sampling@n, replace = TRUE)), xinit = xinit, true.parameter = true.parameter, sampling = sampling, space.discretized = space.discretized, method = method)) else if (modelYuimaGUI$info$class=="Fractional process") simulation <- try(yuima::simulate(object = model, xinit = xinit, true.parameter = true.parameter, hurst = true.parameter[["hurst"]], sampling = sampling, space.discretized = space.discretized, method = method)) else if (modelYuimaGUI$info$class=="Point Process") simulation <- try(yuima::simulate(object = modelYuima, xinit = xinit, true.parameter = true.parameter, sampling = sampling, space.discretized = space.discretized, method = method)) else simulation <- try(yuima::simulate(object = model, xinit = xinit, true.parameter = true.parameter, sampling = sampling, space.discretized = space.discretized, method = method)) if (class(simulation)=="try-error"){ is.valid <- FALSE break() } else { dimension <- length(simulation@[email protected]) if (modelYuimaGUI$info$class %in% c("CARMA","COGARCH")) dimension <- dimension - 2 if (saveTraj==TRUE){ x <- do.call(merge,simulation@[email protected]) if(i==1) { timeindex <- index(x) x <- as.matrix(x) trajectory <- matrix(nrow = nrow(x), ncol = nsim*dimension) colnames(trajectory) <- seq(1:ncol(trajectory)) hist <- NA } else x <- as.matrix(x) x[,toLog==TRUE] <- exp(x[,toLog==TRUE]) if(any( is.na(x) | !is.finite(x) )){ is.valid <- FALSE break() } colindex <- seq(1+(i-1)*dimension, i*dimension) trajectory[,colindex] <- x[,1:dimension] colnames(trajectory)[colindex] <- paste(seriesnames[1:dimension], i, sep = "_sim") } else { x <- do.call(c, lapply(simulation@[email protected], FUN = function(x) as.numeric(last(x)))) if(i==1) { trajectory <- NA hist <- matrix(nrow = dimension, ncol = nsim, dimnames = list(seriesnames[1:dimension])) } hist[,i] <- x } } } }) if (!is.valid){ if(modelYuimaGUI$info$class %in% c("CARMA","COGARCH")) msg <- paste("Unable to simulate ", symbName," by ", modelYuimaGUI$info$modName, ". Probably something wrong with the estimation of this model", sep = "") else msg <- paste("Unable to simulate", symbName,"by", modelYuimaGUI$info$modName) createAlert(session = session, anchorId = anchorId, alertId = alertId, content = msg, style = "danger") return() } if(saveTraj==TRUE){ trajectory <- zoo(trajectory, order.by = timeindex) if(convert==TRUE){ if(is.numeric(data_index)) index(trajectory) <- as.numeric(timeindex/used_delta*real_delta) else index(trajectory) <- as.POSIXct(24*60*60*(timeindex-timeindex[1])/used_delta*real_delta, origin = simulate.from) } } return(list(hist=hist, trajectory=trajectory, nstep = sampling@n[1], simulate.from = simulate.from, simulate.to = simulate.to, delta = sampling@delta)) } addSimulation <- function(modelYuimaGUI, symbName, xinit, nsim, nstep, simulate.from, simulate.to, saveTraj, seed, sampling, true.parameter = NULL, space.discretized = FALSE, method = "euler", session, anchorId, is.multi = FALSE){ if(!is.na(seed)) set.seed(seed) if(is.na(seed)) set.seed(NULL) sim <- simulateGUI(symbName = symbName, modelYuimaGUI = modelYuimaGUI, xinit = xinit, nsim = nsim, nstep = nstep, simulate.from = simulate.from, simulate.to = simulate.to, saveTraj = saveTraj, space.discretized = space.discretized, method = method, session = session, anchorId = anchorId, true.parameter = true.parameter) if(!is.null(sim)){ if(is.multi==FALSE) yuimaGUIdata$simulation[[symbName]][[ifelse(is.null(length(yuimaGUIdata$simulation[[symbName]])),1,length(yuimaGUIdata$simulation[[symbName]])+1)]] <<- list( model = modelYuimaGUI, trajectory = sim$trajectory, hist = sim$hist, info = list(nsim = nsim, nstep = sim$nstep, simulate.from = sim$simulate.from, simulate.to = sim$simulate.to, delta = sim$delta) ) else yuimaGUIdata$multisimulation[[symbName]][[ifelse(is.null(length(yuimaGUIdata$multisimulation[[symbName]])),1,length(yuimaGUIdata$multisimulation[[symbName]])+1)]] <<- list( model = modelYuimaGUI, trajectory = sim$trajectory, hist = sim$hist, info = list(nsim = nsim, nstep = sim$nstep, simulate.from = sim$simulate.from, simulate.to = sim$simulate.to, delta = sim$delta) ) } } delSimulation <- function(symb, n=1, multi=FALSE){ if(multi==FALSE){ for(i in length(symb):1){ yuimaGUIdata$simulation[[symb[i]]][as.numeric(n[i])] <<- NULL if (length(yuimaGUIdata$simulation[[symb[i]]])==0) yuimaGUIdata$simulation[[symb[i]]] <<- NULL } } else { for(i in length(symb):1){ yuimaGUIdata$multisimulation[[symb[i]]][as.numeric(n[i])] <<- NULL if (length(yuimaGUIdata$multisimulation[[symb[i]]])==0) yuimaGUIdata$multisimulation[[symb[i]]] <<- NULL } } } profit_distribution <- function(nOpt, nAss, type, strike, priceAtMaturity, optMarketPrice, assMarketPrice, percCostAss, minCostAss, lotCostOpt, lotMultiplier, shortCostPerYear, t0=Sys.Date(), maturity){ if (nOpt==0 & nAss==0) return(0) if (type=="call"){ payoff <- pmax(priceAtMaturity-strike,0) return(nOpt*(payoff-optMarketPrice)- nAss*(priceAtMaturity-assMarketPrice)- pmax(nAss*assMarketPrice*percCostAss, minCostAss)*ifelse(nAss!=0,1,0)- pmax(nAss*priceAtMaturity*percCostAss, minCostAss)*ifelse(nAss!=0,1,0)- nOpt/lotMultiplier*lotCostOpt- shortCostPerYear*(nAss*assMarketPrice)*as.numeric(as.Date(maturity)-as.Date(t0))/365 ) } if (type=="put"){ payoff <- pmax(strike-priceAtMaturity,0) return(nOpt*(payoff-optMarketPrice)+ nAss*(priceAtMaturity-assMarketPrice)- pmax(nAss*assMarketPrice*percCostAss, minCostAss)*ifelse(nAss!=0,1,0)- pmax(nAss*priceAtMaturity*percCostAss, minCostAss)*ifelse(nAss!=0,1,0)- nOpt/lotMultiplier*lotCostOpt ) } } addHedging <- function(modelYuimaGUI, symbName, info, xinit, nsim, nstep, simulate.from, simulate.to, session, anchorId){ alertId <- "addHedging_alert" closeAlert(session, alertId) sim <- simulateGUI(symbName = symbName, modelYuimaGUI = modelYuimaGUI, xinit = xinit, simulate.from = simulate.from, simulate.to = simulate.to, nstep = nstep, nsim = nsim, saveTraj = FALSE, space.discretized = FALSE, method = "euler", session = session, anchorId = anchorId, alertId = alertId) if(!is.null(sim)){ today <- simulate.from profits <- profit_distribution(nOpt=1*info$optLotMult, nAss=0, type=info$type, strike=info$strike, priceAtMaturity=sim$hist, optMarketPrice=info$optPrice, assMarketPrice=info$assPrice, percCostAss=info$assPercCost, minCostAss=info$assMinCost, lotCostOpt=info$optLotCost, lotMultiplier=info$optLotMult, shortCostPerYear=info$assRateShortSelling, t0=today, maturity=info$maturity) info$profit <- mean(profits)/(info$optLotMult*info$optPrice+info$optLotCost) info$stdErr <- sd(profits)/sqrt(length(profits))/(info$optLotMult*info$optPrice+info$optLotCost) info$nsim <- nsim info$buy <- ifelse(info$type=="call",NA,0) info$sell <- ifelse(info$type=="put",NA,0) info$LotsToBuy <- 1 info$today <- today yuimaGUIdata$hedging[[length(yuimaGUIdata$hedging)+1]] <<- list( model = modelYuimaGUI, hist = sim$hist, info = info, symb = symbName ) } } delHedging <- function(n){ yuimaGUIdata$hedging <<- yuimaGUIdata$hedging[-n] } MYdist <- function(object, percentage = TRUE){ l <- length(colnames(object)) d <- matrix(ncol = l, nrow = l) f <- function(x, dens){ res <- c() getY <- function(xi){ i <- which(dens$x==xi) if (length(i)!=0) return(dens$y[i]) else { i_x1 <- which.min(abs(dens$x-xi)) i_x2 <- min(i_x1+1,length(dens$x)) return(0.5*(dens$y[i_x1]+dens$y[i_x2])) } } res <- sapply(X = x, FUN = getY) return(res) } withProgress(message = 'Clustering: ', value = 0, { k <- 1 for(i in 1:l){ #delta_i <- as.numeric(abs(mean(diff(index(object)[!is.na(object[,i])]), na.rm = TRUE))) if (percentage == TRUE) data_i <- as.vector(na.omit(Delt(object[,i]))) else data_i <- as.vector(na.omit(diff(object[,i]))) data_i <- data_i[data_i!="Inf"] dens1 <- density(data_i, na.rm = TRUE)#/sqrt(delta_i)+mean(data_i, na.rm = TRUE)*(1/delta_i-1/sqrt(delta_i)), na.rm = TRUE) for(j in i:l) if (i!=j){ incProgress(2/(l*(l-1)), detail = paste(k,"(/", l*(l-1)/2 ,")")) #delta_j <- as.numeric(abs(mean(diff(index(object)[!is.na(object[,j])]), na.rm = TRUE))) if (percentage == TRUE) data_j <- as.vector(na.omit(Delt(object[,j]))) else data_j <- as.vector(na.omit(diff(object[,j]))) data_j <- data_j[data_j!="Inf"] dens2 <- density(data_j, na.rm = TRUE)#/sqrt(delta_j)+mean(data_j, na.rm = TRUE)*(1/delta_j-1/sqrt(delta_j)), na.rm = TRUE) f_dist <- function(x) {0.5*abs(f(x,dens1)-f(x,dens2))} dist <- try(integrate(f_dist, lower = min(dens1$x[1],dens2$x[1]), upper = max(last(dens1$x), last(dens2$x)), subdivisions = 100000, rel.tol = 0.01)) d[j,i] <- min(1, ifelse(class(dist)=="try-error", 1, dist$value)) k <- k + 1 } } }) rownames(d) <- colnames(object) colnames(d) <- colnames(object) return(as.dist(d)) } CPanalysis <- function(x, method = c("KSdiff", "KSperc"), pvalue = 0.01, symb){ if (pvalue > 0.1){ pvalue <- 0.1 warning("pvalue re-defined: 0.1") } if(method=="KSdiff" | method=="KSperc"){ x_incr <- switch (method, "KSdiff" = na.omit(diff(x)), "KSperc" = na.omit(Delt(x))) index_x_incr <- index(x_incr) x_incr_num <- as.numeric(x_incr) tau <- NULL p.value <- NULL getCPoint <- function(n0, nTot){ if(abs(nTot-n0)<10) return() grid <- seq(from = n0, to=(nTot-1), by = as.integer(1+(nTot-n0)/100)) ks<-matrix(nrow = length(grid), ncol = 2, dimnames = list(NULL, c("index", "pvalue"))) j <- 1 for (i in grid){ ks[j,"index"] <- i ks[j, "pvalue"]<- suppressWarnings(ks.test(x_incr_num[n0:i],x_incr_num[(i+1):nTot])$p.value) j <- j+1 } if(min(ks[,"pvalue"], na.rm=TRUE) > pvalue) return() else { new_n0 <- as.integer(ks[which.min(ks[,"pvalue"]), "index"]) env <- environment(getCPoint) assign(x = "tau", value = append(x = get("tau", envir = env), values = index_x_incr[new_n0]), envir = env) assign(x = "p.value", value = append(x = get("p.value", envir = env), values = as.numeric(ks[which(ks[,"index"]==new_n0), "pvalue"])), envir = env) getCPoint(n0 = n0, nTot = new_n0) getCPoint(n0 = new_n0+1, nTot = nTot) } } getCPoint(n0 = 1, nTot = length(x_incr_num)) if (is.null(tau)){ tau <- NA p.value <- NA } return (list(tau=tau,pvalue=p.value, method=method, series = x, symb = symb)) } } addCPoint_distribution <- function(symb, method = c("KSdiff", "KSperc"), pvalue = 0.01){ temp <- try(CPanalysis(x=getData(symb), method = method, pvalue = pvalue, symb = symb)) if (class(temp)!="try-error") { i <- 1 symb_id <- symb repeat { if(symb_id %in% names(yuimaGUIdata$cp)){ symb_id <- paste(symb, i) i <- i+1 } else break } yuimaGUIdata$cp[[symb_id]] <<- temp return(list(error=NULL)) } else return(list(error=symb)) } ###Save all available data saveData <- function() { dataDownload_series <- reactive({ for (symb in names(yuimaGUIdata$series)){ data <- getData(symb) if(is.numeric(index(data))) { if (!exists("data_num", inherits = FALSE)) data_num <- data else data_num <- merge(data_num, data) } else { if (!exists("data_date", inherits = FALSE)) data_date <- data else data_date <- merge(data_date, data) } } if (exists("data_date") & !exists("data_num")) return(as.data.frame(data_date[order(index(data_date)), , drop = FALSE])) if (!exists("data_date") & exists("data_num")) return(as.data.frame(data_num[order(index(data_num)), , drop = FALSE])) if (exists("data_date") & exists("data_num")) return(rbind.fill(as.data.frame(data_num[order(index(data_num)), , drop = FALSE]), as.data.frame(data_date[order(index(data_date)), , drop = FALSE]))) }) downloadHandler( filename = "yuimaGUIdata.txt", content = function(file) { write.table(dataDownload_series(), file, quote = FALSE) } ) } jumps_shortcut <- function(class, jumps){ switch(class, "Diffusion process" = NA, "Fractional process" = NA,"Compound Poisson" = jumps, "COGARCH"=NA, "CARMA" = NA, "Levy process" = jumps) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/functions.R
output$video_intro <- renderUI({ HTML('<iframe width="90%" height="250px" src="https://www.youtube.com/embed/XX_bmCrI_gc?rel=0" frameborder="0" allowfullscreen></iframe>') })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/home/home.R
###Download data and display message observeEvent(input$finDataGo, priority = 1, { if (input$symb!=""){ closeAlert(session, "finDataAlert_err") closeAlert(session, "finDataAlert_warn") closeAlert(session, "finDataAlert_succ") symb <- unlist(strsplit(input$symb, split = "[, ]+" , fixed = FALSE)) err <- c() already_in <- c() withProgress(message = 'Loading: ', value = 0, { for (i in symb){ incProgress(1/length(symb), detail = i) x <- try(window(getSymbols(i, src = input$sources ,auto.assign = FALSE), start = input$dR[1], end = input$dR[2])) if (class(x)[1]=="try-error") err <- cbind(err,i) else { info <- addData(x, typeIndex = "%Y-%m-%d") err <- c(err, info$err) already_in <- c(already_in, info$already_in) } } }) if(!is.null(err)) createAlert(session = session, anchorId = "finDataAlert", alertId = "finDataAlert_err", content = paste("Unable to load following symbols:", paste(err,collapse = " ")), style = "error") if(!is.null(already_in)) createAlert(session = session, anchorId = "finDataAlert", alertId = "finDataAlert_warn", content = paste("WARNING! Following symbols already loaded:", paste(already_in,collapse = " ")), style = "warning") if(is.null(err) & is.null(already_in)) createAlert(session = session, anchorId = "finDataAlert", alertId = "finDataAlert_succ", content = paste("All symbols loaded successfully"), style = "success") } }) ###Display available data output$database1 <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)!=0) return(yuimaGUItable$series) }) ###Interactive range of finDataPlot chart range_finDataPlot <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$finDataPlot_brush)){ range_finDataPlot$x <- c(as.Date(input$finDataPlot_brush$xmin), as.Date(input$finDataPlot_brush$xmax)) range_finDataPlot$y <- c(input$finDataPlot_brush$ymin, input$finDataPlot_brush$ymax) } }) observeEvent(input$finDataPlot_dbclick,{ range_finDataPlot$x <- c(NULL, NULL) range_finDataPlot$y <- c(NULL, NULL) }) ###Display chart of last clicked symbol observeEvent(input$database1_rows_selected, priority = -1, { symb <- yuimaGUItable$series$Symb[tail(input$database1_rows_selected,1)] shinyjs::show("finDataPlot") shinyjs::show("scale_finDataPlot") valid_data <- NULL range_finDataPlot$x <- c(NULL, NULL) output$finDataPlot <- renderPlot({ if (length(yuimaGUItable$series)==0){ shinyjs::hide("finDataPlot") shinyjs::hide("scale_finDataPlot") } else{ if (!(symb %in% as.character(yuimaGUItable$series[,"Symb"]))){ shinyjs::hide("finDataPlot") shinyjs::hide("scale_finDataPlot") } else { data <- window(getData(symb), start = range_finDataPlot$x[1], end = range_finDataPlot$x[2]) if(is.null(valid_data) | length(index(data))>3) valid_data <<- data par(bg="black") plot.zoo(valid_data, main=symb, log=ifelse(input$scale_finDataPlot=="Linear","","y"), xlab="Index", ylab=NA, col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") grid(col="grey") } } }) }) ###Delete Button observeEvent(input$finDataDelete, priority = 1,{ delData(yuimaGUItable$series$Symb[input$database1_rows_selected]) }) ###DeleteAll Button observeEvent(input$finDataDeleteAll, priority = 1,{ delData(yuimaGUItable$series$Symb[input$database1_rows_all]) }) ###Save Button output$finDataSave <- { saveData() }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/load_data/finance.R
###Read file fileUp_O <- reactive({ if (!is.null(input$yourFile$datapath)){ sep <- input$yourFileSep if(input$yourFileSep=="default") sep <- "" skip <- input$yourFileLine-1 if(is.na(skip)) skip <- 0 dec <- input$yourFileDec if(input$yourFileDec=="") dec <- "." if(input$yourFileHeader=="Only rows") z <- read.csv(input$yourFile$datapath ,sep = sep, header = FALSE, row.names = 1, check.names = FALSE, stringsAsFactors = FALSE, dec = dec, na.strings = input$yourFileNA, skip = skip) if(input$yourFileHeader=="Only columns"){ z <- read.csv(input$yourFile$datapath, sep = sep, header = FALSE, check.names = FALSE, stringsAsFactors = FALSE, dec = dec, na.strings = input$yourFileNA, skip = skip) z <- data.frame(t(z), row.names = 1, check.names = FALSE) z <- data.frame(t(z), check.names = FALSE) } if (input$yourFileHeader=="Both") z <- read.csv(input$yourFile$datapath, sep = sep, header = TRUE, check.names = FALSE, stringsAsFactors = FALSE, dec = dec, na.strings = input$yourFileNA, skip = skip) if (input$yourFileHeader=="None") z <- read.csv(input$yourFile$datapath, sep = sep, header = FALSE, check.names = FALSE, stringsAsFactors = FALSE, dec = dec, na.strings = input$yourFileNA, skip = skip) if (input$yourFileHeader=="Default") z <- read.csv(input$yourFile$datapath, sep = sep, check.names = FALSE, stringsAsFactors = FALSE, dec = dec, na.strings = input$yourFileNA, skip = skip) if (input$yourFileHeader=="Only rows" | identical(colnames(z),paste("V",seq(1,length(colnames(z))),sep=""))) colnames(z) <- paste("X",seq(1,length(colnames(z))),"_",make.names(input$yourFile$name),sep="") dec <- isolate({ifelse(input$yourFileDec=="", ".", input$yourFileDec)}) if(dec==".") dec <- "\\." thnd <- input$yourFileThnd if(thnd==".") thnd <- "\\." zz <- data.frame(row.names = rownames(z), x = apply(z, 2, function(x) gsub(pattern = dec, replacement = ".", x = gsub(pattern = thnd, replacement = "", x = as.character(x))))) colnames(zz) <- colnames(z) return(zz) } }) ###Display Index choices: columns of file or transposed file output$yourFileIndex <- renderUI({ temp <- try(colnames(fileUp_O())) if (input$yourFileSwitch==TRUE){ temp <- try(rownames(fileUp_O())) if(class(temp)!="try-error") if (input$yourFileHeader=="Only columns" | identical(temp,paste("V",seq(1,length(temp)),sep=""))) temp <- paste("X",seq(1,length(temp)),"_",make.names(input$yourFile$name),sep="") } if (class(temp)=="try-error") return(selectInput("yourFileIndex",label = "Index", width = "60%", choices = c("Row Headers"="default","Numeric"="numeric"), selected = "default")) if (class(temp)!="try-error") return(selectInput("yourFileIndex",label = "Index", width = "60%", choices = c("Row Headers"="default","Numeric"="numeric",temp), selected = "default")) }) ###File to upload fileUp <- reactive({ if (!is.null(input$yourFile$datapath)){ z <- fileUp_O() if (input$yourFileSwitch==TRUE) { z <- as.data.frame(t(z), check.names = FALSE) if (identical(colnames(z), as.character(seq(1,length(colnames(z)))))) colnames(z) <- paste("X",seq(1,length(colnames(z))),"_",make.names(input$yourFile$name),sep="") } ###Display choices for Index Type and set to "numeric" if Index is "numeric" output$yourFileFUN <- renderUI({ if (!is.null(input$yourFileIndex)){ sel <- "%Y-%m-%d" if (input$yourFileIndex=="numeric" | !all(is.na(as.numeric(as.character(rownames(z))))) ) sel <- "numeric" selectInput("yourFileFUN", label = "Index Format", width = "60%", choices = c("Numeric"="numeric", "Year-Month-Day (yyyy-mm-dd)"="%Y-%m-%d", "Month-Day-Year (mm-dd-yyyy)"="%m-%d-%Y", "Month-Day-Year (mm-dd-yy)"="%m-%d-%y", "Day-Month-Year (dd-mm-yyyy)"="%d-%m-%Y", "Day-Month-Year (dd-mm-yy)"="%d-%m-%y", "Year/Month/Day (yyyy/mm/dd)"="%Y/%m/%d", "Month/Day/Year (mm/dd/yyyy)"="%m/%d/%Y", "Month/Day/Year (mm/dd/yy)"="%m/%d/%y", "Day/Month/Year (dd/mm/yyyy)"="%d/%m/%Y", "Day/Month/Year (dd/mm/yy)"="%d/%m/%y"), selected = sel) } }) if(input$yourFileIndex!="default" & input$yourFileIndex!="numeric") z <- data.frame(z, row.names = which(colnames(z)==input$yourFileIndex), check.names = FALSE) if(input$yourFileIndex=="numeric") z <- data.frame(z, row.names = seq(1,length(rownames(z))), check.names = FALSE) return (z) } }) ###Display Upload Button output$yourFileButton <- renderUI ({ if (!is.null(input$yourFile$datapath)) return(tags$button(type="button", id="yourFileGo", class = "action-button", em("Load data"))) }) observe({ shinyjs::toggle("yourFileButton", condition = "try-error"!=(class(try(fileUp())))) }) ###Display text "Preview" output$yourFilePreviewText <- renderText ({ if (!is.null(input$yourFile$datapath)) return("Preview") }) ###Display Preview of file to upload output$yourFilePreview <- DT::renderDataTable(options=list(scrollX=TRUE, scrollY = 250, scrollCollapse = FALSE, deferRender = TRUE, dom = 'frtiS'), extensions = 'Scroller', selection = "none", rownames = TRUE, { if (!is.null(input$yourFile$datapath)) return (fileUp()) }) ###Upload file observeEvent(input$yourFileGo, priority = 1, { closeAlert(session, "yourDataAlert_err") closeAlert(session, "yourDataAlert_warn") closeAlert(session, "yourDataAlert_succ") info <- addData(fileUp(), typeIndex = input$yourFileFUN) if(!is.null(info$err)) createAlert(session = session, anchorId = "yourDataAlert", alertId = "yourDataAlert_err", content = paste("Unable to load following symbols:", paste(info$err,collapse = " ")), style = "error") if(!is.null(info$already_in)) createAlert(session = session, anchorId = "yourDataAlert", alertId = "yourDataAlert_warn", content = paste("WARNING! Following symbols already loaded:", paste(info$already_in,collapse = " ")), style = "warning") if(is.null(info$err) & is.null(info$already_in)) createAlert(session = session, anchorId = "yourDataAlert", alertId = "yourDataAlert_succ", content = paste("All symbols loaded successfully"), style = "success") }) ###Display data available output$database2 <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)!=0) return (yuimaGUItable$series) }) ###Delete Button observeEvent(input$yourFileDelete, priority = 1,{ delData(yuimaGUItable$series$Symb[input$database2_rows_selected]) }) ###DeleteAll Button observeEvent(input$yourFileDeleteAll, priority = 1,{ delData(yuimaGUItable$series$Symb[input$database2_rows_all]) }) ###Save Button output$yourFileSave <- { saveData() } observe({ shinyjs::toggle("buttons_DataIO_file", condition = length(yuimaGUIdata$series)!=0) shinyjs::toggle("buttons_DataIO_fin", condition = length(yuimaGUIdata$series)!=0) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/load_data/your_file.R
###Display estimated models output$multi_databaseModels <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$multimodel)==0){ NoData <- data.frame("Symb"=NA,"Here will be stored models you estimate in the previous tabs"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$multimodel) }) multi_rowToPrint <- reactiveValues(id = NULL) observe(priority = 1, { multi_rowToPrint$id <<- NULL n <- nrow(yuimaGUItable$multimodel) if (n > 0) { multi_rowToPrint$id <<- n if (!is.null(input$multi_databaseModels_row_last_clicked)) multi_rowToPrint$id <- min(n, input$multi_databaseModels_row_last_clicked) } }) ###Print estimated model in Latex output$multi_estimatedModelsLatex <- renderUI({ if (!is.null(multi_rowToPrint$id)){ id <- rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id] id1 <- unlist(strsplit(id, split = " "))[1] id2 <- as.numeric(unlist(strsplit(id, split = " "))[2]) symbs <- yuimaGUIdata$multimodel[[id1]][[id2]]$info$symb withMathJax(printModelLatex(multi = TRUE, symb = symbs, as.character(yuimaGUItable$multimodel[multi_rowToPrint$id, "Model"]), process = as.character(yuimaGUItable$multimodel[multi_rowToPrint$id, "Class"]), jumps = as.character(yuimaGUItable$multimodel[multi_rowToPrint$id, "Jumps"]))) } }) ###Print Symbol output$multi_SymbolName <- renderText({ if (!is.null(multi_rowToPrint$id)) rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id] }) ###More Info output$multi_text_MoreInfo <- renderUI({ id <- unlist(strsplit(rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id], split = " ")) info <- yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info div( h3(id[1], " - " , info$modName, class = "hModal"), h4( em("series:"), paste(info$symb, collapse = ", "), br(), em("series to log:"), paste(info$toLog, collapse = ", "), br(), em("delta:"), max(info$delta), br(), br(), em("method:"), info$method, br(), em("threshold:"), info$threshold, br(), em("trials:"), info$trials, br(), em("seed:"), info$seed, br(), #REMOVE# em("joint:"), info$joint, br(), #REMOVE# em("aggregation:"), info$aggregation, br(), #REMOVE# em("threshold:"), info$threshold class = "hModal" ), align="center" ) }) output$multi_table_MoreInfo <- renderTable(digits=5, rownames = TRUE, { id <- unlist(strsplit(rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id], split = " ")) info <- yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info if (info$class=="Fractional process") coef <- as.data.frame(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$qmle) else coef <- as.data.frame(t(summary(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$qmle)@coef)) params <- getAllParams(mod = yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model, class = info$class) lower <- data.frame(info$lower) upper <- data.frame(info$upper) fixed <- data.frame(info$fixed) start <- data.frame(info$start) startMin <- data.frame(info$startMin) startMax <- data.frame(info$startMax) if(length(lower)==0) lower[1,params[1]] <- NA if(length(upper)==0) upper[1,params[1]] <- NA #if(length(fixed)==0) fixed[1,params[1]] <- NA if(length(start)==0) start[1,params[1]] <- NA if(length(startMin)==0) startMin[1,params[1]] <- NA if(length(startMax)==0) startMax[1,params[1]] <- NA table <- rbind.fill(coef[,unique(colnames(coef))], #fixed, start, startMin, startMax, lower, upper) rownames(table) <- c("Estimate", "Std. Error", #"fixed", "start", "startMin", "startMax", "lower", "upper") return(t(table)) }) ###Print estimates observe({ if (!is.null(multi_rowToPrint$id)){ symb <- unlist(strsplit(rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id], split = " "))[1] modN <- as.numeric(unlist(strsplit(rownames(yuimaGUItable$multimodel)[multi_rowToPrint$id], split = " "))[2]) if (yuimaGUIdata$multimodel[[symb]][[modN]]$info$class=="Fractional process") table <- yuimaGUIdata$multimodel[[symb]][[modN]]$qmle else table <- t(summary(yuimaGUIdata$multimodel[[symb]][[modN]]$qmle)@coef) outputTable <- changeBase(table = table, yuimaGUI = yuimaGUIdata$multimodel[[symb]][[modN]], newBase = input$multi_baseModels, session = session, choicesUI="multi_baseModels", anchorId = "multi_panel_estimates_alert", alertId = "multi_modelsAlert_conversion") output$multi_estimatedModelsTable <- renderTable(rownames = TRUE, { if (!is.null(multi_rowToPrint$id)) return(outputTable) }) } }) observe({ shinyjs::toggle("multi_estimates_info", condition = !is.null(input$multi_databaseModels_rows_all)) }) observe({ test <- FALSE choices <- NULL if(length(names(yuimaGUIdata$multimodel))!=0) for (i in names(yuimaGUIdata$multimodel)) for (j in 1:length(yuimaGUIdata$multimodel[[i]])) if(yuimaGUIdata$multimodel[[i]][[j]]$info$class %in% c("Diffusion process", "Compound Poisson", "Levy process", "COGARCH")){ test <- TRUE choices <- c(choices, paste(i,j)) } shinyjs::toggle(id = "multi_model_modal_fitting_body", condition = test) shinyjs::toggle(id = "multi_databaseModels_button_showResults", condition = test) output$multi_model_modal_model_id <- renderUI({ if (test==TRUE){ selectInput("multi_model_modal_model_id", label = "Model ID", choices = choices) } }) output$multi_model_modal_series_id <- renderUI({ if (!is.null(input$multi_model_modal_model_id)){ id <- unlist(strsplit(input$multi_model_modal_model_id, split = " " , fixed = FALSE)) symb <- try(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info$symb) choices <- 1:length(symb) names(choices) <- symb if(class(choices)!='try-error') selectInput("multi_model_modal_series_id", label = "Series", choices = choices) } }) }) observe({ if(!is.null(input$multi_model_modal_model_id)) { id <- unlist(strsplit(input$multi_model_modal_model_id, split = " " , fixed = FALSE)) type <- isolate({yuimaGUIdata$multimodel})[[id[1]]][[as.numeric(id[2])]]$info$class shinyjs::toggle(id = "multi_model_modal_plot_intensity", condition = type %in% c("Compound Poisson", "Levy process")) shinyjs::toggle(id = "multi_model_modal_plot_variance", condition = type %in% c("COGARCH")) shinyjs::toggle(id = "multi_model_modal_plot_distr", condition = type %in% c("Diffusion process","Compound Poisson", "Levy process")) shinyjs::toggle(id = "multi_model_modal_plot_test", condition = type %in% c("Diffusion process","Compound Poisson", "Levy process")) } }) observe({ if(!is.null(input$multi_model_modal_model_id)){ id <- unlist(strsplit(input$multi_model_modal_model_id, split = " " , fixed = FALSE)) isolated_yuimaGUIdataModel <- isolate({yuimaGUIdata$multimodel}) if(id[1] %in% names(isolated_yuimaGUIdataModel)) if (length(isolated_yuimaGUIdataModel[[id[1]]])>=as.integer(id[2])){ y <- isolated_yuimaGUIdataModel[[id[1]]][[as.numeric(id[2])]] if (y$info$class=="Diffusion process"){ delta <- y$model@sampling@delta t <- y$model@sampling@grid[[1]][-length(y$model@sampling@grid[[1]])] for (i in 1:length(y$model@[email protected])) { if(i==1) x <- y$model@[email protected][[i]] else x <- merge(x, y$model@[email protected][[i]]) } dx <- diff(x) x <- x[-length(x),] for (i in names(y$qmle@coef)) assign(i, value = as.numeric(y$qmle@coef[i])) mu <- sapply(y$model@model@drift, function(x) eval(x)) sigma <- do.call(rbind, (lapply(y$model@model@diffusion, FUN = function(x) sapply(x, function(y) eval(y))))) sigma_inv <- try(solve(sigma)) if(class(sigma_inv)=="try-error"){ shinyjs::hide("multi_model_modal_plot_distr") output$multi_model_modal_plot_test <- renderUI({ HTML(paste("<div><h2 class='hModal'>Tool not available for this model.<br/>The diffusion matrix is not invertible.</h2></div>")) }) } else { z <- apply(as.matrix((dx-mu*delta)/sqrt(delta)), MARGIN = 1, FUN = function(y) sigma_inv%*%y) if(class(z)=="numeric") z <- t(z) if(!is.null(input$multi_model_modal_series_id)) if(nrow(z)>=input$multi_model_modal_series_id){ z_univ <- data.frame("V1" = as.numeric(z[as.numeric(input$multi_model_modal_series_id),])) shinyjs::show("multi_model_modal_plot_distr") output$multi_model_modal_plot_distr <- renderPlot({ return( ggplot(z_univ, aes(x = V1)) + theme( plot.title = element_text(size=14, face= "bold", hjust = 0.5), axis.title=element_text(size=12), legend.position="none" ) + stat_function(fun = dnorm, args = list(mean = 0, sd = 1), fill = "blue",color = "blue", geom = 'area', alpha = 0.5) + geom_density(alpha = 0.5, fill = "green", color = "green") + xlim(-4, 4) + labs(fill="", title = "Empirical VS Theoretical Distribution", x = "Standardized Increments", y = "Density") ) }) output$multi_model_modal_plot_test <- renderUI({ ksTest <- try(ks.test(x = z_univ$V1, "pnorm")) if(class(ksTest)!="try-error") HTML(paste("<div><h5 class='hModal'>Kolmogorov-Smirnov p-value (the two distributions coincide): ", format(ksTest$p.value, scientific=T, digits = 2), "</h5></div>")) }) } } } # else if (y$info$class=="COGARCH"){ # # dx <- diff(y$model@[email protected][,1]) # v <- sqrt(cogarchNoise(y$model, param = as.list(coef(y$qmle)))[email protected][,"v"]) # v <- v/mean(v)*sd(dx) # z <- data.frame("dx" = dx, "vplus" = v[-1], "vminus" = -v[-1], "time" = index(dx)) # output$multi_model_modal_plot_variance <- renderPlot({ # return( # ggplot(z, aes(x = time)) + # geom_line(aes(y = dx), size = 1, color = "black") + # geom_line(aes(y = vplus), size = 1, color = "green") + # geom_line(aes(y = vminus), size = 1, color = "green") + # scale_color_manual(values=c("black", "green", "green")) + # theme( # plot.title = element_text(size=14, face= "bold", hjust = 0.5), # axis.title=element_text(size=12), # legend.position="none" # ) + # labs(fill="", title = "Empirical VS Estimated Volatility", x = "", y = "Increments") # ) # }) # } # # else if (y$info$class=="Compound Poisson" | y$info$class=="Levy process"){ # if (is.null(y$info$threshold)) threshold <- 0 # else threshold <- ifelse(is.na(y$info$threshold), 0, y$info$threshold) # x <- as.numeric(y$model@[email protected][[1]]) # dx <- diff(x) # dx <- dx[abs(dx)>threshold] # #dx <- dx-sign(dx)*threshold # for (i in names(y$qmle@coef)) assign(i, value = as.numeric(y$qmle@coef[i])) # dx <- data.frame("V1" = dx) # if(y$info$jumps=="Gaussian"){ # output$multi_model_modal_plot_distr <- renderPlot({ # return( # ggplot(dx, aes(x = V1)) + # theme( # plot.title = element_text(size=14, face= "bold", hjust = 0.5), # axis.title=element_text(size=12), # legend.position="none" # ) + # stat_function(fun = dnorm, args = list(mean = mu_jump, sd = sigma_jump), fill = "blue",color = "blue", geom = 'area', alpha = 0.5) + # geom_density(alpha = 0.5, fill = "green", color = "green") + # xlim(-4, 4) + # labs(fill="", title = "Empirical VS Estimated Distribution", x = "Increments", y = "Density") # ) # }) # ksTest <- try(ks.test(x = as.numeric(dx$V1), "pnorm", mean = mu_jump, sd = sigma_jump)) # output$multi_model_modal_plot_test <- renderUI({ # if(class(ksTest)!="try-error") # HTML(paste("<div><h5 class='hModal'>Kolmogorov-Smirnov p-value (the two distributions coincide): ", format(ksTest$p.value, scientific=T, digits = 2), "</h5></div>")) # }) # } # if(y$info$jumps=="Uniform"){ # output$multi_model_modal_plot_distr <- renderPlot({ # return( # ggplot(dx, aes(x = V1)) + # theme( # plot.title = element_text(size=14, face= "bold", hjust = 0.5), # axis.title=element_text(size=12), # legend.position="none" # ) + # stat_function(fun = dunif, args = list(min = a_jump, max = b_jump), fill = "blue",color = "blue", geom = 'area', alpha = 0.5) + # geom_density(alpha = 0.5, fill = "green", color = "green") + # xlim(min(dx$V1),max(dx$V1)) + # labs(fill="", title = "Empirical VS Estimated Distribution", x = "Increments", y = "Density") # ) # }) # ksTest <- try(ks.test(x = as.numeric(dx$V1), "punif", min = a_jump, max = b_jump)) # output$multi_model_modal_plot_test <- renderUI({ # if(class(ksTest)!="try-error") # HTML(paste("<div><h5 class='hModal'>Kolmogorov-Smirnov p-value (the two distributions coincide): ", format(ksTest$p.value, scientific=T, digits = 2), "</h5></div>")) # }) # } # # # delta <- y$model@sampling@delta # jumps <- ifelse(abs(diff(x))>threshold,1,0) # jumps[is.na(jumps)] <- 0 # empirical_Lambda <- cumsum(jumps) # t <- y$model@sampling@grid[[1]][-1] # theory_Lambda <- cumsum(eval(y$model@model@measure$intensity)*rep(delta, length(t))) # Lambda <- data.frame(empirical = empirical_Lambda, theory = theory_Lambda, time = index(y$model@[email protected])[-1]) # output$multi_model_modal_plot_intensity <- renderPlot({ # return( # ggplot(Lambda, aes(x = time)) + # geom_line(aes(y = empirical), size = 1, color = "green") + # geom_line(aes(y = theory), size = 1, color = "blue") + # scale_color_manual(values=c("green", "blue")) + # theme( # plot.title = element_text(size=14, face= "bold", hjust = 0.5), # axis.title=element_text(size=12), # legend.position="none" # ) + # labs(fill="", title = "Empirical VS Estimated Intensity", x = "", y = "Number of Jumps") # ) # # }) # # } } } }) ###Delete Model observeEvent(input$multi_databaseModelsDelete, priority = 1, { if(!is.null(input$multi_databaseModels_rows_selected) & !is.null(input$multi_databaseModels_row_last_clicked)){ if(input$multi_databaseModels_row_last_clicked %in% input$multi_databaseModels_rows_selected){ rowname <- unlist(strsplit(rownames(yuimaGUItable$multimodel)[input$multi_databaseModels_row_last_clicked], split = " " , fixed = FALSE)) delMultiModel(symb=rowname[1], n=rowname[2]) closeAlert(session, alertId = "modelsAlert_conversion") } } }) ###DeleteAll Model observeEvent(input$multi_databaseModelsDeleteAll, priority = 1, { if(!is.null(input$multi_databaseModels_rows_all)){ closeAlert(session, alertId = "modelsAlert_conversion") rowname <- unlist(strsplit(rownames(yuimaGUItable$multimodel)[input$multi_databaseModels_rows_all], split = " " , fixed = FALSE)) delMultiModel(symb=rowname[seq(1,length(rowname),2)], n=rowname[seq(2,length(rowname),2)]) } })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/modeling/multivariate_results.R
###Model Input depending on Class Input output$multi_model <- renderUI({ choices <- as.vector(defaultMultiModels[names(defaultMultiModels)==input$multi_modelClass]) if(input$multi_modelClass!="Fractional process") for(i in names(yuimaGUIdata$usr_multimodel)) if (yuimaGUIdata$usr_multimodel[[i]]$class==input$multi_modelClass) { if(input$multi_modelClass!="Diffusion process") choices <- c(i, choices) else if (length(getAllParams(mod = setModelByName(name = i), class = input$multi_modelClass))!=0) choices <- c(i, choices) } return (selectInput("multi_model",label = "Model Name", choices = choices, multiple = FALSE)) }) output$multi_jumps <- renderUI({ if (input$multi_modelClass=="Compound Poisson") return(selectInput("multi_jumps",label = "Jumps", choices = defaultJumps)) if (input$multi_modelClass=="Levy process"){ jump_choices <- defaultJumps jump_sel <- NULL if(!is.null(input$multi_model)){ if(input$multi_model=="Geometric Brownian Motion with Jumps") jump_sel <- "Gaussian" } return(div( column(6,selectInput("model_levy_intensity", label = "Intensity", choices = c(#"None", "Constant"="lambda"))), column(6,selectInput("multi_jumps",label = "Jumps", choices = jump_choices, selected = jump_sel))) ) } }) output$multi_pq_C <- renderUI({ if (input$multi_modelClass=="CARMA") return(div( column(6,numericInput("AR_C",label = "AR degree (p)", value = 2, min = 1, step = 1)), column(6,numericInput("MA_C",label = "MA degree (q)", value = 1, min = 1, step = 1)) )) if (input$multi_modelClass=="COGARCH") return(div( column(6,numericInput("AR_C",label = "AR degree (p)", value = 1, min = 1, step = 1)), column(6,numericInput("MA_C",label = "MA degree (q)", value = 1, min = 1, step = 1)) )) }) ###Print last selected multi_model in Latex output$multi_PrintModelLatex <- renderUI({ shinyjs::hide("multi_titlePrintModelLatex") if (!is.null(input$multi_model)){ shinyjs::show("multi_titlePrintModelLatex") class <- isolate({input$multi_modelClass}) return(withMathJax(printModelLatex(multi = TRUE, symb = rownames(multi_seriesToEstimate$table), names = input$multi_model, process = class, jumps = jumps_shortcut(class = class, jumps = input$multi_jumps)))) } }) ###Display available data output$multi_database3 <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to multi_model multi_seriesToEstimate <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$multi_buttonSelect_models_Univariate, priority = 1, { multi_seriesToEstimate$table <<- rbind(multi_seriesToEstimate$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$multi_database3_rows_selected]) & !(rownames(yuimaGUItable$series) %in% rownames(multi_seriesToEstimate$table)),]) }) ###SelectAll Button observeEvent(input$multi_buttonSelectAll_models_Univariate, priority = 1, { multi_seriesToEstimate$table <<- rbind(multi_seriesToEstimate$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$multi_database3_rows_all]) & !(rownames(yuimaGUItable$series) %in% rownames(multi_seriesToEstimate$table)),]) }) ###Display Selected Data output$multi_database4 <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (nrow(multi_seriesToEstimate$table)==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (multi_seriesToEstimate$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(multi_seriesToEstimate$table)!=0){ if (length(yuimaGUItable$series)==0) multi_seriesToEstimate$table <<- data.frame() else multi_seriesToEstimate$table <<- multi_seriesToEstimate$table[which(as.character(multi_seriesToEstimate$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$multi_buttonDelete_models_Univariate, priority = 1,{ if (!is.null(input$multi_database4_rows_selected)) multi_seriesToEstimate$table <<- multi_seriesToEstimate$table[-input$multi_database4_rows_selected,] }) ###DeleteAll Button observeEvent(input$multi_buttonDeleteAll_models_Univariate, priority = 1,{ if (!is.null(input$multi_database4_rows_all)) multi_seriesToEstimate$table <<- multi_seriesToEstimate$table[-input$multi_database4_rows_all,] }) ###Interactive range of multi_selectRange chart range_selectRange <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$multi_selectRange_brush) & !is.null(input$multi_plotsRangeSeries)){ data <- getData(input$multi_plotsRangeSeries) test <- (length(index(window(data, start = input$multi_selectRange_brush$xmin, end = input$multi_selectRange_brush$xmax))) > 3) if (test==TRUE){ range_selectRange$x <- c(as.Date(input$multi_selectRange_brush$xmin), as.Date(input$multi_selectRange_brush$xmax)) range_selectRange$y <- c(input$multi_selectRange_brush$ymin, input$multi_selectRange_brush$ymax) } } }) observe({ shinyjs::toggle(id="multi_plotsRangeErrorMessage", condition = nrow(multi_seriesToEstimate$table)==0) shinyjs::toggle(id="multi_plotsRangeAll", condition = nrow(multi_seriesToEstimate$table)!=0) }) ###Display charts: series and its increments observe({ symb <- input$multi_plotsRangeSeries if(!is.null(symb)) if (symb %in% rownames(yuimaGUItable$series)){ data <- getData(symb) incr <- na.omit(Delt(data, type = "arithmetic")) condition <- all(is.finite(incr)) shinyjs::toggle("multi_selectRangeReturns", condition = condition) range_selectRange$x <- NULL range_selectRange$y <- NULL start <- as.character(multi_seriesToEstimate$table[input$multi_plotsRangeSeries,"From"]) end <- as.character(multi_seriesToEstimate$table[input$multi_plotsRangeSeries,"To"]) if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } output$multi_selectRange <- renderPlot({ if ((symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(multi_seriesToEstimate$table)))){ par(bg="black") plot.zoo(window(data, start = range_selectRange$x[1], end = range_selectRange$x[2]), main=symb, xlab="Index", ylab=NA, log=switch(input$multi_scale_selectRange,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(data, start = start, end = end), col = "green") grid(col="grey") } }) output$multi_selectRangeReturns <- renderPlot({ if (symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(multi_seriesToEstimate$table)) & condition){ par(bg="black") plot.zoo( window(incr, start = range_selectRange$x[1], end = range_selectRange$x[2]), main=paste(symb, " - Percentage Increments"), xlab="Index", ylab=NA, log=switch(input$multi_scale_selectRange,"Linear"="","Logarithmic (Y)"="", "Logarithmic (X)"="x", "Logarithmic (XY)"="x"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(incr, start = start, end = end), col = "green") grid(col="grey") } }) } }) output$multi_plotsRangeSeries <- renderUI({ selectInput("multi_plotsRangeSeries", label = "Series", choices = rownames(multi_seriesToEstimate$table), selected = input$multi_plotsRangeSeries) }) ###Choose Range input set to "Select range from charts" if charts have been brushed output$multi_chooseRange <- renderUI({ sel <- "full" if (!is.null(range_selectRange$x)) sel <- "selected" selectInput("multi_chooseRange", label = "Range", choices = c("Full Range" = "full", "Select Range from Charts" = "selected", "Specify Range" = "specify"), selected = sel) }) output$multi_chooseRange_specify <- renderUI({ if(!is.null(input$multi_plotsRangeSeries)) { data <- getData(input$multi_plotsRangeSeries) if(class(index(data))=="numeric") return(div( column(6,numericInput("chooseRange_specify_t0", label = "From", min = start(data), max = end(data), value = start(data))), column(6,numericInput("chooseRange_specify_t1", label = "To", min = start(data), max = end(data), value = end(data))) )) if(class(index(data))=="Date") return(dateRangeInput("chooseRange_specify_date", start = start(data), end = end(data), label = "Specify Range")) } }) observe({ shinyjs::toggle(id = "multi_chooseRange_specify", condition = (input$multi_chooseRange)=="specify") }) ###Function to update data range to use to estimate models updateRange_multi_seriesToEstimate <- function(symb, range = c("full","selected","specify"), type = c("Date", "numeric")){ for (i in symb){ data <- getData(i) if (range == "full"){ levels(multi_seriesToEstimate$table[,"From"]) <- c(levels(multi_seriesToEstimate$table[,"From"]), as.character(start(data))) levels(multi_seriesToEstimate$table[,"To"]) <- c(levels(multi_seriesToEstimate$table[,"To"]), as.character(end(data))) multi_seriesToEstimate$table[i,"From"] <<- as.character(start(data)) multi_seriesToEstimate$table[i,"To"] <<- as.character(end(data)) } if (range == "selected"){ if(!is.null(range_selectRange$x) & class(index(data))==type){ start <- range_selectRange$x[1] end <- range_selectRange$x[2] if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } start <- max(start(data),start) end <- min(end(data), end) levels(multi_seriesToEstimate$table[,"From"]) <- c(levels(multi_seriesToEstimate$table[,"From"]), as.character(start)) levels(multi_seriesToEstimate$table[,"To"]) <- c(levels(multi_seriesToEstimate$table[,"To"]), as.character(end)) multi_seriesToEstimate$table[i,"From"] <<- as.character(start) multi_seriesToEstimate$table[i,"To"] <<- as.character(end) } } if (range == "specify"){ if(class(index(data))==type){ if(class(index(data))=="Date"){ start <- input$chooseRange_specify_date[1] end <- input$chooseRange_specify_date[2] } if(class(index(data))=="numeric"){ start <- input$chooseRange_specify_t0 end <- input$chooseRange_specify_t1 } start <- max(start(data),start) end <- min(end(data), end) levels(multi_seriesToEstimate$table[,"From"]) <- c(levels(multi_seriesToEstimate$table[,"From"]), as.character(start)) levels(multi_seriesToEstimate$table[,"To"]) <- c(levels(multi_seriesToEstimate$table[,"To"]), as.character(end)) multi_seriesToEstimate$table[i,"From"] <<- as.character(start) multi_seriesToEstimate$table[i,"To"] <<- as.character(end) } } } } ###Apply selected range by double click observeEvent(input$multi_selectRange_dbclick, priority = 1, { updateRange_multi_seriesToEstimate(input$multi_plotsRangeSeries, range = "selected", type = class(index(getData(input$multi_plotsRangeSeries)))) }) ###Apply selected range observeEvent(input$multi_buttonApplyRange, priority = 1, { updateRange_multi_seriesToEstimate(input$multi_plotsRangeSeries, range = input$multi_chooseRange, type = class(index(getData(input$multi_plotsRangeSeries)))) }) ###ApplyAll selected range observeEvent(input$multi_buttonApplyAllRange, priority = 1, { updateRange_multi_seriesToEstimate(rownames(multi_seriesToEstimate$table), range = input$multi_chooseRange, type = class(index(getData(input$multi_plotsRangeSeries)))) }) prev_dim <- 0 prev_buttonDelta <- 0 prev_buttonAllDelta <- 0 observe({ class <- isolate({input$multi_modelClass}) for (symb in rownames(multi_seriesToEstimate$table)){ if (is.null(yuimaGUIsettings$delta[[symb]])) { i <- index(getData(symb)) if(is.numeric(i)) yuimaGUIsettings$delta[[symb]] <<- mode(diff(i)) else yuimaGUIsettings$delta[[symb]] <<- mode(diff(i))/100 } if (is.null(yuimaGUIsettings$toLog[[symb]])) yuimaGUIsettings$toLog[[symb]] <<- FALSE } if(!is.null(input$multi_model)) if (class(try(setModelByName(input$multi_model, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = class, jumps = input$multi_jumps), AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA))))!="try-error" & nrow(multi_seriesToEstimate$table)>0){ if (is.null(yuimaGUIsettings$estimation[[input$multi_model]])) yuimaGUIsettings$estimation[[input$multi_model]] <<- list() if (is.null(yuimaGUIsettings$estimation[[input$multi_model]])) yuimaGUIsettings$estimation[[input$multi_model]] <<- list() if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["fixed"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[input$multi_model]][["fixed"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["start"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[input$multi_model]][["start"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["threshold"]])) yuimaGUIsettings$estimation[[input$multi_model]][["threshold"]] <<- setThreshold(class = class, data = data) deltas <- NULL datas <- NULL for (symb in rownames(multi_seriesToEstimate$table)){ deltas <- c(deltas, yuimaGUIsettings$delta[[symb]]) data <- getData(symb) if (yuimaGUIsettings$toLog[[symb]]==TRUE) data <- log(data) if(is.null(datas)) datas <- data else datas <- merge(datas, data) } startMinMax <- defaultBounds(name = input$multi_model, jumps = jumps_shortcut(class = class, jumps = input$multi_jumps), intensity = input$model_levy_intensity, threshold = yuimaGUIsettings$estimation[[input$multi_model]][["threshold"]], AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA), strict = FALSE, data = datas, delta = deltas) upperLower <- defaultBounds(name = input$multi_model, jumps = jumps_shortcut(class = class, jumps = input$multi_jumps), intensity = input$model_levy_intensity, threshold = yuimaGUIsettings$estimation[[input$multi_model]][["threshold"]], AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA), strict = TRUE, data = datas, delta = deltas) if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["startMin"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta | nrow(multi_seriesToEstimate$table)!=prev_dim) yuimaGUIsettings$estimation[[input$multi_model]][["startMin"]] <<- startMinMax$lower if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["startMax"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta | nrow(multi_seriesToEstimate$table)!=prev_dim) yuimaGUIsettings$estimation[[input$multi_model]][["startMax"]] <<- startMinMax$upper if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["upper"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta | nrow(multi_seriesToEstimate$table)!=prev_dim) yuimaGUIsettings$estimation[[input$multi_model]][["upper"]] <<- upperLower$upper if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["lower"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$multi_advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$multi_advancedSettingsButtonApplyAllDelta | nrow(multi_seriesToEstimate$table)!=prev_dim) yuimaGUIsettings$estimation[[input$multi_model]][["lower"]] <<- upperLower$lower if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["method"]])){ if(class=="COGARCH" | class=="CARMA") yuimaGUIsettings$estimation[[input$multi_model]][["method"]] <<- "SANN" else yuimaGUIsettings$estimation[[input$multi_model]][["method"]] <<- "L-BFGS-B" } if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["trials"]])) yuimaGUIsettings$estimation[[input$multi_model]][["trials"]] <<- 1 if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["seed"]])) yuimaGUIsettings$estimation[[input$multi_model]][["seed"]] <<- NA if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["joint"]])) yuimaGUIsettings$estimation[[input$multi_model]][["joint"]] <<- FALSE if (is.null(yuimaGUIsettings$estimation[[input$multi_model]][["aggregation"]])) yuimaGUIsettings$estimation[[input$multi_model]][["aggregation"]] <<- TRUE } prev_dim <<- nrow(multi_seriesToEstimate$table) prev_buttonDelta <<- input$multi_advancedSettingsButtonApplyDelta prev_buttonAllDelta <<- input$multi_advancedSettingsButtonApplyAllDelta }) observe({ valid <- TRUE if (nrow(multi_seriesToEstimate$table)==0 | is.null(input$multi_model)) valid <- FALSE else for(mod in input$multi_model) if (class(try(setModelByName(mod, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$multi_modelClass, jumps = input$multi_jumps), AR_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA))))=="try-error") valid <- FALSE shinyjs::toggle(id="multi_advancedSettingsAll", condition = valid) shinyjs::toggle(id="multi_advancedSettingsErrorMessage", condition = !valid) }) output$multi_advancedSettingsSeries <- renderUI({ if (nrow(multi_seriesToEstimate$table)!=0) selectInput(inputId = "multi_advancedSettingsSeries", label = "Series", choices = rownames(multi_seriesToEstimate$table)) }) output$multi_advancedSettingsDelta <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) return (numericInput("multi_advancedSettingsDelta", label = paste("delta", input$multi_advancedSettingsSeries), value = yuimaGUIsettings$delta[[input$multi_advancedSettingsSeries]], min = 0)) }) output$multi_advancedSettingsToLog <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)){ choices <- FALSE if (all(getData(input$multi_advancedSettingsSeries)>0)) choices <- c(FALSE, TRUE) return (selectInput("multi_advancedSettingsToLog", label = "Convert to log", choices = choices, selected = yuimaGUIsettings$toLog[[input$multi_advancedSettingsSeries]])) } }) output$multi_advancedSettingsModel <- renderUI({ if(!is.null(input$multi_model)) selectInput(inputId = "multi_advancedSettingsModel", label = "Model", choices = input$multi_model) }) output$multi_advancedSettingsParameter <- renderUI({ if (!is.null(input$multi_model)) if (!is.null(input$multi_advancedSettingsModel)){ mod <- setModelByName(input$multi_advancedSettingsModel, dimension = nrow(multi_seriesToEstimate$table), intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$multi_modelClass, jumps = input$multi_jumps), AR_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA)) par <- getAllParams(mod, input$multi_modelClass) selectInput(inputId = "multi_advancedSettingsParameter", label = "Parameter", choices = par) } }) #REMOVE# output$multi_advancedSettingsFixed <- renderUI({ #REMOVE# if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) #REMOVE# numericInput(inputId = "multi_advancedSettingsFixed", label = "fixed", value = ifelse(is.null(yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][[input$multi_advancedSettingsSeries]][["fixed"]][[input$multi_advancedSettingsParameter]]),NA,yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][[input$multi_advancedSettingsSeries]][["fixed"]][[input$multi_advancedSettingsParameter]])) #REMOVE#}) output$multi_advancedSettingsStart <- renderUI({ if (#REMOVE# !is.null(input$multi_advancedSettingsFixed) & !is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) #REMOVE# if (is.na(input$multi_advancedSettingsFixed)) numericInput(inputId = "multi_advancedSettingsStart", label = "start", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["start"]][[input$multi_advancedSettingsParameter]]) }) output$multi_advancedSettingsStartMin <- renderUI({ input$multi_advancedSettingsButtonApplyDelta input$multi_advancedSettingsButtonApplyAllDelta if (#REMOVE# !is.null(input$multi_advancedSettingsFixed) & !is.null(input$multi_advancedSettingsStart) & !is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) if (#REMOVE# is.na(input$multi_advancedSettingsFixed) & is.na(input$multi_advancedSettingsStart)) numericInput(inputId = "multi_advancedSettingsStartMin", label = "start: Min", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["startMin"]][[input$multi_advancedSettingsParameter]]) }) output$multi_advancedSettingsStartMax <- renderUI({ input$multi_advancedSettingsButtonApplyDelta input$multi_advancedSettingsButtonApplyAllDelta if (#REMOVE# !is.null(input$multi_advancedSettingsFixed) & !is.null(input$multi_advancedSettingsStart) & !is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) if (#REMOVE# is.na(input$multi_advancedSettingsFixed) & is.na(input$multi_advancedSettingsStart)) numericInput(inputId = "multi_advancedSettingsStartMax", label = "start: Max", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["startMax"]][[input$multi_advancedSettingsParameter]]) }) output$multi_advancedSettingsLower <- renderUI({ if (#REMOVE# !is.null(input$multi_advancedSettingsFixed) & !is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) #REMOVE# if (is.na(input$multi_advancedSettingsFixed)) if (input$multi_advancedSettingsMethod=="L-BFGS-B" | input$multi_advancedSettingsMethod=="Brent") numericInput("multi_advancedSettingsLower", label = "lower", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["lower"]][[input$multi_advancedSettingsParameter]]) }) output$multi_advancedSettingsUpper <- renderUI({ if (#REMOVE# !is.null(input$multi_advancedSettingsFixed) & !is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsParameter)) #REMOVE# if (is.na(input$multi_advancedSettingsFixed)) if (input$multi_advancedSettingsMethod=="L-BFGS-B" | input$multi_advancedSettingsMethod=="Brent") numericInput("multi_advancedSettingsUpper", label = "upper", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["upper"]][[input$multi_advancedSettingsParameter]]) }) #REMOVE# output$multi_advancedSettingsJoint <- renderUI({ #REMOVE# if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) #REMOVE# selectInput("multi_advancedSettingsJoint", label = "joint", choices = c(FALSE, TRUE), selected = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["joint"]]) #REMOVE# }) output$multi_advancedSettingsMethod <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) selectInput("multi_advancedSettingsMethod", label = "method", choices = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", "Brent"), selected = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["method"]]) }) #REMOVE# output$multi_advancedSettingsAggregation <- renderUI({ #REMOVE# if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) #REMOVE# selectInput("multi_advancedSettingsAggregation", label = "aggregation", choices = c(TRUE, FALSE), selected = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["aggregation"]]) #REMOVE# }) output$multi_advancedSettingsThreshold <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) if(isolate({input$multi_modelClass})=="Levy process") numericInput("multi_advancedSettingsThreshold", label = "threshold", value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["threshold"]]) }) output$multi_advancedSettingsTrials <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries) & !is.null(input$multi_advancedSettingsMethod)) numericInput("multi_advancedSettingsTrials", label = "trials", min = 1, value = ifelse(input$multi_advancedSettingsMethod=="SANN" & yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["method"]]!="SANN",1,yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["trials"]])) }) output$multi_advancedSettingsSeed <- renderUI({ if (!is.null(input$multi_advancedSettingsModel) & !is.null(input$multi_advancedSettingsSeries)) numericInput("multi_advancedSettingsSeed", label = "seed", min = 1, value = yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["seed"]]) }) observeEvent(input$multi_advancedSettingsButtonApplyDelta, { yuimaGUIsettings$delta[[input$multi_advancedSettingsSeries]] <<- input$multi_advancedSettingsDelta yuimaGUIsettings$toLog[[input$multi_advancedSettingsSeries]] <<- input$multi_advancedSettingsToLog }) observeEvent(input$multi_advancedSettingsButtonApplyAllDelta, { for (symb in rownames(multi_seriesToEstimate$table)){ yuimaGUIsettings$delta[[symb]] <<- input$multi_advancedSettingsDelta if (input$multi_advancedSettingsToLog==FALSE) yuimaGUIsettings$toLog[[symb]] <<- input$multi_advancedSettingsToLog else if (all(getData(symb)>0)) yuimaGUIsettings$toLog[[symb]] <<- input$multi_advancedSettingsToLog } }) observeEvent(input$multi_advancedSettingsButtonApplyModel,{ #REMOVE# yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["fixed"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsFixed yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["start"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsStart yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["startMin"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsStartMin yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["startMax"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsStartMax yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["lower"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsLower yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["upper"]][[input$multi_advancedSettingsParameter]] <<- input$multi_advancedSettingsUpper }) observeEvent(input$multi_advancedSettingsButtonApplyGeneral,{ yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["method"]] <<- input$multi_advancedSettingsMethod yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["trials"]] <<- input$multi_advancedSettingsTrials yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["seed"]] <<- input$multi_advancedSettingsSeed #REMOVE# yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["joint"]] <<- input$multi_advancedSettingsJoint #REMOVE# yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["aggregation"]] <<- input$multi_advancedSettingsAggregation yuimaGUIsettings$estimation[[input$multi_advancedSettingsModel]][["threshold"]] <<- input$multi_advancedSettingsThreshold }) observe({ closeAlert(session = session, alertId = "CARMA_COGARCH_err") if(!is.null(input$multi_modelClass)) if(input$multi_modelClass=="CARMA" ) if(!is.null(input$AR_C)) if(!is.null(input$MA_C)) if(!is.na(input$AR_C) & !is.na(input$MA_C)) { if(input$AR_C<=input$MA_C) createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR degree (p) must be greater than MA degree (q)") if(input$AR_C== 0 | input$MA_C==0) createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR and MA degree (p,q) must be positive") } if(!is.null(input$multi_modelClass)) if(input$multi_modelClass=="COGARCH" ) if(!is.null(input$AR_C)) if(!is.null(input$MA_C)) if(!is.na(input$AR_C) & !is.na(input$MA_C)) { if(input$AR_C<input$MA_C) createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR degree (p) must be greater than or equal to MA degree (q)") if(input$AR_C== 0 | input$MA_C==0) createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR and MA degree (p,q) must be positive") } }) ###Estimate models observeEvent(input$multi_EstimateModels,{ closeAlert(session = session, alertId = "modelsErr") valid <- TRUE if(is.null(input$multi_model) | nrow(multi_seriesToEstimate$table)==0) { valid <- FALSE } else if (input$multi_modelClass=="Compound Poisson" & is.null(input$multi_jumps)) { valid <- FALSE } else for(mod in input$multi_model) if (class(try(setModelByName(mod, dimension = nrow(multi_seriesToEstimate$table), intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$multi_modelClass, jumps = input$multi_jumps), AR_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA))))=="try-error") valid <- FALSE if(!valid){ createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "modelsAlert_err", content = "Select some series and (valid) models to estimate", style = "warning") } else { deltas <- NULL; datas <- NULL; toLogs <- NULL for (symb in rownames(multi_seriesToEstimate$table)){ deltas <- c(deltas, yuimaGUIsettings$delta[[symb]]) toLogs <- c(toLogs, yuimaGUIsettings$toLog[[symb]]) data <- getData(symb) start <- as.character(multi_seriesToEstimate$table[symb,"From"]) end <- as.character(multi_seriesToEstimate$table[symb,"To"]) times <- index(data) if (class(times)=="numeric") data <- data[(times >= as.numeric(start)) & (times <= as.numeric(end)), , drop = FALSE] else data <- data[(times >= start) & (times <= end), , drop = FALSE] if(is.null(datas)) datas <- data else datas <- merge(datas, data) } test <- try(setDataGUI(datas, delta = deltas)) if (class(test)=="try-error"){ createAlert(session = session, anchorId = "multi_panel_run_estimation_alert", alertId = "modelsAlert_err", content = "Unable to construct a synchronous grid for the data provided", style = "error") } else { withProgress(message = 'Estimating: ',{ for (modName in input$multi_model){ incProgress(1/(length(input$multi_model)), detail = modName) addModel( modName = modName, multi = TRUE, modClass = input$multi_modelClass, intensity_levy = input$model_levy_intensity, AR_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$multi_modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA), jumps = jumps_shortcut(class = input$multi_modelClass, jumps = input$multi_jumps), symbName = paste(ncol(datas), "Series", sep = ""), data = datas, delta = deltas, toLog = toLogs, start = yuimaGUIsettings$estimation[[modName]][["start"]], startMin = yuimaGUIsettings$estimation[[modName]][["startMin"]], startMax = yuimaGUIsettings$estimation[[modName]][["startMax"]], method=yuimaGUIsettings$estimation[[modName]][["method"]], trials=yuimaGUIsettings$estimation[[modName]][["trials"]], seed = yuimaGUIsettings$estimation[[modName]][["seed"]], fixed = yuimaGUIsettings$estimation[[modName]][["fixed"]], lower = yuimaGUIsettings$estimation[[modName]][["lower"]], upper = yuimaGUIsettings$estimation[[modName]][["upper"]], joint = yuimaGUIsettings$estimation[[modName]][["joint"]], aggregation = yuimaGUIsettings$estimation[[modName]][["aggregation"]], threshold = yuimaGUIsettings$estimation[[modName]][["threshold"]], session = session, anchorId = "multi_panel_estimates_alert", alertId = NULL ) } }) updateTabsetPanel(session = session, inputId = "multi_panel_estimates", selected = "Estimates") } } }) observe({ valid <- TRUE if(is.null(input$multi_model) | nrow(multi_seriesToEstimate$table)==0) valid <- FALSE else if (input$multi_modelClass=="Compound Poisson" & is.null(input$multi_jumps)) valid <- FALSE if(valid) closeAlert(session, alertId = "modelsAlert_err") })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/modeling/multivariate_start_estimation.R
###Display estimated models output$databaseModels <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$model)==0){ NoData <- data.frame("Symb"=NA,"Here will be stored models you estimate in the previous tabs"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$model) }) rowToPrint <- reactiveValues(id = NULL) observe(priority = 1, { rowToPrint$id <<- NULL n <- nrow(yuimaGUItable$model) if (n > 0) { rowToPrint$id <<- n if (!is.null(input$databaseModels_row_last_clicked)) rowToPrint$id <- min(n, input$databaseModels_row_last_clicked) } }) ###Print estimated model in Latex output$estimatedModelsLatex <- renderUI({ if (!is.null(rowToPrint$id)) withMathJax(printModelLatex(as.character(yuimaGUItable$model[rowToPrint$id, "Model"]), process = as.character(yuimaGUItable$model[rowToPrint$id, "Class"]), jumps = as.character(yuimaGUItable$model[rowToPrint$id, "Jumps"]))) }) ###Print Symbol output$SymbolName <- renderText({ if (!is.null(rowToPrint$id)) rownames(yuimaGUItable$model)[rowToPrint$id] }) ###More Info output$text_MoreInfo <- renderUI({ id <- unlist(strsplit(rownames(yuimaGUItable$model)[rowToPrint$id], split = " ")) info <- yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$info div( h3(id[1], " - " , info$modName, class = "hModal"), h4( em("series:"), info$symb, br(), em("series to log:"), info$toLog, br(), em("delta:"), info$delta, br(), br(), em("method:"), info$method, br(), em("threshold:"), info$threshold, br(), em("trials:"), info$trials, br(), em("seed:"), info$seed, br(), #REMOVE# em("joint:"), info$joint, br(), #REMOVE# em("aggregation:"), info$aggregation, br(), #REMOVE# em("threshold:"), info$threshold class = "hModal" ), align="center" ) }) output$table_MoreInfo <- renderTable(digits=5, rownames = TRUE, { id <- unlist(strsplit(rownames(yuimaGUItable$model)[rowToPrint$id], split = " ")) info <- yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$info if (info$class=="Fractional process") coef <- as.data.frame(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$qmle) else coef <- as.data.frame(t(summary(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$qmle)@coef)) params <- getAllParams(mod = yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model, class = info$class) lower <- data.frame(info$lower) upper <- data.frame(info$upper) fixed <- data.frame(info$fixed) start <- data.frame(info$start) startMin <- data.frame(info$startMin) startMax <- data.frame(info$startMax) if(length(lower)==0) lower[1,params[1]] <- NA if(length(upper)==0) upper[1,params[1]] <- NA #if(length(fixed)==0) fixed[1,params[1]] <- NA if(length(start)==0) start[1,params[1]] <- NA if(length(startMin)==0) startMin[1,params[1]] <- NA if(length(startMax)==0) startMax[1,params[1]] <- NA table <- rbind.fill(coef[,unique(colnames(coef))], #fixed, start, startMin, startMax, lower, upper) rownames(table) <- c("Estimate", "Std. Error", #"fixed", "start", "startMin", "startMax", "lower", "upper") return(t(table)) }) ###Print estimates observe({ if (!is.null(rowToPrint$id)){ symb <- unlist(strsplit(rownames(yuimaGUItable$model)[rowToPrint$id], split = " "))[1] modN <- as.numeric(unlist(strsplit(rownames(yuimaGUItable$model)[rowToPrint$id], split = " "))[2]) if (yuimaGUIdata$model[[symb]][[modN]]$info$class=="Fractional process") table <- yuimaGUIdata$model[[symb]][[modN]]$qmle else table <- t(summary(yuimaGUIdata$model[[symb]][[modN]]$qmle)@coef) outputTable <- changeBase(table = table, yuimaGUI = yuimaGUIdata$model[[symb]][[modN]], newBase = input$baseModels, session = session, choicesUI="baseModels", anchorId = "panel_estimates_alert", alertId = "modelsAlert_conversion") output$estimatedModelsTable <- renderTable(rownames = TRUE, { if (!is.null(rowToPrint$id)) return(outputTable) }) } }) observe({ shinyjs::toggle("estimates_info", condition = !is.null(input$databaseModels_rows_all)) }) observe({ test <- FALSE choices <- NULL if(length(names(yuimaGUIdata$model))!=0) for (i in names(yuimaGUIdata$model)) for (j in 1:length(yuimaGUIdata$model[[i]])) if(yuimaGUIdata$model[[i]][[j]]$info$class %in% c("Diffusion process", "Compound Poisson", "Levy process", "COGARCH")){ test <- TRUE choices <- c(choices, paste(i,j)) } shinyjs::toggle(id = "model_modal_fitting_body", condition = test) shinyjs::toggle(id = "databaseModels_button_showResults", condition = test) output$model_modal_model_id <- renderUI({ if (test==TRUE){ selectInput("model_modal_model_id", label = "Model ID", choices = choices) } }) }) observe({ if(!is.null(input$model_modal_model_id)) { id <- unlist(strsplit(input$model_modal_model_id, split = " " , fixed = FALSE)) type <- isolate({yuimaGUIdata$model})[[id[1]]][[as.numeric(id[2])]]$info$class shinyjs::toggle(id = "model_modal_plot_intensity", condition = type %in% c("Compound Poisson", "Levy process")) shinyjs::toggle(id = "model_modal_plot_variance", condition = type %in% c("COGARCH")) shinyjs::toggle(id = "model_modal_plot_distr", condition = type %in% c("Diffusion process","Compound Poisson", "Levy process")) shinyjs::toggle(id = "model_modal_plot_test", condition = type %in% c("Diffusion process","Compound Poisson", "Levy process")) } }) observeEvent(input$model_modal_model_id,{ if(!is.null(input$model_modal_model_id)){ id <- unlist(strsplit(input$model_modal_model_id, split = " " , fixed = FALSE)) isolated_yuimaGUIdataModel <- isolate({yuimaGUIdata$model}) if(id[1] %in% names(isolated_yuimaGUIdataModel)) if (length(isolated_yuimaGUIdataModel[[id[1]]])>=as.integer(id[2])){ y <- isolated_yuimaGUIdataModel[[id[1]]][[as.numeric(id[2])]] if (y$info$class=="Diffusion process"){ delta <- y$model@sampling@delta t <- y$model@sampling@grid[[1]][-length(y$model@sampling@grid[[1]])] x <- as.numeric(y$model@[email protected][[1]]) dx <- diff(x) x <- x[-length(x)] for (i in names(y$qmle@coef)) assign(i, value = as.numeric(y$qmle@coef[i])) z <- (dx-eval(y$model@model@drift)*delta)/(eval(y$model@model@diffusion[[1]])*sqrt(delta)) z <- data.frame("V1" = z) output$model_modal_plot_distr <- renderPlot({ return( ggplot(z, aes(x = V1)) + theme( plot.title = element_text(size=14, face= "bold", hjust = 0.5), axis.title=element_text(size=12), legend.position="none" ) + stat_function(fun = dnorm, args = list(mean = 0, sd = 1), fill = "blue",color = "blue", geom = 'area', alpha = 0.5) + geom_density(alpha = 0.5, fill = "green", color = "green") + xlim(-4, 4) + labs(fill="", title = "Empirical VS Theoretical Distribution", x = "Standardized Increments", y = "Density") ) }) ksTest <- try(ks.test(x = as.numeric(z$V1), "pnorm")) output$model_modal_plot_test <- renderUI({ if(class(ksTest)!="try-error") HTML(paste("<div><h5 class='hModal'>Kolmogorov-Smirnov p-value (the two distributions coincide): ", format(ksTest$p.value, scientific=T, digits = 2), "</h5></div>")) }) } else if (y$info$class=="COGARCH"){ dx <- diff(y$model@[email protected][,1]) v <- sqrt(cogarchNoise(y$model, param = as.list(coef(y$qmle)))[email protected][,"v"]) v <- v/mean(v)*sd(dx) z <- data.frame("dx" = dx, "vplus" = v[-1], "vminus" = -v[-1], "time" = index(dx)) output$model_modal_plot_variance <- renderPlot({ return( ggplot(z, aes(x = time)) + geom_line(aes(y = dx), size = 1, color = "black") + geom_line(aes(y = vplus), size = 1, color = "green") + geom_line(aes(y = vminus), size = 1, color = "green") + scale_color_manual(values=c("black", "green", "green")) + theme( plot.title = element_text(size=14, face= "bold", hjust = 0.5), axis.title=element_text(size=12), legend.position="none" ) + labs(fill="", title = "Empirical VS Estimated Volatility", x = "", y = "Increments") ) }) } else if (y$info$class=="Compound Poisson" | y$info$class=="Levy process"){ if (is.null(y$info$threshold)) threshold <- 0 else threshold <- ifelse(is.na(y$info$threshold), 0, y$info$threshold) x <- as.numeric(y$model@[email protected][[1]]) dx <- diff(x) dx <- dx[abs(dx)>threshold] #dx <- dx-sign(dx)*threshold for (i in names(y$qmle@coef)) assign(i, value = as.numeric(y$qmle@coef[i])) dx <- data.frame("V1" = dx) switch(y$info$jumps, "Gaussian" = { dfun <- dnorm pfun <- "pnorm" args <- list(mean = mu_jump, sd = sigma_jump) }, "Constant" = { dfun <- dconst pfun <- "pconst" args <- list(k = k_jump) pconst <- function(q, k){q>=k} }, "Uniform" = { dfun <- dunif pfun <- "punif" args <- list(min = a_jump, max = b_jump) }, "Inverse Gaussian" = { dfun <- dIG pfun <- "pIG" args <- list(delta = delta_jump, gamma = gamma_jump) }, "Normal Inverse Gaussian" = { dfun <- dNIG.gui pfun <- "pNIG.gui" args <- list(alpha = alpha_jump, beta = beta_jump, delta = delta_jump, mu = mu_jump) }, "Hyperbolic" = { dfun <- dhyp.gui pfun <- "phyp.gui" args <- list(alpha = alpha_jump, beta = beta_jump, delta = delta_jump, mu = mu_jump) }, "Student t" = { dfun <- dt pfun <- "pt" args <- list(df = nu_jump, ncp = mu_jump) }, "Variance Gamma" = { dfun <- dVG.gui pfun <- "pVG.gui" args <- list(lambda = lambda_jump, alpha = alpha_jump, beta = beta_jump, mu = mu_jump) }, "Generalized Hyperbolic" = { dfun <- dghyp.gui pfun <- "pghyp.gui" args <- list(lambda = lambda_jump, alpha = alpha_jump, delta = delta_jump, beta = beta_jump, mu = mu_jump) } ) if(exists('args') & exists('dfun') & exists('pfun')){ output$model_modal_plot_distr <- renderPlot({ return( ggplot(dx, aes(x = V1)) + theme( plot.title = element_text(size=14, face= "bold", hjust = 0.5), axis.title=element_text(size=12), legend.position="none" ) + stat_function(fun = dfun, args = args, fill = "blue",color = "blue", geom = 'area', alpha = 0.5) + geom_density(alpha = 0.5, fill = "green", color = "green") + xlim(-4, 4) + labs(fill="", title = "Empirical VS Estimated Distribution", x = "Increments", y = "Density") ) }) ksTest <- try(do.call(what = 'ks.test', args = append( list(x = as.numeric(dx$V1), y = pfun), lapply(args, FUN = function(x) x)) )) output$model_modal_plot_test <- renderUI({ if(class(ksTest)!="try-error") HTML(paste("<div><h5 class='hModal'>Kolmogorov-Smirnov p-value (the two distributions coincide): ", format(ksTest$p.value, scientific=T, digits = 2), "</h5></div>")) }) } delta <- y$model@sampling@delta jumps <- ifelse(abs(diff(x))>threshold,1,0) jumps[is.na(jumps)] <- 0 empirical_Lambda <- cumsum(jumps) t <- y$model@sampling@grid[[1]][-1] theory_Lambda <- cumsum(eval(y$model@model@measure$intensity)*rep(delta, length(t))) Lambda <- data.frame(empirical = empirical_Lambda, theory = theory_Lambda, time = index(y$model@[email protected])[-1]) output$model_modal_plot_intensity <- renderPlot({ return( ggplot(Lambda, aes(x = time)) + geom_line(aes(y = empirical), size = 1, color = "green") + geom_line(aes(y = theory), size = 1, color = "blue") + scale_color_manual(values=c("green", "blue")) + theme( plot.title = element_text(size=14, face= "bold", hjust = 0.5), axis.title=element_text(size=12), legend.position="none" ) + labs(fill="", title = "Empirical VS Estimated Intensity", x = "", y = "Number of Jumps") ) }) } } } }) ###Delete Model observeEvent(input$databaseModelsDelete, priority = 1, { if(!is.null(input$databaseModels_rows_selected) & !is.null(input$databaseModels_row_last_clicked)){ if(input$databaseModels_row_last_clicked %in% input$databaseModels_rows_selected){ rowname <- unlist(strsplit(rownames(yuimaGUItable$model)[input$databaseModels_row_last_clicked], split = " " , fixed = FALSE)) delModel(symb=rowname[1], n=rowname[2]) closeAlert(session, alertId = "modelsAlert_conversion") } } }) ###DeleteAll Model observeEvent(input$databaseModelsDeleteAll, priority = 1, { if(!is.null(input$databaseModels_rows_all)){ closeAlert(session, alertId = "modelsAlert_conversion") rowname <- unlist(strsplit(rownames(yuimaGUItable$model)[input$databaseModels_rows_all], split = " " , fixed = FALSE)) delModel(symb=rowname[seq(1,length(rowname),2)], n=rowname[seq(2,length(rowname),2)]) } })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/modeling/univariate_results.R
output$usr_modelClass_latex <- renderUI({ if (input$usr_modelClass=="Diffusion process") return(withMathJax("$$dX=a(t,X,\\theta)\\;dt\\;+\\;b(t,X,\\theta)\\;dW$$")) if (input$usr_modelClass=="Fractional process") return(withMathJax("$$dX=a(t,X,\\theta)\\;dt\\;+\\;b(t,X,\\theta)\\;dW^H$$")) if (input$usr_modelClass=="Compound Poisson") return(withMathJax("$$X_t = X_0+\\sum_{i=0}^{N_t} Y_i \\; : \\;\\;\\; N_t \\sim Poi\\Bigl(\\int_0^t \\lambda(t)dt\\Bigl)$$")) if (input$usr_modelClass=="Levy process") return(withMathJax("$$dX_t = \\mu X_t \\; dt + \\sigma X_t \\; dW_t + X_t \\; dZ_t$$")) }) observe({ if (input$usr_modelClass=="Fractional process") createAlert(session = session, anchorId = "panel_set_model_alert", alertId = "alert_fracinfo", style = "info", content = "Fractional process you set here will be available for simulation purposes, but not for estimation.") else closeAlert(session = session, alertId = "alert_fracinfo") }) output$usr_model_coeff <- renderUI({ if (input$usr_modelClass=="Diffusion process") return( div(align="center", column(6, textInput("usr_model_coeff_drift", width = "70%", label = withMathJax("$$a(t,X,\\theta)$$"))), column(6, textInput("usr_model_coeff_diff", width = "70%", label = withMathJax("$$b(t,X,\\theta)$$"))) ) ) if (input$usr_modelClass=="Fractional process") return( div(align="center", column(6, textInput("usr_model_coeff_drift", width = "70%", label = withMathJax("$$a(t,X,\\theta)$$"))), column(6, textInput("usr_model_coeff_diff", width = "70%", label = withMathJax("$$b(t,X,\\theta)$$"))) ) ) if (input$usr_modelClass=="Compound Poisson") return( div(align="center", textInput("usr_model_coeff_intensity", width = "45%", label = withMathJax("$$\\lambda(t)$$")) ) ) if (input$usr_modelClass=="Levy process") return( div(align="center", fluidRow(column(12,textInput("usr_model_coeff_intensity", width = "45%", label = withMathJax("$$\\lambda(t)$$")))), fluidRow( column(6, textInput("usr_model_coeff_drift", width = "70%", label = withMathJax("$$a(t,X,\\theta)$$"))), column(6, textInput("usr_model_coeff_diff", width = "70%", label = withMathJax("$$b(t,X,\\theta)$$"))) ) ) ) }) observeEvent(input$usr_model_button_save, { entered <- FALSE switch(input$usr_modelClass, "Diffusion process" = { if (input$usr_model_name!="" & (input$usr_model_coeff_drift!="" | input$usr_model_coeff_diff!="")){ mod <- try(setModel(drift = tolower(input$usr_model_coeff_drift), diffusion = tolower(input$usr_model_coeff_diff), solve.variable = "x")) if(class(mod)!="try-error") yuimaGUIdata$usr_model[[input$usr_model_name]] <<- list(object=mod, class=input$usr_modelClass) entered <- TRUE } }, "Fractional process" = { if (input$usr_model_name!="" & (input$usr_model_coeff_drift!="" | input$usr_model_coeff_diff!="")){ mod <- try(setModel(drift = tolower(input$usr_model_coeff_drift), diffusion = tolower(input$usr_model_coeff_diff), hurst = NA, solve.variable = "x")) if(class(mod)!="try-error") yuimaGUIdata$usr_model[[input$usr_model_name]] <<- list(object=mod, class=input$usr_modelClass) entered <- TRUE } }, "Compound Poisson" = { if (input$usr_model_name!="" & (input$usr_model_coeff_intensity!="")){ mod <- try(setPoisson(intensity = tolower(input$usr_model_coeff_intensity), df = "", solve.variable = "x")) if(class(mod)!="try-error") yuimaGUIdata$usr_model[[input$usr_model_name]] <<- list(intensity=tolower(input$usr_model_coeff_intensity), class=input$usr_modelClass) entered <- TRUE } }, "Levy process" = { if (input$usr_model_name!=""){ mod <- try(setModel(drift=input$usr_model_coeff_drift, diffusion=input$usr_model_coeff_diff, measure.type = ifelse(is.na(input$usr_model_coeff_intensity), "code", "CP"), measure = list(intensity = input$usr_model_coeff_intensity, df = ""), solve.variable = "x")) if(class(mod)!="try-error") yuimaGUIdata$usr_model[[input$usr_model_name]] <<- list(intensity=tolower(input$usr_model_coeff_intensity), drift = input$usr_model_coeff_drift, diffusion = input$usr_model_coeff_diff, class=input$usr_modelClass) entered <- TRUE } } ) if (entered){ yuimaGUIsettings$estimation[[input$usr_model_name]] <<- list() closeAlert(session, "alert_savingModels") if(class(mod)!="try-error") createAlert(session = session, anchorId = "panel_set_model_alert", alertId = "alert_savingModels", style = "success", content = "Model saved successfully") else createAlert(session = session, anchorId = "panel_set_model_alert", alertId = "alert_savingModels", style = "error", content = "Model is not correctly specified") } }) observe({ for(mod in names(yuimaGUIsettings$estimation)) if (!(mod %in% c(names(yuimaGUIdata$usr_model), names(defaultModels)))) yuimaGUIsettings$estimation[[mod]] <<- list() }) output$usr_model_saved <- renderUI({ if (length(names(yuimaGUIdata$usr_model))!=0) selectInput("usr_model_saved", label = "Saved Models", choices = names(yuimaGUIdata$usr_model), selected = tail(names(yuimaGUIdata$usr_model),1)) }) output$usr_model_saved_latex <- renderUI({ input$usr_model_button_save if (!is.null(input$usr_model_saved)) if (input$usr_model_saved %in% names(yuimaGUIdata$usr_model)) withMathJax(printModelLatex(input$usr_model_saved, process = yuimaGUIdata$usr_model[[input$usr_model_saved]]$class)) }) observeEvent(input$usr_model_button_delete, { for (i in input$usr_model_saved) yuimaGUIdata$usr_model[i] <<- NULL }) observe({ shinyjs::toggle("usr_model_saved_div", condition = length(names(yuimaGUIdata$usr_model))!=0) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/modeling/univariate_set_model.R
###Model Input depending on Class Input output$model <- renderUI({ choices <- as.vector(defaultModels[names(defaultModels)==input$modelClass]) if(input$modelClass!="Fractional process") for(i in names(yuimaGUIdata$usr_model)) if (yuimaGUIdata$usr_model[[i]]$class==input$modelClass) { if(input$modelClass!="Diffusion process") choices <- c(i, choices) else if (length(getAllParams(mod = setModelByName(name = i), class = input$modelClass))!=0) choices <- c(i, choices) } return (selectInput("model",label = "Model Name", choices = choices, multiple = TRUE)) }) output$jumps <- renderUI({ if (input$modelClass=="Compound Poisson") return(selectInput("jumps",label = "Jumps", choices = defaultJumps)) if (input$modelClass=="Levy process"){ jump_choices <- defaultJumps jump_sel <- NULL if(!is.null(input$model)){ if(input$model=="Geometric Brownian Motion with Jumps") jump_sel <- "Gaussian" } return(div( column(6,selectInput("model_levy_intensity", label = "Intensity", choices = c(#"None", "Constant"="lambda"))), column(6,selectInput("jumps",label = "Jumps", choices = jump_choices, selected = jump_sel))) ) } }) output$pq_C <- renderUI({ if (input$modelClass=="CARMA") return(div( column(6,numericInput("AR_C",label = "AR degree (p)", value = 2, min = 1, step = 1)), column(6,numericInput("MA_C",label = "MA degree (q)", value = 1, min = 1, step = 1)) )) if (input$modelClass=="COGARCH") return(div( column(6,numericInput("AR_C",label = "AR degree (p)", value = 1, min = 1, step = 1)), column(6,numericInput("MA_C",label = "MA degree (q)", value = 1, min = 1, step = 1)) )) }) ###Print last selected model in Latex output$PrintModelLatex <- renderUI({ shinyjs::hide("titlePrintModelLatex") if (!is.null(input$model)){ shinyjs::show("titlePrintModelLatex") class <- isolate({input$modelClass}) return(withMathJax(printModelLatex(names = input$model, process = class, jumps = jumps_shortcut(class = class, jumps = input$jumps)))) } }) ###Display available data output$database3 <- DT::renderDataTable(options=list(scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', selection = "multiple", rownames = FALSE,{ if (length(yuimaGUItable$series)==0){ NoData <- data.frame("Symb"=NA,"Please load some data first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$series) }) ###Table of selected data to model seriesToEstimate <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$buttonSelect_models_Univariate, priority = 1, { seriesToEstimate$table <<- rbind(seriesToEstimate$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$database3_rows_selected]) & !(rownames(yuimaGUItable$series) %in% rownames(seriesToEstimate$table)),]) }) ###SelectAll Button observeEvent(input$buttonSelectAll_models_Univariate, priority = 1, { seriesToEstimate$table <<- rbind(seriesToEstimate$table, yuimaGUItable$series[(rownames(yuimaGUItable$series) %in% rownames(yuimaGUItable$series)[input$database3_rows_all]) & !(rownames(yuimaGUItable$series) %in% rownames(seriesToEstimate$table)),]) }) ###Display Selected Data output$database4 <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = FALSE, selection = "multiple",{ if (nrow(seriesToEstimate$table)==0){ NoData <- data.frame("Symb"=NA,"Select from table beside"=NA, check.names = FALSE) return(NoData[-1,]) } return (seriesToEstimate$table) }) ###Control selected data to be in yuimaGUIdata$series observe({ if(length(seriesToEstimate$table)!=0){ if (length(yuimaGUItable$series)==0) seriesToEstimate$table <<- data.frame() else seriesToEstimate$table <<- seriesToEstimate$table[which(as.character(seriesToEstimate$table[,"Symb"]) %in% as.character(yuimaGUItable$series[,"Symb"])),] } }) ###Delete Button observeEvent(input$buttonDelete_models_Univariate, priority = 1,{ if (!is.null(input$database4_rows_selected)) seriesToEstimate$table <<- seriesToEstimate$table[-input$database4_rows_selected,] }) ###DeleteAll Button observeEvent(input$buttonDeleteAll_models_Univariate, priority = 1,{ if (!is.null(input$database4_rows_all)) seriesToEstimate$table <<- seriesToEstimate$table[-input$database4_rows_all,] }) ###Interactive range of selectRange chart range_selectRange <- reactiveValues(x=NULL, y=NULL) observe({ if (!is.null(input$selectRange_brush) & !is.null(input$plotsRangeSeries)){ data <- getData(input$plotsRangeSeries) test <- (length(index(window(data, start = input$selectRange_brush$xmin, end = input$selectRange_brush$xmax))) > 3) if (test==TRUE){ range_selectRange$x <- c(as.Date(input$selectRange_brush$xmin), as.Date(input$selectRange_brush$xmax)) range_selectRange$y <- c(input$selectRange_brush$ymin, input$selectRange_brush$ymax) } } }) observe({ shinyjs::toggle(id="plotsRangeErrorMessage", condition = nrow(seriesToEstimate$table)==0) shinyjs::toggle(id="plotsRangeAll", condition = nrow(seriesToEstimate$table)!=0) }) ###Display charts: series and its increments observe({ symb <- input$plotsRangeSeries if(!is.null(symb)) if (symb %in% rownames(yuimaGUItable$series)){ data <- getData(symb) incr <- na.omit(Delt(data, type = "arithmetic")) condition <- all(is.finite(incr)) shinyjs::toggle("selectRangeReturns", condition = condition) range_selectRange$x <- NULL range_selectRange$y <- NULL start <- as.character(seriesToEstimate$table[input$plotsRangeSeries,"From"]) end <- as.character(seriesToEstimate$table[input$plotsRangeSeries,"To"]) if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } output$selectRange <- renderPlot({ if ((symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(seriesToEstimate$table)))){ par(bg="black") plot.zoo(window(data, start = range_selectRange$x[1], end = range_selectRange$x[2]), main=symb, xlab="Index", ylab=NA, log=switch(input$scale_selectRange,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(data, start = start, end = end), col = "green") grid(col="grey") } }) output$selectRangeReturns <- renderPlot({ if (symb %in% rownames(yuimaGUItable$series) & (symb %in% rownames(seriesToEstimate$table)) & condition){ par(bg="black") plot.zoo( window(incr, start = range_selectRange$x[1], end = range_selectRange$x[2]), main=paste(symb, " - Percentage Increments"), xlab="Index", ylab=NA, log=switch(input$scale_selectRange,"Linear"="","Logarithmic (Y)"="", "Logarithmic (X)"="x", "Logarithmic (XY)"="x"), col="grey", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(window(incr, start = start, end = end), col = "green") grid(col="grey") } }) } }) output$plotsRangeSeries <- renderUI({ selectInput("plotsRangeSeries", label = "Series", choices = rownames(seriesToEstimate$table), selected = input$plotsRangeSeries) }) ###Choose Range input set to "Select range from charts" if charts have been brushed output$chooseRange <- renderUI({ sel <- "full" if (!is.null(range_selectRange$x)) sel <- "selected" selectInput("chooseRange", label = "Range", choices = c("Full Range" = "full", "Select Range from Charts" = "selected", "Specify Range" = "specify"), selected = sel) }) output$chooseRange_specify <- renderUI({ if(!is.null(input$plotsRangeSeries)) { data <- getData(input$plotsRangeSeries) if(class(index(data))=="numeric") return(div( column(6,numericInput("chooseRange_specify_t0", label = "From", min = start(data), max = end(data), value = start(data))), column(6,numericInput("chooseRange_specify_t1", label = "To", min = start(data), max = end(data), value = end(data))) )) if(class(index(data))=="Date") return(dateRangeInput("chooseRange_specify_date", start = start(data), end = end(data), label = "Specify Range")) } }) observe({ shinyjs::toggle(id = "chooseRange_specify", condition = (input$chooseRange)=="specify") }) ###Function to update data range to use to estimate models updateRange_seriesToEstimate <- function(symb, range = c("full","selected","specify"), type = c("Date", "numeric")){ for (i in symb){ data <- getData(i) if (range == "full"){ levels(seriesToEstimate$table[,"From"]) <- c(levels(seriesToEstimate$table[,"From"]), as.character(start(data))) levels(seriesToEstimate$table[,"To"]) <- c(levels(seriesToEstimate$table[,"To"]), as.character(end(data))) seriesToEstimate$table[i,"From"] <<- as.character(start(data)) seriesToEstimate$table[i,"To"] <<- as.character(end(data)) } if (range == "selected"){ if(!is.null(range_selectRange$x) & class(index(data))==type){ start <- range_selectRange$x[1] end <- range_selectRange$x[2] if(class(index(data))=="numeric"){ start <- as.numeric(start) end <- as.numeric(end) } start <- max(start(data),start) end <- min(end(data), end) levels(seriesToEstimate$table[,"From"]) <- c(levels(seriesToEstimate$table[,"From"]), as.character(start)) levels(seriesToEstimate$table[,"To"]) <- c(levels(seriesToEstimate$table[,"To"]), as.character(end)) seriesToEstimate$table[i,"From"] <<- as.character(start) seriesToEstimate$table[i,"To"] <<- as.character(end) } } if (range == "specify"){ if(class(index(data))==type){ if(class(index(data))=="Date"){ start <- input$chooseRange_specify_date[1] end <- input$chooseRange_specify_date[2] } if(class(index(data))=="numeric"){ start <- input$chooseRange_specify_t0 end <- input$chooseRange_specify_t1 } start <- max(start(data),start) end <- min(end(data), end) levels(seriesToEstimate$table[,"From"]) <- c(levels(seriesToEstimate$table[,"From"]), as.character(start)) levels(seriesToEstimate$table[,"To"]) <- c(levels(seriesToEstimate$table[,"To"]), as.character(end)) seriesToEstimate$table[i,"From"] <<- as.character(start) seriesToEstimate$table[i,"To"] <<- as.character(end) } } } } ###Apply selected range by double click observeEvent(input$selectRange_dbclick, priority = 1, { updateRange_seriesToEstimate(input$plotsRangeSeries, range = "selected", type = class(index(getData(input$plotsRangeSeries)))) }) ###Apply selected range observeEvent(input$buttonApplyRange, priority = 1, { updateRange_seriesToEstimate(input$plotsRangeSeries, range = input$chooseRange, type = class(index(getData(input$plotsRangeSeries)))) }) ###ApplyAll selected range observeEvent(input$buttonApplyAllRange, priority = 1, { updateRange_seriesToEstimate(rownames(seriesToEstimate$table), range = input$chooseRange, type = class(index(getData(input$plotsRangeSeries)))) }) prev_buttonDelta <- 0 prev_buttonAllDelta <- 0 observe({ class <- isolate({input$modelClass}) for (symb in rownames(seriesToEstimate$table)){ if (is.null(yuimaGUIsettings$delta[[symb]])) { i <- index(getData(symb)) if(is.numeric(i)) yuimaGUIsettings$delta[[symb]] <<- mode(diff(i)) else yuimaGUIsettings$delta[[symb]] <<- 0.01 } if (is.null(yuimaGUIsettings$toLog[[symb]])) yuimaGUIsettings$toLog[[symb]] <<- FALSE data <- getData(symb) if (yuimaGUIsettings$toLog[[symb]]==TRUE) data <- log(data) for (modName in input$model){ if (class(try(setModelByName(modName, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = class, jumps = input$jumps), AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA))))!="try-error"){ if (is.null(yuimaGUIsettings$estimation[[modName]])) yuimaGUIsettings$estimation[[modName]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]])) yuimaGUIsettings$estimation[[modName]][[symb]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["start"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["start"]] <<- list() if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]] <<- setThreshold(class = class, data = data) startMinMax <- defaultBounds(name = modName, jumps = jumps_shortcut(class = class, jumps = input$jumps), intensity = input$model_levy_intensity, threshold = yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]], AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA), strict = FALSE, data = data, delta = yuimaGUIsettings$delta[[symb]]) upperLower <- defaultBounds(name = modName, jumps = jumps_shortcut(class = class, jumps = input$jumps), intensity = input$model_levy_intensity, threshold = yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]], AR_C = ifelse(class %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(class %in% c("CARMA","COGARCH"), input$MA_C, NA), strict = TRUE, data = data, delta = yuimaGUIsettings$delta[[symb]]) if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]] <<- startMinMax$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]] <<- startMinMax$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]] <<- upperLower$upper if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]]) | !(class %in% c("Diffusion process", "Fractional process")) | prev_buttonDelta!=input$advancedSettingsButtonApplyDelta | prev_buttonAllDelta!=input$advancedSettingsButtonApplyAllDelta) yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]] <<- upperLower$lower if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["method"]])){ if(class=="COGARCH" | class=="CARMA") yuimaGUIsettings$estimation[[modName]][[symb]][["method"]] <<- "SANN" else yuimaGUIsettings$estimation[[modName]][[symb]][["method"]] <<- "L-BFGS-B" } if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]] <<- 1 if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]] <<- NA if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]] <<- FALSE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]] <<- TRUE if (is.null(yuimaGUIsettings$estimation[[modName]][[symb]][["timeout"]])) yuimaGUIsettings$estimation[[modName]][[symb]][["timeout"]] <<- Inf } } } prev_buttonDelta <<- input$advancedSettingsButtonApplyDelta prev_buttonAllDelta <<- input$advancedSettingsButtonApplyAllDelta }) observe({ valid <- TRUE if (nrow(seriesToEstimate$table)==0 | is.null(input$model)) valid <- FALSE else for(mod in input$model) if (class(try(setModelByName(mod, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$modelClass, jumps = input$jumps), AR_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA))))=="try-error") valid <- FALSE shinyjs::toggle(id="advancedSettingsAll", condition = valid) shinyjs::toggle(id="advancedSettingsErrorMessage", condition = !valid) }) output$advancedSettingsSeries <- renderUI({ if (nrow(seriesToEstimate$table)!=0) selectInput(inputId = "advancedSettingsSeries", label = "Series", choices = rownames(seriesToEstimate$table)) }) output$advancedSettingsDelta <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) return (numericInput("advancedSettingsDelta", label = paste("delta", input$advancedSettingsSeries), value = yuimaGUIsettings$delta[[input$advancedSettingsSeries]], min = 0)) }) output$advancedSettingsToLog <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)){ choices <- FALSE if (all(getData(input$advancedSettingsSeries)>0)) choices <- c(FALSE, TRUE) return (selectInput("advancedSettingsToLog", label = "Convert to log", choices = choices, selected = yuimaGUIsettings$toLog[[input$advancedSettingsSeries]])) } }) output$advancedSettingsModel <- renderUI({ if(!is.null(input$model)) selectInput(inputId = "advancedSettingsModel", label = "Model", choices = input$model) }) output$advancedSettingsParameter <- renderUI({ if (!is.null(input$model)) if (!is.null(input$advancedSettingsModel)){ mod <- setModelByName(input$advancedSettingsModel, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$modelClass, jumps = input$jumps), AR_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA)) par <- getAllParams(mod, input$modelClass) selectInput(inputId = "advancedSettingsParameter", label = "Parameter", choices = par) } }) #REMOVE# output$advancedSettingsFixed <- renderUI({ #REMOVE# if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) #REMOVE# numericInput(inputId = "advancedSettingsFixed", label = "fixed", value = ifelse(is.null(yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["fixed"]][[input$advancedSettingsParameter]]),NA,yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["fixed"]][[input$advancedSettingsParameter]])) #REMOVE#}) output$advancedSettingsStart <- renderUI({ if (#REMOVE# !is.null(input$advancedSettingsFixed) & !is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) #REMOVE# if (is.na(input$advancedSettingsFixed)) numericInput(inputId = "advancedSettingsStart", label = "start", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["start"]][[input$advancedSettingsParameter]]) }) output$advancedSettingsStartMin <- renderUI({ input$advancedSettingsButtonApplyDelta input$advancedSettingsButtonApplyAllDelta if (#REMOVE# !is.null(input$advancedSettingsFixed) & !is.null(input$advancedSettingsStart) & !is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) if (#REMOVE# is.na(input$advancedSettingsFixed) & is.na(input$advancedSettingsStart)) numericInput(inputId = "advancedSettingsStartMin", label = "start: Min", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["startMin"]][[input$advancedSettingsParameter]]) }) output$advancedSettingsStartMax <- renderUI({ input$advancedSettingsButtonApplyDelta input$advancedSettingsButtonApplyAllDelta if (#REMOVE# !is.null(input$advancedSettingsFixed) & !is.null(input$advancedSettingsStart) & !is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) if (#REMOVE# is.na(input$advancedSettingsFixed) & is.na(input$advancedSettingsStart)) numericInput(inputId = "advancedSettingsStartMax", label = "start: Max", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["startMax"]][[input$advancedSettingsParameter]]) }) output$advancedSettingsLower <- renderUI({ if (#REMOVE# !is.null(input$advancedSettingsFixed) & !is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) #REMOVE# if (is.na(input$advancedSettingsFixed)) if (input$advancedSettingsMethod=="L-BFGS-B" | input$advancedSettingsMethod=="Brent") numericInput("advancedSettingsLower", label = "lower", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["lower"]][[input$advancedSettingsParameter]]) }) output$advancedSettingsUpper <- renderUI({ if (#REMOVE# !is.null(input$advancedSettingsFixed) & !is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsParameter)) #REMOVE# if (is.na(input$advancedSettingsFixed)) if (input$advancedSettingsMethod=="L-BFGS-B" | input$advancedSettingsMethod=="Brent") numericInput("advancedSettingsUpper", label = "upper", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["upper"]][[input$advancedSettingsParameter]]) }) #REMOVE# output$advancedSettingsJoint <- renderUI({ #REMOVE# if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) #REMOVE# selectInput("advancedSettingsJoint", label = "joint", choices = c(FALSE, TRUE), selected = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["joint"]]) #REMOVE# }) output$advancedSettingsMethod <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) selectInput("advancedSettingsMethod", label = "method", choices = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", "Brent"), selected = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["method"]]) }) #REMOVE# output$advancedSettingsAggregation <- renderUI({ #REMOVE# if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) #REMOVE# selectInput("advancedSettingsAggregation", label = "aggregation", choices = c(TRUE, FALSE), selected = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["aggregation"]]) #REMOVE# }) output$advancedSettingsThreshold <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) if(isolate({input$modelClass})=="Levy process") numericInput("advancedSettingsThreshold", label = "threshold", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["threshold"]]) }) output$advancedSettingsTrials <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries) & !is.null(input$advancedSettingsMethod)) numericInput("advancedSettingsTrials", label = "trials", min = 1, value = ifelse(input$advancedSettingsMethod=="SANN" & yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["method"]]!="SANN",1,yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["trials"]])) }) output$advancedSettingsSeed <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) numericInput("advancedSettingsSeed", label = "seed", min = 1, value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["seed"]]) }) output$advancedSettingsTimeout <- renderUI({ if (!is.null(input$advancedSettingsModel) & !is.null(input$advancedSettingsSeries)) numericInput("advancedSettingsTimeout", label = "timeout (s)", value = yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["timeout"]]) }) observeEvent(input$advancedSettingsButtonApplyDelta, { yuimaGUIsettings$delta[[input$advancedSettingsSeries]] <<- input$advancedSettingsDelta yuimaGUIsettings$toLog[[input$advancedSettingsSeries]] <<- input$advancedSettingsToLog }) observeEvent(input$advancedSettingsButtonApplyAllDelta, { for (symb in rownames(seriesToEstimate$table)){ yuimaGUIsettings$delta[[symb]] <<- input$advancedSettingsDelta if (input$advancedSettingsToLog==FALSE) yuimaGUIsettings$toLog[[symb]] <<- input$advancedSettingsToLog else if (all(getData(symb)>0)) yuimaGUIsettings$toLog[[symb]] <<- input$advancedSettingsToLog } }) observeEvent(input$advancedSettingsButtonApplyModel,{ #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["fixed"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsFixed yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["start"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStart yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["startMin"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStartMin yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["startMax"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStartMax yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["lower"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsLower yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["upper"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsUpper }) observeEvent(input$advancedSettingsButtonApplyAllModel,{ for (symb in rownames(seriesToEstimate$table)){ #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["fixed"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsFixed yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["start"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStart yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["startMin"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStartMin yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["startMax"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsStartMax yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["lower"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsLower yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["upper"]][[input$advancedSettingsParameter]] <<- input$advancedSettingsUpper } }) observeEvent(input$advancedSettingsButtonApplyGeneral,{ yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["method"]] <<- input$advancedSettingsMethod yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["trials"]] <<- input$advancedSettingsTrials yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["seed"]] <<- input$advancedSettingsSeed #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["joint"]] <<- input$advancedSettingsJoint #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["aggregation"]] <<- input$advancedSettingsAggregation yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["threshold"]] <<- input$advancedSettingsThreshold yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[input$advancedSettingsSeries]][["timeout"]] <<- input$advancedSettingsTimeout }) observeEvent(input$advancedSettingsButtonApplyAllModelGeneral,{ for (symb in rownames(seriesToEstimate$table)){ yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["method"]] <<- input$advancedSettingsMethod yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["trials"]] <<- input$advancedSettingsTrials yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["seed"]] <<- input$advancedSettingsSeed #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["joint"]] <<- input$advancedSettingsJoint #REMOVE# yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["aggregation"]] <<- input$advancedSettingsAggregation yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["threshold"]] <<- input$advancedSettingsThreshold yuimaGUIsettings$estimation[[input$advancedSettingsModel]][[symb]][["timeout"]] <<- input$advancedSettingsTimeout } }) observeEvent(input$advancedSettingsButtonApplyAllGeneral,{ for (mod in input$model){ for (symb in rownames(seriesToEstimate$table)){ yuimaGUIsettings$estimation[[mod]][[symb]][["method"]] <<- input$advancedSettingsMethod yuimaGUIsettings$estimation[[mod]][[symb]][["trials"]] <<- input$advancedSettingsTrials yuimaGUIsettings$estimation[[mod]][[symb]][["seed"]] <<- input$advancedSettingsSeed #REMOVE# yuimaGUIsettings$estimation[[mod]][[symb]][["joint"]] <<- input$advancedSettingsJoint #REMOVE# yuimaGUIsettings$estimation[[mod]][[symb]][["aggregation"]] <<- input$advancedSettingsAggregation yuimaGUIsettings$estimation[[mod]][[symb]][["threshold"]] <<- input$advancedSettingsThreshold yuimaGUIsettings$estimation[[mod]][[symb]][["timeout"]] <<- input$advancedSettingsTimeout } } }) observe({ closeAlert(session = session, alertId = "CARMA_COGARCH_err") if(!is.null(input$modelClass)) if(input$modelClass=="CARMA" ) if(!is.null(input$AR_C)) if(!is.null(input$MA_C)) if(!is.na(input$AR_C) & !is.na(input$MA_C)) { if(input$AR_C<=input$MA_C) createAlert(session = session, anchorId = "panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR degree (p) must be greater than MA degree (q)") if(input$AR_C== 0 | input$MA_C==0) createAlert(session = session, anchorId = "panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR and MA degree (p,q) must be positive") } if(!is.null(input$modelClass)) if(input$modelClass=="COGARCH" ) if(!is.null(input$AR_C)) if(!is.null(input$MA_C)) if(!is.na(input$AR_C) & !is.na(input$MA_C)) { if(input$AR_C<input$MA_C) createAlert(session = session, anchorId = "panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR degree (p) must be greater than or equal to MA degree (q)") if(input$AR_C== 0 | input$MA_C==0) createAlert(session = session, anchorId = "panel_run_estimation_alert", alertId = "CARMA_COGARCH_err", style = "error", content = "AR and MA degree (p,q) must be positive") } }) ###Estimate models observeEvent(input$EstimateModels,{ closeAlert(session = session, alertId = "modelsErr") valid <- TRUE if(is.null(input$model) | nrow(seriesToEstimate$table)==0) valid <- FALSE else if (input$modelClass=="Compound Poisson" & is.null(input$jumps)) valid <- FALSE else for(mod in input$model) if (class(try(setModelByName(mod, intensity = input$model_levy_intensity, jumps = jumps_shortcut(class = input$modelClass, jumps = input$jumps), AR_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA))))=="try-error") valid <- FALSE if(!valid){ createAlert(session = session, anchorId = "panel_run_estimation_alert", alertId = "modelsAlert_err", content = "Select some series and (valid) models to estimate", style = "warning") } if(valid){ withProgress(message = 'Estimating: ',{ for (modName in input$model){ for (i in rownames(seriesToEstimate$table)){ symb <- as.character(seriesToEstimate$table[i,"Symb"]) incProgress(1/(length(input$model)*nrow(seriesToEstimate$table)), detail = paste(symb,"-",modName)) data <- getData(symb) start <- as.character(seriesToEstimate$table[i,"From"]) end <- as.character(seriesToEstimate$table[i,"To"]) times <- index(data) if (class(times)=="numeric") data <- data[(times >= as.numeric(start)) & (times <= as.numeric(end)), , drop = FALSE] else data <- data[(times >= start) & (times <= end), , drop = FALSE] addModel( timeout = ifelse(is.na(yuimaGUIsettings$estimation[[modName]][[symb]][["timeout"]]), Inf, yuimaGUIsettings$estimation[[modName]][[symb]][["timeout"]]), modName = modName, modClass = input$modelClass, intensity_levy = input$model_levy_intensity, AR_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$AR_C, NA), MA_C = ifelse(input$modelClass %in% c("CARMA","COGARCH"), input$MA_C, NA), jumps = jumps_shortcut(class = input$modelClass, jumps = input$jumps), symbName = symb, data = data, delta = yuimaGUIsettings$delta[[symb]], toLog = yuimaGUIsettings$toLog[[symb]], start = yuimaGUIsettings$estimation[[modName]][[symb]][["start"]], startMin = yuimaGUIsettings$estimation[[modName]][[symb]][["startMin"]], startMax = yuimaGUIsettings$estimation[[modName]][[symb]][["startMax"]], method=yuimaGUIsettings$estimation[[modName]][[symb]][["method"]], trials=yuimaGUIsettings$estimation[[modName]][[symb]][["trials"]], seed = yuimaGUIsettings$estimation[[modName]][[symb]][["seed"]], fixed = yuimaGUIsettings$estimation[[modName]][[symb]][["fixed"]], lower = yuimaGUIsettings$estimation[[modName]][[symb]][["lower"]], upper = yuimaGUIsettings$estimation[[modName]][[symb]][["upper"]], joint = yuimaGUIsettings$estimation[[modName]][[symb]][["joint"]], aggregation = yuimaGUIsettings$estimation[[modName]][[symb]][["aggregation"]], threshold = yuimaGUIsettings$estimation[[modName]][[symb]][["threshold"]], session = session, anchorId = "panel_estimates_alert", alertId = NULL ) } } }) updateTabsetPanel(session = session, inputId = "panel_estimates", selected = "Estimates") } }) observe({ valid <- TRUE if(is.null(input$model) | nrow(seriesToEstimate$table)==0) valid <- FALSE else if (input$modelClass=="Compound Poisson" & is.null(input$jumps)) valid <- FALSE if(valid) closeAlert(session, alertId = "modelsAlert_err") })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/modeling/univariate_start_estimation.R
#shinyapp web app if(!exists("yuimaGUIdata")) yuimaGUIdata <- reactiveValues(series=list(), model=list(), multimodel=list(), usr_model = list(), usr_multimodel = list(), simulation=list(), multisimulation=list(), usr_simulation = list(), usr_multisimulation = list(), cp=list(), cpYuima=list(), llag = list(), cluster = list(), hedging = list()) yuimaGUItable <- reactiveValues(series=data.frame(), model=data.frame(), multimodel=data.frame(), simulation=data.frame(), multisimulation=data.frame(), hedging=data.frame()) yuimaGUIsettings <- list(simulation = list(), estimation = list(), delta = list(), toLog = list()) output$saveSession <- { downloadHandler( filename = "session.yuimaGUI", content = function(file) { save("yuimaGUIdata", file = file) } ) } observeEvent(input$loadSession, { if (!is.null(input$loadSession$datapath)){ try(load(input$loadSession$datapath)) for(i in names(yuimaGUIdata)) yuimaGUIdata[[i]] <<- yuimaGUIdata[[i]] } }) observeEvent(yuimaGUIdata$series, priority = 10, { yuimaGUItable$series <<- data.frame() for (symb in names(yuimaGUIdata$series)){ test <- try(rbind(yuimaGUItable$series, data.frame(Symb = as.character(symb), From = as.character(start(yuimaGUIdata$series[[symb]])), To = as.character(end(yuimaGUIdata$series[[symb]]))))) if (class(test)!="try-error") yuimaGUItable$series <<- test else yuimaGUIdata$series <<- yuimaGUIdata$series[-which(names(yuimaGUIdata$series)==symb)] } if (length(yuimaGUItable$series)!=0) rownames(yuimaGUItable$series) <<- yuimaGUItable$series[,"Symb"] }) observeEvent(yuimaGUIdata$model, priority = 10, { yuimaGUItable$model <<- data.frame() for (symb in names(yuimaGUIdata$model)){ for (i in 1:length(yuimaGUIdata$model[[symb]])){ newRow <- data.frame( Symb = symb, Class = yuimaGUIdata$model[[symb]][[i]]$info$class, Model = yuimaGUIdata$model[[symb]][[i]]$info$modName, Jumps = yuimaGUIdata$model[[symb]][[i]]$info$jumps, From = as.character(start(yuimaGUIdata$model[[symb]][[i]]$model@[email protected])), To = as.character(end(yuimaGUIdata$model[[symb]][[i]]$model@[email protected])), AIC = yuimaGUIdata$model[[symb]][[i]]$aic, BIC = yuimaGUIdata$model[[symb]][[i]]$bic, stringsAsFactors = FALSE) rownames(newRow) <- as.character(paste(symb," ", i, sep="")) yuimaGUItable$model <<- rbind(yuimaGUItable$model, newRow) } } }) observeEvent(yuimaGUIdata$multimodel, priority = 10, { yuimaGUItable$multimodel <<- data.frame() for (symb in names(yuimaGUIdata$multimodel)){ for (i in 1:length(yuimaGUIdata$multimodel[[symb]])){ newRow <- data.frame( Symb = symb, Class = yuimaGUIdata$multimodel[[symb]][[i]]$info$class, Model = yuimaGUIdata$multimodel[[symb]][[i]]$info$modName, Jumps = yuimaGUIdata$multimodel[[symb]][[i]]$info$jumps, From = as.character(start(yuimaGUIdata$multimodel[[symb]][[i]]$model@[email protected])), To = as.character(end(yuimaGUIdata$multimodel[[symb]][[i]]$model@[email protected])), AIC = yuimaGUIdata$multimodel[[symb]][[i]]$aic, BIC = yuimaGUIdata$multimodel[[symb]][[i]]$bic, stringsAsFactors = FALSE) rownames(newRow) <- as.character(paste(symb," ", i, sep="")) yuimaGUItable$multimodel <<- rbind(yuimaGUItable$multimodel, newRow) } } }) observeEvent(yuimaGUIdata$simulation, priority = 10, { yuimaGUItable$simulation <<- data.frame() for (symb in names(yuimaGUIdata$simulation)){ for (i in 1:length(yuimaGUIdata$simulation[[symb]])){ estimated.from <- NA estimated.to <- NA if (!is.null(yuimaGUIdata$simulation[[symb]][[i]]$model$model@[email protected])){ estimated.from <- as.character(start(yuimaGUIdata$simulation[[symb]][[i]]$model$model@[email protected])) estimated.to <- as.character(end(yuimaGUIdata$simulation[[symb]][[i]]$model$model@[email protected])) } newRow <- data.frame( "Symb" = symb, "Class" = yuimaGUIdata$simulation[[symb]][[i]]$model$info$class, "Model" = yuimaGUIdata$simulation[[symb]][[i]]$model$info$modName, "Jumps" = yuimaGUIdata$simulation[[symb]][[i]]$model$info$jumps, "N sim" = yuimaGUIdata$simulation[[symb]][[i]]$info$nsim, "N step" = yuimaGUIdata$simulation[[symb]][[i]]$info$nstep, "delta" = yuimaGUIdata$simulation[[symb]][[i]]$info$delta, "Simulated from" = as.character(yuimaGUIdata$simulation[[symb]][[i]]$info$simulate.from), "Simulated to" = as.character(yuimaGUIdata$simulation[[symb]][[i]]$info$simulate.to), "Estimated from" = estimated.from, "Estimated to" = estimated.to, check.names = FALSE, stringsAsFactors = FALSE) rownames(newRow) <- as.character(paste(symb," ", i, sep="")) yuimaGUItable$simulation <<- rbind(yuimaGUItable$simulation, newRow) } } }) observeEvent(yuimaGUIdata$multisimulation, priority = 10, { yuimaGUItable$multisimulation <<- data.frame() for (symb in names(yuimaGUIdata$multisimulation)){ for (i in 1:length(yuimaGUIdata$multisimulation[[symb]])){ estimated.from <- NA estimated.to <- NA if (!is.null(yuimaGUIdata$multisimulation[[symb]][[i]]$model$model@[email protected])){ estimated.from <- as.character(start(yuimaGUIdata$multisimulation[[symb]][[i]]$model$model@[email protected])) estimated.to <- as.character(end(yuimaGUIdata$multisimulation[[symb]][[i]]$model$model@[email protected])) } newRow <- data.frame( "Symb" = symb, "Class" = yuimaGUIdata$multisimulation[[symb]][[i]]$model$info$class, "Model" = yuimaGUIdata$multisimulation[[symb]][[i]]$model$info$modName, "Jumps" = yuimaGUIdata$multisimulation[[symb]][[i]]$model$info$jumps, "N sim" = yuimaGUIdata$multisimulation[[symb]][[i]]$info$nsim, "N step" = yuimaGUIdata$multisimulation[[symb]][[i]]$info$nstep, "delta" = yuimaGUIdata$multisimulation[[symb]][[i]]$info$delta, "Simulated from" = as.character(yuimaGUIdata$multisimulation[[symb]][[i]]$info$simulate.from), "Simulated to" = as.character(yuimaGUIdata$multisimulation[[symb]][[i]]$info$simulate.to), "Estimated from" = estimated.from, "Estimated to" = estimated.to, check.names = FALSE, stringsAsFactors = FALSE) rownames(newRow) <- as.character(paste(symb," ", i, sep="")) yuimaGUItable$multisimulation <<- rbind(yuimaGUItable$multisimulation, newRow) } } }) observeEvent(yuimaGUIdata$series, priority = 10, { n <- names(yuimaGUIdata$series) for (i in names(yuimaGUIsettings$estimation)) if(!(i %in% n)) yuimaGUIsettings$estimation[[i]] <<- NULL for (i in names(yuimaGUIsettings$delta)) if(!(i %in% n)) yuimaGUIsettings$delta[[i]] <<- NULL }) observeEvent(yuimaGUIdata$hedging, priority = 10, { yuimaGUItable$hedging <<- data.frame() if (length(yuimaGUIdata$hedging)!=0){ for (i in 1:length(yuimaGUIdata$hedging)){ newRow <- data.frame( "Symb" = yuimaGUIdata$hedging[[i]]$symb, "Number of Simulations" = yuimaGUIdata$hedging[[i]]$info$nsim, "Average Return (%)" = round(yuimaGUIdata$hedging[[i]]$info$profit*100,2), "Option Lots_to_Buy" = yuimaGUIdata$hedging[[i]]$info$LotsToBuy, "Assets to Buy" = yuimaGUIdata$hedging[[i]]$info$buy, "Assets to Sell" = yuimaGUIdata$hedging[[i]]$info$sell, "Asset Price" = yuimaGUIdata$hedging[[i]]$info$assPrice, "Option Price" = yuimaGUIdata$hedging[[i]]$info$optPrice, "Option Type" = yuimaGUIdata$hedging[[i]]$info$type, "Strike" = yuimaGUIdata$hedging[[i]]$info$strike, "Maturity" = yuimaGUIdata$hedging[[i]]$info$maturity, "Lot Multiplier"=yuimaGUIdata$hedging[[i]]$info$optLotMult, "Trading_Cost per Lot"=yuimaGUIdata$hedging[[i]]$info$optLotCost, "Asset Trading_Cost (%)"=yuimaGUIdata$hedging[[i]]$info$assPercCost*100, "Asset Min Trading_Cost"=yuimaGUIdata$hedging[[i]]$info$assMinCost, "Asset Yearly_Short_Rate (%)"=yuimaGUIdata$hedging[[i]]$info$assRateShortSelling*100, "Model" = yuimaGUIdata$hedging[[i]]$model$info$modName, "Estimated from" = start(yuimaGUIdata$hedging[[i]]$model$model@[email protected]), "Estimated to" = end(yuimaGUIdata$hedging[[i]]$model$model@[email protected]), "AIC" = yuimaGUIdata$hedging[[i]]$model$aic, "BIC" = yuimaGUIdata$hedging[[i]]$model$bic, check.names = FALSE, stringsAsFactors = FALSE) yuimaGUItable$hedging <<- rbind.fill(yuimaGUItable$hedging, newRow) } } }) defaultModels <- c("Diffusion process"="Geometric Brownian Motion", "Diffusion process"="Brownian Motion", "Diffusion process"="Ornstein-Uhlenbeck (OU)", "Diffusion process"="Vasicek model (VAS)", "Diffusion process"="Constant elasticity of variance (CEV)", "Diffusion process"= "Cox-Ingersoll-Ross (CIR)", "Diffusion process"="Chan-Karolyi-Longstaff-Sanders (CKLS)", "Diffusion process"="Hyperbolic (Barndorff-Nielsen)", "Diffusion process"="Hyperbolic (Bibby and Sorensen)", "Compound Poisson" = "Constant Intensity", "Compound Poisson" = "Linear Intensity", "Compound Poisson" = "Power Low Intensity", "Compound Poisson" = "Exponentially Decaying Intensity", "Compound Poisson" = "Periodic Intensity", "Point Process" = "Hawkes", "Point Process" = "Hawkes Power Law Kernel", #"Fractional process"="Frac. Geometric Brownian Motion", #"Fractional process"="Frac. Brownian Motion", "Fractional process"="Frac. Ornstein-Uhlenbeck (OU)", "CARMA" = "Carma(p,q)", "COGARCH" = "Cogarch(p,q)", "Levy process" = "Geometric Brownian Motion with Jumps" ) defaultMultiModels <- c("Diffusion process" = "Correlated Brownian Motion") defaultJumps <- c("Gaussian", "Constant", "Uniform", "Student t", "Variance Gamma", "Inverse Gaussian", "Normal Inverse Gaussian", "Hyperbolic", "Generalized Hyperbolic")
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/settings.R
output$multi_simulate_databaseModels <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ if (length(yuimaGUItable$multimodel)==0){ NoData <- data.frame("Symb"=NA,"Please estimate some models first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$multimodel) }) multi_modelsToSimulate <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$multi_simulate_button_selectModels, priority = 1, { multi_modelsToSimulate$table <<- rbind.fill(multi_modelsToSimulate$table, yuimaGUItable$multimodel[(rownames(yuimaGUItable$multimodel) %in% rownames(yuimaGUItable$multimodel)[input$multi_simulate_databaseModels_rows_selected]) & !(rownames(yuimaGUItable$multimodel) %in% rownames(multi_modelsToSimulate$table)),]) }) ###SelectAll Button observeEvent(input$multi_simulate_button_selectAllModels, priority = 1, { multi_modelsToSimulate$table <<- rbind.fill(multi_modelsToSimulate$table, yuimaGUItable$multimodel[(rownames(yuimaGUItable$multimodel) %in% rownames(yuimaGUItable$multimodel)[input$multi_simulate_databaseModels_rows_all]) & !(rownames(yuimaGUItable$multimodel) %in% rownames(multi_modelsToSimulate$table)),]) }) observe({ if("AIC" %in% colnames(multi_modelsToSimulate$table)) multi_modelsToSimulate$table[,"AIC"] <<- as.numeric(as.character(multi_modelsToSimulate$table[,"AIC"])) if("BIC" %in% colnames(multi_modelsToSimulate$table)) multi_modelsToSimulate$table[,"BIC"] <<- as.numeric(as.character(multi_modelsToSimulate$table[,"BIC"])) }) ###Control selected models to be in yuimaGUIdata$multimodel or user defined observe({ if(length(rownames(multi_modelsToSimulate$table))!=0){ names.valid <- c(names(yuimaGUIdata$usr_multisimulation), rownames(yuimaGUItable$multimodel)) col <- colnames(multi_modelsToSimulate$table) updatedtable <- data.frame(multi_modelsToSimulate$table[which(rownames(multi_modelsToSimulate$table) %in% names.valid),], row.names = rownames(multi_modelsToSimulate$table)[rownames(multi_modelsToSimulate$table) %in% names.valid]) colnames(updatedtable) <- col multi_modelsToSimulate$table <<- updatedtable } }) output$multi_simulate_selectedModels <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollX=TRUE, scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ if (length(rownames(multi_modelsToSimulate$table))==0){ NoData <- data.frame("Symb"=NA,"Please select models from the table above"=NA, check.names = FALSE) return(NoData[-1,]) } return (multi_modelsToSimulate$table) }) ###Delete Button observeEvent(input$multi_simulation_button_deleteModels, priority = 1,{ if (!is.null(input$multi_simulate_selectedModels_rows_selected)) multi_modelsToSimulate$table <<- multi_modelsToSimulate$table[-input$multi_simulate_selectedModels_rows_selected,] }) ###DeleteAll Button observeEvent(input$multi_simulation_button_deleteAllModels, priority = 1,{ if (!is.null(input$multi_simulate_selectedModels_rows_all)) multi_modelsToSimulate$table <<- multi_modelsToSimulate$table[-input$multi_simulate_selectedModels_rows_all,] }) observe({ shinyjs::toggle(id="multi_simulate_setSimulation_errorMessage", condition = length(rownames(multi_modelsToSimulate$table))==0) shinyjs::toggle(id="multi_simulate_setSimulation_body", condition = length(rownames(multi_modelsToSimulate$table))!=0) }) observe({ shinyjs::toggle(id="multi_simulate_advancedSettings_errorMessage", condition = length(rownames(multi_modelsToSimulate$table))==0) shinyjs::toggle(id="multi_simulate_advancedSettings_body", condition = length(rownames(multi_modelsToSimulate$table))!=0) }) observe({ for (modID in rownames(multi_modelsToSimulate$table)[input$multi_simulate_selectedModels_rows_all]){ if (modID %in% names(yuimaGUIdata$usr_multisimulation)){ if (is.null(yuimaGUIsettings$simulation[[modID]])) yuimaGUIsettings$simulation[[modID]] <<- list() if (is.null(yuimaGUIsettings$simulation[[modID]][["xinit"]])){ dim <- yuimaGUIdata$usr_multisimulation[[modID]]$Dimension if(!is.null(dim)) yuimaGUIsettings$simulation[[modID]][["xinit"]] <<- as.data.frame(t(data.frame(rep(1, dim), row.names = paste("x", 1:dim, sep = "")))) else { ###add other models } } if (is.null(yuimaGUIsettings$simulation[[modID]][["nstep"]])) yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- 1000 if (is.null(yuimaGUIsettings$simulation[[modID]][["nsim"]])) yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["t0"]])) yuimaGUIsettings$simulation[[modID]][["t0"]] <<- 0 if (is.null(yuimaGUIsettings$simulation[[modID]][["t1"]])) yuimaGUIsettings$simulation[[modID]][["t1"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["traj"]])) yuimaGUIsettings$simulation[[modID]][["traj"]] <<- TRUE if (is.null(yuimaGUIsettings$simulation[[modID]][["seed"]])) yuimaGUIsettings$simulation[[modID]][["seed"]] <<- NA } if (modID %in% rownames(yuimaGUItable$multimodel)){ id <- unlist(strsplit(modID, split = " ")) if (is.null(yuimaGUIsettings$simulation[[modID]])) yuimaGUIsettings$simulation[[modID]] <<- list() if (is.null(yuimaGUIsettings$simulation[[modID]][["xinit"]])){ xinit <- last(as.xts(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected])) toLog <- yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info$toLog xinit[1,toLog==TRUE] <- exp(xinit[1,toLog==TRUE]) yuimaGUIsettings$simulation[[modID]][["xinit"]] <<- xinit } if (is.null(yuimaGUIsettings$simulation[[modID]][["nstep"]])) yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- NA if (is.null(yuimaGUIsettings$simulation[[modID]][["nsim"]])) yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["t0"]])) yuimaGUIsettings$simulation[[modID]][["t0"]] <<- end(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]) if (is.null(yuimaGUIsettings$simulation[[modID]][["t1"]])) if(is.numeric(index(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))) yuimaGUIsettings$simulation[[modID]][["t1"]] <<- 2*end(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected])-start(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]) else yuimaGUIsettings$simulation[[modID]][["t1"]] <<- end(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected])+365 if (is.null(yuimaGUIsettings$simulation[[modID]][["traj"]])) yuimaGUIsettings$simulation[[modID]][["traj"]] <<- TRUE if (is.null(yuimaGUIsettings$simulation[[modID]][["seed"]])) yuimaGUIsettings$simulation[[modID]][["seed"]] <<- NA } } }) output$multi_simulate_modelID <- renderUI({ selectInput("multi_simulate_modelID", label = "Simulation ID", choices = rownames(multi_modelsToSimulate$table)) }) output$multi_simulate_advancedSettings_modelID <- renderUI({ selectInput("multi_simulate_advancedSettings_modelID", label = "Simulation ID", choices = rownames(multi_modelsToSimulate$table)) }) output$multi_simulate_seed <- renderUI({ if(!is.null(input$multi_simulate_advancedSettings_modelID)) numericInput("multi_simulate_seed", label = "RNG seed", step = 1, min = 0, value = yuimaGUIsettings$simulation[[input$multi_simulate_advancedSettings_modelID]][["seed"]]) }) output$multi_simulate_traj <- renderUI({ if(!is.null(input$multi_simulate_advancedSettings_modelID)) selectInput("multi_simulate_traj", label = "Save trajectory", choices = c(TRUE,FALSE), selected = yuimaGUIsettings$simulation[[input$multi_simulate_advancedSettings_modelID]][["traj"]]) }) output$multi_simulate_nsim <- renderUI({ if(!is.null(input$multi_simulate_modelID)) numericInput("multi_simulate_nsim", label = "Number of simulations", value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["nsim"]], min = 1, step = 1) }) output$multi_simulate_nstep <- renderUI({ if(!is.null(input$multi_simulate_modelID)){ id <- unlist(strsplit(input$multi_simulate_modelID, split = " ")) if (input$multi_simulate_modelID %in% names(yuimaGUIdata$usr_multisimulation)){ numericInput("multi_simulate_nstep", label = "Number of steps per simulation", value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["nstep"]], min = 1, step = 1) } else if (!(isolate({yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info$class}) %in% c("COGARCH", "CARMA"))) numericInput("multi_simulate_nstep", label = "Number of steps per simulation", value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["nstep"]], min = 1, step = 1) } }) output$multi_simulate_xinit_symb <- renderUI({ if(!is.null(input$multi_simulate_modelID)) selectInput("multi_simulate_xinit_symb", label = "Symb", choices = names(yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["xinit"]])) }) observe({ if(!is.null(input$multi_simulate_modelID) & !is.null(input$multi_simulate_xinit_symb)) if (input$multi_simulate_xinit_symb %in% names(yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["xinit"]])) output$multi_simulate_xinit <- renderUI({ isolate({numericInput("multi_simulate_xinit", label = "Initial value", value = as.numeric(yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["xinit"]][,input$multi_simulate_xinit_symb]))}) }) }) output$multi_simulate_range <- renderUI({ if(!is.null(input$multi_simulate_modelID)){ if (input$multi_simulate_modelID %in% names(yuimaGUIdata$usr_multisimulation)){ return(div( column(6,numericInput("multi_simulate_rangeNumeric_t0", label = "From", min = 0 ,value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]])), column(6,numericInput("multi_simulate_rangeNumeric_t1", label = "To", min = 0, value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]])) )) } if (input$multi_simulate_modelID %in% rownames(yuimaGUItable$multimodel)){ id <- unlist(strsplit(input$multi_simulate_modelID, split = " ")) if (class(index(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date") dateRangeInput("multi_simulate_rangeDate", label = "Simulation interval", start = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]], end = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]]) else{ div( column(6,numericInput("multi_simulate_rangeNumeric_t0", label = "From", min = 0 ,value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]])), column(6,numericInput("multi_simulate_rangeNumeric_t1", label = "To", min = 0, value = yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]])) ) } } } }) observeEvent(input$multi_simulate_button_apply_advancedSettings, { yuimaGUIsettings$simulation[[input$multi_simulate_advancedSettings_modelID]][["seed"]] <<- input$multi_simulate_seed yuimaGUIsettings$simulation[[input$multi_simulate_advancedSettings_modelID]][["traj"]] <<- input$multi_simulate_traj }) observeEvent(input$multi_simulate_button_applyAll_advancedSettings, { for (modID in rownames(multi_modelsToSimulate$table)){ yuimaGUIsettings$simulation[[modID]][["seed"]] <<- input$multi_simulate_seed yuimaGUIsettings$simulation[[modID]][["traj"]] <<- input$multi_simulate_traj } }) observeEvent(input$multi_simulate_button_apply_nsim, { yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["nsim"]] <<- input$multi_simulate_nsim yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["nstep"]] <<- input$multi_simulate_nstep }) observeEvent(input$multi_simulate_button_applyAll_nsim, { for (modID in rownames(multi_modelsToSimulate$table)){ yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- input$multi_simulate_nsim yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- input$multi_simulate_nstep } }) observeEvent(input$multi_simulate_button_apply_xinit, { yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["xinit"]][,input$multi_simulate_xinit_symb] <<- input$multi_simulate_xinit }) observeEvent(input$multi_simulate_button_applyAll_xinit, { for (modID in rownames(multi_modelsToSimulate$table)) if(input$multi_simulate_xinit_symb %in% names(yuimaGUIsettings$simulation[[modID]][["xinit"]])) yuimaGUIsettings$simulation[[modID]][["xinit"]][,input$multi_simulate_xinit_symb] <<- input$multi_simulate_xinit }) observeEvent(input$multi_simulate_button_apply_range, { if (input$multi_simulate_modelID %in% names(yuimaGUIdata$usr_multisimulation)){ yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]] <<- input$multi_simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]] <<- input$multi_simulate_rangeNumeric_t1 } if (input$multi_simulate_modelID %in% rownames(yuimaGUItable$multimodel)){ id <- unlist(strsplit(input$multi_simulate_modelID, split = " ")) if (class(index(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date"){ yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]] <<- input$multi_simulate_rangeDate[1] yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]] <<- input$multi_simulate_rangeDate[2] } else{ yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t0"]] <<- input$multi_simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[input$multi_simulate_modelID]][["t1"]] <<- input$multi_simulate_rangeNumeric_t1 } } }) observeEvent(input$multi_simulate_button_applyAll_range, { for (modID in rownames(multi_modelsToSimulate$table)){ if (modID %in% names(yuimaGUIdata$usr_multisimulation)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$multi_simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$multi_simulate_rangeNumeric_t1 } if (modID %in% rownames(yuimaGUItable$multimodel)){ id <- unlist(strsplit(modID, split = " ")) if (class(index(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date" & !is.null(input$multi_simulate_rangeDate)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$multi_simulate_rangeDate[1] yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$multi_simulate_rangeDate[2] } if (class(index(yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="numeric" & !is.null(input$multi_simulate_rangeNumeric_t0)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$multi_simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$multi_simulate_rangeNumeric_t1 } } } }) observe({ if (!is.null(multi_modelsToSimulate$table)) if (nrow(multi_modelsToSimulate$table)!=0) { closeAlert(session, alertId = "multi_simulate_alert_buttonEstimate1") closeAlert(session, alertId = "multi_simulate_alert_buttonEstimate2") } }) observeEvent(input$multi_simulate_simulateModels, { if (is.null(multi_modelsToSimulate$table)) { if (input$panel_multi_simulations=="Estimated models") createAlert(session = session, anchorId = "panel_multi_simulate_model_alert", alertId = "multi_simulate_alert_buttonEstimate1", content = "Table 'Selected Models' is empty", style = "warning") if (input$panel_multi_simulations=="Non-estimated models") createAlert(session = session, anchorId = "panel_multi_simulate_equation_alert", alertId = "multi_simulate_alert_buttonEstimate2", content = "Table 'Selected Models' is empty", style = "warning") } else if (nrow(multi_modelsToSimulate$table)==0) { if (input$panel_multi_simulations=="Estimated models") createAlert(session = session, anchorId = "panel_multi_simulate_model_alert", alertId = "multi_simulate_alert_buttonEstimate1", content = "Table 'Selected Models' is empty", style = "warning") if (input$panel_multi_simulations=="Non-estimated models") createAlert(session = session, anchorId = "panel_multi_simulate_equation_alert", alertId = "multi_simulate_alert_buttonEstimate2", content = "Table 'Selected Models' is empty", style = "warning") } else{ withProgress(message = 'Simulating: ', value = 0, { for (modID in rownames(multi_modelsToSimulate$table)){ if(modID %in% names(yuimaGUIdata$usr_multisimulation)){ incProgress(1/nrow(multi_modelsToSimulate$table), detail = paste(modID,"-",yuimaGUIdata$usr_multisimulation[[modID]][["Model"]])) jumps <- ifelse(is.null(yuimaGUIdata$usr_multisimulation[[modID]][["Jumps"]]),NA, yuimaGUIdata$usr_multisimulation[[modID]][["Jumps"]]) dimension <- ifelse(is.null(yuimaGUIdata$usr_multisimulation[[modID]][["Dimension"]]),NA, yuimaGUIdata$usr_multisimulation[[modID]][["Dimension"]]) modName <- yuimaGUIdata$usr_multisimulation[[modID]][["Model"]] modelYuimaGUI <- list(model = setYuima(model = setModelByName(name = modName, jumps = jumps, dimension = dimension)), info = list(class = yuimaGUIdata$usr_multisimulation[[modID]][["Class"]], modName = modName, jumps = jumps, dimension = dimension, symb = colnames(yuimaGUIsettings$simulation[[modID]][["xinit"]]) ) ) addSimulation( modelYuimaGUI = modelYuimaGUI, symbName = modID, xinit = yuimaGUIsettings$simulation[[modID]][["xinit"]], true.parameter = lapply(yuimaGUIdata$usr_multisimulation[[modID]][["true.param"]], FUN = function(x) as.numeric(x)), nsim = yuimaGUIsettings$simulation[[modID]][["nsim"]], nstep = yuimaGUIsettings$simulation[[modID]][["nstep"]], simulate.from = yuimaGUIsettings$simulation[[modID]][["t0"]], simulate.to = yuimaGUIsettings$simulation[[modID]][["t1"]], saveTraj = yuimaGUIsettings$simulation[[modID]][["traj"]], seed = yuimaGUIsettings$simulation[[modID]][["seed"]], session = session, anchorId = "panel_multi_simulations_alert", is.multi = TRUE ) } else if(modID %in% rownames(yuimaGUItable$multimodel)){ id <- unlist(strsplit(modID, split = " ")) incProgress(1/nrow(multi_modelsToSimulate$table), detail = paste(id[1],"-",yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]]$info$modName)) addSimulation( modelYuimaGUI = yuimaGUIdata$multimodel[[id[1]]][[as.numeric(id[2])]], symbName = id[1], xinit = yuimaGUIsettings$simulation[[modID]][["xinit"]], nsim = yuimaGUIsettings$simulation[[modID]][["nsim"]], nstep = yuimaGUIsettings$simulation[[modID]][["nstep"]], simulate.from = yuimaGUIsettings$simulation[[modID]][["t0"]], simulate.to = yuimaGUIsettings$simulation[[modID]][["t1"]], saveTraj = yuimaGUIsettings$simulation[[modID]][["traj"]], seed = yuimaGUIsettings$simulation[[modID]][["seed"]], session = session, anchorId = "panel_multi_simulations_alert", is.multi = TRUE ) } } }) updateTabsetPanel(session = session, inputId = "panel_multi_simulations", selected = "Simulations") } }) observe({ shinyjs::toggle("multi_div_simulations", condition = (input$panel_multi_simulations!="Simulations")) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/multivariate_estimated.R
output$multi_simulate_PrintModelLatex <- renderUI({ if (!is.null(input$multi_simulate_model_usr_selectModel)){ return(withMathJax(printModelLatex(multi = TRUE, names = input$multi_simulate_model_usr_selectModel, process = isolate({input$multi_simulate_model_usr_selectClass}), dimension = input$multi_simulate_model_usr_selectDimension, jumps = jumps_shortcut(class = isolate({input$multi_simulate_model_usr_selectClass}), jumps = input$multi_simulate_model_usr_selectJumps)))) } }) output$multi_simulate_model_usr_selectModel <- renderUI({ choices <- as.vector(defaultMultiModels[names(defaultMultiModels)==input$multi_simulate_model_usr_selectClass]) sel <- choices[1] for(i in names(yuimaGUIdata$multiusr_model)) if (yuimaGUIdata$multiusr_model[[i]]$class==input$multi_simulate_model_usr_selectClass) choices <- c(i, choices) selectInput("multi_simulate_model_usr_selectModel", label = "Model Name", choices = choices, selected = sel) }) output$multi_simulate_model_usr_selectJumps <- renderUI({ if(input$multi_simulate_model_usr_selectClass %in% c("Compound Poisson", "Levy process")) return(selectInput("multi_simulate_model_usr_selectJumps",label = "Jumps", choices = defaultJumps)) }) output$multi_simulate_model_usr_selectDimension <- renderUI({ if(!is.null(input$multi_simulate_model_usr_selectModel)) if(input$multi_simulate_model_usr_selectModel %in% c("Correlated Brownian Motion")) return(numericInput("multi_simulate_model_usr_selectDimension",label = "Dimension", value = 2, step = 1)) }) output$multi_simulate_model_usr_selectParam <- renderUI({ valid <- TRUE if (is.null(input$multi_simulate_model_usr_selectModel)) valid <- FALSE else if (isolate({input$multi_simulate_model_usr_selectClass=="Compound Poisson"}) & is.null(input$multi_simulate_model_usr_selectJumps)) valid <- FALSE else if (isolate({input$multi_simulate_model_usr_selectModel %in% c("Correlated Brownian Motion")}) & is.null(input$multi_simulate_model_usr_selectDimension)) valid <- FALSE if (valid) { mod <- setModelByName(input$multi_simulate_model_usr_selectModel, dimension = input$multi_simulate_model_usr_selectDimension, jumps = jumps_shortcut(class = isolate({input$multi_simulate_model_usr_selectClass}), jumps = input$multi_simulate_model_usr_selectJumps)) choices <- getAllParams(mod = mod, class = input$multi_simulate_model_usr_selectClass) if (input$multi_simulate_model_usr_selectClass=="Fractional process") choices <- c(choices, "hurst") return(selectInput("multi_simulate_model_usr_selectParam", label = "Parameter", choices = choices)) } }) output$multi_simulate_model_usr_param <- renderUI({ numericInput("multi_simulate_model_usr_param", label = "Parameter value", value = NA) }) output$multi_simulate_model_usr_ID <- renderUI({ textInput("multi_simulate_model_usr_ID", label = "Simulation ID") }) observeEvent(input$multi_simulate_model_usr_button_save, { if(input$multi_simulate_model_usr_ID!=""){ id <- gsub(pattern = " ", x = input$multi_simulate_model_usr_ID, replacement = "") if (is.null(yuimaGUIdata$usr_multisimulation[[id]])){ yuimaGUIdata$usr_multisimulation[[id]] <<- list() } yuimaGUIdata$usr_multisimulation[[id]][["Class"]] <<- input$multi_simulate_model_usr_selectClass yuimaGUIdata$usr_multisimulation[[id]][["Model"]] <<- input$multi_simulate_model_usr_selectModel yuimaGUIdata$usr_multisimulation[[id]][["Jumps"]] <<- input$multi_simulate_model_usr_selectJumps yuimaGUIdata$usr_multisimulation[[id]][["Dimension"]] <<- input$multi_simulate_model_usr_selectDimension if (is.null(yuimaGUIdata$usr_multisimulation[[id]][["true.param"]])){ yuimaGUIdata$usr_multisimulation[[id]][["true.param"]] <<- list() } mod <- setModelByName(input$multi_simulate_model_usr_selectModel, jumps = input$multi_simulate_model_usr_selectJumps, dimension = input$multi_simulate_model_usr_selectDimension) allparam <- getAllParams(mod = mod, class = input$multi_simulate_model_usr_selectClass) if (length(allparam)==0) yuimaGUIdata$usr_multisimulation[[id]]["true.param"] <<- NULL if (length(allparam)!=0){ for(i in c(allparam, names(yuimaGUIdata$usr_multisimulation[[id]][["true.param"]]))){ if (!(i %in% names(yuimaGUIdata$usr_multisimulation[[id]][["true.param"]]))) yuimaGUIdata$usr_multisimulation[[id]][["true.param"]][[i]] <<- "MISSING" if(!(i %in% allparam)) yuimaGUIdata$usr_multisimulation[[id]][["true.param"]][i] <<- NULL } } } }) observe({ if (!is.null(input$multi_simulate_model_usr_ID) & !is.null(input$multi_simulate_model_usr_selectParam) & !is.null(input$multi_simulate_model_usr_param)){ id <- gsub(pattern = " ", x = input$multi_simulate_model_usr_ID, replacement = "") if (!is.null(yuimaGUIdata$usr_multisimulation[[id]])){ valid <- TRUE if(yuimaGUIdata$usr_multisimulation[[id]][["Model"]]!=input$multi_simulate_model_usr_selectModel | input$multi_simulate_model_usr_selectParam=="") valid <- FALSE else if (yuimaGUIdata$usr_multisimulation[[id]][["Class"]] %in% c("Compound Poisson", "Levy process")) if (yuimaGUIdata$usr_multisimulation[[id]][["Jumps"]]!=input$multi_simulate_model_usr_selectJumps) valid <- FALSE if (valid) yuimaGUIdata$usr_multisimulation[[id]][["true.param"]][[input$multi_simulate_model_usr_selectParam]] <- ifelse(is.na(input$multi_simulate_model_usr_param),"MISSING",input$multi_simulate_model_usr_param) } } }) observe({ for(i in names(yuimaGUIdata$usr_multisimulation)) if (!(yuimaGUIdata$usr_multisimulation[[i]]$Model %in% c(defaultMultiModels, names(yuimaGUIdata$multiusr_model)))) yuimaGUIdata$usr_multisimulation[i] <<- NULL }) output$multi_simulate_model_usr_table <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollX=TRUE, scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ table <- data.frame() for (i in names(yuimaGUIdata$usr_multisimulation)){ newRow <- as.data.frame(yuimaGUIdata$usr_multisimulation[[i]]) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } if (length(table)==0){ NoData <- data.frame("Model"=NA, "Parameters"=NA) return(NoData[-1,]) } return (data.frame(table, row.names = names(yuimaGUIdata$usr_multisimulation))) }) observeEvent(input$multi_simulate_model_usr_button_select, { if (!is.null(input$multi_simulate_model_usr_table_rows_selected)){ table <- data.frame() for (i in names(yuimaGUIdata$usr_multisimulation)[input$multi_simulate_model_usr_table_rows_selected]){ if ("MISSING" %in% yuimaGUIdata$usr_multisimulation[[i]][["true.param"]]){ createAlert(session = session, anchorId = "panel_multi_simulate_equation_alert", alertId = "multi_simulate_alert_usr_button_select", content = "There are still missing values in selected models", style = "error") } else { closeAlert(session, "multi_simulate_alert_usr_button_select") newRow <- as.data.frame(yuimaGUIdata$usr_multisimulation[[i]], row.names=i) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } } if (length(rownames(table))!=0) multi_modelsToSimulate$table <<- multi_modelsToSimulate$table[-which(rownames(multi_modelsToSimulate$table) %in% rownames(table)),] multi_modelsToSimulate$table <<- rbind.fill(multi_modelsToSimulate$table, table) } }) observeEvent(input$multi_simulate_model_usr_button_selectAll, { if (!is.null(input$multi_simulate_model_usr_table_rows_all)){ table <- data.frame() for (i in names(yuimaGUIdata$usr_multisimulation)[input$multi_simulate_model_usr_table_rows_all]){ if ("MISSING" %in% yuimaGUIdata$usr_multisimulation[[i]][["true.param"]]){ createAlert(session = session, anchorId = "panel_multi_simulate_equation_alert", alertId = "multi_simulate_alert_usr_button_select", content = "There are still missing values in selected models", style = "error") } else { closeAlert(session, "multi_simulate_alert_usr_button_select") newRow <- as.data.frame(yuimaGUIdata$usr_multisimulation[[i]], row.names=i) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } } if (length(rownames(table))!=0) multi_modelsToSimulate$table <<- multi_modelsToSimulate$table[-which(rownames(multi_modelsToSimulate$table) %in% rownames(table)),] multi_modelsToSimulate$table <<- rbind.fill(multi_modelsToSimulate$table, table) } }) observeEvent(input$multi_simulate_model_usr_button_delete, { if (!is.null(input$multi_simulate_model_usr_table_rows_selected)){ for (i in input$multi_simulate_model_usr_table_rows_selected){ yuimaGUIdata$usr_multisimulation[i] <- NULL } } }) observeEvent(input$multi_simulate_model_usr_button_deleteAll, { if (!is.null(input$multi_simulate_model_usr_table_rows_all)){ for (i in input$multi_simulate_model_usr_table_rows_all){ yuimaGUIdata$usr_multisimulation[i] <- NULL } } })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/multivariate_non_estimated.R
###Create simulations table output$multi_simulate_monitor_table <- DT::renderDataTable(options=list(scrollY = 200, scrollX=TRUE, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$multisimulation)==0){ NoData <- data.frame("Symb"=NA,"Here will be stored simulations you run in the previous tabs"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$multisimulation) }) observe({ shinyjs::toggle("multi_simulate_monitor_button_showSimulation", condition = (length(names(yuimaGUIdata$multisimulation))!=0)) }) ###Delete Simulation observeEvent(input$multi_simulate_monitor_button_delete, priority = 1, { if(!is.null(input$multi_simulate_monitor_table_rows_selected) & !is.null(input$multi_simulate_monitor_table_row_last_clicked)){ if(input$multi_simulate_monitor_table_row_last_clicked %in% input$multi_simulate_monitor_table_rows_selected){ rowname <- unlist(strsplit(rownames(yuimaGUItable$multisimulation)[input$multi_simulate_monitor_table_row_last_clicked], split = " " , fixed = FALSE)) delSimulation(symb=rowname[1], n=rowname[2], multi = TRUE) } } }) ###DeleteAll Simulation observeEvent(input$multi_simulate_monitor_button_deleteAll, priority = 1, { if(!is.null(input$multi_simulate_monitor_table_rows_all)){ rowname <- unlist(strsplit(rownames(yuimaGUItable$multisimulation)[input$multi_simulate_monitor_table_rows_all], split = " " , fixed = FALSE)) delSimulation(symb=rowname[seq(1,length(rowname),2)], n=rowname[seq(2,length(rowname),2)], multi = TRUE) } }) output$multi_simulate_showSimulation_simID <- renderUI({ selectInput(inputId = "multi_simulate_showSimulation_simID", label = "Simulation ID", choices = rownames(yuimaGUItable$multisimulation)) }) multi_observationTime <- reactiveValues(x = numeric()) observeEvent(input$multi_simulate_showSimulation_simID,{ id <- unlist(strsplit(input$multi_simulate_showSimulation_simID, split = " ")) if(!is.na(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])) multi_observationTime$x <<- as.numeric(end(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory)) }) observe({ if (!is.null(input$multi_simulate_showSimulation_plot_click$x) & !is.null(input$multi_simulate_showSimulation_simID)){ id <- unlist(strsplit(input$multi_simulate_showSimulation_simID, split = " ")) if(!is.na(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])) multi_observationTime$x <<- input$multi_simulate_showSimulation_plot_click$x } }) params_multi_simulate_showSimulation_plot <- reactiveValues(id = NULL, y = NULL, z = NULL) output$multi_simulate_showSimulation_plot_series1 <- renderUI({ if(!is.null(input$multi_simulate_showSimulation_simID)) if(input$multi_simulate_showSimulation_simID %in% rownames(yuimaGUItable$multisimulation)){ id <- unlist(strsplit(input$multi_simulate_showSimulation_simID, split = " ")) shinyjs::toggle("multi_simulate_showSimulation_plot_div", condition = !is.na(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[1])) choices <- yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$model$info$symb params_multi_simulate_showSimulation_plot$id <<- input$multi_simulate_showSimulation_simID params_multi_simulate_showSimulation_plot$y <<- choices[1] selectInput("multi_simulate_showSimulation_plot_series1", label="y-Axis", choices = choices, selected = choices[1]) } }) output$multi_simulate_showSimulation_plot_series2 <- renderUI({ if(!is.null(input$multi_simulate_showSimulation_simID)) if(input$multi_simulate_showSimulation_simID %in% rownames(yuimaGUItable$multisimulation)){ id <- unlist(strsplit(input$multi_simulate_showSimulation_simID, split = " ")) choices <- yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$model$info$symb params_multi_simulate_showSimulation_plot$z <<- last(choices) selectInput("multi_simulate_showSimulation_plot_series2", label="z-Axis", choices = choices, selected = last(choices)) } }) observe({ params_multi_simulate_showSimulation_plot$y <<- input$multi_simulate_showSimulation_plot_series1 params_multi_simulate_showSimulation_plot$z <<- input$multi_simulate_showSimulation_plot_series2 }) observeEvent(params_multi_simulate_showSimulation_plot$id,{ if(!is.null(params_multi_simulate_showSimulation_plot$id) & !is.null(params_multi_simulate_showSimulation_plot$y) & !is.null(params_multi_simulate_showSimulation_plot$z) ){ id <- unlist(strsplit(params_multi_simulate_showSimulation_plot$id, split = " ")) if(!is.na(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])){ filtered.colnames <- gsub(colnames(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory), pattern = "_sim.*", replacement = "") seriesnames <- unique(filtered.colnames) d <- data.frame(sapply(seriesnames, function(x) {matrix(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[, filtered.colnames==x])})) x <- index(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory) n.x <- length(x) n.row.d <- nrow(d) d$x6428347364932 <- rep(x, n.row.d/n.x) #avoid index name matching a real seriesname d$ID432793740239 <- rep(seq(1:(n.row.d/n.x)), each = n.x) #avoid id name matching a real seriesname output$multi_simulate_showSimulation_plot <- renderPlotly({ y <- params_multi_simulate_showSimulation_plot$y z <- params_multi_simulate_showSimulation_plot$z if(y!=z) plot_ly(d, x=~x6428347364932, y=d[,y], z=d[,z], split = ~ID432793740239, type="scatter3d", mode="lines", source = "multi_simulate_showSimulation_plot") %>% layout( showlegend = FALSE, title = paste("ID:", isolate({params_multi_simulate_showSimulation_plot$id})), scene = list ( xaxis = list( title = "" ), yaxis = list( title = y ), zaxis = list( title = z ) ) ) else plot_ly(d, x=~x6428347364932, y=d[,y], split = ~ID432793740239, type="scatter", mode="lines", source = "multi_simulate_showSimulation_plot") %>% layout( showlegend = FALSE, title = paste("ID:", isolate({params_multi_simulate_showSimulation_plot$id})), xaxis = list( title = "" ), yaxis = list( title = y ) ) }) } } }) multi_simulation_hist <- reactiveValues(values=NULL, x=NULL, y=NULL, z=NULL) observe({ if(!is.null(params_multi_simulate_showSimulation_plot$id) & !is.null(params_multi_simulate_showSimulation_plot$y) & !is.null(params_multi_simulate_showSimulation_plot$z) ){ id <- unlist(strsplit(params_multi_simulate_showSimulation_plot$id, split = " ")) if(id[1] %in% names(yuimaGUIdata$multisimulation)) if(length(yuimaGUIdata$multisimulation[[id[1]]])>=as.numeric(id[2])) if(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$info$nsim > 1){ if(is.na(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$hist[1])){ shinyjs::toggle("multi_simulate_showSimulation_hist_div", condition = yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$info$nsim > 1) filtered.colnames <- gsub(colnames(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory), pattern = "_sim.*", replacement = "") seriesnames <- unique(filtered.colnames) x <- index(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory) click <- event_data(event = "plotly_click", source = "multi_simulate_showSimulation_plot") if (!is.null(click)) extract.x <- as.character(click$x[1]) else extract.x <- as.character(last(x)) extract.index <- which(as.character(index(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory))==extract.x) d <- data.frame(sapply(seriesnames, function(x) {matrix(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory[extract.index, filtered.colnames==x])})) multi_simulation_hist$x <<- extract.x multi_simulation_hist$values <<- d } else { multi_simulation_hist$x <<- yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$info$simulate.to multi_simulation_hist$values <<- t(yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$hist) } multi_simulation_hist$y <<- params_multi_simulate_showSimulation_plot$y multi_simulation_hist$z <<- params_multi_simulate_showSimulation_plot$z } } }) observeEvent(multi_simulation_hist$values, { output$multi_simulate_showSimulation_hist <- renderPlotly({ if(multi_simulation_hist$y!=multi_simulation_hist$z){ plot_ly(x=multi_simulation_hist$values[,multi_simulation_hist$y], y=multi_simulation_hist$values[,multi_simulation_hist$z], type = "histogram2d") %>% layout( title = paste("Distribution at index =", multi_simulation_hist$x), xaxis = list( title = multi_simulation_hist$y ), yaxis = list( title = multi_simulation_hist$z ) ) } else plot_ly(x=multi_simulation_hist$values[,multi_simulation_hist$y], type = "histogram") %>% layout( title = paste("Distribution at index =", multi_simulation_hist$x), xaxis = list( title = multi_simulation_hist$y ), yaxis = list( title = "Frequency" ) ) }) }, once = TRUE) output$multi_simulate_showSimulation_hist_text <- renderUI({ if(length(multi_simulation_hist$values)!=0 & !is.null(input$multi_simulate_showSimulation_hist_probability_slider)){ val1 <- as.numeric(multi_simulation_hist$values[,multi_simulation_hist$y]) qq1 <- quantile(val1, probs = input$multi_simulate_showSimulation_hist_probability_slider/100) val2 <- as.numeric(multi_simulation_hist$values[,multi_simulation_hist$z]) qq2 <- quantile(val2, probs = input$multi_simulate_showSimulation_hist_probability_slider/100) HTML(paste("<div>", multi_simulation_hist$y , "<br/>", "Lower:", qq1[1],"<br/>", "Upper: ", qq1[2], "<br/>", "Mean: ", mean(val1[val1>=qq1[1] & val1<=qq1[2]]), "</div>", "<br/>", "<div>", multi_simulation_hist$z , "<br/>", "Lower:", qq2[1],"<br/>", "Upper: ", qq2[2], "<br/>", "Mean: ", mean(val2[val2>=qq2[1] & val2<=qq2[2]]), "</div>")) } }) ###Save Trajectory Button output$multi_simulate_showSimulation_button_saveTrajectory <- { dataDownload_multi_traj <- reactive({ id <- unlist(strsplit(input$multi_simulate_showSimulation_simID, split = " ")) x <- yuimaGUIdata$multisimulation[[id[1]]][[as.numeric(id[2])]]$trajectory d <- data.frame(x, row.names = index(x)) return(d) }) downloadHandler( filename = function() { paste(input$multi_simulate_showSimulation_simID, ".txt", sep="") }, content = function(file) { write.table(dataDownload_multi_traj(), file, row.names = TRUE, col.names = TRUE, quote = TRUE) } ) } ###Save Histogram Button output$multi_simulate_showSimulation_button_saveHist <- { dataDownload_multi_hist <- reactive({ multi_simulation_hist$values }) downloadHandler( filename = function() { paste(input$multi_simulate_showSimulation_simID, "_hist",".txt", sep="") }, content = function(file) { write.table(dataDownload_multi_hist(), file, row.names = FALSE, col.names = TRUE) } ) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/multivariate_results.R
output$simulate_databaseModels <- DT::renderDataTable(options=list(scrollY = 200, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ if (length(yuimaGUItable$model)==0){ NoData <- data.frame("Symb"=NA,"Please estimate some models first"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$model) }) modelsToSimulate <- reactiveValues(table=data.frame()) ###Select Button observeEvent(input$simulate_button_selectModels, priority = 1, { modelsToSimulate$table <<- rbind.fill(modelsToSimulate$table, yuimaGUItable$model[(rownames(yuimaGUItable$model) %in% rownames(yuimaGUItable$model)[input$simulate_databaseModels_rows_selected]) & !(rownames(yuimaGUItable$model) %in% rownames(modelsToSimulate$table)),]) }) ###SelectAll Button observeEvent(input$simulate_button_selectAllModels, priority = 1, { modelsToSimulate$table <<- rbind.fill(modelsToSimulate$table, yuimaGUItable$model[(rownames(yuimaGUItable$model) %in% rownames(yuimaGUItable$model)[input$simulate_databaseModels_rows_all]) & !(rownames(yuimaGUItable$model) %in% rownames(modelsToSimulate$table)),]) }) observe({ if("AIC" %in% colnames(modelsToSimulate$table)) modelsToSimulate$table[,"AIC"] <<- as.numeric(as.character(modelsToSimulate$table[,"AIC"])) if("BIC" %in% colnames(modelsToSimulate$table)) modelsToSimulate$table[,"BIC"] <<- as.numeric(as.character(modelsToSimulate$table[,"BIC"])) }) ###Control selected models to be in yuimaGUIdata$model or user defined observe({ if(length(rownames(modelsToSimulate$table))!=0){ names.valid <- c(names(yuimaGUIdata$usr_simulation), rownames(yuimaGUItable$model)) col <- colnames(modelsToSimulate$table) updatedtable <- data.frame(modelsToSimulate$table[which(rownames(modelsToSimulate$table) %in% names.valid),], row.names = rownames(modelsToSimulate$table)[rownames(modelsToSimulate$table) %in% names.valid]) colnames(updatedtable) <- col modelsToSimulate$table <<- updatedtable } }) output$simulate_selectedModels <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollX=TRUE, scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ if (length(rownames(modelsToSimulate$table))==0){ NoData <- data.frame("Symb"=NA,"Please select models from the table above"=NA, check.names = FALSE) return(NoData[-1,]) } return (modelsToSimulate$table) }) ###Delete Button observeEvent(input$simulation_button_deleteModels, priority = 1,{ if (!is.null(input$simulate_selectedModels_rows_selected)) modelsToSimulate$table <<- modelsToSimulate$table[-input$simulate_selectedModels_rows_selected,] }) ###DeleteAll Button observeEvent(input$simulation_button_deleteAllModels, priority = 1,{ if (!is.null(input$simulate_selectedModels_rows_all)) modelsToSimulate$table <<- modelsToSimulate$table[-input$simulate_selectedModels_rows_all,] }) observe({ shinyjs::toggle(id="simulate_setSimulation_errorMessage", condition = length(rownames(modelsToSimulate$table))==0) shinyjs::toggle(id="simulate_setSimulation_body", condition = length(rownames(modelsToSimulate$table))!=0) }) observe({ shinyjs::toggle(id="simulate_advancedSettings_errorMessage", condition = length(rownames(modelsToSimulate$table))==0) shinyjs::toggle(id="simulate_advancedSettings_body", condition = length(rownames(modelsToSimulate$table))!=0) }) observe({ for (modID in rownames(modelsToSimulate$table)[input$simulate_selectedModels_rows_all]){ if (modID %in% names(yuimaGUIdata$usr_simulation)){ if (is.null(yuimaGUIsettings$simulation[[modID]])) yuimaGUIsettings$simulation[[modID]] <<- list() if (is.null(yuimaGUIsettings$simulation[[modID]][["xinit"]])) yuimaGUIsettings$simulation[[modID]][["xinit"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["nstep"]])) yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- 1000 if (is.null(yuimaGUIsettings$simulation[[modID]][["nsim"]])) yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["t0"]])) yuimaGUIsettings$simulation[[modID]][["t0"]] <<- 0 if (is.null(yuimaGUIsettings$simulation[[modID]][["t1"]])) yuimaGUIsettings$simulation[[modID]][["t1"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["traj"]])) yuimaGUIsettings$simulation[[modID]][["traj"]] <<- TRUE if (is.null(yuimaGUIsettings$simulation[[modID]][["seed"]])) yuimaGUIsettings$simulation[[modID]][["seed"]] <<- NA } if (modID %in% rownames(yuimaGUItable$model)){ id <- unlist(strsplit(modID, split = " ")) if (is.null(yuimaGUIsettings$simulation[[modID]])) yuimaGUIsettings$simulation[[modID]] <<- list() if (is.null(yuimaGUIsettings$simulation[[modID]][["xinit"]])){ xinit <- as.numeric(tail(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected],1))[1] toLog <- yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$info$toLog if(toLog==TRUE) xinit <- exp(xinit) yuimaGUIsettings$simulation[[modID]][["xinit"]] <<- xinit } if (is.null(yuimaGUIsettings$simulation[[modID]][["nstep"]])) yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- NA if (is.null(yuimaGUIsettings$simulation[[modID]][["nsim"]])) yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- 1 if (is.null(yuimaGUIsettings$simulation[[modID]][["t0"]])) yuimaGUIsettings$simulation[[modID]][["t0"]] <<- end(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]) if (is.null(yuimaGUIsettings$simulation[[modID]][["t1"]])) if(is.numeric(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))) yuimaGUIsettings$simulation[[modID]][["t1"]] <<- 2*end(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected])-start(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]) else yuimaGUIsettings$simulation[[modID]][["t1"]] <<- end(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected])+365 if (is.null(yuimaGUIsettings$simulation[[modID]][["traj"]])) yuimaGUIsettings$simulation[[modID]][["traj"]] <<- TRUE if (is.null(yuimaGUIsettings$simulation[[modID]][["seed"]])) yuimaGUIsettings$simulation[[modID]][["seed"]] <<- NA } } }) output$simulate_modelID <- renderUI({ selectInput("simulate_modelID", label = "Simulation ID", choices = rownames(modelsToSimulate$table)) }) output$simulate_advancedSettings_modelID <- renderUI({ selectInput("simulate_advancedSettings_modelID", label = "Simulation ID", choices = rownames(modelsToSimulate$table)) }) output$simulate_seed <- renderUI({ if(!is.null(input$simulate_advancedSettings_modelID)) numericInput("simulate_seed", label = "RNG seed", step = 1, min = 0, value = yuimaGUIsettings$simulation[[input$simulate_advancedSettings_modelID]][["seed"]]) }) output$simulate_traj <- renderUI({ if(!is.null(input$simulate_advancedSettings_modelID)) selectInput("simulate_traj", label = "Save trajectory", choices = c(TRUE,FALSE), selected = yuimaGUIsettings$simulation[[input$simulate_advancedSettings_modelID]][["traj"]]) }) output$simulate_nsim <- renderUI({ if(!is.null(input$simulate_modelID)) numericInput("simulate_nsim", label = "Number of simulations", value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["nsim"]], min = 1, step = 1) }) output$simulate_nstep <- renderUI({ if(!is.null(input$simulate_modelID)){ id <- unlist(strsplit(input$simulate_modelID, split = " ")) if (input$simulate_modelID %in% names(yuimaGUIdata$usr_simulation)){ numericInput("simulate_nstep", label = "Number of steps per simulation", value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["nstep"]], min = 1, step = 1) } else if (!(isolate({yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$info$class}) %in% c("COGARCH", "CARMA"))) numericInput("simulate_nstep", label = "Number of steps per simulation", value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["nstep"]], min = 1, step = 1) } }) output$simulate_xinit <- renderUI({ if(!is.null(input$simulate_modelID)) numericInput("simulate_xinit", label = "Initial value", value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["xinit"]]) }) output$simulate_range <- renderUI({ if(!is.null(input$simulate_modelID)){ if (input$simulate_modelID %in% names(yuimaGUIdata$usr_simulation)){ return(div( column(6,numericInput("simulate_rangeNumeric_t0", label = "From", min = 0 ,value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]])), column(6,numericInput("simulate_rangeNumeric_t1", label = "To", min = 0, value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]])) )) } if (input$simulate_modelID %in% rownames(yuimaGUItable$model)){ id <- unlist(strsplit(input$simulate_modelID, split = " ")) if (class(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date") dateRangeInput("simulate_rangeDate", label = "Simulation interval", start = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]], end = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]]) else{ div( column(6,numericInput("simulate_rangeNumeric_t0", label = "From", min = 0 ,value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]])), column(6,numericInput("simulate_rangeNumeric_t1", label = "To", min = 0, value = yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]])) ) } } } }) observeEvent(input$simulate_button_apply_advancedSettings, { yuimaGUIsettings$simulation[[input$simulate_advancedSettings_modelID]][["seed"]] <<- input$simulate_seed yuimaGUIsettings$simulation[[input$simulate_advancedSettings_modelID]][["traj"]] <<- input$simulate_traj }) observeEvent(input$simulate_button_applyAll_advancedSettings, { for (modID in rownames(modelsToSimulate$table)){ yuimaGUIsettings$simulation[[modID]][["seed"]] <<- input$simulate_seed yuimaGUIsettings$simulation[[modID]][["traj"]] <<- input$simulate_traj } }) observeEvent(input$simulate_button_apply_nsim, { yuimaGUIsettings$simulation[[input$simulate_modelID]][["nsim"]] <<- input$simulate_nsim yuimaGUIsettings$simulation[[input$simulate_modelID]][["nstep"]] <<- input$simulate_nstep }) observeEvent(input$simulate_button_applyAll_nsim, { for (modID in rownames(modelsToSimulate$table)){ yuimaGUIsettings$simulation[[modID]][["nsim"]] <<- input$simulate_nsim yuimaGUIsettings$simulation[[modID]][["nstep"]] <<- input$simulate_nstep } }) observeEvent(input$simulate_button_apply_xinit, { yuimaGUIsettings$simulation[[input$simulate_modelID]][["xinit"]] <<- input$simulate_xinit }) observeEvent(input$simulate_button_applyAll_xinit, { for (modID in rownames(modelsToSimulate$table)) yuimaGUIsettings$simulation[[modID]][["xinit"]] <<- input$simulate_xinit }) observeEvent(input$simulate_button_apply_range, { if (input$simulate_modelID %in% names(yuimaGUIdata$usr_simulation)){ yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]] <<- input$simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]] <<- input$simulate_rangeNumeric_t1 } if (input$simulate_modelID %in% rownames(yuimaGUItable$model)){ id <- unlist(strsplit(input$simulate_modelID, split = " ")) if (class(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date"){ yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]] <<- input$simulate_rangeDate[1] yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]] <<- input$simulate_rangeDate[2] } else{ yuimaGUIsettings$simulation[[input$simulate_modelID]][["t0"]] <<- input$simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[input$simulate_modelID]][["t1"]] <<- input$simulate_rangeNumeric_t1 } } }) observeEvent(input$simulate_button_applyAll_range, { for (modID in rownames(modelsToSimulate$table)){ if (modID %in% names(yuimaGUIdata$usr_simulation)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$simulate_rangeNumeric_t1 } if (modID %in% rownames(yuimaGUItable$model)){ id <- unlist(strsplit(modID, split = " ")) if (class(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="Date" & !is.null(input$simulate_rangeDate)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$simulate_rangeDate[1] yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$simulate_rangeDate[2] } if (class(index(yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$model@[email protected]))=="numeric" & !is.null(input$simulate_rangeNumeric_t0)){ yuimaGUIsettings$simulation[[modID]][["t0"]] <<- input$simulate_rangeNumeric_t0 yuimaGUIsettings$simulation[[modID]][["t1"]] <<- input$simulate_rangeNumeric_t1 } } } }) observe({ if (!is.null(modelsToSimulate$table)) if (nrow(modelsToSimulate$table)!=0) { closeAlert(session, alertId = "simulate_alert_buttonEstimate1") closeAlert(session, alertId = "simulate_alert_buttonEstimate2") } }) observeEvent(input$simulate_simulateModels, { if (is.null(modelsToSimulate$table)) { if (input$panel_simulations=="Estimated models") createAlert(session = session, anchorId = "panel_simulate_model_alert", alertId = "simulate_alert_buttonEstimate1", content = "Table 'Selected Models' is empty", style = "warning") if (input$panel_simulations=="Non-estimated models") createAlert(session = session, anchorId = "panel_simulate_equation_alert", alertId = "simulate_alert_buttonEstimate2", content = "Table 'Selected Models' is empty", style = "warning") } else if (nrow(modelsToSimulate$table)==0) { if (input$panel_simulations=="Estimated models") createAlert(session = session, anchorId = "panel_simulate_model_alert", alertId = "simulate_alert_buttonEstimate1", content = "Table 'Selected Models' is empty", style = "warning") if (input$panel_simulations=="Non-estimated models") createAlert(session = session, anchorId = "panel_simulate_equation_alert", alertId = "simulate_alert_buttonEstimate2", content = "Table 'Selected Models' is empty", style = "warning") } else{ withProgress(message = 'Simulating: ', value = 0, { for (modID in rownames(modelsToSimulate$table)){ if(modID %in% names(yuimaGUIdata$usr_simulation)){ incProgress(1/nrow(modelsToSimulate$table), detail = paste(modID,"-",yuimaGUIdata$usr_simulation[[modID]][["Model"]])) jumps <- ifelse(is.null(yuimaGUIdata$usr_simulation[[modID]][["Jumps"]]),NA, yuimaGUIdata$usr_simulation[[modID]][["Jumps"]]) modName <- yuimaGUIdata$usr_simulation[[modID]][["Model"]] if(yuimaGUIdata$usr_simulation[[modID]][["Class"]]=='Point Process') modelYuimaGUI <- list(model = setModelByName(name = modName, jumps = jumps), info = list(class = yuimaGUIdata$usr_simulation[[modID]][["Class"]], modName = modName, jumps = jumps ) ) else modelYuimaGUI <- list(model = setYuima(model = setModelByName(name = modName, jumps = jumps)), info = list(class = yuimaGUIdata$usr_simulation[[modID]][["Class"]], modName = modName, jumps = jumps ) ) addSimulation( modelYuimaGUI = modelYuimaGUI, symbName = modID, xinit = yuimaGUIsettings$simulation[[modID]][["xinit"]], true.parameter = yuimaGUIdata$usr_simulation[[modID]][["true.param"]], nsim = yuimaGUIsettings$simulation[[modID]][["nsim"]], nstep = yuimaGUIsettings$simulation[[modID]][["nstep"]], simulate.from = yuimaGUIsettings$simulation[[modID]][["t0"]], simulate.to = yuimaGUIsettings$simulation[[modID]][["t1"]], saveTraj = yuimaGUIsettings$simulation[[modID]][["traj"]], seed = yuimaGUIsettings$simulation[[modID]][["seed"]], session = session, anchorId = "panel_simulations_alert" ) } else if(modID %in% rownames(yuimaGUItable$model)){ id <- unlist(strsplit(modID, split = " ")) incProgress(1/nrow(modelsToSimulate$table), detail = paste(id[1],"-",yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]]$info$modName)) addSimulation( modelYuimaGUI = yuimaGUIdata$model[[id[1]]][[as.numeric(id[2])]], symbName = id[1], xinit = yuimaGUIsettings$simulation[[modID]][["xinit"]], nsim = yuimaGUIsettings$simulation[[modID]][["nsim"]], nstep = yuimaGUIsettings$simulation[[modID]][["nstep"]], simulate.from = yuimaGUIsettings$simulation[[modID]][["t0"]], simulate.to = yuimaGUIsettings$simulation[[modID]][["t1"]], saveTraj = yuimaGUIsettings$simulation[[modID]][["traj"]], seed = yuimaGUIsettings$simulation[[modID]][["seed"]], session = session, anchorId = "panel_simulations_alert" ) } } }) updateTabsetPanel(session = session, inputId = "panel_simulations", selected = "Simulations") } }) observe({ shinyjs::toggle("div_simulations", condition = (input$panel_simulations!="Simulations")) })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/univariate_estimated.R
output$simulate_PrintModelLatex <- renderUI({ if (!is.null(input$simulate_model_usr_selectModel)){ return(withMathJax(printModelLatex(names = input$simulate_model_usr_selectModel, process = isolate({input$simulate_model_usr_selectClass}), jumps = jumps_shortcut(class = isolate({input$simulate_model_usr_selectClass}), jumps = input$simulate_model_usr_selectJumps)))) } }) output$simulate_model_usr_selectModel <- renderUI({ choices <- as.vector(defaultModels[names(defaultModels)==input$simulate_model_usr_selectClass]) sel <- choices[1] for(i in names(yuimaGUIdata$usr_model)) if (yuimaGUIdata$usr_model[[i]]$class==input$simulate_model_usr_selectClass) choices <- c(i, choices) selectInput("simulate_model_usr_selectModel", label = "Model Name", choices = choices, selected = sel) }) output$simulate_model_usr_selectJumps <- renderUI({ if(input$simulate_model_usr_selectClass %in% c("Compound Poisson", "Levy process")) return(selectInput("simulate_model_usr_selectJumps",label = "Jumps", choices = defaultJumps)) }) output$simulate_model_usr_selectParam <- renderUI({ valid <- TRUE if (is.null(input$simulate_model_usr_selectModel)) valid <- FALSE else if (isolate({input$simulate_model_usr_selectClass=="Compound Poisson"}) & is.null(input$simulate_model_usr_selectJumps)) valid <- FALSE if (valid) { mod <- setModelByName(input$simulate_model_usr_selectModel, jumps = jumps_shortcut(class = isolate({input$simulate_model_usr_selectClass}), jumps = input$simulate_model_usr_selectJumps)) choices <- getAllParams(mod = mod, class = input$simulate_model_usr_selectClass) return(selectInput("simulate_model_usr_selectParam", label = "Parameter", choices = choices)) } }) output$simulate_model_usr_param <- renderUI({ numericInput("simulate_model_usr_param", label = "Parameter value", value = NA) }) output$simulate_model_usr_ID <- renderUI({ textInput("simulate_model_usr_ID", label = "Simulation ID") }) observeEvent(input$simulate_model_usr_button_save, { if(input$simulate_model_usr_ID!=""){ id <- gsub(pattern = " ", x = input$simulate_model_usr_ID, replacement = "") if (is.null(yuimaGUIdata$usr_simulation[[id]])){ yuimaGUIdata$usr_simulation[[id]] <<- list() } yuimaGUIdata$usr_simulation[[id]][["Class"]] <<- input$simulate_model_usr_selectClass yuimaGUIdata$usr_simulation[[id]][["Model"]] <<- input$simulate_model_usr_selectModel yuimaGUIdata$usr_simulation[[id]][["Jumps"]] <<- input$simulate_model_usr_selectJumps if(!(input$simulate_model_usr_selectClass %in% c("Compound Poisson", "Levy process"))) yuimaGUIdata$usr_simulation[[id]][["Jumps"]] <<- NA if (is.null(yuimaGUIdata$usr_simulation[[id]][["true.param"]])){ yuimaGUIdata$usr_simulation[[id]][["true.param"]] <<- list() } mod <- setModelByName(input$simulate_model_usr_selectModel, jumps = input$simulate_model_usr_selectJumps) allparam <- getAllParams(mod = mod, class = input$simulate_model_usr_selectClass) if (length(allparam)==0) yuimaGUIdata$usr_simulation[[id]]["true.param"] <<- NULL if (length(allparam)!=0){ for(i in c(allparam, names(yuimaGUIdata$usr_simulation[[id]][["true.param"]]))){ if (!(i %in% names(yuimaGUIdata$usr_simulation[[id]][["true.param"]]))) yuimaGUIdata$usr_simulation[[id]][["true.param"]][[i]] <<- "MISSING" if(!(i %in% allparam)) yuimaGUIdata$usr_simulation[[id]][["true.param"]][i] <<- NULL } } } }) observe({ if (!is.null(input$simulate_model_usr_ID) & !is.null(input$simulate_model_usr_selectParam) & !is.null(input$simulate_model_usr_param)){ id <- gsub(pattern = " ", x = input$simulate_model_usr_ID, replacement = "") if (!is.null(yuimaGUIdata$usr_simulation[[id]])){ valid <- TRUE if(yuimaGUIdata$usr_simulation[[id]][["Model"]]!=input$simulate_model_usr_selectModel | input$simulate_model_usr_selectParam=="") valid <- FALSE else if (yuimaGUIdata$usr_simulation[[id]][["Class"]] %in% c("Compound Poisson", "Levy process")) if (yuimaGUIdata$usr_simulation[[id]][["Jumps"]]!=input$simulate_model_usr_selectJumps) valid <- FALSE if (valid) yuimaGUIdata$usr_simulation[[id]][["true.param"]][[input$simulate_model_usr_selectParam]] <- ifelse(is.na(input$simulate_model_usr_param),"MISSING",input$simulate_model_usr_param) } } }) observe({ for(i in names(yuimaGUIdata$usr_simulation)) if (!(yuimaGUIdata$usr_simulation[[i]]$Model %in% c(defaultModels, names(yuimaGUIdata$usr_model)))) yuimaGUIdata$usr_simulation[i] <<- NULL }) output$simulate_model_usr_table <- DT::renderDataTable(options=list(order = list(1, 'desc'), scrollX=TRUE, scrollY = 150, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "multiple",{ table <- data.frame() for (i in names(yuimaGUIdata$usr_simulation)){ newRow <- as.data.frame(yuimaGUIdata$usr_simulation[[i]]) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } if (length(table)==0){ NoData <- data.frame("Model"=NA, "Parameters"=NA) return(NoData[-1,]) } return (data.frame(table, row.names = names(yuimaGUIdata$usr_simulation))) }) observeEvent(input$simulate_model_usr_button_select, { if (!is.null(input$simulate_model_usr_table_rows_selected)){ table <- data.frame() for (i in names(yuimaGUIdata$usr_simulation)[input$simulate_model_usr_table_rows_selected]){ if ("MISSING" %in% yuimaGUIdata$usr_simulation[[i]][["true.param"]]){ createAlert(session = session, anchorId = "panel_simulate_equation_alert", alertId = "simulate_alert_usr_button_select", content = "There are still missing values in selected models", style = "error") } else { closeAlert(session, "simulate_alert_usr_button_select") newRow <- as.data.frame(yuimaGUIdata$usr_simulation[[i]], row.names=i) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } } if (length(rownames(table))!=0) modelsToSimulate$table <<- modelsToSimulate$table[-which(rownames(modelsToSimulate$table) %in% rownames(table)),] modelsToSimulate$table <<- rbind.fill(modelsToSimulate$table, table) } }) observeEvent(input$simulate_model_usr_button_selectAll, { if (!is.null(input$simulate_model_usr_table_rows_all)){ table <- data.frame() for (i in names(yuimaGUIdata$usr_simulation)[input$simulate_model_usr_table_rows_all]){ if ("MISSING" %in% yuimaGUIdata$usr_simulation[[i]][["true.param"]]){ createAlert(session = session, anchorId = "panel_simulate_equation_alert", alertId = "simulate_alert_usr_button_select", content = "There are still missing values in selected models", style = "error") } else { closeAlert(session, "simulate_alert_usr_button_select") newRow <- as.data.frame(yuimaGUIdata$usr_simulation[[i]], row.names=i) colnames(newRow) <- gsub(pattern = "true.param.", x = colnames(newRow), replacement = "") table <- rbind.fill(table, newRow) } } if (length(rownames(table))!=0) modelsToSimulate$table <<- modelsToSimulate$table[-which(rownames(modelsToSimulate$table) %in% rownames(table)),] modelsToSimulate$table <<- rbind.fill(modelsToSimulate$table, table) } }) observeEvent(input$simulate_model_usr_button_delete, { if (!is.null(input$simulate_model_usr_table_rows_selected)){ for (i in input$simulate_model_usr_table_rows_selected){ yuimaGUIdata$usr_simulation[i] <- NULL } } }) observeEvent(input$simulate_model_usr_button_deleteAll, { if (!is.null(input$simulate_model_usr_table_rows_all)){ for (i in input$simulate_model_usr_table_rows_all){ yuimaGUIdata$usr_simulation[i] <- NULL } } })
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/univariate_non_estimated.R
###Create simulations table output$simulate_monitor_table <- DT::renderDataTable(options=list(scrollY = 200, scrollX=TRUE, scrollCollapse = FALSE, deferRender = FALSE, dom = 'frtS'), extensions = 'Scroller', rownames = TRUE, selection = "single",{ if (length(yuimaGUItable$simulation)==0){ NoData <- data.frame("Symb"=NA,"Here will be stored simulations you run in the previous tabs"=NA, check.names = FALSE) return(NoData[-1,]) } return (yuimaGUItable$simulation) }) observe({ shinyjs::toggle("simulate_monitor_button_showSimulation", condition = (length(names(yuimaGUIdata$simulation))!=0)) }) ###Delete Simulation observeEvent(input$simulate_monitor_button_delete, priority = 1, { if(!is.null(input$simulate_monitor_table_rows_selected) & !is.null(input$simulate_monitor_table_row_last_clicked)){ if(input$simulate_monitor_table_row_last_clicked %in% input$simulate_monitor_table_rows_selected){ rowname <- unlist(strsplit(rownames(yuimaGUItable$simulation)[input$simulate_monitor_table_row_last_clicked], split = " " , fixed = FALSE)) delSimulation(symb=rowname[1], n=rowname[2]) } } }) ###DeleteAll Simulation observeEvent(input$simulate_monitor_button_deleteAll, priority = 1, { if(!is.null(input$simulate_monitor_table_rows_all)){ rowname <- unlist(strsplit(rownames(yuimaGUItable$simulation)[input$simulate_monitor_table_rows_all], split = " " , fixed = FALSE)) delSimulation(symb=rowname[seq(1,length(rowname),2)], n=rowname[seq(2,length(rowname),2)]) } }) output$simulate_showSimulation_simID <- renderUI({ selectInput(inputId = "simulate_showSimulation_simID", label = "Simulation ID", choices = rownames(yuimaGUItable$simulation)) }) observationTime <- reactiveValues(x = numeric()) observeEvent(input$simulate_showSimulation_simID,{ id <- unlist(strsplit(input$simulate_showSimulation_simID, split = " ")) if(!is.na(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])) observationTime$x <<- as.numeric(end(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory)) }) observe({ if (!is.null(input$simulate_showSimulation_plot_click$x) & !is.null(input$simulate_showSimulation_simID)){ id <- unlist(strsplit(input$simulate_showSimulation_simID, split = " ")) if(!is.na(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])) observationTime$x <<- input$simulate_showSimulation_plot_click$x } }) observe({ if(!is.null(input$simulate_showSimulation_simID)){ if(input$simulate_showSimulation_simID %in% rownames(yuimaGUItable$simulation)){ id <- unlist(strsplit(input$simulate_showSimulation_simID, split = " ")) shinyjs::toggle("simulate_showSimulation_plot_div", condition = !is.na(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory[1])) if(!is.na(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory[[1]])){ output$simulate_showSimulation_plot <- renderPlot({ if(input$simulate_showSimulation_simID %in% rownames(yuimaGUItable$simulation)){ par(bg="black") plot(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory, screens = 1, main = "Trajectory", xlab = "Index", ylab = "", log=switch(input$simulate_showSimulation_plot_scale,"Linear"="","Logarithmic (Y)"="y", "Logarithmic (X)"="x", "Logarithmic (XY)"="xy"), col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") abline(v = observationTime$x, col="yellow") grid(col="grey") } }) } } } }) simulation_hist <- reactiveValues(distribution=list(), values=vector()) observe({ if(!is.null(input$simulate_showSimulation_simID)){ if(input$simulate_showSimulation_simID %in% rownames(yuimaGUItable$simulation)) { id <- unlist(strsplit(input$simulate_showSimulation_simID, split = " ")) shinyjs::toggle("simulate_showSimulation_hist_div", condition = yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$info$nsim > 1) if(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$info$nsim > 1){ if(!is.na(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$hist[1])){ if(!is.null(input$simulate_showSimulation_hist_nBins)){ output$simulate_showSimulation_hist <- renderPlot({ par(bg="black") simulation_hist$values <<- yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$hist simulation_hist$distribution[[1]] <<- hist(yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$hist, freq = FALSE ,main = "Histogram", xlab = "", breaks = input$simulate_showSimulation_hist_nBins, col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(density(simulation_hist$values), col = "orange") grid() }) } } else{ if(!is.null(input$simulate_showSimulation_hist_nBins)){ traj <- yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory if(class(index(traj))[1]=="numeric"){ data <- traj[which(abs(index(traj)-observationTime$x) == min(abs(index(traj)-observationTime$x))),] } else { x <- as.Date(as.POSIXct.numeric(observationTime$x, origin = "1970-01-01")) data <- traj[which(abs(as.Date(index(traj))-x) == min(abs(as.Date(index(traj))-x))),] } output$simulate_showSimulation_hist <- renderPlot({ par(bg="black") simulation_hist$values <<- data simulation_hist$distribution[[1]] <<- hist(data, freq = FALSE ,main = "Histogram", xlab = "", breaks = input$simulate_showSimulation_hist_nBins, col="green", col.axis="grey", col.lab="grey", col.main="grey", fg="black") lines(density(simulation_hist$values), col = "orange") grid() }) } } } } } }) output$simulate_showSimulation_hist_text <- renderUI({ if(length(simulation_hist$values)!=0 & !is.null(input$simulate_showSimulation_hist_probability_slider)){ val <- as.numeric(simulation_hist$values) qq <- quantile(val, probs = input$simulate_showSimulation_hist_probability_slider/100) HTML(paste("<div>", "Lower:", qq[1],"<br/>", "Upper: ", qq[2], "<br/>", "Mean: ", mean(val[val>=qq[1] & val<=qq[2]]), "</div>")) } }) ###Save Trajectory Button output$simulate_showSimulation_button_saveTrajectory <- { dataDownload_traj <- reactive({ id <- unlist(strsplit(input$simulate_showSimulation_simID, split = " ")) x <- yuimaGUIdata$simulation[[id[1]]][[as.numeric(id[2])]]$trajectory d <- data.frame(x, row.names = index(x)) colnames(d) <- paste(id[1],id[2],"_",seq(1, ncol(d)), sep = "") return(d) }) downloadHandler( filename = function() { paste(input$simulate_showSimulation_simID, ".txt", sep="") }, content = function(file) { write.table(dataDownload_traj(), file, row.names = TRUE, col.names = TRUE, quote = TRUE) } ) } ###Save Histogram Button output$simulate_showSimulation_button_saveHist <- { dataDownload_hist <- reactive({ h <- simulation_hist$distribution[[1]] data.frame(midPoints = h$mids, counts = h$counts, frequency=h$counts/sum(h$counts),density = h$density) }) downloadHandler( filename = function() { paste(input$simulate_showSimulation_simID, "_hist",".txt", sep="") }, content = function(file) { write.table(dataDownload_hist(), file, row.names = FALSE, col.names = TRUE) } ) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server/simulation/univariate_results.R
options(shiny.maxRequestSize = 100*1024^2) options("getSymbols.warning4.0"=FALSE) server <- function(input, output, session) { ### comment this for web app version ### session$onSessionEnded(function() { stopApp() }) ### comment this for web app version ### debug.gui <- function(){} debug(debug.gui) source("server/settings.R", local = TRUE) source("server/functions.R", local = TRUE) source("server/home/home.R", local = TRUE) source("server/load_data/finance.R", local = TRUE) source("server/load_data/your_file.R", local = TRUE) source("server/eda/clustering.R", local = TRUE) source("server/eda/changepoint_non_parametric.R", local = TRUE) source("server/eda/changepoint_parametric.R", local = TRUE) source("server/eda/llag_and_corr.R", local = TRUE) source("server/modeling/univariate_start_estimation.R", local = TRUE) source("server/modeling/univariate_set_model.R", local = TRUE) source("server/modeling/univariate_results.R", local = TRUE) source("server/modeling/multivariate_start_estimation.R", local = TRUE) source("server/modeling/multivariate_results.R", local = TRUE) source("server/simulation/univariate_estimated.R", local = TRUE) source("server/simulation/univariate_non_estimated.R", local = TRUE) source("server/simulation/univariate_results.R", local = TRUE) source("server/simulation/multivariate_estimated.R", local = TRUE) source("server/simulation/multivariate_non_estimated.R", local = TRUE) source("server/simulation/multivariate_results.R", local = TRUE) source("server/finance/profit_and_loss.R", local = TRUE) }
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/server.R
tabItem(tabName = "changepoint", fluidRow( column(12, h3("Change Point Estimation",class = "hTitle"), h4("Select the data you wish to estimate change points for.", br(), "Choose the algorithm you want to use for estimation.", br(), "The results will be displayed below by plotting the series and the detected change points."), hr(class = "hrHeader") ) ), fluidRow(column(12,tabsetPanel(id = "panel_cpoint", type = "tabs", tabPanel(title = "Nonparametric", fluidRow(column(12,bsAlert("nonparametric_changepoint_alert"))), fluidRow(column(12, column(4, h4("Available data"), DT::dataTableOutput("changepoint_table_select") ), column(4, h4("Selected data"), DT::dataTableOutput("changepoint_table_selected") ), column(4,br(),br(),br(),br(), div(align="center", selectInput("changepoint_method", "Method", choices = c("Percentage Increments Distribution"="KSperc", "Increments Distribution"="KSdiff"))), div(align="center", numericInput("changepoint_pvalue", label = "p-value", value=0.01, min=0, max=1)) ) )), br(), fluidRow(column(12, column(2,actionButton("changepoint_button_select",label = "Select", align = "center")), bsTooltip("changepoint_button_select", title = "Select data", placement = "top"), column(2,actionButton("changepoint_button_selectAll",label = "Select All", align = "center")), bsTooltip("changepoint_button_selectAll", title = "Select all data that are displayed", placement = "top"), column(2,actionButton("changepoint_button_delete",label = "Delete", align = "center")), bsTooltip("changepoint_button_delete", title = "Delete selected data", placement = "top"), column(2,actionButton("changepoint_button_deleteAll",label = "Delete All", align = "center")), bsTooltip("changepoint_button_deleteAll", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("changepoint_button_startEstimation", label = "Start Estimation", align = "center")) )), br(),br(), fluidRow(column(12,shinyjs::hidden(div(id="changepoint_charts", hr(class = "hrHeader"), uiOutput("changepoint_symb", align="center"), div(fluidRow( column(6, div(align = "left", selectInput("changepoint_scale", label = "Scale", choices=c("Linear","Logarithmic (Y)","Logarithmic (X)", "Logarithmic (XY)"), width = "150px"))), column(6, div(align = "right", br(), a(id = "linkChangePointInfo", "Change Points Info", style = "font-size: 140%;", href = "#"))) )), bsModal(id = "ChangePointInfo", trigger = "linkChangePointInfo", title = "Change Points Info", column(12, fluidRow(uiOutput("text_ChangePointInfo")), br(), fluidRow(div(tableOutput("table_ChangePointInfo"), align="center")) ) ), fluidRow( column(6,plotOutput("changepoint_plot_series", brush = brushOpts(id = "changePoint_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "changePoint_dbclick")), column(6,plotOutput("changepoint_plot_incr", brush = brushOpts(id = "changePoint_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "changePoint_dbclick")) ),br(), fluidRow( column(8), column(2,actionButton("changepoint_button_delete_estimated",label = "Delete", align = "center")), bsTooltip("changepoint_button_delete_estimated", title = "Delete selected series", placement = "top"), column(2,actionButton("changepoint_button_deleteAll_estimated",label = "Delete All", align = "center")), bsTooltip("changepoint_button_deleteAll_estimated", title = "Delete all series", placement = "top") ) )))) ), tabPanel(title = "Parametric", fluidRow(column(12,bsAlert("parametric_changepoint_alert"))), fluidRow(column(12, column(4, h4("Available data"), DT::dataTableOutput("parametric_changepoint_table_select") ), column(4, h4("Selected data"), DT::dataTableOutput("parametric_changepoint_table_selected") ), column(4,br(),br(),div(align="center", uiOutput("parametric_changepoint_model"), sliderInput("parametric_modal_rangeFraction", label = "Training set (%)",min = 0, max = 100, value = c(20,80), step = 1, ticks = F), br(), column(6,div(actionButton("parametric_button_setRange", width = '95%', label = "Set Range"), align = "center")), column(6,div(actionButton("parametric_button_settings", width = '95%', label = "Advanced Settings"), align = "center")) )), bsModal(id="parametric_plotsRange", trigger = "parametric_button_setRange", title = "Select range to use for change point estimation", size = "large", div(id="parametric_plotsRangeErrorMessage",align = "center",h3("Select some series from table 'Available Data'", class = "hModal")), div(id="parametric_plotsRangeAll", fluidRow( column(8, plotOutput("parametric_selectRange", height = "350px", brush = brushOpts(id = "parametric_selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "parametric_selectRange_dbclick"), br(), plotOutput("parametric_selectRangeReturns", height = "350px", brush = brushOpts(id = "parametric_selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "parametric_selectRange_dbclick") ), column(4, div(selectInput("parametric_scale_selectRange", label = "Chart Scale", choices = c("Linear", "Logarithmic (Y)", "Logarithmic (X)", "Logarithmic (XY)")), align = "center"), br(),br(),br(), uiOutput("parametric_plotsRangeSeries", align = "center"), uiOutput("parametric_chooseRange", align = "center"), uiOutput("parametric_chooseRange_specify", align = "center"), column(6, tags$button(type="button", id="parametric_buttonApplyRange", class = "action-button", em("Apply")), bsTooltip("parametric_buttonApplyRange", title = "Apply Range to selected symbol", placement = "top") ), column(6, tags$button(type="button", id="parametric_buttonApplyAllRange", class = "action-button", em("Apply All")), bsTooltip("parametric_buttonApplyAllRange", title = "Apply Range to all symbols that are displayed", placement = "bottom") ) ) ) ) ), bsModal(id="parametric_modal_id", title="Advanced Settings", trigger = "parametric_button_settings", size = "large", div(id="parametric_modal_errorMessage", align = "center", h3("Select some series (from table 'Available Data')", class = "hModal")), div(id="parametric_modal_body", fluidRow( column(6, box(width = 12,div(align="center", h3("Series Settings", class = "hModal"), uiOutput("parametric_modal_series", align="center"), fluidRow( column(6,uiOutput("parametric_modal_delta", align="center")), column(6,uiOutput("parametric_modal_toLog", align="center")) ), fluidRow( column(6, tags$button(type="button", id="parametric_modal_button_applyDelta", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="parametric_modal_button_applyAllDelta", class = "action-button", em("Apply to All series"))) ) )), box(width = 12,div(align="center", h3("General Settings", class = "hModal"), uiOutput("parametric_modal_method", align="center"), fluidRow( column(6,uiOutput("parametric_modal_trials", align="center")), column(6,uiOutput("parametric_modal_seed", align="center")) ), fluidRow( column(6, tags$button(type="button", id="parametric_modal_button_applyGeneral", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="parametric_modal_button_applyAllModelGeneral", class = "action-button", em("Apply to All series"))) ) )) ), column(6, box(width = 12,div(align="center", h3("Model Settings", class = "hModal"), uiOutput("parametric_modal_model", align="center"), uiOutput("parametric_modal_parameter", align="center"), uiOutput("parametric_modal_start", align="center"), fluidRow( column(6,uiOutput("parametric_modal_startMin", align="center")), column(6,uiOutput("parametric_modal_startMax", align="center")) ), fluidRow( column(6,uiOutput("parametric_modal_lower", align="center")), column(6,uiOutput("parametric_modal_upper", align="center")) ), fluidRow( column(6, tags$button(type="button", id="parametric_modal_button_applyModel", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="parametric_modal_button_applyAllModel", class = "action-button", em("Apply to All series"))) ) )) ) ) ) ) )), br(), fluidRow(column(12, column(2,actionButton("parametric_changepoint_button_select",label = "Select", align = "center")), bsTooltip("changepoint_button_select", title = "Select data", placement = "top"), column(2,actionButton("parametric_changepoint_button_selectAll",label = "Select All", align = "center")), bsTooltip("changepoint_button_selectAll", title = "Select all data that are displayed", placement = "top"), column(2,actionButton("parametric_changepoint_button_delete",label = "Delete", align = "center")), bsTooltip("changepoint_button_delete", title = "Delete selected data", placement = "top"), column(2,actionButton("parametric_changepoint_button_deleteAll",label = "Delete All", align = "center")), bsTooltip("changepoint_button_deleteAll", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("parametric_changepoint_button_startEstimation", label = "Start Estimation", align = "center")) )), br(),br(), fluidRow(column(12,shinyjs::hidden(div(id="parametric_changepoint_charts", hr(class = "hrHeader"), uiOutput("parametric_changepoint_symb", align="center"), div(fluidRow( column(12, selectInput("parametric_changepoint_scale", label = "Scale", choices=c("Linear","Logarithmic (Y)","Logarithmic (X)", "Logarithmic (XY)"), width = "150px")) )), fluidRow( column(6,plotOutput("parametric_changepoint_plot_series", brush = brushOpts(id = "parametric_changePoint_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "parametric_changePoint_dbclick")), column(6, div(uiOutput("parametric_changepoint_info"), a(id = "parametric_linkChangePointInfo", "Change Point Info", style = "font-size: 140%;", href = "#"), align="center"),br(),br(),br(),br(),br(),br(),br(),br(),br(), fluidRow( column(2), column(4,actionButton("parametric_changepoint_button_delete_estimated",label = "Delete", align = "center")), bsTooltip("parametric_changepoint_button_delete_estimated", title = "Delete selected series", placement = "top"), column(4,actionButton("parametric_changepoint_button_deleteAll_estimated",label = "Delete All", align = "center")), bsTooltip("parametric_changepoint_button_deleteAll_estimated", title = "Delete all series", placement = "top") ) ) ), bsModal(id = "parametric_changepoint_modal_info", title = "Change Point Info", trigger = "parametric_linkChangePointInfo", fluidRow(column(12, uiOutput("parametric_changepoint_modal_info_text"))), br(), fluidRow( column(6, div(h5("Estimates before the Change Point", class = "hModal"), tableOutput("parametric_changepoint_modal_info_tableL"), align="center")), column(6, div(h5("Estimates after the Change Point", class = "hModal"), tableOutput("parametric_changepoint_modal_info_tableR"), align="center")) ) ) )))) ) ))) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/eda/changepoint.R
tabItem(tabName = "cluster", fluidRow( column(12, h3("Clustering",class = "hTitle"), h4("Select data you want to cluster.", br(), "Choose the distance you want to use and the kind of linkage for the hierarchical cluster analysis.", br(), "The results will be shown below by plotting a dendrogram and multidimensional scaling output."), hr(class = "hrHeader") ) ), fluidRow(column(12,bsAlert("cluster_alert"))), fluidRow(column(12, column(4, h4("Available data"), DT::dataTableOutput("cluster_table_select") ), column(4, h4("Selected data"), DT::dataTableOutput("cluster_table_selected") ), column(4,br(),br(), div(align="center", selectInput("cluster_linkage", "Linkage", choices = c("Complete"="complete", "Single"="single", "Average"="average", "Ward"="ward.D", "Ward squared"="ward.D2", "McQuitty"="mcquitty", "Median"="median", "Centroid"="centroid")), selectInput("cluster_distance", "Metric", choices = c("Percentage Increments Distribution"="MYdist_perc", "Increments Distribution"="MYdist_ass", "Markov Operator"="MOdist", "Euclidean"="euclidean", "Maximum"="maximum", "Manhattan"="manhattan", "Canberra"="canberra", "Minkowski"="minkowski")), shinyjs::hidden(numericInput("cluster_distance_minkowskiPower", label = "Power", value = 2))) ) )), br(), fluidRow(column(12, column(2,actionButton("cluster_button_select",label = "Select", align = "center")), bsTooltip("cluster_button_select", title = "Select data to cluster", placement = "top"), column(2,actionButton("cluster_button_selectAll",label = "Select All", align = "center")), bsTooltip("cluster_button_selectAll", title = "Select all data that are displayed", placement = "top"), column(2,actionButton("cluster_button_delete",label = "Delete", align = "center")), bsTooltip("cluster_button_delete", title = "Delete selected data", placement = "top"), column(2,actionButton("cluster_button_deleteAll",label = "Delete All", align = "center")), bsTooltip("cluster_button_deleteAll", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("cluster_button_startCluster", label = "Start Clustering", align = "center")) )), div(id="cluster_charts", align = "center", br(),br(), hr(class = "hrHeader"), fluidRow( column(4), column(4, uiOutput("cluster_analysis_id")) ), fluidRow(column(11, div(align="left", uiOutput("cluster_moreInfo")))), fluidRow(column(12, column(8, plotOutput("cluster_dendogram", click = "cluster_dendrogram_click")), column(4, plotOutput("cluster_scaling2D")) )), br(), fluidRow(column(12, column(2, div(actionButton("cluster_button_delete_analysis", label = "Delete"))), column(2, div(actionButton("cluster_button_deleteAll_analysis", label = "Delete All"))), column(2), column(2, div(downloadButton("cluster_button_saveDendogram", label = "Dendrogram"))), column(2), column(2, div(downloadButton("cluster_button_saveScaling2D", label = "Scaling"))) )) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/eda/cluster.R
tabItem(tabName = "llag", fluidRow( column(12, h3("Lead-Lag and Correlation Analysis",class = "hTitle"), h4("Select the series you wish to analyze and the kind of analysis you want to perform (Lead-Lag or Correlation).", br(), "Choose the correlation measure (if you selected Correlation) or the maximum lag to use (if you selected Lead-Lag).",br(), "You can specify which interval to use over the whole series for your analysis."), hr(class = "hrHeader") ) ), fluidRow(column(12,bsAlert("llag_alert"))), fluidRow(column(12, column(4, h4("Available data"), DT::dataTableOutput("llag_table_select") ), column(4, h4("Selected data"), DT::dataTableOutput("llag_table_selected") ), column(4,br(),br(), div(align="center", selectInput("llag_type", label = "Type of analysis", choices = c("Lead-Lag"="llag", "Correlation"="corr"), selected = "llag"), numericInput("llag_maxLag", label = "Max Lag", value = 20, min = 1, step = 1), bsTooltip("llag_maxLag", title = "Max Lag is expressed in days if you are using series indexed by date. It is expressed in the same unit of measure of the index if you are using numerical indexes.", placement = "top"), shinyjs::hidden(selectInput("llag_corr_method", label = "Method", choices = c("Pearson"="pearson", "Kendall"="kendall", "Spearman"="spearman", "Hayashi-Yoshida"="HY", "Pre-averaged Hayashi-Yoshida"="PHY", "Modulated Realized Covariance"="MRC", "Two Scales realized CoVariance"="TSCV", "Generalized Multiscale Estimator"="GME", "Realized Kernel"="RK", "Quasi Maximum Likelihood Estimator"="QMLE", "Separating Information Maximum Likelihood"="SIML", "Truncated Hayashi-Yoshida"="THY", "Pre-averaged Truncated Hayashi-Yoshida"="PTHY", "Subsampled Realized Covariance"="SRC", "Subsampled realized BiPower Covariation"="SBPC"), selected = "HY")), dateRangeInput("llag_range_date", label = "Range", start = Sys.Date()-365, end = Sys.Date()), shinyjs::hidden(div(id="llag_range_numeric", column(6,numericInput("llag_range_numeric1", label = "From", value = 0)), column(6,numericInput("llag_range_numeric2", label = "To", value = 1)) )) ) ) )), br(), fluidRow(column(12, column(2,actionButton("llag_button_select",label = "Select", align = "center")), bsTooltip("llag_button_select", title = "Select data", placement = "top"), column(2,actionButton("llag_button_selectAll",label = "Select All", align = "center")), bsTooltip("llag_button_selectAll", title = "Select all data that are displayed", placement = "top"), column(2,actionButton("llag_button_delete",label = "Delete", align = "center")), bsTooltip("llag_button_delete", title = "Delete selected data", placement = "top"), column(2,actionButton("llag_button_deleteAll",label = "Delete All", align = "center")), bsTooltip("llag_button_deleteAll", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("llag_button_startEstimation", label = "Start Analysis", align = "center")) )), br(), fluidRow(column(12, shinyjs::hidden(div(id = "llag_plot_body", align = "center", hr(class = "hrHeader"), fluidRow( column(4), column(4,uiOutput("llag_analysis_id")) ), fluidRow( column(12, div(align="center", numericInput("llag_plot_confidence", label = "Confidence Level",width = "20%", value = 0.001, min = 0, max = 1, step = 0.0001)), div(align="center", uiOutput("llag_plot_corr_method")) ), bsTooltip(id = "llag_plot_confidence", title = "The evaluated p-values should carefully be interpreted because they are calculated based on pointwise confidence intervals rather than simultaneous confidence intervals (so there would be a multiple testing problem). Evaluation of p-values based on the latter will be implemented in the future extension of this function: Indeed, so far no theory has been developed for this. However, it is conjectured that the error distributions of the estimated cross-correlation functions are asymptotically independent if the grid is not dense too much, so p-values evaluated by this function will still be meaningful as long as sufficiently low significance levels are used.") ), fluidRow( column(1), column(10,plotOutput("llag_plot", height = "600px")) ), fluidRow( column(1), column(2,actionButton("llag_delete_analysis", label = "Delete")), column(6), column(2,actionButton("llag_deleteAll_analysis", label = "Delete All")) ), HTML("<div id = 'llag_plot_howToRead'><h4><b>How to read the plot:</b><br/>If the lead-lag is positive: 'row.name' anticipates 'col.name of 'X' periods<br/>If the lead-lag is negative: 'row.name' follows 'col.name' with 'X' delay periods<br/><br/><b>'X'</b> are the numbers in the plot above.<br/>They are expressed in days if you are using time series, or in the same unit of measure of time if you are using numerical time index.<br/>The numbers in round brackets are correlations between the series shifted by the corresponding estimated lead-lag parameter.</h4></div>") ))) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/eda/llag.R
tabItem(tabName = "hedging", fluidRow( column(12, h3("Here you can manage the risk of a portfolio composed of options and the underlying asset.",class = "hTitle"), h4("The evolution of the underlying asset is simulated by the models you estimated in the Modeling section.", br(), "After performing the simulation, click on the Show P&L button in the Profit&Loss tab and customize your portfolio.",br(), "The Profit&Loss distribution of your portfolio will be displayed (it includes transaction costs that you can customize)."), hr(class = "hrHeader") ) ), fluidRow(column(12,bsAlert("hedging_alert"))), tabsetPanel(id = "panel_hedging", type = "tabs", tabPanel(title = "Start simulations", fluidRow(column(12, br(), h4("Click on the model in order to simulate the evolution of the underlying asset"), DT::dataTableOutput("hedging_databaseModels") ) ), br(), fluidRow(column(12,div(align="center", br(), fluidRow( column(3,selectInput("hedging_type", label="Option Type:", c(Call="call", Put="put"))), column(3,uiOutput("hedging_strike")), column(3,dateInput("hedging_maturity", label="Maturity:", value = Sys.Date()+30)), column(3,numericInput("hedging_optMarketPrice", label="Option Market Price:", value=NA, min = 0)) ), fluidRow( column(3), column(3,uiOutput("hedging_assMarketPrice")), column(3,numericInput("hedging_lotMult", label="Number of Options per Lot:", value=1, min = 1)), column(3) ), fluidRow( column(4), column(4,numericInput("hedging_nSim", label="Number of Simulations", value=1000, min = 1)), column(4) ), fluidRow( column(4), column(4, actionButton("hedging_button_startComputation", label = "Start Computation", width = "50%")) ) ))) ), tabPanel(title = "Profit&Loss", bsModal(id="hedging_commissionPlan", trigger = "hedging_button_show", title = "Profit & Loss", size = "large", div(id="hedging_body",align="center", fluidRow( column(3), column(6, uiOutput("hedging_modal_id")), column(3, uiOutput("hedging_modal_id_hidden")) ), fluidRow( column(3), column(3,uiOutput("hedging_nOptLot_hedge")), column(3,uiOutput("hedging_nAss_hedge")) ), fluidRow( column(9, plotOutput("hedging_plot_distribution")), column(3, sliderInput("hedging_slider_nBin", label = "Adjust bin width", min=1, max=100, value = 30, step = 1, ticks = FALSE), br(), sliderInput("hedging_slider_rangeHist", label = "Quantiles (%)", min = 0, max = 100, value = c(5,95), ticks = FALSE, step = 0.01), uiOutput("hedging_quantiles_text"), br(),br(), uiOutput("hedging_capital_text"), br(),br(), actionButton("hedging_button_saveHedging", "Save Changes", width = "80%") ) ), br(), box(title = p("Modify Option", style="color:black; font-weight: bold;"),collapsible = TRUE, collapsed = FALSE, width = 12, fluidRow( column(4,uiOutput("hedging_type2")), column(4,uiOutput("hedging_strike2")), column(4,uiOutput("hedging_optMarketPrice2")) ) ), box(title = p("Trading Costs", style="color:black; font-weight: bold;"),collapsible = TRUE, collapsed = FALSE, width = 12, fluidRow( column(3,br(),numericInput("hedging_percCostAss", label="Asset: Trading cost (%):", value=0.19, min = 0)), column(3,br(),numericInput("hedging_minCostAss", label="Asset: Min trading cost:", value=2.95, min = 0)), column(3,numericInput("hedging_rateShort", label="Asset: Yearly interest rate short position (%):", value=4.95, min = 0)), column(3,numericInput("hedging_lotCostOpt", label="Option: Trading cost per lot:", value=5.95, min = 0)) ) ) ) ), fluidRow(column(12,br(), DT::dataTableOutput("hedging_table_results") )), br(), fluidRow( column(2,actionButton(inputId = "hedging_button_show", label = "Show P&L")), column(6), column(2,actionButton(inputId = "hedging_button_delete", label = "Delete")), column(2,actionButton(inputId = "hedging_button_deleteAll", label = "Delete All")) ) ) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/finance/hedging.R
tabItem(tabName = "home", fluidRow( column(12, h1("Welcome to yuimaGUI", align = "center", class = "hTitle"), h4("An amazingly powerful tool for your analyses", align = "center"), hr(class = "hrHeader"), h4("Get acquainted with yuimaGUI and learn how to get the most out of it in a few simple steps", class = "hTitle", align = "center"), br() )), fluidRow( column(8, h4("Step 1", class = "hTitle"), h4("Load the data you wish to analyze in the section Data I/O.", br(), "The interface provides an easy way to load economic data (e.g. GDP) or a financial series (stocks and shares) from the Internet. If you prefer, you can load data from your own files.",br(), "Once the data is loaded, you can then use the Explorative Data Analysis and Modeling sections."), h4("Step 2", class = "hTitle"), h4("Model data in section Modeling.", br(), "Here you can fit models choosing between a number of default options or defining your own model.", br(), "Now you are ready to go to the Simulate section."), h4("Step 3", class = "hTitle"), h4("Read the short explanation at the beginning of each section for further information. Enjoy!") ), column(4, br(), br(), uiOutput("video_intro", align = "center") ) ), fluidRow( column(8,h4(),br(),br(),br(), h4("Tips", class = "hTitle"), h4("Press F11 to go to full screen.", br(), "Press CTRL+ or CTRL- to zoom in and out.") ), column(4, h3(em("Developed by"), class = "hTitle", align = "center"), h4("Emanuele Guidotti", align = "center"), h3(em("in collaboration with"), class = "hTitle", align = "center"), h4("Stefano M. Iacus & Lorenzo Mercuri", align = "center") ) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/home/home.R
tabItem(tabName="finData", fluidRow( column(12, h3("Load Financial and Economic data",class = "hTitle"), h4("For Stocks and Shares, select Yahoo as the source using the symbols you can find ", a("here", href="http://finance.yahoo.com/lookup", target = "_blank"), ".", br(), "For currencies and metals, select Oanda as the source and type the two symbols divided by '/' (e.g. EUR/USD or XAU/USD ).", "The symbols are available ", a("here",href="http://www.oanda.com/help/currency-iso-code", target = "_blank"), ".", br(), "Economic series are available from ",a("Federal Reserve Bank of St. Louis", href="https://research.stlouisfed.org/fred2/", target = "_blank"), ".", "Follow this ", a("example",href="example.jpg", target = "_blank"), " to find the symbols.", br(), "Multiple symbols are allowed if divided by empty spaces and/or commas (e.g. AAPL FB CSCO or AAPL,FB,CSCO)."), hr(class = "hrHeader") ) ), fluidRow(column(12,bsAlert("finDataAlert"))), fluidRow( column(6, textInput(inputId="symb", value = NULL,label = "Insert Symbol"), dateRangeInput(inputId="dR", label = "Download data from", start = "1900-01-01" ,end = Sys.Date()), selectInput(inputId="sources", label = "Source", choices = c("Yahoo (OHLC data)" = "yahoo", "Oanda (Currencies & Metals)" = "oanda", "Federal Reserve Bank of St. Louis" = "FRED")), tags$button(type="button", id="finDataGo", class = "action-button", em("Load data")), br(),br(),br(), column(9), column(3,shinyjs::hidden(selectInput("scale_finDataPlot", label = "Chart Scale", choices = c("Linear", "Logarithmic")))) ), column(6, plotOutput("finDataPlot", height = "350px", brush = brushOpts(id = "finDataPlot_brush", delayType = "debounce", clip = TRUE, delay = 10000, resetOnNew = TRUE), dblclick = "finDataPlot_dbclick") ) ), br(), fluidRow( column(12, DT::dataTableOutput("database1")) ), shinyjs::hidden(div(id="buttons_DataIO_fin", br(), fluidRow( column(6), column(2,downloadButton(outputId = "finDataSave", label = "Save")), bsTooltip("finDataSave", title = "Save data to file", placement = "top"), column(2,actionButton(inputId = "finDataDelete", label = "Delete")), bsTooltip("finDataDelete", title = "Delete selected data", placement = "top"), column(2,actionButton(inputId = "finDataDeleteAll", label = "Delete All")), bsTooltip("finDataDeleteAll", title = "Delete all data that are displayed", placement = "top") ) )) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/load_data/finData.R
tabItem("yourData", fluidRow( column(12, h3("Load data from Your Own Files",class = "hTitle"), h4("Upload your file and specify its structure. A preview will appear below.", br(), "Declare if the file contains raw and/or column headers and specify what kind of field separator has to be used to read the data.", br(), "Each column will be uploaded as a different series. So you may wish to switch columns with rows if your file is organized differently.", br(), "Specify the format and the column to use as an index."), hr(class = "hrHeader") ) ), fluidRow(column(12,bsAlert("yourDataAlert"))), fluidRow( column(5, fileInput(inputId = "yourFile", width = "60%", label = "Choose file to upload", multiple = FALSE), selectInput('yourFileHeader', 'Headers',width = "60%", choices = c("Auto"="Default","Only columns", "Only rows", "Both", "None"), selected = "Default"), selectInput(inputId = 'yourFileSep',width = "60%", label = 'Field Separator', choices = c("Space"="default", "Comma"=',', "Semicolon"=';', "Tab"='\t'), selected = "default"), uiOutput("yourFileIndex"), uiOutput("yourFileFUN"), br(), div(align = "center", style="width:55%", box(background = switch(getOption("yuimaGUItheme"), "black"="black", "white"=NULL), width = 12, title = "More Settings", collapsible = TRUE, id = "yourFileMoreSettings", collapsed = TRUE, textInput('yourFileDec', 'Decimal Separator', value = "."), textInput('yourFileThnd', 'Thousands Separator', value = ""), textInput("yourFileNA", "Missing Value string", value = "NA"), numericInput("yourFileLine", "Begin from line", value = 1, min = 1, step = 1), selectInput('yourFileSwitch', 'Switch rows/columns', choices = c("No"=FALSE, "Yes"=TRUE)) ) )), column(7, textOutput("yourFilePreviewText"), DT::dataTableOutput("yourFilePreview"), br(), uiOutput("yourFileButton", align = "center") ) ), br(), br(), fluidRow( column(12, DT::dataTableOutput("database2") ) ), shinyjs::hidden(div(id="buttons_DataIO_file", br(), fluidRow( column(6), column(2, downloadButton(outputId = "yourFileSave", label = "Save")), bsTooltip("yourFileSave", title = "Save data to file", placement = "top"), column(2,actionButton(inputId = "yourFileDelete", label = "Delete")), bsTooltip("yourFileDelete", title = "Delete selected data", placement = "top"), column(2,actionButton(inputId = "yourFileDeleteAll", label = "Delete All")), bsTooltip("yourFileDeleteAll", title = "Delete all data that are displayed", placement = "top") ) )) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/load_data/yourData.R
tabItem(tabName="models", fluidRow(column(12, fluidRow( column(12, h3("Univariate Model Estimation",class = "hTitle"), h4("Select the data and the model you wish to estimate. Each model will be fitted to each selected series.", br(), "Click on the Set Range and Advanced Settings buttons to customize the estimation process.", br(), "A number of default models are available but you can set your own model (tab Set model) and use it for estimation and/or simulation purposes."), hr(class = "hrHeader") ) ), fluidRow(column(12,tabsetPanel(id = "panel_estimates", type = "tabs", tabPanel(title = "Run estimation", fluidRow(column(12,bsAlert("panel_run_estimation_alert"))), br(), fluidRow( column(4,div(align="center", selectInput("modelClass",label = "Model Class", choices = c("Diffusion process", "Fractional process", "Compound Poisson","Point Process", #"Levy process", "CARMA", "COGARCH"), selected = "Diffusion process"), uiOutput("model"), uiOutput("jumps"), uiOutput("pq_C") )), column(5, fluidRow(shinyjs::hidden(h4(id="titlePrintModelLatex","Models to estimate:", style="font-size: 2em;"))), fluidRow(uiOutput("PrintModelLatex")) ) ), br(), fluidRow( column(4, h4("Available data"), DT::dataTableOutput("database3") ), column(4, h4("Selected data"), DT::dataTableOutput("database4") ), column(4, br(),br(),br(),br(),br(),br(), div(actionButton("DisplayPlotsRange", label = "Set Range"), align = "center"), br(), div(actionButton("advancedSettingsButton", label = "Advanced Settings", align = "center"), align = "center") ) ), br(), fluidRow( column(2,actionButton("buttonSelect_models_Univariate",label = "Select", align = "center")), bsTooltip("buttonSelect_models_Univariate", title = "Select data to model", placement = "top"), column(2,actionButton("buttonSelectAll_models_Univariate",label = "Select All", align = "center")), bsTooltip("buttonSelectAll_models_Univariate", title = "Select all data that are displayed", placement = "top") , column(2,actionButton("buttonDelete_models_Univariate",label = "Delete", align = "center")), bsTooltip("buttonDelete_models_Univariate", title = "Delete selected data", placement = "top"), column(2,actionButton("buttonDeleteAll_models_Univariate",label = "Delete All", align = "center")), bsTooltip("buttonDeleteAll_models_Univariate", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("EstimateModels", label = "Start Models Estimation", align = "center")) ) ), tabPanel(title = "Set model", fluidRow(column(12,bsAlert("panel_set_model_alert"))), br(), fluidRow(div(align="center", column(6, fluidRow(selectInput("usr_modelClass",label = "Model Class", width = "50%", choices = c("Diffusion process", "Fractional process", "Compound Poisson"), selected = "Diffusion process")), fluidRow(textInput("usr_model_name", label = "Model Name", width = "50%")), fluidRow(uiOutput("usr_modelClass_latex")), fluidRow(uiOutput("usr_model_coeff")), br(),br(), fluidRow( column(4), column(4,actionButton("usr_model_button_save", label = "Save Model")) ) ), column(6,div(id="usr_model_saved_div",align="center", uiOutput("usr_model_saved"), uiOutput("usr_model_saved_latex"), br(), actionButton("usr_model_button_delete", label = "Delete Model(s)") )) )) ), tabPanel(title = "Estimates", fluidRow(column(12,bsAlert("panel_estimates_alert"))), shinyjs::hidden(div(id="estimates_info", fluidRow( column(12, textOutput("SymbolName"), a(id = "linkMoreInfo", tags$u("More Info"), href = "#"), bsModal(id = "MoreInfo", trigger = "linkMoreInfo", title = "Info", size = "large", column(12, fluidRow(uiOutput("text_MoreInfo")), br(), fluidRow(div(tableOutput("table_MoreInfo"), align="center")), bsTooltip(id = "table_MoreInfo" ,"Estimates and Std. Errors are coherent with delta that has been used. No conversion to other units of measure has been applied.") ) ), uiOutput("estimatedModelsLatex") ), column(12, div(align = "center", tableOutput("estimatedModelsTable"), shinyjs::hidden(selectInput(inputId = "baseModels", label = "Base", width = "150px", choices = c("Yearly","Semestral","Quarterly","Trimestral","Bimestral","Monthly","Weekly","Daily"), selected = "Yearly")) ) ) ))), fluidRow( column(12, br(), DT::dataTableOutput("databaseModels")) ), br(), fluidRow( column(2,actionButton(inputId = "databaseModels_button_showResults", label = "Show Fitting")), bsTooltip("databaseModels_button_showResults", title = "Available for: Diffusive Processes, Compound Poisson and COGARCH", placement = "top"), column(6), column(2,actionButton(inputId = "databaseModelsDelete", label = "Delete")), bsTooltip("databaseModelsDelete", title = "Delete selected model", placement = "top"), column(2,actionButton(inputId = "databaseModelsDeleteAll", label = "Delete All")), bsTooltip("databaseModelsDeleteAll", title = "Delete all models that are displayed", placement = "top") ), bsModal(id = "model_modal_fitting", title = "Fitting", trigger = "databaseModels_button_showResults", size = "Large", div(id = "model_modal_fitting_body", fluidRow( column(2), column(8, uiOutput("model_modal_model_id", align = "center")) ), fluidRow( column(12, plotOutput("model_modal_plot_variance"), plotOutput("model_modal_plot_intensity"), plotOutput("model_modal_plot_distr"), uiOutput("model_modal_plot_test", align = "center") ) ) ) ) ) ))), bsModal(id="plotsRange", trigger = "DisplayPlotsRange", title = "Select range to use for models estimation", size = "large", div(id="plotsRangeErrorMessage",align = "center",h3("Select some series from table 'Available Data'", class = "hModal")), div(id="plotsRangeAll", fluidRow( column(8, plotOutput("selectRange", height = "350px", brush = brushOpts(id = "selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "selectRange_dbclick"), br(), plotOutput("selectRangeReturns", height = "350px", brush = brushOpts(id = "selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "selectRange_dbclick") ), column(4, div(selectInput("scale_selectRange", label = "Chart Scale", choices = c("Linear", "Logarithmic (Y)", "Logarithmic (X)", "Logarithmic (XY)")), align = "center"), br(),br(),br(), uiOutput("plotsRangeSeries", align = "center"), uiOutput("chooseRange", align = "center"), uiOutput("chooseRange_specify", align = "center"), column(6, tags$button(type="button", id="buttonApplyRange", class = "action-button", em("Apply")), bsTooltip("buttonApplyRange", title = "Apply Range to selected symbol", placement = "top") ), column(6, tags$button(type="button", id="buttonApplyAllRange", class = "action-button", em("Apply All")), bsTooltip("buttonApplyAllRange", title = "Apply Range to all symbols that are displayed", placement = "bottom") ) ) ) ) ), bsModal(id="advancedSettings", title="Advanced Settings", trigger = "advancedSettingsButton", size = "large", div(id="advancedSettingsErrorMessage",align = "center",h3("Select some models and series (from table 'Available Data')", class = "hModal")), div(id="advancedSettingsAll", fluidRow( column(6, box(width = 12,div(align="center", h3("Series Settings", class = "hModal"), uiOutput("advancedSettingsSeries", align="center"), fluidRow( column(6,uiOutput("advancedSettingsDelta", align="center")), column(6,uiOutput("advancedSettingsToLog", align="center")) ), fluidRow( column(6, tags$button(type="button", id="advancedSettingsButtonApplyDelta", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="advancedSettingsButtonApplyAllDelta", class = "action-button", em("Apply to All series"))) ) )), box(width = 12,div(align="center", h3("General Settings", class = "hModal"), uiOutput("advancedSettingsMethod", align="center"), uiOutput("advancedSettingsThreshold", align="center"), fluidRow( column(6,uiOutput("advancedSettingsTrials", align="center")), column(6,uiOutput("advancedSettingsSeed", align="center")) ), uiOutput("advancedSettingsJoint", align="center"), uiOutput("advancedSettingsAggregation", align="center"), uiOutput("advancedSettingsTimeout", align="center"), fluidRow( column(6, tags$button(type="button", id="advancedSettingsButtonApplyGeneral", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="advancedSettingsButtonApplyAllModelGeneral", class = "action-button", em("Apply to All series"))) ), fluidRow(column(12, tags$button(type="button", id="advancedSettingsButtonApplyAllGeneral", class = "action-button", em("Apply to All series & models")))) )) ), column(6, box(width = 12,div(align="center", h3("Model Settings", class = "hModal"), uiOutput("advancedSettingsModel", align="center"), uiOutput("advancedSettingsParameter", align="center"), uiOutput("advancedSettingsFixed", align="center"), uiOutput("advancedSettingsStart", align="center"), fluidRow( column(6,uiOutput("advancedSettingsStartMin", align="center")), column(6,uiOutput("advancedSettingsStartMax", align="center")) ), fluidRow( column(6,uiOutput("advancedSettingsLower", align="center")), column(6,uiOutput("advancedSettingsUpper", align="center")) ), fluidRow( column(6, tags$button(type="button", id="advancedSettingsButtonApplyModel", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="advancedSettingsButtonApplyAllModel", class = "action-button", em("Apply to All series"))) ) )) ) ) ) ) )) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/modeling/models.R
tabItem(tabName="multi_models", fluidRow(column(12, fluidRow( column(12, h3("Multivariate Model Estimation",class = "hTitle"), h4("Select the data and the model you wish to estimate. The model will be fitted to the selected series.", br(), "Click on buttons Set Range and Advanced Settings to customize the estimation process.", br(), 'Building your own multivariate model is not possible at the moment.' #"Some default models are available but you can set your own model (tab 'Set model') and use it for estimation and/or simulation purposes." ), hr(class = "hrHeader") ) ), fluidRow(column(12,tabsetPanel(id = "multi_panel_estimates", type = "tabs", tabPanel(title = "Run estimation", fluidRow(column(12,bsAlert("multi_panel_run_estimation_alert"))), br(), fluidRow( column(4,div(align="center", selectInput("multi_modelClass",label = "Model Class", choices = c("Diffusion process"), selected = "Diffusion process"), uiOutput("multi_model"), uiOutput("multi_jumps"), uiOutput("multi_pq_C") )), column(5, fluidRow(shinyjs::hidden(h4(id="multi_titlePrintModelLatex","Models to estimate:", style="font-size: 2em;"))), fluidRow(uiOutput("multi_PrintModelLatex")) ) ), br(), fluidRow( column(4, h4("Available data"), DT::dataTableOutput("multi_database3") ), column(4, h4("Selected data"), DT::dataTableOutput("multi_database4") ), column(4, br(),br(),br(),br(),br(),br(), div(actionButton("multi_DisplayPlotsRange", label = "Set Range"), align = "center"), br(), div(actionButton("multi_advancedSettingsButton", label = "Advanced Settings", align = "center"), align = "center") ) ), br(), fluidRow( column(2,actionButton("multi_buttonSelect_models_Univariate",label = "Select", align = "center")), bsTooltip("multi_buttonSelect_models_Univariate", title = "Select data to model", placement = "top"), column(2,actionButton("multi_buttonSelectAll_models_Univariate",label = "Select All", align = "center")), bsTooltip("multi_buttonSelectAll_models_Univariate", title = "Select all data that are displayed", placement = "top") , column(2,actionButton("multi_buttonDelete_models_Univariate",label = "Delete", align = "center")), bsTooltip("multi_buttonDelete_models_Univariate", title = "Delete selected data", placement = "top"), column(2,actionButton("multi_buttonDeleteAll_models_Univariate",label = "Delete All", align = "center")), bsTooltip("multi_buttonDeleteAll_models_Univariate", title = "Delete all data that are displayed", placement = "top"), column(4,actionButton("multi_EstimateModels", label = "Start Models Estimation", align = "center")) ) ), # tabPanel(title = "Set model", # fluidRow(column(12,bsAlert("multi_panel_set_model_alert"))), # br(), # fluidRow(div(align="center", # column(6, # fluidRow(selectInput("multi_usr_modelClass",label = "Model Class", width = "50%", choices = c("Diffusion process", "Fractional process", "Compound Poisson"), selected = "Diffusion process")), # fluidRow(textInput("multi_usr_model_name", label = "Model Name", width = "50%")), # fluidRow(uiOutput("multi_usr_modelClass_latex")), # fluidRow(uiOutput("multi_usr_model_coeff")), # br(),br(), # fluidRow( # column(4), # column(4,actionButton("multi_usr_model_button_save", label = "Save Model")) # ) # ), # column(6,div(id="multi_usr_model_saved_div",align="center", # uiOutput("multi_usr_model_saved"), # uiOutput("multi_usr_model_saved_latex"), # br(), # actionButton("multi_usr_model_button_delete", label = "Delete Model(s)") # )) # )) # ), tabPanel(title = "Estimates", fluidRow(column(12,bsAlert("multi_panel_estimates_alert"))), shinyjs::hidden(div(id="multi_estimates_info", fluidRow( column(12, textOutput("multi_SymbolName"), a(id = "multi_linkMoreInfo", tags$u("More Info"), href = "#"), bsModal(id = "multi_MoreInfo", trigger = "multi_linkMoreInfo", title = "Info", size = "large", column(12, fluidRow(uiOutput("multi_text_MoreInfo")), br(), fluidRow(div(tableOutput("multi_table_MoreInfo"), align="center")), bsTooltip(id = "multi_table_MoreInfo" ,"Estimates and Std. Errors are coherent with delta that has been used. No conversion to other units of measure has been applied.") ) ), uiOutput("multi_estimatedModelsLatex") ), column(12, div(align = "center", tableOutput("multi_estimatedModelsTable"), shinyjs::hidden(selectInput(inputId = "multi_baseModels", label = "Base", width = "150px", choices = c("Yearly","Semestral","Quarterly","Trimestral","Bimestral","Monthly","Weekly","Daily"), selected = "Yearly")) ) ) ))), fluidRow( column(12, br(), DT::dataTableOutput("multi_databaseModels")) ), br(), fluidRow( column(2,actionButton(inputId = "multi_databaseModels_button_showResults", label = "Show Fitting")), bsTooltip("multi_databaseModels_button_showResults", title = "Available for: Diffusive Processes", placement = "top"), column(6), column(2,actionButton(inputId = "multi_databaseModelsDelete", label = "Delete")), bsTooltip("multi_databaseModelsDelete", title = "Delete selected model", placement = "top"), column(2,actionButton(inputId = "multi_databaseModelsDeleteAll", label = "Delete All")), bsTooltip("multi_databaseModelsDeleteAll", title = "Delete all models that are displayed", placement = "top") ), bsModal(id = "multi_model_modal_fitting", title = "Fitting", trigger = "multi_databaseModels_button_showResults", size = "Large", div(id = "multi_model_modal_fitting_body", fluidRow( column(2), column(8, uiOutput("multi_model_modal_model_id", align = "center"), uiOutput("multi_model_modal_series_id", align = "center") ) ), fluidRow( column(12, plotOutput("multi_model_modal_plot_variance"), plotOutput("multi_model_modal_plot_intensity"), plotOutput("multi_model_modal_plot_distr"), uiOutput("multi_model_modal_plot_test", align = "center") ) ) ) ) ) ))), bsModal(id="multi_plotsRange", trigger = "multi_DisplayPlotsRange", title = "Select range to use for models estimation", size = "large", div(id="multi_plotsRangeErrorMessage",align = "center",h3("Select some series from table 'Available Data'", class = "hModal")), div(id="multi_plotsRangeAll", fluidRow( column(8, plotOutput("multi_selectRange", height = "350px", brush = brushOpts(id = "multi_selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "multi_selectRange_dbclick"), br(), plotOutput("multi_selectRangeReturns", height = "350px", brush = brushOpts(id = "multi_selectRange_brush", delayType = "debounce", delay = 10000, resetOnNew = TRUE), dblclick = "multi_selectRange_dbclick") ), column(4, div(selectInput("multi_scale_selectRange", label = "Chart Scale", choices = c("Linear", "Logarithmic (Y)", "Logarithmic (X)", "Logarithmic (XY)")), align = "center"), br(),br(),br(), uiOutput("multi_plotsRangeSeries", align = "center"), uiOutput("multi_chooseRange", align = "center"), uiOutput("multi_chooseRange_specify", align = "center"), column(6, tags$button(type="button", id="multi_buttonApplyRange", class = "action-button", em("Apply")), bsTooltip("multi_buttonApplyRange", title = "Apply Range to selected symbol", placement = "top") ), column(6, tags$button(type="button", id="multi_buttonApplyAllRange", class = "action-button", em("Apply All")), bsTooltip("multi_buttonApplyAllRange", title = "Apply Range to all symbols that are displayed", placement = "bottom") ) ) ) ) ), bsModal(id="multi_advancedSettings", title="Advanced Settings", trigger = "multi_advancedSettingsButton", size = "large", div(id="multi_advancedSettingsErrorMessage",align = "center",h3("Select some models and series (from table 'Available Data')", class = "hModal")), div(id="multi_advancedSettingsAll", fluidRow( column(6, box(width = 12,div(align="center", h3("Series Settings", class = "hModal"), uiOutput("multi_advancedSettingsSeries", align="center"), fluidRow( column(6,uiOutput("multi_advancedSettingsDelta", align="center")), column(6,uiOutput("multi_advancedSettingsToLog", align="center")) ), fluidRow( column(6, tags$button(type="button", id="multi_advancedSettingsButtonApplyDelta", class = "action-button", em("Apply"))), column(6, tags$button(type="button", id="multi_advancedSettingsButtonApplyAllDelta", class = "action-button", em("Apply to All series"))) ) )), box(width = 12,div(align="center", h3("General Settings", class = "hModal"), uiOutput("multi_advancedSettingsMethod", align="center"), uiOutput("multi_advancedSettingsThreshold", align="center"), fluidRow( column(6,uiOutput("multi_advancedSettingsTrials", align="center")), column(6,uiOutput("multi_advancedSettingsSeed", align="center")) ), uiOutput("multi_advancedSettingsJoint", align="center"), uiOutput("multi_advancedSettingsAggregation", align="center"), fluidRow( column(3), column(6, tags$button(type="button", id="multi_advancedSettingsButtonApplyGeneral", class = "action-button", em("Apply"))) ) )) ), column(6, box(width = 12,div(align="center", h3("Model Settings", class = "hModal"), uiOutput("multi_advancedSettingsModel", align="center"), uiOutput("multi_advancedSettingsParameter", align="center"), uiOutput("multi_advancedSettingsFixed", align="center"), uiOutput("multi_advancedSettingsStart", align="center"), fluidRow( column(6,uiOutput("multi_advancedSettingsStartMin", align="center")), column(6,uiOutput("multi_advancedSettingsStartMax", align="center")) ), fluidRow( column(6,uiOutput("multi_advancedSettingsLower", align="center")), column(6,uiOutput("multi_advancedSettingsUpper", align="center")) ), fluidRow( column(3), column(6, tags$button(type="button", id="multi_advancedSettingsButtonApplyModel", class = "action-button", em("Apply"))) ) )) ) ) ) ) ) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/modeling/multi_models.R
tabItem(tabName = "multi_simulate", fluidRow( column(12, h3("Multivariate Simulation",class = "hTitle"), h4("Select the estimated models you wish to simulate.", #br(), #"If you want to simulate a model that has not been estimated, you can use the 'Non-estimated models' tab.", br(), "Click on the Set Simulation and Advanced Settings buttons to customize the simulation process."), hr(class = "hrHeader") ) ), fluidRow(column(12,tabsetPanel(id = "panel_multi_simulations", type = "tabs", tabPanel(title = "Estimated models", fluidRow(column(12,bsAlert("panel_multi_simulate_model_alert"))), fluidRow(column(12, br(), h4("Available models"), DT::dataTableOutput("multi_simulate_databaseModels"), br(), fluidRow( column(8), column(2,actionButton(inputId = "multi_simulate_button_selectModels", label = "Select")), bsTooltip("multi_simulate_button_selectModels", title = "Select model", placement = "top"), column(2,actionButton(inputId = "multi_simulate_button_selectAllModels", label = "Select All")), bsTooltip("multi_simulate_button_selectAllModels", title = "Select all models that are displayed", placement = "top") ) ) )), tabPanel(title = "Non-estimated models", fluidRow(column(12,bsAlert("panel_multi_simulate_equation_alert"))), fluidRow( uiOutput("multi_simulate_PrintModelLatex") ), fluidRow( column(6, br(), div(align="center", fluidRow( column(1), column(5,selectInput("multi_simulate_model_usr_selectClass", label = "Class", choices = c("Diffusion process"))), column(5,uiOutput("multi_simulate_model_usr_selectModel")) ), uiOutput("multi_simulate_model_usr_ID"), uiOutput("multi_simulate_model_usr_selectJumps"), uiOutput("multi_simulate_model_usr_selectDimension"), fluidRow( column(1), column(5,uiOutput("multi_simulate_model_usr_selectParam")), column(5,uiOutput("multi_simulate_model_usr_param")) ), fluidRow( column(4), column(4,actionButton("multi_simulate_model_usr_button_save", label = "Save", align = "center")) ) )), column(6, br(), DT::dataTableOutput("multi_simulate_model_usr_table"), br(), fluidRow( column(3,actionButton("multi_simulate_model_usr_button_select", label = "Select")), column(3,actionButton("multi_simulate_model_usr_button_selectAll", label = "Select All")), column(3,actionButton("multi_simulate_model_usr_button_delete", label = "Delete")), column(3,actionButton("multi_simulate_model_usr_button_deleteAll", label = "Delete All")) ) ) ) ), tabPanel(title = "Simulations", fluidRow(column(12,bsAlert("panel_multi_simulations_alert"))), br(), fluidRow(column(12, DT::dataTableOutput("multi_simulate_monitor_table"))), br(), fluidRow( column(2,actionButton(inputId = "multi_simulate_monitor_button_showSimulation", label = "Show Simulations")), bsTooltip("multi_simulate_monitor_button_showSimulation", title = "Show selected simulation", placement = "top"), column(6), column(2,actionButton(inputId = "multi_simulate_monitor_button_delete", label = "Delete")), bsTooltip("multi_simulate_monitor_button_delete", title = "Delete selected simulation", placement = "top"), column(2,actionButton(inputId = "multi_simulate_monitor_button_deleteAll", label = "Delete All")), bsTooltip("multi_simulate_monitor_button_deleteAll", title = "Delete all simulations that are displayed", placement = "top") ) ) ))), div(id="multi_div_simulations", fluidRow( column(12,br(),br(),br()), column(8, h4("Selected Models"), DT::dataTableOutput("multi_simulate_selectedModels") ), column(4, br(),br(),br(),br(),br(),br(), div(actionButton("multi_simulate_button_setSimulation", label = "Set Simulation"), align = "center"), br(), div(actionButton("multi_simulate_button_advancedSettings", label = "Advanced Settings", align = "center"), align = "center") ) ), br(), fluidRow( column(4,actionButton("multi_simulation_button_deleteModels",label = "Delete", align = "center")), bsTooltip("multi_simulation_button_deleteModels", title = "Delete selected models", placement = "top"), column(4,actionButton("multi_simulation_button_deleteAllModels",label = "Delete All", align = "center")), bsTooltip("multi_simulation_button_deleteAllModels", title = "Delete all models that are displayed", placement = "top"), column(4,actionButton("multi_simulate_simulateModels", label = "Start Simulation", align = "center")) ) ), bsModal(id="multi_simulate_showSimulation", trigger = "multi_simulate_monitor_button_showSimulation", title = "Simulation", size = "large", fluidRow(column(12, fluidRow(column(12, div(align="center", uiOutput("multi_simulate_showSimulation_simID") ) ) ), fluidRow(column(3), column(3, uiOutput('multi_simulate_showSimulation_plot_series1')), column(3, uiOutput('multi_simulate_showSimulation_plot_series2')), column(3) ), fluidRow(div(id="multi_simulate_showSimulation_plot_div", align = "center", column(12, plotlyOutput("multi_simulate_showSimulation_plot"), downloadButton(outputId = "multi_simulate_showSimulation_button_saveTrajectory", label = "Save Trajectories"), hr() ) )), br(), fluidRow(shinyjs::hidden(div(id="multi_simulate_showSimulation_hist_div", column(8, plotlyOutput("multi_simulate_showSimulation_hist") ), column(4, div(align="center",br(),br(),br(), sliderInput("multi_simulate_showSimulation_hist_probability_slider", width = "75%", min = 0, max = 100, value = c(5, 95), label = "Quantiles Marginal Distribution (%)", step = 0.01, ticks=FALSE), uiOutput("multi_simulate_showSimulation_hist_text"), br(), downloadButton(outputId = "multi_simulate_showSimulation_button_saveHist", label = "Save Histogram") ) ) ))) )) ), bsModal(id="multi_simulate_setSimulation", trigger = "multi_simulate_button_setSimulation", title = "Set Simulation", size = "small", tags$style(type = "text/css", ".datepicker{z-index: 1100 !important;}"), div(id="multi_simulate_setSimulation_errorMessage",align = "center", h3("Select some models first", class = "hModal")), div(id="multi_simulate_setSimulation_body", align = "center", uiOutput("multi_simulate_modelID"), br(), box(width = 12, uiOutput("multi_simulate_range"), column(6,tags$button(type="button", id="multi_simulate_button_apply_range", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="multi_simulate_button_applyAll_range", class = "action-button", em("Apply All"))) ), box(width =12, uiOutput("multi_simulate_xinit_symb"), uiOutput("multi_simulate_xinit"), column(6,tags$button(type="button", id="multi_simulate_button_apply_xinit", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="multi_simulate_button_applyAll_xinit", class = "action-button", em("Apply All"))) ), box(width = 12, uiOutput("multi_simulate_nsim"), uiOutput("multi_simulate_nstep"), column(6,tags$button(type="button", id="multi_simulate_button_apply_nsim", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="multi_simulate_button_applyAll_nsim", class = "action-button", em("Apply All"))) ) ) ), bsModal(id="multi_simulate_advancedSettings", trigger = "multi_simulate_button_advancedSettings", title = "Advanced Settings", size = "small", div(id="multi_simulate_advancedSettings_errorMessage", align = "center", h3("Select some models first", class = "hModal")), div(id="multi_simulate_advancedSettings_body", align = "center", uiOutput("multi_simulate_advancedSettings_modelID"), uiOutput("multi_simulate_seed"), uiOutput("multi_simulate_traj"), column(6,tags$button(type="button", id="multi_simulate_button_apply_advancedSettings", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="multi_simulate_button_applyAll_advancedSettings", class = "action-button", em("Apply All"))) ) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/simulation/multivariate.R
tabItem(tabName = "simulate", fluidRow( column(12, h3("Univariate Simulation",class = "hTitle"), h4("Select the estimated models you wish to simulate.", br(), "If you want to simulate a model that has not been estimated, you can use the Non-estimated models tab.", br(), "Click on the Set Simulation and Advanced Settings buttons to customize the simulation process."), hr(class = "hrHeader") ) ), fluidRow(column(12,tabsetPanel(id = "panel_simulations", type = "tabs", tabPanel(title = "Estimated models", fluidRow(column(12,bsAlert("panel_simulate_model_alert"))), fluidRow(column(12, br(), h4("Available models"), DT::dataTableOutput("simulate_databaseModels"), br(), fluidRow( column(8), column(2,actionButton(inputId = "simulate_button_selectModels", label = "Select")), bsTooltip("simulate_button_selectModels", title = "Select model", placement = "top"), column(2,actionButton(inputId = "simulate_button_selectAllModels", label = "Select All")), bsTooltip("simulate_button_selectAllModels", title = "Select all models that are displayed", placement = "top") ) ) )), tabPanel(title = "Non-estimated models", fluidRow(column(12,bsAlert("panel_simulate_equation_alert"))), fluidRow( uiOutput("simulate_PrintModelLatex") ), fluidRow( column(6, br(), div(align="center", fluidRow( column(1), column(5,selectInput("simulate_model_usr_selectClass", label = "Class", choices = c("Diffusion process", "Fractional process", "Compound Poisson", "Point Process"))), column(5,uiOutput("simulate_model_usr_selectModel")) ), uiOutput("simulate_model_usr_ID"), uiOutput("simulate_model_usr_selectJumps"), fluidRow( column(1), column(5,uiOutput("simulate_model_usr_selectParam")), column(5,uiOutput("simulate_model_usr_param")) ), fluidRow( column(4), column(4,actionButton("simulate_model_usr_button_save", label = "Save", align = "center")) ) )), column(6, br(), DT::dataTableOutput("simulate_model_usr_table"), br(), fluidRow( column(3,actionButton("simulate_model_usr_button_select", label = "Select")), column(3,actionButton("simulate_model_usr_button_selectAll", label = "Select All")), column(3,actionButton("simulate_model_usr_button_delete", label = "Delete")), column(3,actionButton("simulate_model_usr_button_deleteAll", label = "Delete All")) ) ) ) ), tabPanel(title = "Simulations", fluidRow(column(12,bsAlert("panel_simulations_alert"))), br(), fluidRow(column(12, DT::dataTableOutput("simulate_monitor_table"))), br(), fluidRow( column(2,actionButton(inputId = "simulate_monitor_button_showSimulation", label = "Show Simulations")), bsTooltip("simulate_monitor_button_showSimulation", title = "Show selected simulation", placement = "top"), column(6), column(2,actionButton(inputId = "simulate_monitor_button_delete", label = "Delete")), bsTooltip("simulate_monitor_button_delete", title = "Delete selected simulation", placement = "top"), column(2,actionButton(inputId = "simulate_monitor_button_deleteAll", label = "Delete All")), bsTooltip("simulate_monitor_button_deleteAll", title = "Delete all simulations that are displayed", placement = "top") ) ) ))), div(id="div_simulations", fluidRow( column(12,br(),br(),br()), column(8, h4("Selected Models"), DT::dataTableOutput("simulate_selectedModels") ), column(4, br(),br(),br(),br(),br(),br(), div(actionButton("simulate_button_setSimulation", label = "Set Simulation"), align = "center"), br(), div(actionButton("simulate_button_advancedSettings", label = "Advanced Settings", align = "center"), align = "center") ) ), br(), fluidRow( column(4,actionButton("simulation_button_deleteModels",label = "Delete", align = "center")), bsTooltip("simulation_button_deleteModels", title = "Delete selected models", placement = "top"), column(4,actionButton("simulation_button_deleteAllModels",label = "Delete All", align = "center")), bsTooltip("simulation_button_deleteAllModels", title = "Delete all models that are displayed", placement = "top"), column(4,actionButton("simulate_simulateModels", label = "Start Simulation", align = "center")) ) ), bsModal(id="simulate_showSimulation", trigger = "simulate_monitor_button_showSimulation", title = "Simulation", size = "large", fluidRow(column(12, fluidRow(column(8,div(align="center",uiOutput("simulate_showSimulation_simID")))), fluidRow(div(id="simulate_showSimulation_plot_div", align = "center", column(8, plotOutput("simulate_showSimulation_plot", height = "350px", click = "simulate_showSimulation_plot_click") ), column(4,br(),br(),br(), div(selectInput("simulate_showSimulation_plot_scale", label = "Chart Scale", choices = c("Linear", "Logarithmic (Y)", "Logarithmic (X)", "Logarithmic (XY)")), align = "center"), br(),br(),br(),br(),br(),br(),br(), downloadButton(outputId = "simulate_showSimulation_button_saveTrajectory", label = "Save Trajectories") ) )), br(), fluidRow(div(id="simulate_showSimulation_hist_div", column(8, plotOutput("simulate_showSimulation_hist", height = "350px") ), column(4, div(align="center",br(),br(),br(), sliderInput("simulate_showSimulation_hist_nBins", width = "75%",min = 1, max = 100, step = 1,value = 30, ticks = FALSE, label = "Adjust bin width"), sliderInput("simulate_showSimulation_hist_probability_slider", width = "75%", min = 0, max = 100, value = c(5, 95), label = "Quantiles (%)", step = 0.01, ticks=FALSE), uiOutput("simulate_showSimulation_hist_text"), br(), downloadButton(outputId = "simulate_showSimulation_button_saveHist", label = "Save Histogram") ) ) )) )) ), bsModal(id="simulate_setSimulation", trigger = "simulate_button_setSimulation", title = "Set Simulation", size = "small", tags$style(type = "text/css", ".datepicker{z-index: 1100 !important;}"), div(id="simulate_setSimulation_errorMessage",align = "center", h3("Select some models first", class = "hModal")), div(id="simulate_setSimulation_body", align = "center", uiOutput("simulate_modelID"), br(), box(width = 12, uiOutput("simulate_range"), column(6,tags$button(type="button", id="simulate_button_apply_range", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="simulate_button_applyAll_range", class = "action-button", em("Apply All"))) ), box(width =12, uiOutput("simulate_xinit"), column(6,tags$button(type="button", id="simulate_button_apply_xinit", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="simulate_button_applyAll_xinit", class = "action-button", em("Apply All"))) ), box(width = 12, uiOutput("simulate_nsim"), uiOutput("simulate_nstep"), column(6,tags$button(type="button", id="simulate_button_apply_nsim", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="simulate_button_applyAll_nsim", class = "action-button", em("Apply All"))) ) ) ), bsModal(id="simulate_advancedSettings", trigger = "simulate_button_advancedSettings", title = "Advanced Settings", size = "small", div(id="simulate_advancedSettings_errorMessage", align = "center", h3("Select some models first", class = "hModal")), div(id="simulate_advancedSettings_body", align = "center", uiOutput("simulate_advancedSettings_modelID"), uiOutput("simulate_seed"), uiOutput("simulate_traj"), column(6,tags$button(type="button", id="simulate_button_apply_advancedSettings", class = "action-button", em("Apply"))), column(6,tags$button(type="button", id="simulate_button_applyAll_advancedSettings", class = "action-button", em("Apply All"))) ) ) )
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui/simulation/univariate.R
header <- dashboardHeader( title = "yuimaGUI" ) sidebar<-dashboardSidebar( sidebarMenu( menuItem("Home", tabName = "home", icon = icon("home")), menuItem("Data I/O", tabName = "data_section", icon = icon("upload"), menuSubItem("Financial & Economic Data", tabName = "finData"), menuSubItem("Your Data", tabName = "yourData") ), menuItem("Explorative Data Analysis", tabName = "eda_section", icon = icon("map"), menuSubItem("Change Point Estimation", tabName = "changepoint"), menuSubItem("Clustering", tabName = "cluster"), menuSubItem("Lead-Lag & Correlation", tabName = "llag") ), menuItem("Modeling", tabName = "models_section", icon = icon("sliders"), menuSubItem("Univariate", tabName = "models"), menuSubItem("Multivariate", tabName = "multi_models") ), menuItem("Simulation", tabName = "simulate_section", icon = icon("area-chart"), menuSubItem("Univariate", tabName = "simulate"), menuSubItem("Multivariate", tabName = "multi_simulate") ), hr(), menuItem("Finance", tabName = "finance", menuSubItem("P&L distribution", tabName = "hedging") ), hr(),br(), div(id="sessionButtons", fluidRow( downloadButton("saveSession", label = "Save Session")), br(), fluidRow(column(1),column(9,fileInput("loadSession", label = "Load Session", multiple=FALSE))) ), hr(),br(), div(id="theyuimaprojct", a("User Guide", href="https://yuimaproject.com/wp-content/uploads/2018/08/manual_yuimagui_v1-02.pdf", target="_blank"),br(), br() ) ) ) body<-dashboardBody( tags$head(tags$link(rel = "stylesheet", type = "text/css", href = paste(getOption("yuimaGUItheme"), ".css", sep = ""))), tags$head(tags$link(rel="shortcut icon", href="yuimaLogo.ico")), shinyjs::useShinyjs(), withMathJax(), tabItems( source("ui/home/home.R", local = TRUE)$value, source("ui/load_data/finData.R", local = TRUE)$value, source("ui/load_data/yourData.R", local = TRUE)$value, source("ui/eda/cluster.R", local = TRUE)$value, source("ui/eda/changepoint.R", local = TRUE)$value, source("ui/eda/llag.R", local = TRUE)$value, source("ui/modeling/models.R", local = TRUE)$value, source("ui/modeling/multi_models.R", local = TRUE)$value, source("ui/simulation/univariate.R", local = TRUE)$value, source("ui/simulation/multivariate.R", local = TRUE)$value, source("ui/finance/hedging.R", local = TRUE)$value ) ) ui <- dashboardPage(header,sidebar,body)
/scratch/gouwar.j/cran-all/cranData/yuimaGUI/inst/yuimaGUI/ui.R
## biorxiv_get_publication <- function(url) { ## # url <- "https://www.biorxiv.org/search/visualization%20numresults%3A75%20sort%3Arelevance-rank" ## x <- readLines(url) ## pub <- x[grep("/content/10.1101", x)] ## pub_url <- gsub(".*(/content/[[:digit:]\\.v/]+).*", "\\1", pub) ## pub_url <- paste0("https://www.biorxiv.org", pub_url) ## pub_title <- gsub("<[^>]+>", "", pub) %>% ## sub("^\\s+", "", .) %>% ## sub("\\s+$", "", .) ## data.frame(url = pub_url, ## title = pub_title) ## } ## biorxiv_get_correspondance <- function(url) { ## # url <- "https://www.biorxiv.org/content/10.1101/701680v3" ## x <- readLines(url) ## i <- grep("citation_author\"", x) ## j <- grep("citation_author_email", x) ## idx <- vapply(j, function(ii) { ## jj <- ii - i ## i[which(jj == min(jj[jj >0]))] ## }, numeric(1)) ## author <- x[idx] %>% unique %>% ## sub(".*content=\"([^\"]+).*", "\\1", .) ## email <- x[j] %>% unique %>% ## sub(".*content=\"([^\"]+).*", "\\1", .) ## data.frame(author = author, email = email) %>% unique ## } ## url <- "https://www.biorxiv.org/search/visualization%20numresults%3A75%20sort%3Arelevance-rank" ## y <- biorxiv_get_publication(url) ## xx <- lapply(y$url, function(x) { ## cat("parsing", x, "\n") ## biorxiv_get_correspondance(x) ## })
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/biorxiv.R
##' @rdname yulab-cache ##' @export initial_cache <- function() { pos <- 1 envir <- as.environment(pos) assign(".yulabCache", new.env(), envir = envir) } ##' @rdname yulab-cache ##' @export get_cache <- function() { if (!exists(".yulabCache", envir = .GlobalEnv)) { initial_cache() } get(".yulabCache", envir = .GlobalEnv) } ##' @rdname yulab-cache ##' @export rm_cache <- function() { if (exists(".yulabCache", envir = .GlobalEnv)) { rm(".yulabCache", envir = .GlobalEnv) } } ##' @rdname yulab-cache ##' @export initial_cache_item <- function(item) { env <- get_cache() assign(item, list(), envir = env) } ##' @rdname yulab-cache ##' @export get_cache_item <- function(item) { env <- get_cache() if (!exists(item, envir = env)) { initial_cache_item(item) } get(item, envir = env, inherits = FALSE) } ##' @rdname yulab-cache ##' @export rm_cache_item <- function(item) { env <- get_cache() if (exists(item, envir = env)) { rm(list = item, envir = env) } } ##' cache intermediate data ##' ##' Yulab provides a set of utilities to cache intermediate data, ##' including initialize the cached item, update cached item and rmove the cached item, etc. ##' ##' @rdname yulab-cache ##' @param item the name of the cached item ##' @param elements elements to be cached in the item ##' @return return the cache environment, item or selected elements, depends on the functions. ##' @importFrom utils modifyList ##' @export ##' @examples ##' \dontrun{ ##' slow_fib <- function(x) { ##' if (x < 2) return(1) ##' slow_fib(x-2) + slow_fib(x-1) ##' } ##' ##' fast_fib <- function(x) { ##' if (x < 2) return(1) ##' res <- get_cache_element('fibonacci', as.character(x)) ##' if (!is.null(res)) { ##' return(res) ##' } ##' res <- fast_fib(x-2) + fast_fib(x-1) ##' e <- list() ##' e[[as.character(x)]] <- res ##' update_cache_item('fibonacci', e) ##' return(res) ##' } ##' ##' system.time(slow_fib(30)) ##' system.time(fast_fib(30)) ##' ##' } update_cache_item <- function(item, elements) { msg <- "new elements should be stored as a named list" if (!inherits(elements, 'list')) { stop(msg) } if (is.null(names(elements))) { stop(msg) } if(any(names(elements) == "")) { stop(msg) } env <- get_cache() res <- get_cache_item(item) res <- modifyList(res, elements) assign(item, res, envir = env) } ##' @rdname yulab-cache ##' @export get_cache_element <- function(item, elements) { x <- get_cache_item(item) n <- length(elements) if (n == 1) return(x[[elements]]) return(x[elements]) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/cache.R
#' all possible combinations of n sets #' #' @title combinations #' @param n number of sets #' @return a list of all combinations #' @importFrom utils combn #' @export combinations <- function(n){ l <- lapply(seq_len(n), function(x){ m <- combn(n,x) mat2list(m) }) unlist(l, recursive = F) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/combinations.R
##' run system command ##' ##' ##' @title exec ##' @param command system command to run ##' @return An `exec` instance that stores system command outputs ##' @export ##' @author Guangchuang Yu exec <- function(command) { res <- system(command, intern=TRUE) structure(res, class = "exec") } ##' @method print exec ##' @export print.exec <- function(x, ...) { cat(x, sep='\n') }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/exec.R
#' @rdname yread #' @export yread_tsv <- function(file, reader = utils::read.delim, params = list(), cache_dir = tempdir() ) { # e.g. params = list(sep = "\t", header = FALSE) yread(file, reader = reader, params = params, cache_dir = cache_dir ) } #' read file with caching #' #' This function read a file (local or url) and cache the content. #' @title yread #' @rdname yread #' @param file a file or url #' @param reader a function to read the 'file_url' #' @param params a list of parameters that passed to the 'reader' #' @param cache_dir a folder to store cache files #' @return the output of using the 'reader' to read the 'file_url' with parameters specified by the 'params' #' @author Yonghe Xia and Guangchuang Yu #' @importFrom fs path_join #' @importFrom digest digest #' @export yread <- function(file, reader = readLines, params = list(), cache_dir = tempdir()) { # Generate a unique cache filename based on the file URL cache_filename <- fs::path_join(c(cache_dir, paste0(digest::digest(file), ".rds"))) # Check if the cached file exists if (file.exists(cache_filename)) { # If cached file exists, load and return the cached data cached_data <- readRDS(cache_filename) return(cached_data) } else { # If cached file does not exist, read and cache the data data <- do.call(reader, args = c(file, params)) saveRDS(data, cache_filename) return(data) } } ##' read clipboard ##' ##' ##' @title read.cb ##' @param reader function to read the clipboard ##' @param ... parameters for the reader ##' @return clipboard content, output type depends on the output of the reader ##' @author Guangchuang Yu ##' @importFrom utils read.table ##' @export read.cb <- function(reader = read.table, ...) { os <- Sys.info()[1] if (os == "Darwin") { clip <- pipe("pbpaste") } else { clip <- "clipboard" } reader(clip, ...) } ##' open selected directory or file ##' ##' ##' @title o ##' @param file to be open; open working directory by default ##' @return No return value, called for opening specific directory or file ##' @examples ##' \dontrun{ ##' ## to open current working directory ##' o() ##' } ##' @export ##' @author Guangchuang Yu o <- function(file=".") { file <- normalizePath(file) os <- Sys.info()[1] if (is.rserver()) { if (dir.exists(file)) { stop("open directory in RStudio Server is not supported.") } rserver_ip <- getOption("rserver_ip") if (!is.null(rserver_ip)) { rserver_port <- getOption("rserver_port") %||% '8787' if (!startsWith(rserver_ip, "http")) { rserver_ip = paste0("http://", rserver_ip) } utils::browseURL( paste0( paste(rserver_ip, rserver_port, sep=":"), "/file_show?path=", file )) } else { file.edit <- get("file.edit") file.edit(file) } } else if (os == "Darwin") { cmd <- paste("open", file) system(cmd) } else if (os == "Linux") { cmd <- paste("xdg-open", file, "&") system(cmd) } else if (os == "Windows") { ## wd <- sub("/", "\\", getwd()) ## cmd <- paste("explorer", wd) ## suppressWarnings(shell(cmd)) cmd <- paste("start", file) shell(cmd) } } is.rserver <- function(){ RStudio.Version = tryCatch(get("RStudio.Version"), error = function(e) NULL) if(is.null(RStudio.Version)) return(FALSE) if(!is.function(RStudio.Version)) return(FALSE) RStudio.Version()$mode == 'server' } ##' Open data frame in Excel. It can be used in pipe. ##' ##' ##' @title show_in_excel ##' @param .data a data frame to be open ##' @return original .data ##' @export ##' @author Guangchuang Yu show_in_excel <- function(.data) { f <- tempfile(fileext = '.csv') utils::write.csv(.data, file=f) o(f) invisible(.data) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/file.R
##' install github package ##' ##' it download the zip file first and use `install_zip` to install it ##' @title install_zip_gh ##' @param repo github repo ##' @param ref github branch, default is HEAD, which means the default branch of the GitHub repo ##' @param args argument to build package ##' @return No return value, called for installing github package ##' @importFrom utils download.file ##' @export ##' @author Guangchuang Yu install_zip_gh <- function(repo, ref = "HEAD", args = "--no-build-vignettes") { ## repo <- 'GuangchuangYu/nCov2019' url <- paste0('https://codeload.github.com/', repo, '/zip/', ref) f <- tempfile(fileext=".zip") method <- "auto" if (.Platform$OS.type == "windows") method <- "curl" utils::download.file(url, destfile=f, method = method) if (!is_valid_zip(f)) { stop("Invalid zip file downloaded, please check the 'ref' parameter to set a correct github branch.") } install_zip(f, args=args) } ##' install R package from zip file of source codes ##' ##' ##' @title install_zip ##' @param file zip file ##' @param args argument to build package ##' @return No return value, called for install R package from zip file of source codes ##' @export ##' @author Guangchuang Yu install_zip <- function(file, args = "--no-build-vignettes") { dir <- tempfile() utils::unzip(file, exdir=dir) fs <- list.files(path=dir, full.names=T) #if (length(fs) == 1 && dir.exists(fs)) { # dir <- fs #} ## dir <- paste0(dir, '/', basename(repo), '-master') dir <- fs[which.max(file.info(fs)$atime)] if ("INDEX" %in% list.files(dir)) { # file is binary package pkg <- file } else { # file is zip of package source ## remotes::install_local(path=dir, ..., force=TRUE) ## pkg <- pkgbuild::build(dir, args=args) build <- get_fun_from_pkg('pkgbuild', 'build') pkg <- build(dir, args=args) } utils::install.packages(pkg, repos=NULL) } is_valid_zip <- function(zipfile) { fs <- tryCatch(utils::unzip(zipfile, list=TRUE), error = function(e) NULL) if (is.null(fs)) return(FALSE) return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/install_zip.R
##' rbind a list ##' ##' ##' @title rbindlist ##' @param x a list that have similar elements that can be rbind to a data.frame ##' @return data.frame ##' @author Guangchuang Yu ##' @export rbindlist <- function(x) { do.call('rbind', x) } ##' Convert a list of vector to a data.frame object. ##' ##' ##' @title Convert a list of vector (e.g, gene IDs) to a data.frame object ##' @param inputList A list of vector ##' @return a data.frame object. ##' @export ls2df <- function(inputList) { # ldf <- lapply(1:length(inputList), function(i) { ldf <- lapply(seq_len(length(inputList)), function(i) { data.frame(category=rep(names(inputList[i]), length(inputList[[i]])), value=inputList[[i]]) }) do.call('rbind', ldf) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/list.R
##' convert a matrix to a tidy data frame ##' (from wide to long format as described in the tidyverse concept) ##' ##' ##' @title mat2df ##' @param x the input matrix ##' @return a data.frame in long format with the 'value' column stores the original values ##' and 'row' and 'col' columns stored in row and column index as in x ##' @examples ##' x <- matrix(1:15, nrow = 3) ##' mat2df(x) ##' @export ##' @author Guangchuang Yu mat2df <- function(x) { nr <- nrow(x) nc <- ncol(x) d <- data.frame( value = as.vector(x), row = rep(1:nr, times = nc), col = rep(1:nc, each = nr) ) return(d) } ##' convert a matrix to a list ##' ##' ##' @title mat2list ##' @param x the input matrix ##' @return a list that contains matrix columns as its elements ##' @examples ##' x <- matrix(1:15, nrow = 3) ##' mat2list(x) ##' @export mat2list <- function(x){ lapply(seq_len(ncol(x)), function(i) x[,i]) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/matrix-utils.R
##' loading a package ##' ##' The function use 'library()' to load the package. ##' If the package is not installed, the function will try to install it before loading it. ##' @title pload ##' @param package package name ##' @param action function used to install package. ##' If 'action = "auto"', it will try to use 'BiocManager::install()' if it is available. ##' @return the selected package loaded to the R session ##' @importFrom rlang as_name ##' @importFrom rlang enquo ##' @importFrom rlang check_installed ##' @importFrom cli cli_h2 ##' @importFrom utils getFromNamespace ##' @export ##' @author Guangchuang Yu pload <- function(package, action = "auto") { pkg <- as_name(enquo(package)) if (action == "auto") { if (is.installed("BiocManager")) { install <- getFromNamespace("install", "BiocManager") action <- function(package, ask=FALSE, update=FALSE, ...){ install(package, ask=ask, update = update, ...) } } else { action <- NULL } } check_installed(pkg, action = action) cli::cli_h2(sprintf("loading the package: %s", pkg)) library(pkg, character.only = TRUE) } ##' get reverse dependencies ##' ##' ##' @title get_dependencies ##' @param pkg package name ##' @param repo 'CRAN' and/or 'BioC' ##' @return reverse dependencies ## @importFrom BiocInstaller biocinstallRepos ##' @importFrom tools package_dependencies ##' @export ##' @author Guangchuang Yu get_dependencies <- function(pkg, repo=c("CRAN", "BioC")) { rp <- get_repo(repo) db <- utils::available.packages(repo=rp) tools::package_dependencies(pkg, db=db, reverse=TRUE) } get_repo <- function(repo = c("CRAN", "BioC")) { rp <- c() if ('CRAN' %in% repo) { cran <- getOption("repos")["CRAN"] if (is.null(cran)) { cran <- "http://cloud.r-project.org/" } rp <- c(rp, cran) } if ('BioC' %in% repo) { bioc <- getOption("BioC_mirror") if (is.null(bioc)) { bioc <- "https://mirrors.tuna.tsinghua.edu.cn/bioconductor/" } rp <- c(rp, bioc) } ## options(repos = biocinstallRepos()) sub("/$", "", rp) } ##' Extract package title ##' ##' ##' @title packageTitle ##' @param pkg package name ##' @param repo 'CRAN' and/or 'BioC' ##' @return reverse dependencies ##' @importFrom utils packageDescription ##' @export ##' @author Guangchuang Yu packageTitle <- function(pkg, repo='CRAN') { title <- tryCatch(packageDescription(pkg)$Title, error=function(e) NULL) if (is.null(title)) { repo_url <- get_repo(repo) if (repo == "CRAN") { url <- sprintf("%s/package=%s", repo_url, pkg) } else { bioc_type <- c("bioc", "workflows", "data/annotation", "data/experiment") url <- sprintf("%s/packages/release/%s/html/%s.html", repo_url, bioc_type, pkg) } ## x <- tryCatch(readLines(url), error = function(e) NULL) ## if (is.null(x)) return("") for (u in url) { x <- tryCatch(yread(u), error = function(e) NULL) if (!is.null(x)) { break() } } if (is.null(x)) { return(NA) } i <- grep('^\\s*<h2>', x) if (grepl("</h2>$", x[i])) { xx <- x[i] } else { j <- grep('</h2>$', x) xx <- paste(x[i:j], collapse=" ") } title <- gsub('</h2>$', '', gsub('\\s*<h2>', '', xx)) } sub("^\\w+\\s*:\\s*", "", gsub("\n", " ", title)) } ##' Check whether the input packages are installed ##' ##' This function check whether the input packages are installed ##' @title is.installed ##' @param packages package names ##' @return logical vector ##' @export ##' @examples ##' is.installed(c("dplyr", "ggplot2")) ##' @author Guangchuang Yu is.installed <- function(packages) { vapply(packages, function(package) { system.file(package=package) != "" }, logical(1)) } ##' Check whether the input packages are installed ##' ##' This function check whether the input packages are installed. If not, it asks the user whether to install the missing packages. ##' @title check_pkg ##' @param pkg package names ##' @param reason the reason to check the pkg. If NULL, it will set the reason to the parent call. ##' @param ... additional parameters that passed to `rlang::check_installed()` ##' @return see also [check_installed][rlang::check_installed] ##' @export ##' @importFrom rlang check_installed ##' @author Guangchuang Yu check_pkg <- function(pkg, reason=NULL, ...) { # v1 # # if (!is.installed(pkg)) { # msg <- sprintf("%s is required, please install it first", pkg) # stop(msg) # } if (is.null(reason)) { call <- sys.call(1L) reason <- sprintf("for %s()", as.character(call)[1]) } rlang::check_installed(pkg, reason, ...) } ##' load function from package ##' ##' ##' @title get_fun_from_pkg ##' @param pkg package ##' @param fun function ##' @return function ##' @export ##' @examples ##' get_fun_from_pkg('utils', 'zip') ##' @author Guangchuang Yu get_fun_from_pkg <- function(pkg, fun) { ## v1 ## ## requireNamespace(pkg) ## eval(parse(text=paste0(pkg, "::", fun))) ## v2 ## ## require(pkg, character.only = TRUE) ## eval(parse(text = fun)) # check_pkg(pkg) utils::getFromNamespace(fun, pkg) } ##' print md text of package with link to homepage (CRAN or Bioconductor) ##' ##' ##' @rdname cran-bioc-pkg ##' @param pkg package name ##' @return md text string ##' @export ##' @author Guangchuang Yu CRANpkg <- function(pkg) { cran <- "https://CRAN.R-project.org/package" fmt <- "[%s](%s=%s)" sprintf(fmt, pkgfmt(pkg), cran, pkg) } ##' @rdname cran-bioc-pkg ##' @export Biocpkg <- function(pkg) { sprintf("[%s](http://bioconductor.org/packages/%s)", pkgfmt(pkg), pkg) } ##' print md text of package with link to github repo ##' ##' ##' @rdname github-pkg ##' @param user github user ##' @param pkg package name ##' @return md text string ##' @export ##' @author Guangchuang Yu Githubpkg <- function(user, pkg) { gh <- "https://github.com" fmt <- "[%s](%s/%s/%s)" sprintf(fmt, pkgfmt(pkg), gh, user, pkg) } ##' print md text of link to a pakcage ##' ##' ##' @title mypkg ##' @param pkg package name ##' @param url package url ##' @return md text string ##' @export ##' @author Guangchuang Yu mypkg <- function(pkg, url) { fmt <- "[%s](%s)" sprintf(fmt, pkgfmt(pkg), url) } pkgfmt <- function(pkg) { fmt <- getOption('yulab.utils_pkgfmt', default="%s") sprintf(fmt, pkg) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/pkg-utils.R
##' @rdname regexpr-style ##' @export set_PCRE <- function() { options(regexpr_use_perl = TRUE) } ##' @rdname regexpr-style ##' @export set_TRE <- function() { options(regexpr_use_perl = FALSE) } ##' @rdname regexpr-style ##' @export use_perl <- function() { res <- getOption("regexpr_use_perl", default = auto_set_regexpr_style()) return(res) } ##' switch regular expression style (PCRE vs TRE) ##' ##' The `set_regexpr_style()` allows user to specify which style to be used, ##' while the `auto_set_regexpr_style()` automatically set the style depdending on ##' the operating system (TRE for Windows and PCRE for other OSs (Linux and Mac)). ##' ##' `set_PCRE()` force to use PCRE style while `set_TRE()` force to use TRE. ##' ##' Note that all these functions are not change the behavior of `gsub()` and `regexpr()`. ##' The functions are just set a global option to store the user's choice of whether using `perl = TRUE`. ##' ##' Users can access the option via `use_perl()` and pass the return value to `gusb()` or `regexpr()` to specify the style in use. ##' ##' @rdname regexpr-style ##' @param style one of 'PCRE' or 'TRE' ##' @return logical value of whether use perl ##' @references <https://stackoverflow.com/questions/47240375/regular-expressions-in-base-r-perl-true-vs-the-default-pcre-vs-tre> ##' @export ##' @author Guangchuang Yu set_regexpr_style <- function(style) { if (missing(style)) { message("style is not specific, set automatically.") auto_set_regexpr_style() } else { style <- match.arg(style, c("PCRE", "TRE")) if (style == "PCRE") { set_PCRE() } else { set_TRE() } } res <- getOption("regexpr_use_perl") invisible(res) } ##' @rdname regexpr-style ##' @export auto_set_regexpr_style <- function() { os <- Sys.info()[1] if (os == "Windows") { set_TRE() res <- FALSE } else { set_PCRE() res <- TRUE } invisible(res) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/regexpr.R
##' normalized data by range ##' ##' ##' @title scale-range ##' @param data the input data. ##' @return normalized data ##' @export ##' @author Guangchuang Yu scale_range <- function(data) { normalized_data <- apply(data, 2, function(x) { (x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE)) }) as.data.frame(normalized_data) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/scale.R
##' download publication via scihub ##' ##' using scihub to download publication using doi ##' @rdname scihub-dl ##' @name scihub_dl ##' @param doi doi ##' @param scihub scihub website ##' @param download whether download the pdf file ##' @return pdf url ##' @author Guangchuang Yu ##' @export scihub_dl <- function(doi, scihub = 'sci-hub.tw', download=TRUE) { url <- paste0('https://', scihub, '/', doi) x <- readLines(url) i <- grep('id = "pdf"', x) pdf_url <-sub(".*(//.*\\.pdf).*", "https:\\1", x[i]) if (download) { outfile <- sub(".*/", "", pdf_url) utils::download.file(pdf_url, destfile = outfile) } invisible(pdf_url) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/scihub-dl.R
##' wraping long string to multiple lines ##' ##' ##' @title str_wrap ##' @param string input string ##' @param width the maximum number of characters before wrapping to a new line ##' @return update strings with new line character inserted ##' @export ##' @author Guangchuang Yu and Erqiang Hu str_wrap <- function(string, width = getOption("width")) { ## ## actually, there is a base::strwrap() function available ## # x <- gregexpr(' ', string) # vapply(seq_along(x), # FUN = function(i) { # y <- x[[i]] # n <- nchar(string[i]) # len <- (c(y,n) - c(0, y)) ## length + 1 # idx <- len > width # j <- which(!idx) # if (length(j) && max(j) == length(len)) { # j <- j[-length(j)] # } # if (length(j)) { # idx[j] <- len[j] + len[j+1] > width # } # idx <- idx[-length(idx)] ## length - 1 # start <- c(1, y[idx] + 1) # end <- c(y[idx] - 1, n) # words <- substring(string[i], start, end) # paste0(words, collapse="\n") # }, # FUN.VALUE = character(1) # ) result <- vapply(string, FUN = function(st) { words <- list() i <- 1 while(nchar(st) > width) { if (length(grep(" ", st)) == 0) break y <- gregexpr(' ', st)[[1]] n <- nchar(st) y <- c(y,n) idx <- which(y < width) # When the length of first word > width if (length(idx) == 0) idx <- 1 # Split the string into two pieces # The length of first piece is small than width words[[i]] <- substring(st, 1, y[idx[length(idx)]] - 1) st <- substring(st, y[idx[length(idx)]] + 1, n) i <- i + 1 } words[[i]] <- st paste0(unlist(words), collapse="\n") }, FUN.VALUE = character(1) ) names(result) <- NULL result } ##' Detect the presence or absence of a pattern at the beginning or end of a string or string vector. ##' ##' ##' @title str_starts ##' @rdname str-starts-ends ##' @param string input string ##' @param pattern pattern with which the string starts or ends ##' @param negate if TRUE, return non-matching elements ##' @return a logical vector ##' @export ##' @author Guangchuang Yu str_starts <- function(string, pattern, negate=FALSE) { pattern <- paste0('^', pattern) str_detect(string, pattern, negate) } ##' @rdname str-starts-ends ##' @export str_ends <- function(string, pattern, negate=FALSE) { pattern <- paste0(pattern, '$') str_detect(string, pattern, negate) } ##' @importFrom stats setNames str_detect <- function(string, pattern, negate) { res <- setNames( vapply(string, grepl, pattern=pattern, FUN.VALUE=logical(1)), NULL) if (negate) res <- !res return(res) } ##' Extract a substring using a pattern ##' ##' ##' @title str_extract ##' @rdname str-extract ##' @param string input string ##' @param pattern a regular expression to describe the pattern to extracted from the 'string' ##' @return substring ##' @export ##' @author Guangchuang Yu str_extract <- function(string, pattern) { i <- regexpr(pattern, string) j <- attr(i, 'match.length') res <- substring(string, i, i+j-1) res[res == ""] <- NA return(res) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/str-utils.R
sudo_install <- function(pkgs) { ## pkgs_str <- paste0('"', pkgs, '"') %>% ## paste(collapse=',') %>% ## paste("c(", ., ")") ## rcmd0 <- 'options(repos = c(CRAN = "https://mirrors.e-ducation.cn/CRAN/"));' os <- Sys.info()[1] if (os == "Windows") { sudo <- "" } else { sudo <- "sudo" } for (pkg in pkgs) { pkg <- paste0('"', pkg, '"') rcmd <- paste0('install.packages(', pkg, ')') ## rcmd <- paste0(rcmd0, rcmd) cmd <- paste0(sudo, " Rscript -e '", rcmd, "'") system(cmd) } }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/sudo-install.R
`%||%` <- function(a, b) ifelse(is.null(a), b, a)
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/utilities.R
##' @importFrom memoise memoise .onLoad <- function(libname, pkgname) { yread <<- memoise::memoise(yread) yread_tsv <<- memoise::memoise(yread_tsv) }
/scratch/gouwar.j/cran-all/cranData/yulab.utils/R/zzz.R
#' Convert the objects loaded from YAML fragments into a tree #' #' If the [data.tree::data.tree] package is installed, this function #' can be used to convert a list of objects, as loaded from extracted #' YAML fragments, into a [data.tree::Node()]. #' #' @param x Either a list of YAML fragments loaded from a file with #' [load_yaml_fragments()], or a list of such lists loaded from all files #' in a directory with [load_yaml_dir()]. #' @param idName The name of the field containing each elements' identifier, #' used to build the data tree when there are references to a parent from a child #' element. #' @param parentIdName The name of the field containing references to an element's #' parent element (i.e. the field containing the identifier of the corresponding #' parent element). #' @param childrenName The name of the field containing an element's children, either #' as a list of elements, or using the 'shorthand' notation, in which case a vector #' is supplied with the identifiers of the children. #' @param autofill A named vector where the names represent fields to fill with #' the values of the fields specified in the vector values. Note that autofill #' replacements are only applied if the fields to be autofilled (i.e. the names of #' the vector specified in `autofill`) do not already have a value. #' @param rankdir How to plot the plot when it's plotted: the default `"LR"` plots from #' left to right. Specify e.g. `"TB"` to plot from top to bottom. #' @param directed Whether the edges should have arrows (`"forward"` or `"backward"`) #' or not (`"false"`). #' @param silent Whether to provide (`FALSE`) or suppress (`TRUE`) more detailed progress updates. #' #' @return a [data.tree::Node()] object. #' #' @examples #' loadedYum <- yum::load_yaml_fragments(text=c( #' "---", #' "-", #' " id: firstFragment", #' "---", #' "Outside of YAML", #' "---", #' "-", #' " id: secondFragment", #' " parentId: firstFragment", #' "---", #' "Also outside of YAML")); #' yum::build_tree(loadedYum); #' @export build_tree <- function(x, idName = 'id', parentIdName = 'parentId', childrenName = 'children', autofill = c(label = 'id'), rankdir="LR", directed="false", silent=TRUE) { if (!requireNamespace("data.tree", quietly = TRUE)) { stop("To build a tree, the \"data.tree\" package is required. ", "Please install it using `install.packages('data.tree');`.", call. = FALSE); } if ("simplifiedYum" %in% class(x)) { ### Nothing more to do - can be processed directly. } else if ("yumFromDir" %in% class(x)) { x <- unlist(x, recursive=FALSE); } else if (!("yumFromFile" %in% class(x)) && !("yumRecursion" %in% class(x)) && !("yumFromList" %in% class(x))) { stop("I can only process the objects resulting from ", "a call to 'load_yaml_fragments', 'load_yaml_dir, ", " or 'load_yaml_list', which have class ", "'yumFromFile', 'yumFromDir', and 'yumFromList'. The ", "object you provided has ", ifelse(length(class(x)) == 1, "class ", "classes "), vecTxtQ(class(x)), "."); } if (is.null(x)) { return(x); } if (!is.null(x[[idName]])) { ### We have an identifier, so this is a node in itself. First check ### and if necessary, clean up this node. if (!silent) { cat("Passed object has identifier '", x[[idName]], "'.", sep=""); } for (currentAutofill in names(autofill)) { if (is.null(x[[currentAutofill]])) { x[[currentAutofill]] <- x[[autofill[currentAutofill]]]; } } ### Then, check whether it has children. if (is.null(x[[childrenName]])) { ### If not, convert this node into a Node and return it. res <- data.tree::Node$new(x[[idName]]); for (currentSub in (setdiff(names(x), idName))) { res[[currentSub]] <- x[[currentSub]]; } return(res); } else { ### Check whether the children are 'shorthand children', and if ### they are, construct the proper sub-object first. if (is.atomic(x[[childrenName]])) { x[[childrenName]] <- lapply(x[[childrenName]], function(childId) { currentChild <- list(); currentChild[[idName]] <- childId; for (currentAutofill in names(autofill)) { currentChild[[currentAutofill]] <- childId; } return(currentChild); }); } if (!silent) { cat("Converting it to a data.tree Node and returning it."); } ### Then convert this node into a Node res <- data.tree::FromListExplicit(x, nameName=idName, childrenName=childrenName); if (!silent) { cat("Tree root object has name '", res$name, "'.", sep=""); } ### Check for missing labels and/or codes and fill them with the identifiers res$Do(function(node) { for (currentAutofill in names(autofill)) { if (is.null(node[[currentAutofill]])) { if (autofill[currentAutofill] == idName) { node[[currentAutofill]] <- node$name; } else { node[[currentAutofill]] <- node[[autofill[currentAutofill]]]; } } } }); ### Set plotting styles data.tree::SetGraphStyle(res, directed = directed); data.tree::SetGraphStyle(res, rankdir = rankdir); ### Return the result return(res); } } else { ### This is a list of nodes, so pass each on to this function and ### collect the results; then start building the tree. if (!silent) { cat("Passed object does not have an identifier; processing it as a list of objects."); } nodeList <- lapply(lapply(x, function(xToStructure) { if (is.null(xToStructure)) { return(structure(list(), class = 'yumRecursion')); } else { return(structure(xToStructure, class = 'yumRecursion')); } }), build_tree, idName = 'id', parentIdName = parentIdName, childrenName = childrenName, autofill = autofill, silent = silent); nodeIds <- data.tree::Get(nodeList, 'name'); if (!silent) { cat("Processed ", length(nodeList), " nodes (", vecTxtQ(nodeIds), ").", sep=""); } ### If it's a single node, just return it immediately. if (length(nodeList) == 1) { if (!silent) { cat("Single node, so returning it."); } return(nodeList[[1]]); } ### Create the data tree object resTree <- data.tree::Node$new(); ### Add all children of nodes without an id as children of the resTree root if (any(nchar(nodeIds)==0)) { for (nodeWithoutId in nodeList[nchar(nodeIds)==0]) { if (!silent) { cat("Found a set of nodes without identifiers; adding the children to the root of the code tree."); } for (subNodeWithoutId in nodeWithoutId$children) { resTree$AddChildNode(subNodeWithoutId); if (!silent) { cat("Added '", subNodeWithoutId$name, "' to the root of the code tree.\n", sep=""); } } } ### Then remove them from the nodeList nodeList <- nodeList[nchar(nodeIds)>0]; } ### Check which nodes have a parent parentIds <- data.tree::Get(nodeList, parentIdName); nodesWithoutParents <- nodeList[unlist(is.na(parentIds))]; nodesWithParents <- nodeList[unlist(!is.na(parentIds))]; ### Attach those that don't to the root. for (i in nodesWithoutParents) { resTree$AddChildNode(i); if (!silent) { cat("Attached parentless node '", i$name, "' to the root of the code tree."); } } ### For those that do, insert them at the appropriate place. for (i in seq_along(nodesWithParents)) { if (!silent) { cat("Starting to process node '", nodesWithParents[[i]]$name, "' to find its parent '", nodesWithParents[[i]][[parentIdName]], "'.\n", sep=""); } parentNode <- data.tree::FindNode(resTree, nodesWithParents[[i]][[parentIdName]]); if (!is.null(parentNode)) { ### Parent is already in the coding tree; attach this child node. parentNode$AddChildNode(nodesWithParents[[i]]); if (!silent) { cat("Attached node '", nodesWithParents[[i]]$name, "' to its parent node '", parentNode$name, "' in the code tree.\n", sep=""); } } else { ### Parent is not in the coding tree; look in the other nodes with ### parents that we still have to process if (i == length(nodesWithParents)) { stop(paste0("Node with identifier '", nodesWithParents[[i]]$name, "' has specified parent '", nodesWithParents[[i]][[parentIdName]], "' but no node with that identifier exists.")); } else { foundParent <- FALSE; for (j in (i+1):length(nodesWithParents)) { parentNode <- data.tree::FindNode(nodesWithParents[[j]], nodesWithParents[[i]][[parentIdName]]); if (!is.null(parentNode)) { ### Parent is not yet in the coding tree; attach this child node. parentNode$AddChildNode(nodesWithParents[[i]]); foundParent <- TRUE; if (!silent) { cat("Attached node '", nodesWithParents[[i]]$name, "' to its parent node '", parentNode$name, "', for now outside the code tree.", sep=""); } } } if (!foundParent) { print(parentNode); stop(paste0("Node with identifier '", nodesWithParents[[i]]$name, "' has specified parent '", nodesWithParents[[i]][[parentIdName]], "' but no node with that identifier exists (all node identifiers are ", vecTxtQ(nodeIds), ").")); } } } } ### Set plotting styles data.tree::SetGraphStyle(resTree, directed = directed); data.tree::SetGraphStyle(resTree, rankdir = rankdir); ### Return the result return(resTree); } }
/scratch/gouwar.j/cran-all/cranData/yum/R/build_tree.R
#' Delete all YAML fragments from a file #' #' These function deletes all YAML fragments from a file, returning #' a character vector without the lines that specified the YAML #' fragments. #' #' @param file The path to a file to scan; if provided, takes precedence #' over `text`. #' @param text A character vector to scan, where every element should #' represent one line in the file; can be specified instead of `file`. #' @param delimiterRegEx The regular expression used to locate YAML #' fragments. #' @param ignoreOddDelimiters Whether to throw an error (FALSE) or #' delete the last delimiter (TRUE) if an odd number of delimiters is #' encountered. #' @param silent Whether to be silent (TRUE) or informative (FALSE). #' #' @return A list of character vectors. #' @examples #' yum::delete_yaml_fragments(text=c("---", "First YAML fragment", "---", #' "Outside of YAML", #' "---", "Second fragment", "---", #' "Also outside of YAML")); #' #' @export delete_yaml_fragments <- function(file, text, delimiterRegEx = "^---$", ignoreOddDelimiters = FALSE, silent=TRUE) { if (missing(file)) { if (missing(text)) { stop("Provide either a `file` or a `text` to scan!"); } else { allLines <- text; } } else { allLines <- readLines(file); } yamlFragments <- grep(delimiterRegEx, allLines); if (length(yamlFragments) == 0) { return(allLines); } if (!is.even(length(yamlFragments))) { if (ignoreOddDelimiters) { yamlFragments <- yamlFragments[-length(yamlFragments)]; } else { stop("Extracted an uneven number of lines with specifications ", "(the regular expression for the specification ", "delimiter that was specified was '", delimiterRegEx, "'). To ignore the last delimiter, specify ", "'ignoreOddDelimiters=TRUE'."); } } yamlFragmentIndices <- seq_along(yamlFragments); ### Rewritten using base R to remove `purrr` dependency # indexSets <- purrr::map2(.x=yamlFragments[is.odd(yamlFragmentIndices)], # .y=yamlFragments[is.even(yamlFragmentIndices)], # .f=`:`); indexPairIndices <- list(yamlFragments[is.odd(yamlFragmentIndices)], yamlFragments[is.even(yamlFragmentIndices)]); indexSets <- lapply(seq_along(indexPairIndices[[1]]), function(pair) { return(seq(indexPairIndices[[1]][pair], indexPairIndices[[2]][pair])); }); return(allLines[-do.call(c, indexSets)]); }
/scratch/gouwar.j/cran-all/cranData/yum/R/delete_yaml_fragments.R