content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' @title Variance-covariance matrix of CUB models with covariates for the feeling component #' @description Compute the variance-covariance matrix of parameter estimates of a CUB model #' with covariates for the feeling component. #' @aliases varcovcub0q #' @usage varcovcub0q(m, ordinal, W, pai, gama) #' @param m Number of ordinal categories #' @param ordinal Vector of ordinal responses #' @param W Matrix of covariates for explaining the feeling component #' @param pai Uncertainty parameter #' @param gama Vector of parameters for the feeling component, whose length is #' NCOL(W)+1 to include an intercept term in the model (first entry of gama) #' @export varcovcub0q #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @keywords internal #' @references #' Piccolo D.(2006), Observed Information Matrix for MUB Models. \emph{Quaderni di Statistica}, #' \bold{8}, 33--78, #' @examples #' data(univer) #' m<-7 #' ordinal<-univer[,9] #' pai<-0.86 #' gama<-c(-1.94, -0.17) #' W<-univer[,4] #' varmat<-varcovcub0q(m, ordinal, W, pai, gama) varcovcub0q <- function(m,ordinal,W,pai,gama){ W<-as.matrix(W) if (ncol(W)==1){ W<-as.numeric(W) } qi<-1/(m*probcub0q(m,ordinal,W,pai,gama)) qistar<-1-(1-pai)*qi qitilde<-qistar*(1-qistar) fi<-logis(W,gama) fitilde<-fi*(1-fi) ai<-(ordinal-1)-(m-1)*(1-fi) g01<-(ai*qi*qistar)/pai hh<-(m-1)*qistar*fitilde-(ai^2)*qitilde WW<-cbind(1,W) i11<-sum((1-qi)^2)/(pai^2) i12<-t(g01)%*%WW i22<-t(WW)%*%(Hadprod(WW,hh)) ### i22=t(WW)%*%(WW*hh) does not work; ### Information matrix ##matinf=rbind(cbind(i11,i12),cbind(t(i12),i22)) nparam<-NCOL(W)+2 matinf<-matrix(NA,nrow=nparam,ncol=nparam) matinf[1,]<-t(c(i11,i12)) for (i in 2:(nparam)){ matinf[i,]<-t(c(i12[i-1],i22[i-1,])) } if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { varmat<-solve(matinf) } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcub0q.R
#' @title Variance-covariance matrix of a CUBE model with covariates #' @description Compute the variance-covariance matrix of parameter estimates of a CUBE model with covariates #' for all the three parameters. #' @aliases varcovcubecov #' @usage varcovcubecov(m, ordinal, Y, W, Z, estbet, estgama, estalpha) #' @param m Number of ordinal categories #' @param ordinal Vector of ordinal responses #' @param Y Matrix of covariates for explaining the uncertainty component #' @param W Matrix of covariates for explaining the feeling component #' @param Z Matrix of covariates for explaining the overdispersion component #' @param estbet Vector of the estimated parameters for the uncertainty component, with length equal to #' NCOL(Y)+1 to account for an intercept term (first entry) #' @param estgama Vector of the estimated parameters for the feeling component, with length equal to #' NCOL(W)+1 to account for an intercept term (first entry) #' @param estalpha Vector of the estimated parameters for the overdispersion component, with length #' equal to NCOL(Z)+1 to account for an intercept term (first entry) #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @keywords internal #' @references #' Piccolo, D. (2014), Inferential issues on CUBE models with covariates, #' \emph{Communications in Statistics - Theory and Methods}, \bold{44}, DOI: 10.1080/03610926.2013.821487 varcovcubecov <- function(m,ordinal,Y,W,Z,estbet,estgama,estalpha){ n<-length(ordinal) Y<-as.matrix(Y); W<-as.matrix(W);Z<-as.matrix(Z); if (ncol(W)==1){ W<-as.numeric(W) } if (ncol(Y)==1){ Y<-as.numeric(Y) } if (ncol(Z)==1){ Z<-as.numeric(Z) } p<-NCOL(Y);q<-NCOL(W);v<-NCOL(Z); paivett<-logis(Y,estbet) csivett<-logis(W,estgama) phivett<-1/(-1+ 1/(logis(Z,estalpha))) # Probability probi<-paivett*(betabinomial(m,ordinal,csivett,phivett)-1/m)+1/m uui<-1-1/(m*probi) ubari<-uui+paivett*(1-uui) ### Matrix computations mats1<-auxmat(m,csivett,phivett,1,-1,1,0,1) mats2<-auxmat(m,csivett,phivett,0, 1,1,0,1) mats3<-auxmat(m,csivett,phivett,1,-1,1,1,1) mats4<-auxmat(m,csivett,phivett,0, 1,1,1,1) mats5<-auxmat(m,csivett,phivett,1, 0,1,1,1) ### for D_i vectors matd1<-auxmat(m,csivett,phivett,1,-1,2,0, 1) matd2<-auxmat(m,csivett,phivett,0, 1,2,0,-1) matd3<-auxmat(m,csivett,phivett,1,-1,2,1, 1) matd4<-auxmat(m,csivett,phivett,0, 1,2,1,-1) ### for H_i vectors math3<-auxmat(m,csivett,phivett,1,-1,2,2,-1) math4<-auxmat(m,csivett,phivett,0, 1,2,2,-1) math5<-auxmat(m,csivett,phivett,1, 0,2,2,-1) ### S1<-S2<-S3<-S4<-D1<-D2<-D3<-D4<-H3<-H4<-rep(NA,m); for(i in 1:n){ S1[i]<-sum(mats1[1:ordinal[i],i])-mats1[ordinal[i],i] S2[i]<-sum(mats2[1:(m-ordinal[i]+1),i])-mats2[(m-ordinal[i]+1),i] S3[i]<-sum(mats3[1:ordinal[i],i])-mats3[ordinal[i],i] S4[i]<-sum(mats4[1:(m-ordinal[i]+1),i])-mats4[(m-ordinal[i]+1),i] D1[i]<-sum(matd1[1:ordinal[i],i])-matd1[ordinal[i],i] D2[i]<-sum(matd2[1:(m-ordinal[i]+1),i])-matd2[(m-ordinal[i]+1),i] D3[i]<-sum(matd3[1:ordinal[i],i])-matd3[ordinal[i],i] D4[i]<-sum(matd4[1:(m-ordinal[i]+1),i])-matd4[(m-ordinal[i]+1),i] H3[i]<-sum(math3[1:ordinal[i],i])-math3[ordinal[i],i] H4[i]<-sum(math4[1:(m-ordinal[i]+1),i])-math4[(m-ordinal[i]+1),i] } ###### Attention !!! S5<-colSums(mats5[1:(m-1),]) H5<-colSums(math5[1:(m-1),]) ########## CC<-S2-S1; EE<-S3+S4-S5; DD<-D2-D1; FF<-D3+D4; GG<-H3+H4-H5; ### Computing vectors v and u vibe<-uui*(1-paivett) viga<-ubari*csivett*(1-csivett)*CC vial<-ubari*phivett*EE #**** ubebe<-uui*(1-paivett)*(1-2*paivett) ugabe<-ubari*csivett*(1-csivett)*(1-paivett)*CC ualbe<-ubari*phivett*(1-paivett)*EE #**** ugaga<-ubari*csivett*(1-csivett)*((1-2*csivett)*CC+csivett*(1-csivett)*(CC^2+DD)) ualga<-ubari*phivett*csivett*(1-csivett)*(FF+CC*EE) #**** ualal<-ubari*phivett*(EE+phivett*(EE^2+GG)) #**** ### Computing vectors g gbebe<-Hadprod(vibe,vibe)-ubebe ggabe<-Hadprod(viga,vibe)-ugabe galbe<-Hadprod(vial,vibe)-ualbe ggaga<-Hadprod(viga,viga)-ugaga galga<-Hadprod(vial,viga)-ualga galal<-Hadprod(vial,vial)-ualal ### Expanding matrices Y, W, Z YY<-cbind(1,Y); WW<-cbind(1,W); ZZ<-cbind(1,Z); ### Elements of the Information matrix infbebe<-t(YY)%*%(Hadprod(YY,gbebe)) infgabe<-t(WW)%*%(Hadprod(YY,ggabe)) infalbe<-t(ZZ)%*%(Hadprod(YY,galbe)) infgaga<-t(WW)%*%(Hadprod(WW,ggaga)) infalga<-t(ZZ)%*%(Hadprod(WW,galga)) infalal<-t(ZZ)%*%(Hadprod(ZZ,galal)) infbega<-t(infgabe) infbeal<-t(infalbe) infgaal<-t(infalga) ### Assembling Information matrix... # # matinf<-rbind( # cbind(infbebe,infbega,infbeal), # cbind(infgabe,infgaga,infgaal), # cbind(infalbe,infalga,infalal)); ### Variance-covariance matrix npai<-NCOL(Y)+1 ncsi<-NCOL(W)+1 nphi<-NCOL(Z)+1 nparam<-npai+ncsi+nphi matinf<-matrix(NA,nrow=nparam,ncol=nparam) for (i in 1:npai){ matinf[i,] <- matrix(c(infbebe[i,],infbega[i,],infbeal[i,]),nrow=1,byrow=TRUE) } for (i in (npai+1):(npai+ncsi)){ matinf[i,] <- matrix(c(infgabe[i-npai,],infgaga[i-npai,],infgaal[i-npai,]),nrow=1,byrow=TRUE) } for (i in (npai+ncsi+1):nparam){ matinf[i,] <- matrix(c(infalbe[i-npai-ncsi,],infalga[i-npai-ncsi,],infalal[i-npai-ncsi,]),nrow=1,byrow=TRUE) } if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { varmat<-solve(matinf) } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubecov.R
#' @title Variance-covariance matrix for CUBE models based on the expected information matrix #' @description Compute the variance-covariance matrix of parameter estimates as the inverse of #' the expected information matrix for a CUBE model without covariates. #' @aliases varcovcubeexp #' @usage varcovcubeexp(m, pai, csi, phi, n) #' @param m Number of ordinal categories #' @param pai Uncertainty parameter #' @param csi Feeling parameter #' @param phi Overdispersion parameter #' @param n Number of observations #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @seealso \code{\link{varcovcubeobs}} #' @keywords internal #' @references #' Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data, #' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 varcovcubeexp <- function(m,pai,csi,phi,n){ pr<-probcube(m,pai,csi,phi); sum1<-sum2<-sum3<-sum4<-rep(NA,m); for(jr in 1:m){ seq1<-1/((1-csi)+phi*((1:jr)-1)); seq2<-1/((csi)+phi*((1:(m-jr+1))-1)); seq3<-((1:jr)-1)/((1-csi)+phi*((1:jr)-1)); seq4<-((1:(m-jr+1))-1)/((csi)+phi*((1:(m-jr+1))-1)); sum1[jr]<-sum(seq1)-seq1[jr]; sum2[jr]<-sum(seq2)-seq2[m-jr+1]; sum3[jr]<-sum(seq3)-seq3[jr]; sum4[jr]<-sum(seq4)-seq4[m-jr+1]; } sum5<-sum(((1:m)-1)/(1+phi*(1:m))); cr<-pr-(1-pai)/m; derpai<-(pr-1/m)/pai; dercsi<-cr*(sum2-sum1); derphi<-cr*(sum3+sum4-sum5); infpaipai<-sum((derpai^2)/pr); infpaicsi<-sum((derpai*dercsi)/pr); infpaiphi<-sum((derpai*derphi)/pr); infcsicsi<-sum((dercsi^2)/pr); infcsiphi<-sum((dercsi*derphi)/pr); infphiphi<-sum((derphi^2)/pr); ### Information matrix inform<-matrix(NA,nrow=3,ncol=3); inform[1,1]<-infpaipai; inform[1,2]<-infpaicsi; inform[1,3]<-infpaiphi; inform[2,1]<-infpaicsi; inform[2,2]<-infcsicsi; inform[2,3]<-infcsiphi; inform[3,1]<-infpaiphi; inform[3,2]<-infcsiphi; inform[3,3]<-infphiphi; ### Var-covar matrix if(any(is.na(inform))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=3,ncol=3) } else { if(det(inform)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=3,ncol=3) } else { varmat<-solve(inform)/n } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubeexp.R
#' @title Variance-covariance matrix for CUBE models based on the observed information matrix #' @description Compute the variance-covariance matrix of parameter estimates for a CUBE model without covariates #' as the inverse of the observed information matrix. #' @aliases varcovcubeobs #' @usage varcovcubeobs(m, pai, csi, phi, freq) #' @param m Number of ordinal categories #' @param pai Uncertainty parameter #' @param csi Feeling parameter #' @param phi Overdispersion parameter #' @param freq Vector of the observed absolute frequencies #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @seealso \code{\link{varcovcubeexp}} #' @keywords internal #' @references #' Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data, #' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 varcovcubeobs <- function(m,pai,csi,phi,freq){ pr<-probcube(m,pai,csi,phi) sum1<-sum2<-sum3<-sum4<-rep(NA,m);### sums computation d1<-d2<-h1<-h2<-h3<-h4<-rep(NA,m); ### derivatives computation ### sum1; sum2; sum3; sum4; sum5; as in Iannario (2013), "Comm. in Stat. Theory & Methods" for(jr in 1:m){ seq1<-1/((1-csi)+phi*((1:jr)-1)) ### a(k) seq2<-1/((csi)+phi*((1:(m-jr+1))-1)) ### b(k) seq3<-((1:jr)-1)/((1-csi)+phi*((1:jr)-1)) seq4<-((1:(m-jr+1))-1)/((csi)+phi*((1:(m-jr+1))-1)) dseq1<-seq1^2 dseq2<-seq2^2 hseq1<-dseq1*((1:jr)-1) hseq2<-dseq2*((1:(m-jr+1))-1) hseq3<-dseq1*((1:jr)-1)^2 hseq4<-dseq2*((1:(m-jr+1))-1)^2 ############# sum1[jr]<-sum(seq1)-seq1[jr] sum2[jr]<-sum(seq2)-seq2[m-jr+1] sum3[jr]<-sum(seq3)-seq3[jr] sum4[jr]<-sum(seq4)-seq4[m-jr+1] d1[jr]<- sum(dseq1)-dseq1[jr] d2[jr]<- -(sum(dseq2)-dseq2[m-jr+1]) h1[jr]<- -(sum(hseq1)-hseq1[jr]) h2[jr]<- -(sum(hseq2)-hseq2[m-jr+1]) h3[jr]<- -(sum(hseq3)-hseq3[jr]) h4[jr]<- -(sum(hseq4)-hseq4[m-jr+1]) } seq5<-(0:(m-2))/(1+phi*(0:(m-2))) ### c(k) correction ?! sum5<-sum(seq5) ### correction ?! h5<- -sum(seq5^2) ### correction ?! ### Symbols as in Iannario (2013), "Comm. in Stat.", ibidem (DP notes) uuur<-1-1/(m*pr) ubar<-uuur+pai*(1-uuur) vbar<-ubar-1 aaar<-sum2-sum1 bbbr<-sum3+sum4-sum5 cccr<-h3+h4-h5 dddr<-h2-h1 eeer<-d2-d1 ###### dummy product prodo<-freq*ubar ###### infpaipai<-sum(freq*uuur^2)/pai^2 infpaicsi<-sum(prodo*(uuur-1)*aaar)/pai infpaiphi<-sum(prodo*(uuur-1)*bbbr)/pai infcsicsi<-sum(prodo*(vbar*aaar^2-eeer)) infcsiphi<-sum(prodo*(vbar*aaar*bbbr-dddr)) infphiphi<-sum(prodo*(vbar*bbbr^2-cccr)) ### Information matrix inform<-matrix(NA,nrow=3,ncol=3) inform[1,1]<-infpaipai; inform[1,2]<-infpaicsi; inform[1,3]<-infpaiphi; inform[2,1]<-infpaicsi; inform[2,2]<-infcsicsi; inform[2,3]<-infcsiphi; inform[3,1]<-infpaiphi; inform[3,2]<-infcsiphi; inform[3,3]<-infphiphi; ### Var-covar matrix nparam<-3 if(any(is.na(inform))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { if(det(inform)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { varmat<-solve(inform) } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubeobs.R
#' @title Variance-covariance matrix of CUB model with covariates for the uncertainty parameter #' @description Compute the variance-covariance matrix of parameter estimates of a CUB model with #' covariates for the uncertainty component. #' @aliases varcovcubp0 #' @usage varcovcubp0(m, ordinal, Y, bet, csi) #' @param m Number of ordinal categories #' @param ordinal Vector of ordinal responses #' @param Y Matrix of covariates for explaining the uncertainty parameter #' @param bet Vector of parameters for the uncertainty component, whose length equals NCOL(Y)+1 #' to include an intercept term (first entry) #' @param csi Feeling parameter #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @seealso \code{\link{probcubpq}} #' @keywords internal #' @references #' Piccolo D. (2006), Observed Information Matrix for CUB Models, \emph{Quaderni di Statistica}, \bold{8}, 33--78 varcovcubp0 <- function(m,ordinal,Y,bet,csi){ Y<-as.matrix(Y); if (ncol(Y)==1){ Y<-as.numeric(Y) } vvi<-(m-ordinal)/csi-(ordinal-1)/(1-csi) ui<-(m-ordinal)/(csi^2)+(ordinal-1)/((1-csi)^2) qi<-1/(m*probcubp0(m,ordinal,Y,bet,csi)) ei<-logis(Y,bet) qistar<-1-(1-ei)*qi eitilde<-ei*(1-ei) qitilde<-qistar*(1-qistar) ff<-eitilde-qitilde g10<-vvi*qitilde YY<-cbind(1,Y) i11<-t(YY)%*%(Hadprod(YY,ff)) ###ALTERNATIVE YY*ff does not work i12<- -t(YY)%*%(g10) i22<-sum(ui*qistar-(vvi^2)*qitilde) # Information matrix ## matinf=rbind(cbind(i11,i12),cbind(t(i12),i22)) # Var-covar matrix nparam<- NCOL(Y) + 2 matinf<-matrix(NA,nrow=nparam,ncol=nparam) for (i in 1:(nparam-1)){ matinf[i,]<-t(c(i11[i,],i12[i])) } matinf[nparam,]<-t(c(t(i12),i22)) if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { varmat<-solve(matinf) } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubp0.R
#' @title Variance-covariance matrix of a CUB model with covariates for both uncertainty and feeling #' @description Compute the variance-covariance matrix of parameter estimates of a CUB model with covariates for #' both the uncertainty and the feeling components. #' @aliases varcovcubpq #' @usage varcovcubpq(m, ordinal, Y, W, bet, gama) #' @param m Number of ordinal categories #' @param ordinal Vector of ordinal responses #' @param Y Matrix of covariates for explaining the uncertainty parameter #' @param W Matrix of covariates for explaining the feeling parameter #' @param bet Vector of parameters for the uncertainty component, with length equal to #' NCOL(Y)+1 to account for an intercept term (first entry) #' @param gama Vector of parameters for the feeling component, with length equal to #' NCOL(W)+1 to account for an intercept term (first entry) #' @details The function checks if the variance-covariance matrix is positive-definite: if not, it returns a warning #' message and produces a matrix with NA entries. #' @seealso \code{\link{probcubpq}} #' @keywords internal #' @references #' Piccolo D. (2006), Observed Information Matrix for CUB Models, \emph{Quaderni di Statistica}, \bold{8}, 33--78 varcovcubpq <- function(m,ordinal,Y,W,bet,gama){ Y<-as.matrix(Y);W<-as.matrix(W); if (ncol(W)==1){ W<-as.numeric(W) } if (ncol(Y)==1){ Y<-as.numeric(Y) } qi<-1/(m*probcubpq(m,ordinal,Y,W,bet,gama)) ei<-logis(Y,bet) eitilde<-ei*(1-ei) qistar<-1-(1-ei)*qi qitilde<-qistar*(1-qistar) fi<-logis(W,gama) fitilde<-fi*(1-fi) ai<-(ordinal-1)-(m-1)*(1-fi) ff<-eitilde-qitilde gg<-ai*qitilde hh<-(m-1)*qistar*fitilde-(ai^2)*qitilde YY<-cbind(1,Y) WW<-cbind(1,W) i11<-t(YY)%*%(Hadprod(YY,ff)) ### i11<-t(YY)%*%(YY*ff); i12<-t(YY)%*%(Hadprod(WW,gg)) ### i12<-t(YY)%*%(WW*gg); i22<-t(WW)%*%(Hadprod(WW,hh)) ### i22<-t(WW)%*%; ## matinf<-rbind(cbind(i11,i12),cbind(t(i12),i22)) # Information matrix nparam<-NCOL(Y)+NCOL(W)+2 npai<-NCOL(Y)+1 ncsi<-NCOL(W)+1 nparam<-npai+ncsi matinf<-matrix(NA,nrow=nparam,ncol=nparam) for (i in 1:npai){ matinf[i,]<-t(c(i11[i,],i12[i,])) } for (i in (npai+1):nparam){ matinf[i,]<-t(c(t(i12)[i-npai,],i22[i-npai,])) } if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=nparam,ncol=nparam) } else { varmat<-solve(matinf) } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubpq.R
#' @title Variance-covariance matrix for CUB models with shelter effect #' @description Compute the variance-covariance matrix of parameter estimates of a CUB model with shelter effect. #' @aliases varcovcubshe #' @usage varcovcubshe(m, pai1, pai2, csi, shelter, n) #' @param m Number of ordinal categories #' @param pai1 Parameter of the mixture distribution: mixing coefficient for the shifted Binomial component #' @param pai2 Second parameter of the mixture distribution: mixing coefficient for the discrete Uniform component #' @param csi Feeling parameter #' @param shelter Category corresponding to the shelter choice #' @param n Number of observations #' @seealso \code{\link{probcubshe1}} #' @keywords internal #' @details The function checks if the variance-covariance matrix is positive-definite: if not, it returns a warning #' message and produces a matrix with NA entries. #' @references Iannario, M. (2012), Modelling shelter choices in ordinal data surveys. #' Statistical Modelling and Applications, \bold{21}, 1--22 varcovcubshe <-function(m,pai1,pai2,csi,shelter,n){ pr<-probcubshe1(m,pai1,pai2,csi,shelter) dd<-rep(0,m);dd[shelter]<-1; bb<-probbit(m,csi) ######################## aaa<-bb-dd bbb<-(1/m)-dd c4<-pai1*bb*(m-(1:m)-csi*(m-1))/(csi*(1-csi)) atilde<-aaa/pr; btilde<-bbb/pr; ctilde<-c4/pr; d11<-sum(aaa*atilde); d22<-sum(bbb*btilde); dxx<-sum(c4*ctilde); d12<-sum(bbb*atilde); d1x<-sum(c4*atilde); d2x<-sum(c4*btilde); ### Information matrix matinf<-matrix(c(d11,d12,d1x,d12,d22,d2x,d1x,d2x,dxx),nrow=3,byrow=T) ### Var-covar matrix if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=3,ncol=3) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=3,ncol=3) } else { varmat<-solve(matinf)/n } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcubshe.R
#' @title Variance-covariance matrix of a CUB model without covariates #' @description Compute the variance-covariance matrix of parameter estimates of a CUB model without covariates. #' @aliases varcovgecub #' @usage varcovgecub(ordinal,Y,W,X,bet,gama,omega,shelter) #' @param ordinal Vector of ordinal responses #' @param Y Matrix of selected covariates to explain the uncertainty component (default: no covariate is included #' in the model) #' @param W Y Matrix of selected covariates to explain the feeling component (default: no covariate is included #' in the model) #' @param X Matrix of selected covariates to explain the shelter component (default: no covariate is included #' in the model) #' @param bet Parameter vector for the Uncertainty component #' @param gama Parameter vector for the Feeling component #' @param omega Parameter vector for the shelter component #' @param shelter Cateogry corresponding to the shelter effect #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. #' @seealso \code{\link{probgecub}} #' @keywords internal varcovgecub<-function(ordinal,Y,W,X,bet,gama,omega,shelter){ Y<-as.matrix(Y);W<-as.matrix(W); X<-as.matrix(X); if (ncol(W)==1){ W<-as.numeric(W) } if (ncol(Y)==1){ Y<-as.numeric(Y) } if (ncol(X)==1){ X<-as.numeric(X) } probi<-probgecub(ordinal,Y,W,X,bet,gama,omega,shelter); vvi<-1/probi; dicotom<-ifelse(ordinal==shelter,1,0) # Y=as.matrix(Y) # W=as.matrix(W) # X=as.matrix(X) paii<-logis(Y,bet); csii<-logis(W,gama); deltai<-logis(X,omega); m<-length(levels(factor(ordinal,ordered=TRUE))) bierrei<-bitgama(m,ordinal,W,gama); YY<-cbind(1,Y); WW<-cbind(1,W); XX<-cbind(1,X); np<-NCOL(YY)+NCOL(WW)+NCOL(XX); # /* vettori (n,1) utili per deriv...prime*/ mconi<-m-ordinal-(m-1)*csii; # /* deriv.prime/prob_i */ vettAA<-paii*(1-paii)*(1-deltai)*(bierrei-1/m)*vvi AA <- Hadprod(YY,vettAA) ### n x p+1 #AA=YY.*paii.*(1-paii).*(1-deltai).*(bierrei-1/m).*vvi; vettBB<-paii*(1-deltai)*mconi*bierrei*vvi; BB <- Hadprod(WW,vettBB) vettCC<-deltai*(dicotom-probi)*vvi CC <- Hadprod(XX,vettCC); # CC=XX.*deltai.*(dicotom-probi).*vvi; # /* utili per deriv.seconde/prob_i*/ dconi<- paii*(1-paii)*(1-2*paii)*(1-deltai)*(bierrei-1/m)*vvi; #dconi=paii.*(1-paii).*(1-2*paii).*(1-deltai).*(bierrei-1/m).*vvi; gconi<- paii*(1-deltai)*bierrei*(mconi^2-(m-1)*csii)*(1-csii)*vvi; # gconi=paii.*(1-deltai).*bierrei.*(mconi^2-(m-1)*csii.*(1-csii)).*vvi; lconi <- deltai*(1-2*deltai)*(dicotom-probi)*vvi; # lconi=deltai.*(1-2*deltai).*(dicotom-probi).*vvi; econi <- paii*(1-paii)*(1-deltai)*(bierrei)*mconi*vvi; # econi=paii.*(1-paii).*(1-deltai).*bierrei.*mconi.*vvi; fconi<- (-paii)*(1-paii)*deltai*(1-deltai)*(bierrei-1/m)*vvi; # fconi=-paii.*(1-paii).*deltai.*(1-deltai).*(bierrei-1/m).*vvi; hconi<-(-paii)*deltai*(1-deltai)*bierrei*mconi*vvi;# hconi=-paii.*deltai.*(1-deltai).*bierrei.*mconi.*vvi; #/* Observed information matrix (gi??? con il segno meno) */ inf11<-t(AA)%*%AA-t(YY)%*%Hadprod(YY,dconi); #inf11=AA'AA-YY'(YY.*dconi); #/* (p+1,p+1) */ inf22<-t(BB)%*%BB-t(WW)%*%Hadprod(WW,gconi); #/* (q+1,q+1) */ inf33<-t(CC)%*%CC-t(XX)%*%Hadprod(XX,lconi); #/* (s+1,s+1) */ inf21<-t(BB)%*%AA-t(WW)%*%Hadprod(YY,econi); #/* (q+1,p+1) */ inf31<-t(CC)%*%AA-t(XX)%*%Hadprod(YY,fconi); #/* (s+1,p+1) */ inf32<-t(CC)%*%BB-t(XX)%*%Hadprod(WW,hconi); #/* (s+1,q+1) */ @...prima era: BB'CC @ inf12<-t(inf21); inf13<-t(inf31); inf23<-t(inf32); matinf<-rbind(cbind(inf11,inf12,inf13),cbind(inf21,inf22,inf23),cbind(inf31,inf32,inf33)); # Information matrix if(any(is.na(matinf))==TRUE){ warning("ATTENTION: NAs produced") varmat<-matrix(NA,nrow=np,ncol=np) } else { if(det(matinf)<=0){ warning("ATTENTION: Variance-covariance matrix NOT positive definite") varmat<-matrix(NA,nrow=np,ncol=np) } else { varmat<-solve(matinf) } } # # if(det(matinf)<=0){ # notpd=1; # cat("=======================================================================","\n") # cat("Variance-covariance matrix NOT positive definite","\n") # cat("=======================================================================","\n") # } else { # notpd=0; # varmat=solve(matinf); # } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovgecub.R
#' @title Variance of CUB models without covariates #' @description Compute the variance of a CUB model without covariates. #' @aliases varcub00 #' @usage varcub00(m,pai,csi) #' @param m Number of ordinal categories #' @param pai Uncertainty parameter #' @param csi Feeling parameter #' @export varcub00 #' @seealso \code{\link{expcub00}}, \code{\link{probcub00}} #' @references #' Piccolo D. (2003). On the moments of a mixture of uniform and shifted binomial random variables. #' \emph{Quaderni di Statistica}, \bold{5}, 85--104 #' @keywords distribution #' @examples #' m<-9 #' pai<-0.6 #' csi<-0.5 #' varcub<-varcub00(m,pai,csi) varcub00 <-function(m,pai,csi){ (m-1)*(pai*csi*(1-csi)+(1-pai)*(((m+1)/12) + pai*(m-1)*(csi-1/2)^2 )) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcub00.R
#' @title Variance of CUBE models without covariates #' @description Compute the variance of a CUBE model without covariates. #' @aliases varcube #' @usage varcube(m,pai,csi,phi) #' @param m Number of ordinal categories #' @param pai Uncertainty parameter #' @param csi Feeling parameter #' @param phi Overdispersion parameter #' @export varcube #' @seealso \code{\link{probcube}}, \code{\link{expcube}} #' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in #' Ordinal Data, \emph{Communications in Statistics - Theory and Methods}, \bold{43}, #' 771--786 #' @keywords distribution #' @examples #' m<-7 #' pai<-0.8 #' csi<-0.2 #' phi<-0.05 #' varianceCUBE<-varcube(m,pai,csi,phi) varcube <-function(m,pai,csi,phi){ odeffect<-pai*csi*(1-csi)*(m-1)*(m-2)*phi/(1+phi) variance<- varcub00(m,pai,csi) + odeffect return(variance) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcube.R
#' @title Variance-covariance matrix for CUB models #' @aliases varmatCUB #' @description Compute the variance-covariance matrix of parameter estimates for CUB models with or without #' covariates for the feeling and the uncertainty parameter, and for extended CUB models with shelter effect. #' @usage varmatCUB(ordinal,m,param,Y=0,W=0,X=0,shelter=0) #' @export varmatCUB #' @param ordinal Vector of ordinal responses #' @param m Number of ordinal categories #' @param param Vector of parameters for the specified CUB model #' @param Y Matrix of selected covariates to explain the uncertainty component (default: no covariate is included #' in the model) #' @param W Matrix of selected covariates to explain the feeling component (default: no covariate is included #' in the model) #' @param X Matrix of selected covariates to explain the shelter effect (default: no covariate is included #' in the model) #' @param shelter Category corresponding to the shelter choice (default: no shelter effect is included in the #' model) #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. No missing value should be present neither #' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be preliminarily run. #' @seealso \code{\link{vcov}}, \code{\link{cormat}} #' @keywords htest #' @references Piccolo D. (2006). Observed Information Matrix for MUB Models, #' \emph{Quaderni di Statistica}, \bold{8}, 33--78 \cr #' Iannario, M. (2012). Modelling shelter choices in ordinal data surveys. #' \emph{Statistical Modelling and Applications}, \bold{21}, 1--22 \cr #' Iannario M. and Piccolo D. (2016b). A generalized framework for modelling ordinal data. #' \emph{Statistical Methods and Applications}, \bold{25}, 163--189.\cr #' @examples #' data(univer) #' m<-7 #' ### CUB model with no covariate #' pai<-0.87; csi<-0.17 #' param<-c(pai,csi) #' varmat<-varmatCUB(univer$global,m,param) #' ####################### #' ### and with covariates for feeling #' data(univer) #' m<-7 #' pai<-0.86; gama<-c(-1.94,-0.17) #' param<-c(pai,gama) #' ordinal<-univer$willingn; W<-univer$gender #' varmat<-varmatCUB(ordinal,m,param,W) #' ####################### #' ### CUB model with uncertainty covariates #' data(relgoods) #' m<-10 #' naord<-which(is.na(relgoods$Physician)) #' nacov<-which(is.na(relgoods$Gender)) #' na<-union(naord,nacov) #' ordinal<-relgoods$Physician[-na] #' Y<-relgoods$Gender[-na] #' bet<-c(-0.81,0.93); csi<-0.20 #' varmat<-varmatCUB(ordinal,m,param=c(bet,csi),Y=Y) #' ####################### #' ### and with covariates for both parameters #' data(relgoods) #' m<-10 #' naord<-which(is.na(relgoods$Physician)) #' nacov<-which(is.na(relgoods$Gender)) #' na<-union(naord,nacov) #' ordinal<-relgoods$Physician[-na] #' W<-Y<-relgoods$Gender[-na] #' gama<-c(-0.91,-0.7); bet<-c(-0.81,0.93) #' varmat<-varmatCUB(ordinal,m,param=c(bet,gama),Y=Y,W=W) #' ####################### #' ### Variance-covariance for a CUB model with shelter #' m<-8; n<-300 #' pai1<-0.5; pai2<-0.3; csi<-0.4 #' shelter<-6 #' pr<-probcubshe1(m,pai1,pai2,csi,shelter) #' ordinal<-sample(1:m,n,prob=pr,replace=TRUE) #' param<-c(pai1,pai2,csi) #' varmat<-varmatCUB(ordinal,m,param,shelter=shelter) varmatCUB<-function(ordinal,m,param,Y=0,W=0,X=0,shelter=0){ if (is.factor(ordinal)){ ordinal<-unclass(ordinal) } ry<-NROW(Y); rw<-NROW(W); rx<-NROW(X); shelter<-as.numeric(shelter) if(shelter!=0){ if (ry==1 & rw==1 & rx==1){ pai1<-param[1] pai2<-param[2] csi<-param[3] n<-length(ordinal) varmat<-varcovcubshe(m,pai1,pai2,csi,shelter,n) }else if(ry!=1 & rw!=1 & rx!=1){ ny<-NCOL(Y);nw<-NCOL(W);nx<-NCOL(X) Y<-as.matrix(Y);W<-as.matrix(W); X<-as.matrix(X); if (ncol(W)==1){ W<-as.numeric(W) } if (ncol(Y)==1){ Y<-as.numeric(Y) } if (ncol(X)==1){ X<-as.numeric(X) } bet<-param[1:(ny+1)]; gama<-param[(ny+2):(ny+nw+2)]; omega<-param[(ny+nw+3):(ny+nw+nx+3)] varmat<-varcovgecub(ordinal,Y,W,X,bet,gama,omega,shelter) } else { varmat<-NULL cat("CUB model with shelter effect available only with covariates for all components") } }else{ if(ry==1 & rw==1 & rx==1) { pai<-param[1] csi<-param[2] varmat<-varcovcub00(m,ordinal,pai,csi) } else{ if(ry!=1 & rw==1 & rx==1) { ncy<-NCOL(Y) Y<-as.matrix(Y); if (ncol(Y)==1){ Y<-as.numeric(Y) } bet<-param[1:(ncy+1)] csi<-param[length(param)] varmat<-varcovcubp0(m,ordinal,Y,bet,csi) } else { if(ry==1 & rw!=1 & rx==1) { pai<-param[1] gama<-param[2:length(param)] W<-as.matrix(W); if (ncol(W)==1){ W<-as.numeric(W) } varmat<-varcovcub0q(m,ordinal,W,pai,gama) } else{ if(ry!=1 & rw!=1& rx==1) { Y<-as.matrix(Y);W<-as.matrix(W);ncy<-NCOL(Y) if (ncol(Y)==1){ Y<-as.numeric(Y) } if (ncol(W)==1){ W<-as.numeric(W) } bet<-param[1:(ncy+1)] gama<-param[(ncy+2):length(param)] varmat<-varcovcubpq(m,ordinal,Y,W,bet,gama) } else { cat("Wrong variables specification") varmat<-NULL } } } } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varmatCUB.R
#' @title Variance-covariance matrix for CUBE models #' @aliases varmatCUBE #' @description Compute the variance-covariance matrix of parameter estimates for CUBE models when no covariate #' is specified, or when covariates are included for all the three parameters. #' @usage varmatCUBE(ordinal,m,param,Y=0,W=0,Z=0,expinform=FALSE) #' @export varmatCUBE #' @param ordinal Vector of ordinal responses #' @param m Number of ordinal categories #' @param param Vector of parameters for the specified CUBE model #' @param Y Matrix of selected covariates to explain the uncertainty component (default: no covariate is included #' in the model) #' @param W Matrix of selected covariates to explain the feeling component (default: no covariate is included #' in the model) #' @param Z Matrix of selected covariates to explain the overdispersion component (default: no covariate is included #' in the model) #' @param expinform Logical: if TRUE and no covariate is included in the model, the function returns #' the expected variance-covariance matrix (default is FALSE: the function returns the observed #' variance-covariance matrix) #' @details The function checks if the variance-covariance matrix is positive-definite: if not, #' it returns a warning message and produces a matrix with NA entries. No missing value should be present neither #' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be preliminarily run. #' @seealso \code{\link{vcov}}, \code{\link{cormat}} #' @keywords htest #' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data, #' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr #' Piccolo D. (2015). Inferential issues for CUBE models with covariates, #' \emph{Communications in Statistics. Theory and Methods}, \bold{44}(23), 771--786. \cr #' @examples #' m<-7; n<-500 #' pai<-0.83; csi<-0.19; phi<-0.045 #' ordinal<-simcube(n,m,pai,csi,phi) #' param<-c(pai,csi,phi) #' varmat<-varmatCUBE(ordinal,m,param) #' ########################## #' ### Including covariates #' data(relgoods) #' m<-10 #' naord<-which(is.na(relgoods$Tv)) #' nacov<-which(is.na(relgoods$BirthYear)) #' na<-union(naord,nacov) #' age<-2014-relgoods$BirthYear[-na] #' lage<-log(age)-mean(log(age)) #' Y<-W<-Z<-lage #' ordinal<-relgoods$Tv[-na] #' estbet<-c(0.18,1.03); estgama<-c(-0.6,-0.3); estalpha<-c(-2.3,0.92) #' param<-c(estbet,estgama,estalpha) #' varmat<-varmatCUBE(ordinal,m,param,Y=Y,W=W,Z=Z,expinform=TRUE) varmatCUBE<-function(ordinal,m,param,Y=0,W=0,Z=0,expinform=FALSE){ if (is.factor(ordinal)){ ordinal<-unclass(ordinal) } ry<-NROW(Y); rw<-NROW(W); rz<-NROW(Z); if(ry==1 & rw==1 & rz==1) { pai<-param[1]; csi<-param[2]; phi<-param[3]; if(expinform==FALSE){ freq<-tabulate(ordinal,nbins=m) varmat<-varcovcubeobs(m,pai,csi,phi,freq) } else{ n<-length(ordinal) varmat<-varcovcubeexp(m,pai,csi,phi,n) } } else { if(ry>1 & rz>1 & rw >1){ ncy<-NCOL(Y) ncw<-NCOL(W) Y<-as.matrix(Y);W<-as.matrix(W); Z<-as.matrix(Z); if (ncol(Y)==1){ Y<-as.numeric(Y) } if (ncol(W)==1){ W<-as.numeric(W) } if (ncol(Z)==1){ Z<-as.numeric(Z) } estbet<-param[1:(ncy+1)]; estgama<-param[(ncy+2):(ncy+ncw+2)]; estalpha<-param[(ncy+ncw+3):length(param)]; varmat<-varcovcubecov(m,ordinal,Y,W,Z,estbet,estgama,estalpha) } else { cat("CUBE models not available for this variables specification") } } return(varmat) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/varmatCUBE.R
#' @title S3 method vcov() for class "GEM" #' @description S3 method: vcov for objects of class \code{\link{GEM}}. #' @aliases vcov.GEM #' @param object An object of class \code{\link{GEM}} #' @param ... Other arguments #' @method vcov GEM #' @export #' @return Variance-covariance matrix of the final ML estimates for parameters of the fitted GEM model. #' It returns the square of the estimated standard error for CUSH and IHG models with no covariates. #' @import methods #' @seealso \code{\link{varmatCUB}}, \code{\link{varmatCUBE}}, \code{\link{GEM}} #' @keywords package #' @rdname vcov.GEM #vcov <- function(object,...) UseMethod("vcov", object) vcov.GEM<-function(object, ...){ arguments<-list(...) digits<-arguments$digits if (is.null(digits)){ digits<-options()$digits } ellipsis<-object$ellipsis family<-object$family varcov<-as.matrix(object$varmat) listanomi<-parnames(object) if (NROW(varcov)>1){ dimnames(varcov)<-list(listanomi,listanomi) } else { dimnames(varcov)<-list(listanomi,"Squared Standard Error") } return(round(varcov,digits=digits)) }
/scratch/gouwar.j/cran-all/cranData/CUB/R/vcov.R
## ----include=FALSE,eval=TRUE,echo=FALSE--------------------------------------- library(knitr) library(digest) opts_chunk$set( engine='R',dev='pdf',fig.width=7,fig.height=5,strip.white=TRUE,tidy=FALSE ) ## ----include=FALSE------------------------------------------------------------ library(knitr) opts_chunk$set( concordance=TRUE ) ## ----eval=TRUE,echo=FALSE,comment=NA------------------------------------------ options(warn=-1) suppressMessages(library(CUB)) library(knitr) options(warn=-1) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula, family, ...) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~Y|W|X), family="cub", ...) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~0|0|0), family="cub") ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~Y|0|0), family="cub") ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~0|W|0), family="cub") ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~Y|W|0), family="cub") ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # GEM(Formula(ordinal~0|0|0), family="cub", shelter=s) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~Y|W|X), family="cub", shelter=s) ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # GEM(Formula(ordinal~0), family="cush", shelter = s) # without covariates # GEM(Formula(ordinal~X), family="cush", shelter = s) # with covariates ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # GEM(Formula(ordinal~0|0|0), family="cube") # without covariates # GEM(Formula(ordinal~0|W|0), family="cube") # with covariates for feeling # GEM(Formula(ordinal~Y|W|Z), family="cube") # with covariates for all parameters ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # GEM(Formula(ordinal~0),family="ihg") # without covariates # GEM(Formula(ordinal~U),family="ihg") # with covariates ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # llCUB <- loglikCUB(ordinal,m,param,Y=Y,W=W,X=X,shelter=s) # llCUBE <- loglikCUBE(ordinal,m,param,Y=Y,W=W,Z=Z) # llIHG <- loglikIHG(ordinal,m,param,U=U) # llCUSH <- loglikCUSH(ordinal,m,param,X=X,shelter=s) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # varCUB <- varmatCUB(ordinal, m, param, Y = Ycovar, W = Wcovar, X = Xcovar, # shelter = shelter) ## ----echo=TRUE,eval=FALSE----------------------------------------------------- # varCUBE <- varmatCUBE(ordinal, m, param, Y = Ycovar, W = Wcovar, Z = Zcovar, # expinform = FALSE) ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # ########################################################################### # ### Selection of 9 CUBE models with csi = 0.3 over 9 ordinal categories *** # ########################################################################### # m<-9; csi<-0.3 # ########### varying pai and phi parameters # paival<-seq(0.9,0.1,by=-0.1) # phival<-rep(c(0.05,0.1,0.3),times=3) # model<-cbind(paival,phival); nmodels<-nrow(model) # ########################################## # par(mfrow = c(3,3)) # par(mar = c(2,4,3,1)+0.1) # ### Probability distribution plots for jmod=1,2,...,9 # for (jmod in 1:nmodels){ # paij<-model[jmod, 1] # phij<-model[jmod, 2] # prob<-probcube(m, paij, csi, phij) # exp<-expcube(m, paij, csi, phij) # var<-round(varcube(m, paij, csi, phij), digits = 2) # plot(1:m, prob, type = "h", lwd = 3, ylim = c(0,0.4), xlab = "", # ylab = "Pr(R=r)", las = 1) # text(2.3, 0.38, bquote(pi == .(paij)), cex = 0.7) # text(5, 0.38, bquote(xi == .(csi)), cex = 0.7) # text(7.8, 0.38, bquote(phi == .(phij)), cex = 0.7) # text(7, 0.285, bquote(sigma^2 == .(var)), cex = 0.7) # text(3, 0.28, bquote(mu == .(exp)), cex = 0.7) # } # par(mar = c(5,4,4,2)+0.1) ### reset standard margins # par(mfrow = c(1,1)) ### reset plot screen ## ----eval=TRUE,echo=FALSE,comment=NA,fig.width=5, fig.height=5.5-------------- m<-9; csi<-0.3 ########### varying pai and phi parameters paival<-seq(0.9,0.1,by=-0.1) phival<-rep(c(0.05,0.1,0.3),times=3) model<-cbind(paival,phival); nmodels<-nrow(model) ########################################## par(mfrow = c(3,3)) ### split the plot screen par(mar = c(2,4,3,1)+0.1); ### set new margins ### Probability distribution plots for jmod=1,2,...,9 for (jmod in 1:nmodels){ paij<-model[jmod,1]; phij<-model[jmod,2]; prob<-probcube(m,paij,csi,phij); exp<-expcube(m,paij,csi,phij); var<-round(varcube(m,paij,csi,phij),digits=2); plot(1:m,prob,type="h",lwd=3,ylim=c(0,0.4),xlab = "", ylab = "Pr(R=r)", las=1); text(2.3, 0.38, bquote(pi == .(paij)), cex = 0.7); text(5, 0.38, bquote(xi == .(csi)), cex = 0.7); text(7.8, 0.38, bquote(phi == .(phij)), cex = 0.7); text(7, 0.285, bquote(sigma^2 == .(var)), cex = 0.7); text(3, 0.28, bquote(mu == .(exp)), cex = 0.7); } par(mar = c(5,4,4,2)+0.1); ### reset standard margins par(mfrow = c(1,1)); ## ----eval=FALSE,echo=TRUE----------------------------------------------------- # data(univer) # listord<-univer[,8:12] # only ratings, excluding covariates # labels<-names(univer)[8:12] # multicub(listord, labels = labels, # caption ="CUB models on Univer data set", pch = 19, # pos = c(1,rep(3, ncol(listord)-1)),ylim=c(0.75,1),xlim=c(0,0.4)) ## ----eval=TRUE,echo=FALSE,comment=NA,fig.width=4.5, fig.height=5-------------- data(univer) listord<-univer[,8:12] # only ratings, excluding covariates labels<-names(univer)[8:12] multicub(listord, labels = labels, caption ="CUB models on Univer data set", symbols = 19, pos = c(1,rep(3, ncol(listord)-1)),ylim=c(0.75,1),xlim=c(0,0.4)) ## ----cub00,eval=TRUE,echo=TRUE,fig.width=5, fig.height=5.5,comment=NA--------- ## CUB model without covariates for "officeho" cub_00<-GEM(Formula(officeho~0|0|0), family="cub",data=univer) summary(cub_00,digits=5) ## ----eval=TRUE,echo=TRUE,cache=TRUE,comment=NA-------------------------------- param<-coef(cub_00,digits=3) param uncertainty<-1-param[1] uncertainty feeling<-1-param[2] feeling ## ----eval=FALSE,cache=TRUE, echo=TRUE,fig.width=5, fig.height=5.5,comment=NA---- # ## CUB model without covariates # makeplot(cub_00) ## ----eval=TRUE,echo=TRUE,comment=NA------------------------------------------- data(univer) freq<-tabulate(univer$officeho,nbins = 7) ini<-inibest(m,freq) # preliminary estimates for c(pai,csi) ini ## ----cub_csi,cache=TRUE,eval=TRUE,echo=TRUE,comment=NA------------------------ cub_csi<-GEM(Formula(officeho~0|freqserv|0), family="cub",data=univer) summary(cub_csi,digits=3) ## ----cache=TRUE,eval=TRUE,echo=TRUE,comment=NA-------------------------------- gama<-coef(cub_csi)[2:3] gama gama0<-gama[1] ## intercept term gama1<-gama[2] ## ----eval=TRUE,echo=TRUE------------------------------------------------------ csi_nru <- logis(0, gama) ## csi parameter for non regular user (freqserv=0) csi_nru csi_ru <- logis(1, gama) ## csi parameter for regular user (freqserv=1) csi_ru ## ----cache=TRUE,echo=TRUE,eval=TRUE,comment=NA-------------------------------- pai<-coef(cub_csi)[1] gama<-coef(cub_csi)[2:3] data(univer) pearson<-chi2cub(m=7, univer$officeho, W = univer$freqserv, pai, gama) str(pearson) ## ----cache=TRUE,eval=TRUE,echo=FALSE,fig.width=5, fig.height=5.5,comment=NA---- makeplot(cub_00) ## ----cache=TRUE,eval=TRUE,echo=FALSE,fig.width=5, fig.height=5.5,comment=NA---- makeplot(cub_csi) ## ----cache=TRUE,eval=TRUE,echo=TRUE,comment=NA-------------------------------- data(univer) inicsicov<-inibestgama(m,univer$officeho,W=univer$freqserv) inicsicov ## ----cub_pai_csi,cache=TRUE,eval=TRUE,echo=TRUE,comment=NA-------------------- data(univer) age<-univer$age lage<-log(age)-mean(log(age)) # Deviation from mean of logged Age cub_pai_csi<-GEM(Formula(officeho~lage+gender|lage+freqserv|0),family="cub",data=univer) summary(cub_pai_csi,correlation=TRUE,digits=3) ## ----eval=TRUE,echo=TRUE------------------------------------------------------ coef(cub_pai_csi,digits=3) ## ----eval=FALSE,echo=TRUE,cache=TRUE,comment=NA------------------------------- # data(univer) # age<-univer$age # average<-mean(log(age)) # ageseq<-log(seq(17, 51, by = 0.1))-average # param<-coef(cub_pai_csi) # #################### # paicov0<-logis(cbind(ageseq, 0), param[1:3]) # paicov1<-logis(cbind(ageseq, 1), param[1:3]) # # csicov0<-logis(cbind(ageseq, 0), param[4:6]) # csicov1<-logis(cbind(ageseq, 1), param[4:6]) # #################### # plot(1-paicov0, 1-csicov0, type = "n", col = "blue", cex = 1, # xlim = c(0, 0.6), ylim = c(0.4, 0.9), font.main = 4, las = 1, # main = "CUB models with covariates", # xlab = expression(paste("Uncertainty ", (1-pi))), # ylab = expression(paste("Feeling ", (1-xi))), cex.main = 0.9, # cex.lab = 0.9) # lines(1-paicov1, 1-csicov1, lty = 1, lwd = 4, col = "red") # lines(1-paicov0, 1-csicov0, lty = 1, lwd = 4, col = "blue") # lines(1-paicov0, 1-csicov1, lty = 1, lwd = 4, col = "black") # lines(1-paicov1, 1-csicov0, lty = 1, lwd = 4, col = "green") # legend("bottomleft", legend = c("Man-User", "Man-Not User", # "Woman-User", "Woman-Not User"), col = c("black", "blue", "red", "green"), # lty = 1, text.col = c("black", "blue", "red", "green"), cex = 0.6) # text(0.1, 0.85, labels = "Young", offset = 0.3, cex = 0.8, font = 4) # text(0.5, 0.5, labels = "Elderly", offset = 0.3, cex = 0.8, font = 4) ## ----eval=TRUE,echo=FALSE,fig.width=4.5,fig.height=4.5,comment=NA------------- average<-mean(log(age)) ageseq<-log(seq(17, 51, by = 0.1))-average; param<-coef(cub_pai_csi) #################### paicov0<-logis(cbind(ageseq, 0), param[1:3]) paicov1<-logis(cbind(ageseq, 1), param[1:3]) csicov0<-logis(cbind(ageseq, 0), param[4:6]) csicov1<-logis(cbind(ageseq, 1), param[4:6]) #################### plot(1-paicov0, 1-csicov0, type = "n", col = "blue", cex = 1, xlim = c(0, 0.6), ylim = c(0.5, 1), font.main = 4, las = 1, main = "CUB models with covariates", xlab = expression(paste("Uncertainty ", (1-pi))), ylab = expression(paste("Feeling ", (1-xi))), cex.main = 0.9, cex.lab = 0.9) lines(1-paicov1, 1-csicov1, lty = 1, lwd = 4, col = "red") lines(1-paicov0, 1-csicov0, lty = 1, lwd = 4, col = "blue") lines(1-paicov0, 1-csicov1, lty = 1, lwd = 4, col = "black") lines(1-paicov1, 1-csicov0, lty = 1, lwd = 4, col = "green") legend("bottomleft", legend = c("Man-User", "Man-Not User", "Woman-User", "Woman-Not User"), col = c("black", "blue", "red", "green"), lty = 1, text.col = c("black", "blue", "red", "green"), cex = 0.6) text(0.08, 0.95, labels = "Young", offset = 0.3, cex = 0.8, font = 4) text(0.4, 0.7, labels = "Elderly", offset = 0.3, cex = 0.8, font = 4) ## ----cube,cache=TRUE,eval=TRUE,echo=TRUE,comment=NA--------------------------- starting<-c(0.5, 0.5, 0.1) cubefit<-GEM(Formula(willingn~0|0|0),family="cube", starting = starting, maxiter = 100, toler = 1e-4,data=univer) summary(cubefit,digits=7) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # GEM(Formula(ordinal~0|W|0),family="cube") ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # GEM(Formula(ordinal~Y|W|Z),family="cube") ## ----ihg,cache=TRUE,eval=TRUE,echo=TRUE,comment=NA---------------------------- ihgfit<-GEM(Formula(willingn~0),family="ihg",data=univer) summary(ihgfit,digits=7) ## ----cache=TRUE,eval=TRUE,echo=TRUE,comment=NA-------------------------------- llcube<-logLik(cubefit) llihg<-logLik(ihgfit) lrt<- -2*(llihg - llcube) ### 495.9135 pv<- 1-pchisq(lrt, 2) ### 0 ## ----eval=TRUE,echo=FALSE,cache=TRUE,comment=NA------------------------------- data(univer) starting<-c(0.5, 0.5, 0.1) cubefit<-GEM(Formula(willingn~0|0|0),family="cube", starting = starting, maxiter = 100, toler = 1e-4,data=univer) makeplot(cubefit) ## ----eval=TRUE,echo=FALSE,cache=TRUE,comment=NA------------------------------- ihgfit<-GEM(Formula(willingn~0),family="ihg",data=univer) makeplot(ihgfit) ## ----cub_she,eval=TRUE,echo=TRUE,comment=NA----------------------------------- cub_she<-GEM(Formula(Writing~0|0|0),family="cub", shelter = 1, maxiter=500,toler=1e-3,data=relgoods) summary(cub_she) ## ----cush,cache=TRUE,eval=TRUE,echo=TRUE,comment=NA--------------------------- cush<-GEM(Formula(Writing~0),family="cush",shelter = 1,data=relgoods) summary(cush,digits=3) ## ----eval=TRUE,echo=FALSE,comment=NA------------------------------------------ data(relgoods) cub_she<-GEM(Formula(Writing~0|0|0),family="cub", shelter = 1, maxiter=500,toler=1e-3,data=relgoods) makeplot(cub_she) ## ----eval=TRUE,echo=FALSE,comment=NA------------------------------------------ cush<-GEM(Formula(Writing~0),family="cush",shelter = 1,data=relgoods) makeplot(cush) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # simCUB <- simcub(n, m, pai, csi) # simCUBE <- simcube(n, m, pai, csi, phi) # simCUBshe <- simcubshe(n, m, pai, csi, delta, shelter) # simCUSH <- simcush(n, m, delta, shelter) # simIHG <- simihg(n, m, theta) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # m<-9; n<-500 # pai<-0.7; csi<-0.2 # pr<-probcub00(m, pai, csi) # set.seed(123) # ordinal<-simcub(n, m, pai, csi) # cub<-GEM(Formula(ordinal~0|0|0),family="cub", maxiter = 50, toler = 1e-4) # pr_est<-fitted(cub)[,1] # plot(1:m, pr, type = "h", xlab = "Ordinal categories", # ylab = "Probability", lwd = 3, ylim = c(0, 0.3)) # vett<-1:m + 0.2 # lines(vett, pr_est, type = "h", col = "blue", lwd = 3, lty = 2) # legend(1, 0.3, legend = c("Theoretical", "Fitted"), col = c("black", "blue"), # lty = c(1, 2), lwd = 3, text.col = c("black", "blue"), bty = "n") ## ----eval=TRUE,echo=FALSE,fig.height=3.8,fig.width=3.8,comment=NA------------- m<-9; n<-500 pai<-0.7; csi<-0.2 pr<-probcub00(m, pai, csi) ordinal<-simcub(n, m, pai, csi) cub<-GEM(Formula(ordinal~0|0|0),family="cub", maxiter = 50, toler = 1e-4) est<-coef(cub) est pr_est<-fitted(cub)[,1] plot(1:m, pr, type = "h", xlab = "Ordinal categories", ylab = "Probability", lwd = 3, ylim = c(0, 0.3)) vett<-1:m + 0.2 lines(vett, pr_est, type = "h", col = "blue", lwd = 3, lty = 2) legend(1, 0.3, legend = c("Theoretical", "Fitted"), col = c("black", "blue"), lty = c(1, 2), lwd = 3, text.col = c("black", "blue"), bty = "n") ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # omega0<- -1.5 # omega1<- -2 # delta0<-as.numeric(logis(0, c(omega0, omega1))) ## 0.1824255 # delta1<-as.numeric(logis(1, c(omega0, omega1))) ## 0.0293122 # m<-9 # n0<-700 # n1<-1300 # set.seed(1234) # ord0<-simcush(n0, m, delta0, shelter = s) # ord1<-simcush(n1, m, delta1, shelter = s) # ordinal<-c(ord0, ord1) # X<-c(rep(0, n0), rep(1, n1)) # cushcov<-GEM(Formula(ordinal~X),family="cush",shelter = m) # coef(cushcov) # makeplot(cushcov) ## ----eval=TRUE,echo=FALSE,fig.height=4,fig.width=4,comment=NA----------------- omega0<- -1.5 omega1<- -2 delta0<-as.numeric(logis(0, c(omega0, omega1))) ## 0.1824255 delta1<-as.numeric(logis(1, c(omega0, omega1))) ## 0.0293122 m<-9 n0<-700 n1<-1300 s<-m # shelter category ord0<-simcush(n0, m, delta0, shelter = s) ord1<-simcush(n1, m, delta1, shelter = s) ordinal<-c(ord0, ord1) X<-c(rep(0, n0), rep(1, n1)) cushcov<-GEM(Formula(ordinal~X), family="cush", shelter = s) coef(cushcov) makeplot(cushcov) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # m<-7 # pai<-0.4 # csi<-0.2 # prob<-probcub00(m, pai, csi) # Giniindex<-round(gini(prob), digits = 3) # Laaksoindex<-round(laakso(prob), digits = 3) # Delta<-round(deltaprob(prob), digits = 3) # plot(1:m, prob, type = "n", ylab = "", xlab = "", ylim = c(0, 0.4), las = 1) # lines(1:m, prob, type = "h", lwd = 3) # legend("topleft", xjust = 1, legend = c(paste("Gini =", Giniindex), # paste("Laakso =", Laaksoindex), # paste("Delta =", Delta)), cex = 0.8) ## ----eval=TRUE,echo=FALSE,comment=NA,fig.height=4,fig.width=4----------------- m<-7 pai<-0.4 csi<-0.2 prob<-probcub00(m, pai, csi) Giniindex<-round(gini(prob), digits = 3) Laaksoindex<-round(laakso(prob), digits = 3) Delta<-round(deltaprob(prob), digits = 3) plot(1:m, prob, type = "h", ylab = "", xlab = "", ylim = c(0, 0.4), las = 1) legend("topleft", xjust = 1, legend = c(paste("Gini =", Giniindex), paste("Laakso =", Laaksoindex), paste("Delta =", Delta)), cex = 0.8) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # pai<-0.3; csi<-0.8 # nsimul<-10000 # n<-300; m<-7 # vectdiss<-rep(NA, nsimul) # for (j in 1:nsimul){ # ordinal<-simcub(n, m, pai, csi) # mod<-GEM(Formula(ordinal~0|0|0),family="cub") # theor<-fitted(mod)[,1] # freq<-tabulate(ordinal, nbins = m)/n # vectdiss[j]<-dissim(freq, theor) # } # # sortvect<-sort(vectdiss) # alpha<-0.05 # signif<-sortvect[(1-alpha)*nsimul] # empirical percentile 0.05 # cr<-vectdiss[vectdiss>signif] # critical region # # effe<-density(vectdiss) # band<-effe$bw # band width of the kernel plot # f<-function(x){ # compute kernel density (the default is Gaussian kernel) # (1/(band*length(vectdiss)))*sum(dnorm((x-vectdiss)/band)) # } # sortcr<-sort(cr) # sup<-numeric(length(cr)) # for (j in 1:length(cr)){ # sup[j]=f(sortcr[j]) # compute kernel density values for critical values # } # title <- paste("Normalized Dissimilarity distribution, Critical level(0.05) = ", # round(signif, 3)) # plot(density(vectdiss), main = title, cex.main = 0.7, lwd = 3, xlab = "", # cex.main = 0.7, las = 1) # polygon(c(signif, sortcr, sortcr[length(sortcr)], signif), c(0, sup, 0, 0), # col = "gray") # abline(h=0) ## ----eval=TRUE,echo=FALSE,fig.width=5,fig.height=5,comment=NA----------------- pai<-0.3; csi<-0.8 nsimul<-10000 n<-300; m<-7 vectdiss<-rep(NA, nsimul) for (j in 1:nsimul){ ordinal<-simcub(n, m, pai, csi) mod<-GEM(Formula(ordinal~0|0|0),family="cub") paiest<-coef(mod)[1] csiest<-coef(mod)[2] theor<-fitted(mod)[,1] freq<-tabulate(ordinal, nbins = m)/n vectdiss[j]<-dissim(freq, theor) } sortvect<-sort(vectdiss) alpha<-0.05 signif<-sortvect[(1-alpha)*nsimul] # empirical percentile 0.05 cr=vectdiss[vectdiss>signif] # critical region effe<-density(vectdiss) band<-effe$bw # band width of the kernel plot f<-function(x){ # compute kernel density (the default is Gaussian kernel) (1/(band*length(vectdiss)))*sum(dnorm((x-vectdiss)/band)) } sortcr<-sort(cr) sup<-numeric(length(cr)) for (j in 1:length(cr)){ sup[j]=f(sortcr[j]) # compute kernel density values for critical values } title = paste("Normalized Dissimilarity distribution \n Critical level(0.05) = ", round(signif, 3)) plot(density(vectdiss), main = title, cex.main = 0.7, lwd = 3, xlab = "", cex.main = 0.7, las = 1) polygon(c(signif, sortcr, sortcr[length(sortcr)], signif), c(0, sup, 0, 0), col = "gray") abline(h=0) ## ----eval=FALSE,echo=TRUE,comment=NA------------------------------------------ # data(univer) # ordinal<-univer$global # lage<-log(univer$age)-mean(log(univer$age)) #Deviation from mean of logged Age # Y<-W<-cbind(univer$officeho,lage) # cub_pai_csi<-GEM(Formula(global~Y|W|0),family="cub",data=univer) # bet<-coef(cub_pai_csi)[1:3] # gama<-coef(cub_pai_csi)[4:6] # paivett<-logis(Y,bet) # csivett<-logis(W,gama) # n<-length(ordinal) # main<- "Scatter plot of estimated parameters" # vettcol<-symb<-rep(NA,n) # vettcol[univer$officeho<=3]<-"red" # vettcol[univer$officeho==4]<-"black" # vettcol[univer$officeho>=5]<-"blue" # # symb[univer$officeho<=3]<-0 # symb[univer$officeho==4]<-1 # symb[univer$officeho>=5]<-2 # # plot(1-paivett,1-csivett,xlim=c(0,1),ylim=c(0,1), # cex=0.8,pch=symb,col=vettcol, # xlab=expression(1-pi),ylab=expression(1-xi), # main=main,cex.main=1,font.main=4) # legend("topright",legend=c("Unsatisfied","Indifferent","Satisfied"), # cex=0.7,text.col=c("red","black","blue"),pch=c(0,1,2), # col=c("red","black","blue")) ## ----eval=TRUE,echo=FALSE,fig.width=4.5,fig.height=4.5,comment=NA------------- data(univer) ordinal<-univer$global lage<-log(univer$age)-mean(log(univer$age)) #Deviation from mean of logged Age Y<-W<-cbind(univer$officeho,lage) cub_pai_csi<-GEM(Formula(global~Y|W|0),family="cub",data=univer) bet<-coef(cub_pai_csi)[1:3] gama<-coef(cub_pai_csi)[4:6] paivett<-logis(Y,bet) csivett<-logis(W,gama) n<-length(ordinal) caption<- "Scatter plot of estimated parameters" vettcol<-symb<-rep(NA,n) vettcol[univer$officeho<=3]<-"red" vettcol[univer$officeho==4]<-"black" vettcol[univer$officeho>=5]<-"blue" symb[univer$officeho<=3]<-0 symb[univer$officeho==4]<-1 symb[univer$officeho>=5]<-2 plot(1-paivett,1-csivett,xlim=c(0,1),ylim=c(0,1), cex=0.8,pch=symb,col=vettcol, xlab=expression(1-pi),ylab=expression(1-xi), main=caption,cex.main=1,font.main=4) legend("topright",legend=c("Unsatisfied","Indifferent","Satisfied"), cex=0.7,text.col=c("red","black","blue"),pch=c(0,1,2), col=c("red","black","blue"))
/scratch/gouwar.j/cran-all/cranData/CUB/inst/doc/CUBvignette-knitr.R
### -*- Coding: utf-8 -*- ### Author: Charles-Édouard Giguère ### ### Function that extract coefficient (or params) from common ### stats model lm/glm/lme/lmer/glmer/t-test. ### Used to copy coefficients quickly into a report. cf <- function(x, addci = TRUE, pv.style = 1, signif = 2, expcf = ifelse("glm" %in% class(x) & family(x)$family == "binomial", TRUE, FALSE), ...){ xcf <- data.frame() xclass <- class(x) ## linear model. if(xclass[1] == "lm" ){ tabformat <- sprintf("%%.%if",signif) xcf <- coef(summary(x)) xcf <- as.data.frame(xcf) names(xcf) <- c("Est.", "s.e.", "t", "P(>|t|)") if(length(tabformat) == 1){ xcf[,1:3] <- sapply(xcf[,1:3], function(x) sprintf(tabformat, x)) } else{ for(i in 1:3) xcf[,i] <- sprintf(tabformat[i], xcf[,i]) } xcf[,4] <- pv(xcf[,4], style = pv.style) if(addci){ xci <- confint(x) xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x) ) } } ## general linear model. else if(xclass[1] == "glm"){ tabformat <- sprintf("%%.%if",signif) xcf <- coef(summary(x)) xcf <- as.data.frame(xcf) names(xcf) <- c("Est.", "s.e.", "z", "P(>|z|)") if(expcf){ xcf[["exp(Est.)"]] <- sprintf(tabformat[1], exp(xcf[,"Est."])) } if(length(tabformat) == 1){ xcf[,1:3] <- sapply(xcf[,1:3], function(x) sprintf(tabformat, x)) } else{ for(i in 1:3) xcf[,i] <- sprintf(tabformat[i], xcf[,i]) } xcf[,4] <- pv(xcf[,4], style = pv.style) if(addci){ xci <- exp(suppressMessages(confint(x))) xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x) ) } } ## mixed-effect linear model. else if(xclass[1] == "lme" ){ tabformat <- sprintf("%%.%if",signif) xcf <- summary(x)$tTable xcf <- as.data.frame(xcf) names(xcf) <- c("Est.", "s.e.", "df", "t", "P(>|t|)") if(length(tabformat) == 1){ xcf[,c(1:2, 4)] <- sapply(xcf[,c(1:2, 4)], function(x) sprintf(tabformat, x)) } else{ for(i in 1:3) xcf[, c(1:2, 4)[i]] <- sprintf(tabformat[i], xcf[,c(1:2, 4)[i]]) } xcf[,5] <- pv(xcf[,5], style = pv.style) if(addci){ xci <- intervals(x)$fixed[,c(1,3)] xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x) ) } } ## t-test. else if(xclass[1] == "htest" ){ if(x$method != "Paired t-test"){ tabformat <- sprintf("%%.%if",signif) xcf <- data.frame(x$estimate[1], x$estimate[2], -diff(x$estimate), x$statistic, x$parameter, x$p.value, row.names = "") nn1 <- sub("^mean in group (.*)|mean of (.*)$", "mean(\\1\\2)", names(x$estimate)) names(xcf) <- c(nn1, "Diff.", "t", "df", "P(>|t|)") if(length(tabformat) == 1){ xcf[,1:4] <- sapply(xcf[,1:4], function(x) sprintf(tabformat, x)) } else{ xcf[, 1:3] <- sapply(xcf[,1:3], function(x) sprintf(tabformat[1], x)) xcf[,4] <- sprintf(tabformat[2], xcf[,4]) } xcf[,5] <- sprintf("%.1f", xcf[,5]) xcf[,6] <- pv(xcf[,6], style = pv.style) if(addci){ xci <- x$conf.int xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x)) } } else if(x$method == "Paired t-test"){ tabformat <- sprintf("%%.%if",signif) xcf <- data.frame(x$estimate[1], x$statistic, x$parameter, x$p.value, row.names = "") names(xcf) <- c("mean diff.", "t", "df", "P(>|t|)") if(length(tabformat) == 1){ xcf[,1:2] <- sapply(xcf[,1:2], function(x) sprintf(tabformat, x)) } else{ xcf[, 1] <- sapply(xcf[,1], function(x) sprintf(tabformat[1], x)) xcf[,2] <- sprintf(tabformat[2], xcf[,2]) } xcf[,3] <- sprintf("%.1f", xcf[,3]) xcf[,4] <- pv(xcf[,4], style = pv.style) if(addci){ xci <- x$conf.int xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x)) } } } ## lmer else if(xclass[1] %in% c("lmerMod", "lmerModLmerTest") ){ tabformat <- sprintf("%%.%if",signif) if(xclass[1] %in% "lmerMod") x <- lmerTest::as_lmerModLmerTest(x) xcf <- summary(x)$coefficient xcf <- as.data.frame(xcf) names(xcf) <- c("Est.", "s.e.", "df", "t", "P(>|t|)") if(length(tabformat) == 1){ xcf[,c(1:2, 4)] <- sapply(xcf[,c(1:2, 4)], function(x) sprintf(tabformat, x)) } else{ for(i in 1:3) xcf[, c(1:2, 4)[i]] <- sprintf(tabformat[i], xcf[,c(1:2, 4)[i]]) } xcf[,5] <- pv(xcf[,5], style = pv.style) if(addci){ xci <- suppressMessages(confint(x, parm = "beta_")) xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x) ) } } ## glmer else if(inherits(x, "glmerMod") ){ tabformat <- sprintf("%%.%if",signif) xcf <- summary(x)$coefficient xcf <- as.data.frame(xcf) names(xcf) <- c("Est.", "s.e.", "Z", "P(>|Z|)") if(length(tabformat) == 1){ xcf[,c(1:2, 3)] <- sapply(xcf[,c(1:2, 3)], function(x) sprintf(tabformat, x)) } else{ for(i in 1:3) xcf[, c(1:3)[i]] <- sprintf(tabformat[i], xcf[,c(1:3)[i]]) } xcf[,4] <- pv(xcf[,4], style = pv.style) if(addci){ xci <- suppressMessages(confint(x, parm = "beta_")) xcf[,c("lower 95% ci", "upper 95% ci")] <- sapply(xci, function(x) sprintf(tabformat[1], x) ) } } ## other model. else{ stop("Not yet implemented for this type of model.") return(NULL) } as.data.frame(xcf) }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/cf.R
### -*- Coding: utf-8 -*- ### Author: Charles-Édouard Giguère ### ### Send a table-like object to clipboard. clip <- function(x, sep = "\t", row.names = FALSE, quote = FALSE, ...){ if(!is.matrix(x) & !is.data.frame(x)){ x <- try(as.data.frame(x), silent = TRUE) if(inherits(x, "try-error")) stop("x cannot be coerced to a data.frame object") } clipr::write_clip(x, sep = sep, row.names = row.names, quote = quote, object_type = "auto", ...) }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/clip.R
### -*- Coding: utf-8 -*- ### Analyste Charles-Édouard Giguère ### Function to create an object of that contains a matrix of bivariate ### correlations their associated N and their p-values correlation <- function(x, y = NULL, method = "pearson", alternative = "two.sided", exact = NULL, use = "pairwise.complete.obs", continuity = FALSE, data = NULL){ if("formula" %in% class(x)){ if(is.null(data) & !is.null(y)) data <- y return(correlation.formula(x, method = method, alternative = alternative, exact = exact, use = use, continuity = continuity, data=data)) } ## matrix dimensions symmetric <- is.null(y) dimx <- dim(x) if(symmetric) dimy <- NULL else dimy <- dim(y) ### Check for empty data. if( is.null(dimx) ){ stop("x must be a data.frame(or matrix) " %+% "with at least 2 columns and 3 rows") } else if(!is.null(dimx) & symmetric & (dimx[2] <= 1) | (dimx[1] < 3)){ stop("x must be a data.frame (or matrix) " %+% "with at least 2 columns and 3 rows") } else if(!is.null(dimy)){ if(dimx[1] != dimy[1]){ stop("x and y must have the same number of rows") } } ## Get dimensions names from the data.frame/matrix. dimnamesx <- dimnames(x) if(symmetric) dimnamesy <- NULL else dimnamesy <- dimnames(y) ## If the dataframe/matrix does not contains names. ## We call them X1, X2 and so forth. if(is.null(dimnamesx)){ dimnamesx <- 'X' %+% 1:dimx[2] } else{ dimnamesx <- dimnamesx[[2]] } if(!symmetric){ if(is.null(dimnamesx)){ dimnamesy <- 'Y' %+% 1:dimy[2] } else{ dimnamesy <- dimnamesy[[2]] } } ## The correlation matrix is created. R <- cor(x, y, use = use, method = method) ## The na.method are ## everything: NA if NA in either variable of the pair of variables; ## all.obs: Error if NA else take everything. Error are generated ## before this point; ## complete.obs: Casewise deletion. Error if no complete case. Error ## will be generated before this point; ## pairwise.complete.obs: Pairwise completion (default). It can results ## in a non positive semi-definite matrix. ## na.or.complete: casewise delete. NA if no complete case. na.method <- pmatch(use, c("everything", "all.obs", "complete.obs", "pairwise.complete.obs", "na.or.complete")) ## Number of subjects in each pair (pairwise method). if(symmetric) N <- t(!is.na(x)) %*% !is.na(x) else N <- t(!is.na(x)) %*% !is.na(y) ## Error if use parameter do not match anything. if (is.na(na.method)){ stop("invalid 'use' argument") } ## If method is "complete" do casewise deletion. if(na.method %in% c(3, 5)){ if(symmetric) N[,] <- dim(x <- na.exclude(x))[1] else{ x <- x[apply(is.na(cbind(x,y)),1,sum) %in% 0,] y <- y[apply(is.na(cbind(x,y)),1,sum) %in% 0,] N[,] <- dim(x)[1] } } ## Compute p-values using cor.test. if(symmetric){ P <- matrix(NA, nrow = dimx[2], ncol = dimx[2]) P[lower.tri(P)] <- mapply( function(i, j){ cor.test(x[,i], x[,j], alternative = alternative, method = method, exact = exact, continuity = continuity)$p.value }, col(R)[lower.tri(R)],row(R)[lower.tri(R)]) P[upper.tri(P)] <- t(P)[upper.tri(P)] } else{ P <- matrix(NA, nrow = dimx[2], ncol = dimy[2]) indexij <- expand.grid(1:dimx[2],1:dimy[2]) P[,] <- mapply( function(i, j){ cor.test(x[,i], y[,j], alternative = alternative, method = method, exact = exact, continuity = continuity)$p.value }, indexij[,1],indexij[,2]) } ### adjust N for if(na.method %in% 1){ N[is.na(R)] <- P[is.na(R)] <- NA } out <- list(R = R, N = N, P = P, Sym = symmetric) attr(out, "nomx") <- dimnamesx attr(out, "nomy") <- dimnamesy class(out) <- "corr" out } correlation.formula <- function(x, ..., data = NULL){ if(length(x) != 2) stop("Invalid formula see help(correlation)") else if (length(x[[2]]) == 3 && identical(x[[2]][[1]], as.name("|"))){ fX <- ~. fX[[2]] <- x[[2]][[2]] X <- model.frame(fX,data=data) fY <- ~. fY[[2]] <- x[[2]][[3]] Y <- model.frame(fY,data=data) } else{ X <- model.frame(x, data=data) Y <- NULL } correlation(x = X, y = Y, ...) } ### Print methods for a correlation object. print.corr <- function(x, ..., toLatex = FALSE, cutstr = NULL, toMarkdown = FALSE){ if(!x$Sym){ ## Send to print.corr.unsym if the correlation matrix is not symmetric. print.corr.unsym(x, ..., toLatex = toLatex, cutstr = cutstr, toMarkdown = toMarkdown) } else { ## Number of variables dx <- dim(x$R)[1] ## Name of variables. nom <- attr(x, "nomx") lnom <- nchar(nom) ## if not cutstr takes the value of the largest variable name. if(is.null(cutstr)) cutstr <- max(lnom, 7) else cutstr <- max(7 ,min(cutstr, max(lnom))) if(toLatex & toMarkdown) stop("Cannot choose both Latex and Markdown format") if(!toLatex & !toMarkdown){ ## Estimating necessary space to print correlation. ## 13 characters are reserved for margins. width <- options()$width - 5 - cutstr if(width < cutstr + 1) stop(sprintf("Not enough space to print correlation matrix.\n" %+% " Change page width using options(width = n) with n >= %d", 6 + 2 * cutstr)) ## Only the first cutstr characters of variable names are printed. ## Estimating the maximum number of columns that can be displayed on ## one line. nmax <- (width %/% (cutstr + 1)) ## variables starting lines. coldebvar <- seq(1, dx - 1, nmax) ## variables closing lines. colfinvar <- apply(cbind(coldebvar + nmax - 1, dx - 1), 1, min) ## Map var names into cutstr-character strings. formatname <- "%" %+% cutstr %+% "." %+% cutstr %+% "s" nom <- sprintf(formatname, nom) ## output print. for(i in 1:length(coldebvar)){ nomi <- coldebvar[i]:colfinvar[i] cat(" " %n% (4 + cutstr), "|", sep="") cat(nom[nomi], sep = " ", fill = TRUE) cat("-" %n% (4 + (cutstr+ 1) * (length(nomi) + 1)),fill = TRUE) for(j in (coldebvar[i] + 1):dx){ cat(gsub("R[(]( +)", "\\1R(", "R(" %+% nom[j]) %+% ") |") cat(numtostr(x$R[j, nomi[nomi < j]], cutstr, 4), fill=TRUE) cat(gsub("N[(]( +)", "\\1N(", "N(" %+% nom[j]) %+% ") |") cat(numtostr(x$N[j, nomi[nomi < j]], cutstr, 0), fill = TRUE) cat(gsub("P[(]( +)", "\\1P(", "P(" %+% nom[j]) %+% ") |") cat(numtostr(x$P[j, nomi[nomi < j]], cutstr, 4), fill = TRUE) cat("-" %n% (4 + (cutstr+ 1) * (length(nomi) + 1)),fill = TRUE) } } } else if(toLatex){ cat("\\begin{tabular}{l |" %+% ("r" %n% (dx - 1)) %+% "}", fill = TRUE) cat("\\hline", fill = TRUE) cat("& " %+% paste(nom[-length(nom)], collapse=" & ") %+% " \\\\\n") cat("\\hline\\hline", fill = TRUE) for(i in 2:length(nom)){ cat("R(" %+% nom[i] %+% ") &") cat(numtostr(x$R[i, 1:(i-1)], digits=4), sep = " & ") cat(" \\\\\n") cat("N(" %+% nom[i] %+% ") &") cat(numtostr(x$N[i, 1:(i-1)], digits = 0), sep = " & ") cat(" \\\\\n") cat("P(" %+% nom[i] %+% ") &") cat(numtostr(x$P[i, 1:(i-1)], digits=4), sep = " & ") cat(" \\\\\n") cat("\\hline", fill = TRUE) } cat("\\end{tabular}", fill = TRUE) } else if(toMarkdown){ formatnom <- sprintf("%%%d.%ds", cutstr, cutstr) nom <- sprintf(formatnom, nom) cat("|" %+% (" " %n% (4 + cutstr)) %+% "|", sprintf(" %s|",nom[1:(dx - 1)]),"\n", sep = "") cat("|:" %+% ("-" %n% (3 + cutstr)) %+% "|", rep(("-" %n% (cutstr )) %+% ":|", dx - 1), "\n", sep = "") for(i in 2:dx){ cat(sub("R[(]( +)(.*)[)] [|]", "R(\\2)\\1 |", "|R(" %+% nom[i] %+% ") |" ), sep = "") cat(numtostr(x$R[i, 1:(i-1)], nch = cutstr + 1, digits = 4) %+% "|", sep = "") cat(rep(" " %n% (cutstr + 1) %+% "|", dx - i ), "\n", sep = "") cat(sub("N[(]( +)(.*)[)] [|]", "N(\\2)\\1 |", "|N(" %+% nom[i] %+% ") |"), sep = "") cat(numtostr(x$N[i, 1:(i-1)], nch = cutstr + 1, digits = 0) %+% "|", sep = "") cat(rep(" " %n% (cutstr + 1) %+% "|", dx - i ), "\n", sep = "") cat(sub("P[(]( +)(.*)[)] [|]", "P(\\2)\\1 |", "|P(" %+% nom[i] %+% ") |"), sep = "") ptemp <- ifelse(x$P[i, 1:(i-1)] < 0.0001,"<0.0001", sprintf("%.4f",x$P[i, 1:(i-1)])) cat(sprintf(" " %+% formatnom,ptemp) %+% "|", sep = "") cat(rep(" " %n% (cutstr + 1) %+% "|", dx - i ), "\n", sep = "") } } } } print.corr.unsym <- function(x, ..., toLatex = FALSE, cutstr = NULL, toMarkdown = FALSE){ ## Variable dimensions. dxy <- dim(x$R) ## Variable names (x, y). nomx <- attr(x, "nomx") nomy <- attr(x, "nomy") lnomx <- nchar(nomx) lnomy <- nchar(nomy) if(is.null(cutstr)) cutstr <- max(c(lnomx,lnomy), 7) else cutstr <- max(7, min(cutstr, max(c(lnomx,lnomy)))) if(toLatex & toMarkdown) stop("Cannot choose both Latex and Markdown format") ## Standard print if(!toLatex & !toMarkdown){ ## Estimating necessary space to print correlation. ## 5 + cutstr characters are reserved for margins. width <- options()$width - 5 - cutstr if(width < cutstr + 1) stop(sprintf("Not enough space to print correlation matrix." %+% "Change page width using options(width = n) with n >= %d", 6 + 2 * cutstr)) ## Only the first cutstr characters of variable names are printed. ## Estimating the maximum number of columns that can be displayed on ## one line. nmax <- (width %/% (cutstr + 1)) ## position of variables starting lines. coldebvar <- seq(1, dxy[2], nmax) ## position of variables ending lines. colfinvar <- apply(cbind(coldebvar + nmax - 1, dxy[2]), 1, min) ## Map variables into cutstr-character strings. formatname <- "%" %+% cutstr %+% "." %+% cutstr %+% "s" nomx <- sprintf(formatname, nomx) nomy <- sprintf(formatname, nomy) ## Print outputs. for(i in 1:length(coldebvar)){ nomi <- coldebvar[i]:colfinvar[i] cat(" " %n% (4 + cutstr), "|", sep="") cat(nomy[nomi], sep = " ", fill = TRUE) cat("-" %n% (5 + cutstr + (cutstr + 1) * length(nomi)),fill = TRUE) for(j in 1:length(nomx)){ cat(gsub("R[(]( +)", "\\1R(", "R(" %+% nomx[j]) %+% ") |") cat(numtostr(x$R[j, nomi], cutstr, 4), fill=TRUE) cat(gsub("N[(]( +)", "\\1N(", "N(" %+% nomx[j]) %+% ") |") cat(numtostr(x$N[j, nomi], cutstr, 0), fill = TRUE) cat(gsub("P[(]( +)", "\\1P(", "P(" %+% nomx[j]) %+% ") |") cat(numtostr(x$P[j, nomi], cutstr, 4), fill = TRUE) cat("-" %n% (5 + cutstr + (cutstr + 1) * length(nomi)), fill = TRUE) } } } ## Print into a latex tabular environment. For use with knitr/Sweave. else if (toLatex){ cat("\\begin{tabular}{l |" %+% ("r" %n% (dxy[2])) %+% "}", fill = TRUE) cat("\\hline", fill = TRUE) cat("& " %+% paste(nomy, collapse=" & ") %+% " \\\\\n") cat("\\hline\\hline", fill = TRUE) for(i in 1:length(nomx)){ cat("R(" %+% nomx[i] %+% ") &") cat(numtostr(x$R[i,], digits=4), sep = " & ") cat(" \\\\\n") cat("N(" %+% nomx[i] %+% ") &") cat(numtostr(x$N[i,], digits = 0), sep = " & ") cat(" \\\\\n") cat("P(" %+% nomx[i] %+% ") &") cat(numtostr(x$P[i,], digits=4), sep = " & ") cat(" \\\\\n") cat("\\hline", fill = TRUE) } cat("\\end{tabular}", fill = TRUE) } else if(toMarkdown){ dx <- length(nomx) dy <- length(nomy) formatnom <- sprintf("%%%d.%ds", cutstr, cutstr) nomx <- sprintf(formatnom, nomx) nomy <- sprintf(formatnom, nomy) cat("|" %+% (" " %n% (4 + cutstr)) %+% "|", sprintf(" %s|",nomy),"\n", sep = "") cat("|:" %+% ("-" %n% (3 + cutstr)) %+% "|", rep(("-" %n% (cutstr )) %+% ":|", dy), "\n", sep = "") for(i in 1:dx){ cat(sub("R[(]( +)(.*)[)] [|]", "R(\\2)\\1 |", "|R(" %+% nomx[i] %+% ") |" ), sep = "") cat(numtostr(x$R[i, 1:dy], nch = cutstr + 1, digits = 4) %+% "|", "\n", sep = "") cat(sub("N[(]( +)(.*)[)] [|]", "N(\\2)\\1 |", "|N(" %+% nomx[i] %+% ") |"), sep = "") cat(numtostr(x$N[i, 1:dy], nch = cutstr + 1, digits = 0) %+% "|", "\n", sep = "") cat(sub("P[(]( +)(.*)[)] [|]", "P(\\2)\\1 |", "|P(" %+% nomx[i] %+% ") |"), sep = "") ptemp <- ifelse(x$P[i, 1:dy] < 0.0001, "<0.0001", sprintf("%.4f",x$P[i, 1:dy])) cat(sprintf(" " %+% formatnom,ptemp) %+% "|", "\n", sep = "") } } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/corr.R
### -*- Coding: utf-8 -*- ### ### Analyste Charles-Édouard Giguère ### ### Creation of an object to manage a two-dimensional table. cross <- function(x, ...){ ## if x is not a table we first create the table ## with t and ... options . if( !( "table" %in% class(x) )){ if( ("formula" %in% class(x)) ){ T <- xtab(x, ...) } else{ T <- table(x, ...) } } else{ T <- x } cr.T <- list() cr.T$T <- T cr.T$PCT.ROW.T <- addmargins(prop.table(T,1), 2, Total) cr.T$PCT.COL.T <- addmargins(prop.table(T,2), 1, Total) cr.T$NAMES <- names(dimnames(cr.T$T)) names(dimnames(cr.T$T)) <- NULL names(dimnames(cr.T$PCT.ROW.T)) <- NULL names(dimnames(cr.T$PCT.COL.T)) <- NULL class(cr.T) <- "cross" cr.T } ### Methods to print a cross object. ### A list of tests can be passed as parameters. ### A chi-square test is displayed by default. ### Results can be exported to pdf (latex is needed to do that). ### or to an Excel spreadsheet (xlsx). print.cross <- function(x, ..., test = "chisq.test", export = NULL){ p <- paste(x$NAMES[1], x$NAMES[2], sep = "*") if(!("tex" %in% export)){ cat("Contingency table for ", p, "\n\n", sep = "") print.table(round(addmargins(x$T, FUN = Total, quiet = TRUE), 1), zero.print = ".") cat("\n\n", "Percentages by row for ", p, "\n\n", sep = "") print.table(round(x$PCT.ROW.T * 100, 2), zero.print = ".") cat("\n\n", "Percentages by column for ", p, "\n\n", sep = "") print.table(round(x$PCT.COL.T*100, 2), zero.print = ".") cat("\n\n", "Statistics for ", p, "\n\n", sep = "") for(i in test){ FUN <- match.fun(i) print(FUN(x$T)) } } if("tex" %in% export){ writeLines(c("\\begin{table}[htp!]", "\\centering")) xt1 <- xtable(round(addmargins(x$T, FUN = Total, quiet = TRUE), 1), align = paste("l|",paste(rep("r",dim(x$T)[2]),collapse=""), "|r",sep=""), digits= 0) print.xtable(xt1, hline.after = c(0,0,dim(x$T)[1]), floating=FALSE) cat("\\caption{Contingency table for ", sub("[*]","$\\\\times$",p),"}","") cat("\\end{table}") writeLines(text = c("\\begin{table}[htp!]", "\\centering")) xt2 <- xtable(round(x$PCT.ROW.T*100, 2), align = paste("l|", paste(rep("r",dim(x$PCT.ROW.T)[2]-1), collapse=""),"|r", sep=""), digits= 2) print.xtable(xt2, hline.after = c(0,0,dim(x$PCT.ROW.T)[1]), floating=FALSE) cat("\\caption{Percentages by row for ", sub("[*]","$\\\\times$",p),"}","") cat("\\end{table}") writeLines(text = c("\\begin{table}[htp!]", "\\centering")) xt2 <- xtable(round(x$PCT.COL.T*100, 2), align = paste("l|", paste(rep("r",dim(x$PCT.COL.T)[2]), collapse=""),"|", sep=""), digits= 2) print.xtable(xt2, hline.after = c(0,0,dim(x$PCT.COL.T)[1]-1), floating=FALSE) cat("\\caption{Percentages by column for ", sub("[*]","$\\\\times$",p),"}","",fill=TRUE) cat("\\end{table}") if("chisq.test" %in% test){ test <- setdiff(test,"chisq.test") tst <- suppressWarnings(chisq.test(x$T)) writeLines(c("\\begin{table}", "\\centering", "\\begin{tabular}{rrr}", "\\hline", "$\\chi^2$ & df & p.value\\\\", "\\hline\\hline", sprintf("%5.2f & %d & %6.4f\\\\",tst$statistic, tst$parameter,tst$p.value), "\\hline", "\\end{tabular}", paste("\\caption{$\\chi^2$ test for ", sub("[*]","$\\\\times$",p),"}"), "\\end{table}")) } writeLines(c("\\begin{table}", "\\centering", "\\begin{verbatim}")) for(i in test){ FUN <- match.fun(i) writeLines(capture.output(FUN(x$T))) } writeLines(c("\\end{verbatim}", paste("\\caption{Other tests for ", sub("[*]","$\\\\times$",p),"}"), "\\end{table}")) } if("pdf" %in% export){ wd <- setwd(Sys.getenv("temp")) f1 <- file("cross_output.tex", open="w") writeLines(con = f1, text = c("\\documentclass{article}", "\\begin{document}", "\\begin{table}[htp!]", "\\centering", "\\pagenumbering{gobble}")) xt1 <- xtable(round(addmargins(x$T, FUN = Total, quiet = TRUE), 1), align = paste("l|",paste(rep("r",dim(x$T)[2]),collapse=""), "|r",sep=""), digits= 0) print.xtable(xt1,file=f1,append=TRUE, hline.after = c(0,0,dim(x$T)[1]), floating=FALSE) cat("\\caption{Contingency table for ", sub("[*]","$\\\\times$",p),"}",file=f1,"") cat("\\end{table}", file = f1) writeLines(con = f1, text = c("\\begin{table}[htp!]", "\\centering")) xt2 <- xtable(round(x$PCT.ROW.T*100, 2), align = paste("l|", paste(rep("r",dim(x$PCT.ROW.T)[2]-1), collapse=""),"|r", sep=""), digits= 2) print.xtable(xt2,file=f1,append=TRUE, hline.after = c(0,0,dim(x$PCT.ROW.T)[1]), floating=FALSE) cat("\\caption{Percentages by row for ", sub("[*]","$\\\\times$",p),"}",file=f1,"") cat("\\end{table}", file = f1) writeLines(con = f1, text = c("\\begin{table}[htp!]", "\\centering")) xt2 <- xtable(round(x$PCT.COL.T*100, 2), align = paste("l|", paste(rep("r",dim(x$PCT.COL.T)[2]), collapse=""),"|", sep=""), digits= 2) print.xtable(xt2,file=f1,append=TRUE, hline.after = c(0,0,dim(x$PCT.COL.T)[1]-1), floating=FALSE) cat("\\caption{Percentages by column for ", sub("[*]","$\\\\times$",p),"}",file=f1,"",fill=TRUE) cat("\\end{table}", file = f1,fill=TRUE) if("chisq.test" %in% test){ test <- setdiff(test,"chisq.test") tst <- chisq.test(x$T) writeLines(c("\\begin{table}", "\\centering", "\\begin{tabular}{rrr}", "\\hline", "$\\chi^2$ & df & p.value\\\\", "\\hline\\hline", sprintf("%5.2f & %d & %6.4f\\\\",tst$statistic, tst$parameter,tst$p.value), "\\hline", "\\end{tabular}", paste("\\caption{$\\chi^2$ test for ", sub("[*]","$\\\\times$",p),"}"), "\\end{table}"), con=f1) } writeLines(c("\\begin{table}", "\\centering", "\\begin{verbatim}"), con = f1) for(i in test){ FUN <- match.fun(i) writeLines(capture.output(FUN(x$T)), con = f1) } writeLines(c("\\end{verbatim}", paste("\\caption{Other tests for ", sub("[*]","$\\\\times$",p),"}"), "\\end{table}"), con = f1) cat("\\end{document}", file = f1) close(f1) out <- shell("pdflatex cross_output.tex",intern = TRUE) shell("start cross_output.pdf") setwd(wd) } if("xlsx" %in% export){ wd <- setwd(Sys.getenv("temp")) wb <- createWorkbook("cross_output.xlsx") addWorksheet(wb, "Frequencies") addWorksheet(wb, "Row percentages") addWorksheet(wb, "Column percentages") writeData(wb, 1, paste("Contingency table for",p, sep = " "),2,2) writeData(wb, 1, addmargins(x$T, FUN = Total, quiet = TRUE), 2,3) writeData(wb, 2, paste("Row percentages for",p, sep = " "),2,2) writeData(wb, 2, round(x$PCT.ROW.T * 100,2),2,3) writeData(wb, 3, paste("Col percentages for",p, sep = " "),2,2) writeData(wb, 3, round(x$PCT.COL.T * 100,2),2,3) addWorksheet(wb, "Statistics") stat.output <- character() for(i in test){ FUN <- match.fun(i) stat.output <- c(stat.output, capture.output(FUN(x$T))) } writeData(wb, 4, stat.output,2,3) saveWorkbook(wb, file = "cross_output.xlsx", overwrite = TRUE) shell("start cross_output.xlsx") setwd(wd) } } ### Fonction xtab overloads xtabs with more parameters to handle ### missing variables in categorical variables. xtab <- function(formula, data = parent.frame(), useNA = FALSE, exclude = c(NA,NaN), miss.char = "-", na.action = na.exclude, subset = NULL, sparse = FALSE, drop.unused.levels = FALSE){ dtaNA <- model.frame(formula,data,na.action = na.pass) if( useNA ){ for(i in names(dtaNA)){ if( is.factor(dtaNA[[i]]) ){ dtaNA[[i]] <- addNA(dtaNA[[i]],ifany=TRUE) } } exclude <- setdiff(exclude,c(NA,NaN)) if(length(exclude)==0){ xt <- do.call("xtabs",list(formula=formula,data = dtaNA, exclude = NULL, na.action = na.pass, subset=subset, sparse = sparse, drop.unused.levels = drop.unused.levels)) for(i in seq(along = dimnames(xt))) dimnames(xt)[[i]][is.na(dimnames(xt)[[i]])] <- miss.char } else{ xt <- do.call("xtabs",list(formula =formula,data=dtaNA, exclude = exclude, na.action = na.pass, subset=subset, sparse = sparse, drop.unused.levels = drop.unused.levels)) for(i in seq(along = dimnames(xt))) dimnames(xt)[[i]][is.na(dimnames(xt)[[i]])] <- miss.char } } else{ xt <- do.call("xtabs",list(formula, data = data, subset = subset, sparse = sparse, na.action = na.action, exclude = exclude, drop.unused.levels = drop.unused.levels)) for(i in seq(along = dimnames(xt))) dimnames(xt)[[i]][is.na(dimnames(xt)[[i]])] <- miss.char } xt } ### Function that overloads sum with na.rm=TRUE and replaces NA with 0. Total = function(x){ sx <- sum(x, na.rm = TRUE) ifelse(is.na(sx), 0, sx) } ### require(xtable, quietly = TRUE, warn.conflicts = FALSE) ### ### df <- expand.grid(test = 1:2, toast = 1:2) ### xt1 <- xtabs( ~ test + toast, df) ### print(cross(xt1), export = "tex")
/scratch/gouwar.j/cran-all/cranData/CUFF/R/cross.R
### -*- Coding: utf-8 -*- ### Author: Charles-Édouard Giguère ### ### Methode pour afficher des frequences de facteur et les conserver ### dans des listes mais les afficher dans un format interessant. freq <- function(x, y = NULL, ..., labels = NULL, data = NULL){ result <- list() class(result) <- "frequencies" if("formula" %in% class(x)){ if(is.null(data) & !is.null(y)) data <- y return(freq.formula(x, labels = labels, data=data)) } if(is.matrix(x)){ ## Changer x en data.frame x <- as.data.frame(x) } if(!is.data.frame(x) & !is.vector(x) & !is.factor(x)) { stop("Object x not suitable for this command") } if(is.data.frame(x)) { for(i in 1:dim(x)[2]) { factlocal <- x[[i]] if(!is.factor(factlocal)) { ### Convertir en facteur. factlocal <- factor(factlocal) } result[[i]] <- cbind( n = table(factlocal, useNA = "always"), "%" =c(prop.table(table(factlocal, useNA = "no")), NA), "% with NA" = prop.table(table(factlocal, useNA = "always"))) } } if(is.vector(x) | is.factor(x)) { factlocal <- x if(!is.factor(factlocal)){ ## Convertir en facteur. factlocal <- factor(factlocal) } result[[1]] <- cbind( "n" = table(factlocal,useNA="always"), "%"=c(prop.table(table(factlocal,useNA="no")),NA), "% with NA"=prop.table(table(factlocal,useNA="always"))) if(!is.null(labels)) names(result) <- labels else names(result) <- deparse(substitute(x)) } else if(!is.null(labels) & length(labels) == dim(x)[2]) names(result) <- labels else{ names(result) <- names(x) } return(result) } freq.formula <- function(x, ..., data = NULL){ if(length(x) != 2) stop("Invalid formula see help(freq)") else{ X <- model.frame(x, data=data) Y <- NULL } freq(x = X, y = Y, ...) } print.frequencies <- function(x, ..., toLatex = FALSE){ test <- labels(x) if(!toLatex){ ### default for(i in 1:length(x)){ xlocal <- x[[i]] xlocal[,2:3] <- round(xlocal[,2:3]*100, digits = 1) cat(test[i], ":\n", sep = "") row.names(xlocal)[dim(xlocal)[1]] = "NA" print(rbind(xlocal, Total = c(sum(xlocal[,1]), 100, 100)), na.print = "-") cat("\n") } } else{ for(i in 1:length(x)){ cat("\\begin{tabular}{l r r r}\n") xlocal <- x[[i]] if(length(grep("[%&$_]", row.names(xlocal))) > 1){ for(j in c("%","&","$","_")) row.names(xlocal) <- gsub(j, paste("\\", j, sep = ""), row.names(xlocal), fixed = TRUE) } xlocal[,2:3] = round(xlocal[,2:3]*100, digits=1) cat("\\multicolumn{4}{ c }{",test[i],"}\\\\\n",sep="") cat("\\hline\n\\hline\n") cat(" & Frequency & Valid Percent & Percent (with NA) \\\\\n") cat("\\hline\n") row.names(xlocal)[dim(xlocal)[1]]="NA" cat() write.table(as.data.frame(xlocal),na="-",sep=" & ", quote=F,eol="\\\\\n",col.names=FALSE) cat("\\hline\n\\hline\n") cat("Total & ", sum(xlocal[,1]),"& 100 & 100 \\\\\n") cat("\\multicolumn{4}{c}{}\\\\\n") cat("\\end{tabular}\n\n") } } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/freq.R
### -*- Coding: utf-8 -*- ### ### Analyste Charles-Édouard Giguère ### ### fonction pour afficher les proportions. ftab <- function(xt, margin = seq_along(dim(xt)), fmt = "%d (%5.1f %%)", quiet = FALSE){ ## Si ce n'est pas une table on sort. if(!is.table(xt)) stop("xt must be a table") ## Table 1d: On affiche les N et les proportions plus le total. if(length(dim(xt)) %in% 1){ xts <- as.table(matrix(addmargins(xt), ncol = 1, dimnames = list(c(names(xt),"Total"), "N(%)"))) xts[] <- sprintf(fmt, addmargins(xt), addmargins(prop.table(xt)*100) ) if(!quiet) print(xts, right = TRUE) invisible(xts) } ## Table 2d: on affiche soit le % dans chaque cellules et on fait else if(length(dim(xt)) %in% 2){ xts <- addmargins(prop.table(xt)*100, FUN = Total, quiet = TRUE) xts[] <- sprintf(fmt, addmargins(xt), addmargins(prop.table(xt))*100) if(is.null(names(dimnames(xts)))) names(dimnames(xts)) <- list("","") if(length(margin) == 1 & margin[1] == 1){ names(dimnames(xts))[2] <- sprintf("%s N(%% %s)", names(dimnames(xts))[2], "In row") xts[1:dim(xt)[1], 1:dim(xt)[2]] <- sprintf(fmt, xt, prop.table(xt,margin = 1 )*100) } else if(length(margin) == 1 & margin[1] == 2){ names(dimnames(xts))[2] <- sprintf("%s N(%% %s)", names(dimnames(xts))[2], "In col") xts[1:dim(xt)[1], 1:dim(xt)[2]] <- sprintf(fmt, xt, prop.table(xt,margin = 2 )*100) } else names(dimnames(xts))[2] <- sprintf("%s N(%%)",names(dimnames(xts))[2]) if(!quiet) print(xts, right = TRUE) invisible(xts) } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/ftab.R
### -*- Coding: utf-8 -*- ### ### Analyste Charles-Édouard Giguère ### ### Creation of a function to display mean (sd) meansd <- function(x, digits = c(1, 1)){ if(length(digits) %in% 1) digits <- rep(digits, 1) format_str <- sprintf("%%.%df (%%.%df)", digits[1], digits[2]) sprintf(format_str, mean(x, na.rm = TRUE), sd(x, na.rm = TRUE)) }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/meansd.R
### -*- Coding: utf-8 -*- ### ### Analyste: Charles-Édouard Giguère ### ### .~ ### ### _\\\\\_ ~.~ ### ### | ~ ~ | .~~. ### ### #--O-O--# ==|| ~~.|| ### ### | L | // ||_____|| ### ### | \_/ | \\ || || ### ### \_____/ ==\\_____// ### ########################################## pal_CUFF <- function(n = 10 , pal = "CUFF"){ sel = ((1:n - 1) %% 10) + 1 if(pal == "CUFF"){ c("#660066", "#004D99", "#00B300", "#B30059", "#FF6666", "#00CC7A", "#737373", "#FF3333", "#CC00FF", "#B57E17")[sel] } else{ stop("For now, only the CUFF palette is available") } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/pal_CUFF.R
### Format a vector of p-value according to APA style guide v6 (1) or with 4 dec (2). pv <- function(p, style = 1){ if(style == 1){ ifelse(p > 0.05, sprintf("%.2f", p), ifelse(p < 0.001, "<0.001", sprintf("%.3f",p))) } else{ ifelse(p < 0.0001, "<0.0001", sprintf("%.4f", p)) } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/pv.R
# -*- coding: utf-8 -*- ########################################################### ### Author : Charles-Edouard Giguere ### ### Function to deal with strings. ### ########################################################### ### Overloading of paste with sep = "" using operator %+%. '%+%' <- function(x,y){ paste(x, y, sep = "") } ### Operator %n% repeats string x, n times. '%n%' <- function(x, y){ sx=as.character(x) sy=as.integer(y) if(length(sx)>0 & length(sy)>0){ mapply(function(x,y)paste(rep(x, y), collapse = ""), { if(length(sy) > 1 & length(sx) %in% 1){ rep(sx, length(sy)) } else{ sx } }, { if(length(sx) > 1 & length(sy) %in% 1){ rep(sy, length(sx)) } else{ sy } }, USE.NAMES = FALSE) } else{ character() } } ### Conversion of a numeric into a character using a formating. ### This is an alternative to sprintf. ### If nch is Null the function use the right amount to print ### the numerical variable with the right number of digits. ### If nch is not enough for the precision a star is returned. numtostr=function(x,nch=NULL,digits=4){ sx <- formatC(x,format="f",digits=digits) sx.length <- nchar(sx) if(!is.null(nch)){ sx[sx.length>nch] <- (" " %n% (nch-1)) %+% "*" sx[sx.length<nch] <- (" " %n% (nch-sx.length[sx.length<nch])) %+% sx[sx.length<nch] } sx } ### Function that print a character with a specified format and align. ### if length is not enough 3 stars are printed padded with space. strl <- function(x,length=max(nchar(x)),align="right"){ x.n <- nchar(x) if(sum(x.n > length) > 0){ if(align=="left") x[x.n>length] <- "***" %+% (" " %n% (length-3)) else x[x.n>length] <- (" " %n% (length-3)) %+% "***" } if(sum(x.n<length)>0){ if(align=="left") x[x.n<length] <- x[x.n<length] %+% (" " %n% (length-x.n[x.n<length])) else x[x.n<length] <- (" " %n% (length-x.n[x.n<length])) %+% x[x.n<length] } x }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/strutil.R
### -*- Coding: utf-8 -*- ### ### Analyste: Charles-Édouard Giguère. ### ### Sum that is weighted by the number of non missing values. ### if less value than n are missing it returns NA. sum.n <- function (x, n = 1, ...){ n.val <- sum(!is.na(x)) l.val <- length(x) if (n.val >= n){ return(mean(x, na.rm = TRUE, ...) * l.val) } else{ return(NA) } }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/sum.n.R
### -*- Coding: utf-8 -*- ### ### Analyste: Charles-Edouard Giguere ### ### .~ ### ### _\\\\\_ ~.~ ### ### | ~ ~ | .~~. ### ### #--O-O--# ==|| ~~.|| ### ### | L | // ||_____|| ### ### | \_/ | \\ || || ### ### \_____/ ==\\_____// ### ########################################## ### to_csv/from_csv is a function used to export data and format factors in two csv files ### 1) The raw data and 2) the format data. ### so they can be easily recuperated but more importantly shared with others. ### All variables are formated in this way, ### | variable | label | format | labels | ### -------------------------------------- ### labels informs on values labels and when they do not apply a NA value is put in. ### ### Five type of data are considered: ### ### * numeric (integer, double, ...) ### * factor (categorical data, package haven *labelled vectors* are treated here) ### * character (Character field) ### * Date (as YYYY-mm-dd) ### * posix (for time and date as YYYY-mm-dd hh:mm:ss) ### ### * other miscellaneous data type are indicated as untreated. ### When a data.frame contains multivariate data it is splitted ### into single columns. # Extract column types. column_types <- function(data){ p <- dim(data)[2] type <- rep("other", p) type[sapply(data, is.numeric)] <- "numeric" type[sapply(data, is.factor)] <- "factor" type[sapply(data, is.character)] <- "character" type[sapply(data, inherits, what = "Date")] <- "Date" type[sapply(data, inherits, what = c("POSIXct","POSIXlt"))] <- "POSIX" type } ### Function to export data in csv with a format csv companion file. to_csv <- function(data, file){ dim_data <- dim(data) N <- dim_data[1] p <- dim_data[2] for(i in 1:p){ if(inherits(data[,i], c("data.frame", "matrix"))){ data_insert <- as.data.frame(data[,i]) names(data_insert) <- paste(names(data)[i], names(data_insert), sep = ".") data = data.frame(data[,1:(i-1), drop = FALSE], data_insert, data[,(i+1):p, drop = FALSE]) p = p + dim(data_insert)[2] i = i + dim(data_insert)[2] } } for(n in names(data)){ if(inherits(data[,n], "haven_labelled")){ data[,n] <- as_factor(data[,n]) } } ### The file is cleaned up of multivariate columns and ### labelled vector. ### ### Now we make a copy of the data.frame (tbs = to be saved) using numeric ### value only instead of factors and string instead of date and POSIX. data_type <- column_types(data) data_tbs <- data data_tbs[,data_type %in% "factor"] <- sapply(data_tbs[,data_type %in% "factor"], as.numeric) data_tbs[,data_type %in% "Date"] <- sapply(data_tbs[,data_type %in% "Date"], format, format = "%Y-%m-%d") data_tbs[,data_type %in% "POSIX"] <- sapply(data_tbs[,data_type %in% "POSIX"], format, format = "%Y-%m-%d %H:%M:%OS") ### We eliminate newline character because they mess csv file. data_tbs[, data_type %in% "character"] <- sapply(data_tbs[, data_type %in% "character"], gsub, pattern = "\n\r", replacement = " |-n-| ") f1 <- file(file, open = "w", encoding = "utf-8") write.table(data_tbs, sep = ",", row.names = FALSE, file = f1) close.connection(f1) ### Now we save the format and label in a file. ### All variables are formated in this way, ### | variable | label | format | value | labels | ### -------------------------------------- ### labels informs on values labels and when ### they do not apply a NA value is put in place ### fmt <- data.frame(order = 1:p, variable = names(data)) labels <- unlist(lapply(data, function(x){ if(is.null(attr(x, "label"))) lab = NA else lab = attr(x, "label") names(lab) <- NULL lab })) label <- data.frame(variable = names(labels), label = labels) fmt <- fmt %>% merge(label, all.x = TRUE) fmt <- fmt[order(fmt$order),] fmt$format <- data_type labs <- mapply( function(x){lvls <- levels(data[,x]) data.frame( variable = x, value = 1:length(lvls), labels = lvls) }, x = names(data)[data_type %in% "factor"], SIMPLIFY = FALSE) fmt <- fmt %>% merge( dplyr::bind_rows(labs), all.x = TRUE) fmt <- fmt[order(fmt$order),] f2 <- file(sub("[.]", "_fmt.",file), open = "w", encoding = "utf-8") write.table(fmt[,c("variable", "label", "format", "value", "labels")], sep = ",", row.names = FALSE, file = f2) close.connection(f2) }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/to_csv.r
### Function view uses DT::datatable as a viewer and sends options to datatable. view <- function(x, ...){ if(is.vector(x)) x <- data.frame(x) datatable(x, ...) }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/view.R
### -*- Coding: utf-8 -*- ### ### Analyste: Charles-Édouard Giguère. ### ### Wrapper that applies function to a variable for levels of a formula ### via a formula. It works like aggregate but it returns a table instead ### of a list. xf <- function(formula, data, FUN = NULL, ..., subset=NULL, na.action = na.omit, useNA = FALSE, addmargins = TRUE){ if(is.null(FUN)){ cat("No function specified, default mean function is used", fill=TRUE) FUN <- mean } N <- dim(data)[1] md.frm <- model.frame(formula,data) frm.terms <- attr(terms(formula),"term.labels") for(t in frm.terms){ if(useNA) data[,t] <- addNA(factor(data[,t]),ifany=TRUE) else data[,t] <- factor(data[,t],exclude=c(NA,NaN)) } data = data[names(md.frm)] p <- length(frm.terms) if(addmargins & length(frm.terms) > 0) { dat1 <- data.frame(rep(data[,1], 2^p)) REP <- expand.grid(as.data.frame( matrix(rep(1:2,p),nrow = 2, ncol = p) )) for(i in 1:p) dat1 <- cbind(dat1,factor(as.vector(t(rbind(as.character(data[,i+1]), rep("Total", N))[REP[,i],])), levels = c(levels(data[,i+1]),"Total"))) names(dat1) <- names(data) data <- dat1 } res <- do.call("aggregate", list(formula, data=data, FUN=FUN, subset=subset, na.action=na.action, ...)) if(length(frm.terms)==1){ terms.length <- length(table(data[,frm.terms], useNA=ifelse(useNA,"ifany","no"))) if(useNA){ terms.exp <- unique(data[frm.terms]) } else{ terms.exp <- unique(na.exclude(data[frm.terms])) } names(terms.exp) <- frm.terms } else if(length(frm.terms)==0){ class(res) <- c("xf","table") return(res) } else{ terms.length <- sapply(data[,frm.terms], function(x) length(table(x, useNA=ifelse(useNA,"ifany","no")))) if(useNA){ terms.exp <- expand.grid(lapply(as.list(data[,frm.terms]), unique)) } else{ terms.exp <- expand.grid(lapply(as.list(data[,frm.terms]), function(x) unique(na.exclude(x)))) } } res.exp <- merge(terms.exp,res,all.x=TRUE) resp <- setdiff(names(md.frm),frm.terms) res.array <- array(dim=terms.length) for(n in frm.terms) res.exp <- res.exp[order(res.exp[,n]),] res.array[] <- res.exp[,resp] attr(res.array,"class") <- c("xf","table") if(length(frm.terms)==1){ if(useNA){ dimnames(res.array) <- list(levels(as.factor(data[,frm.terms]))) } else { dimnames(res.array) <- list(levels(as.factor(na.exclude(data[,frm.terms])))) } } else{ if(useNA){ dimnames(res.array) <- lapply(data[,frm.terms],function(x) levels(as.factor(x))) } else{ dimnames(res.array) <- lapply(data[,frm.terms], function(x) levels(as.factor(na.exclude(x)))) } } res.array }
/scratch/gouwar.j/cran-all/cranData/CUFF/R/xf.R
### -*- Coding: utf-8 -*- ### ### Analyste: Charles-Édouard Giguere ### ### .~ ### ### _\\\\\_ ~.~ ### ### | ~ ~ | .~~. ### ### #--O-O--# ==|| ~~.|| ### ### | L | // ||_____|| ### ### | \_/ | \\ || || ### ### \_____/ ==\\_____// ### ########################################## xyboth <- function(x, y){ ## Must be either 2 vectors or 2 matrix/data.frame of same size. if(is.vector(x) & !is.vector(y) | !is.vector(x) & is.vector(y)){ stop("x and y are not of the same type and cannot be compare") } if((is.matrix(x) | is.data.frame(x)) & !(is.matrix(y) | is.data.frame(y)) | !(is.matrix(x) | is.data.frame(x)) & (is.matrix(y) | is.data.frame(y))){ stop("x and y are not of the same type and cannot be compare") } ## convert x and y to a data.frame if(is.vector(x) & is.vector(y)){ xc <- data.frame(ID = as.character(x)) yc <- data.frame(ID = as.character(y)) } else{ xc <- as.data.frame(x) xc[] <- sapply(xc, as.character) yc <- as.data.frame(y) yc[] <- sapply(yc, as.character) } if(any(c("INX", "INY", "DIMX", "DIMY") %in% c(names(xc), names(yc)) ) ){ stop("Variables INX/INY/DIMX/DIMY are reserved for this command") } ## No test for dimensionality of index but will result no intersection in x and y. xc[,"INX"] <- 1 xc[,"DIMX"] <- sprintf(sprintf("%%0%dd",nchar(dim(xc)[1])),1:dim(xc)[1]) yc[,"INY"] <- 1 yc[,"DIMY"] <- sprintf(sprintf("%%0%dd",nchar(dim(yc)[1])),1:dim(yc)[1]) xyc <- merge(xc, yc, all = TRUE) row.names(xyc) <- sprintf("x:%s y:%s", ifelse(is.na(xyc$DIMX), "", xyc$DIMX), ifelse(is.na(xyc$DIMY), "", xyc$DIMY)) xyc$INX <- ifelse(!is.na(xyc$INX), xyc$INX, 0) xyc$INY <- ifelse(!is.na(xyc$INY), xyc$INY, 0) varxy <- setdiff(names(xyc), c("INX","INY", "DIMX", "DIMY")) xyc <- xyc[order(row.names(xyc)),] list(x = xyc[xyc$INX %in% 1 & xyc$INY %in% 0, varxy], y = xyc[xyc$INX %in% 0 & xyc$INY %in% 1, varxy], both = xyc[xyc$INX %in% 1 & xyc$INY %in% 1, varxy]) } `%xyb%` <- xyboth
/scratch/gouwar.j/cran-all/cranData/CUFF/R/xyboth.R
combGWAS<-function(project="mv",traitlist,traitfile,comb_method=c("z"),betasign=rep(1,length(traitlist)),snpid,beta=NULL,SE=NULL,Z=NULL,coded_all,AF_coded_all,n_total=NULL,pvalue=NULL,Z_sample_weighted=FALSE){ trait<-paste(traitlist,collapse="_",sep="") print(traitlist) if (is.null(snpid) | is.null(AF_coded_all) | is.null(coded_all) | ((is.null(beta) | is.null(SE)) & is.null(Z))){ stop("Missing necessary columns!") }else if (!is.null(beta) & !is.null(SE) & !is.null(n_total)){ headername<-c(snpid,beta,SE,AF_coded_all,coded_all,n_total) }else if (!is.null(beta) & !is.null(SE) & is.null(n_total)){ headername<-c(snpid,beta,SE,AF_coded_all,coded_all) }else if ((is.null(beta) | is.null(SE)) & !is.null(n_total)){ headername<-c(snpid,Z,AF_coded_all,coded_all,n_total) }else if ((is.null(beta) | is.null(SE)) & is.null(n_total)){ headername<-c(snpid,Z,AF_coded_all,coded_all) } if ("beta"%in%comb_method & (is.null(beta)|is.null(SE))){ stop("beta or SE can not be missing for the beta method!") } n<-length(traitfile) data<-list() for (i in 1:n){ if (length(scan(file=traitfile[i], what="character", nlines=1, sep=""))>1) which.sep <- "" else if (length(scan(file=traitfile[i], what="character", nlines=1, sep="\t"))>1) which.sep <- "" else if (length(scan(file=traitfile[i], what="character", nlines=1, sep=" "))>1) which.sep <- " " else if (length(scan(file=traitfile[i], what="character", nlines=1, sep=","))>1) which.sep <- "," else if (length(scan(file=traitfile[i], what="character", nlines=1, sep=";"))>1) which.sep <- ";" else stop(paste("Separator field not recognized for ",traitfile[i],sep="")) data[[i]]<-read.csv(traitfile[i],as.is=TRUE,sep=which.sep,header=TRUE)[,headername] if (is.null(beta) | is.null(SE)){ data[[i]]$BETA<-data[[i]][,Z] data[[i]]$se<-1 data[[i]]<-data[[i]][,c(snpid,"BETA","se",AF_coded_all,coded_all,n_total)] } } if (length(scan(file=traitfile[1], what="character", nlines=1, sep=""))>1) which.sep <- "" else if (length(scan(file=traitfile[1], what="character", nlines=1, sep="\t"))>1) which.sep <- "" else if (length(scan(file=traitfile[1], what="character", nlines=1, sep=" "))>1) which.sep <- " " else if (length(scan(file=traitfile[1], what="character", nlines=1, sep=","))>1) which.sep <- "," else if (length(scan(file=traitfile[1], what="character", nlines=1, sep=";"))>1) which.sep <- ";" else stop(paste("Separator field not recognized for ",traitfile[1],sep="")) data0<-read.csv(traitfile[1],as.is=TRUE,sep=which.sep,header=TRUE) if (is.null(n_total)){ for (i in 1:n){ names(data[[i]])<-c("SNPID",paste("beta",i,sep=""),paste("SE",i,sep=""),paste("AF_coded_all",i,sep=""),paste("coded_all",i,sep="")) } }else{ for (i in 1:n){ names(data[[i]])<-c("SNPID",paste("beta",i,sep=""),paste("SE",i,sep=""),paste("AF_coded_all",i,sep=""),paste("coded_all",i,sep=""),paste("N",i,sep="")) } } dat<-data[[1]] for (i in 2:n){ if (identical(data[[1]]$SNPID,data[[i]]$SNPID)) dat <- cbind(dat,data[[i]][,-1]) else dat=merge(dat,data[[i]],by="SNPID",all=TRUE) } ## flip sign of beta if coded alleles different between two datasets for(i in 1:n){ tmp<-na.omit(dat[,paste("coded_all",c(1,i),sep="")]) if(!identical(tmp[,1],tmp[,2])) { warning(paste("coded alleles differ between datasets 1 and",i,",sign of beta in",i," is reversed for those SNPs")) switch<-dat[,"coded_all1"]!=dat[,paste("coded_all",i,sep="")] &!is.na(dat[,"coded_all1"]!=dat[,paste("coded_all",i,sep="")]) dat[switch,paste("beta",i,sep="")]<- - dat[switch,paste("beta",i,sep="")] dat[switch,paste("coded_all",i,sep="")]<- dat[switch,"coded_all1"] } } ##reverse the beta sign if needed for (i in 1:n){ dat[,paste("beta",i,sep="")]<-dat[,paste("beta",i,sep="")]*betasign[i] } CombN_zchisq<-function(){ z<-matrix(0,nrow(dat),n) maf<-matrix(0,nrow(dat),n) for (i in 1:n){ z[,i]<-ifelse(dat[,paste("SE",i,sep="")]>0,dat[,paste("beta",i,sep="")]/dat[,paste("SE",i,sep="")],NA) maf[,i]<-pmin(dat[,paste("AF_coded_all",i,sep="")],1-dat[,paste("AF_coded_all",i,sep="")]) } MAF<-rowMeans(maf) if (!is.null(n_total)){ N<-matrix(0,nrow(dat),n) for (i in 1:n) { N[,i]<-dat[,paste("N",i,sep="")] } } outcol<-names(data0)[!names(data0)%in%c(beta,SE,pvalue,Z,"direction")] col.keep<-data0[,outcol] if (!is.null(n_total)){ meanN<-apply(dat[,c(paste("N",1:n,sep=""))],1,mean,na.rm=TRUE) minN<-apply(dat[,c(paste("N",1:n,sep=""))],1,min,na.rm=TRUE) maxN<-apply(dat[,c(paste("N",1:n,sep=""))],1,max,na.rm=TRUE) Z=data.frame(dat$SNP,MAF,z,N,meanN,minN,maxN) for (i in 1:n){ names(Z)[names(Z)==paste("X",i,sep="")]<-paste("z",i,sep="") names(Z)[names(Z)==paste("X",i,".1",sep="")]<-paste("N",i,sep="") } }else{ Z=data.frame(dat$SNP,MAF,z) for (i in 1:n){ names(Z)[names(Z)==paste("X",i,sep="")]<-paste("z",i,sep="") } } cov.all=matrix(0,n,n) corr=matrix(0,n,n) for (i in 1:n){ for (j in 1:n){ cov.all[i,j]=cov(Z[,i+2],Z[,j+2],use="complete.obs") } } for (i in 1:n){ cov.all[i,i]=var(Z[,i+2],na.rm=TRUE) } corr<-cor(Z[,3:(n+2)],use="complete.obs") if(min(eigen(corr)$values)<0.01){ stop ("The correlation matrix is nearly singular.") } list(col.keep=col.keep,Z=Z,cov.all=cov.all,corr=corr) } #### For OBrien's method doN_z<-function(){ dat<-CombN_zchisq() outfile<-paste(project,"_",trait,"_z.csv",sep="") print(paste("output is in ", outfile)) if (!is.null(n_total)){ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""),paste("N",1:n,sep=""),"meanN","minN","maxN")] }else{ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""))] } newz<-function(x){ if (any(is.na(unlist(x)[1:n]))){ beta<-NA var<-NA }else if (any(is.na(unlist(x)[(n+1):(2*n)]))){ beta<-matrix(rep(1/n,n),1,n)%*%solve(dat$cov.all)%*%matrix(unlist(x)[1:n])/sqrt(abs(det(solve(dat$cov.all)))) var<-matrix(rep(1/n,n),1,n)%*%solve(dat$cov.all)%*%matrix(rep(1/n,n),n,1)/abs(det(solve(dat$cov.all))) }else{ N_sum<-sum(unlist(x)[(n+1):(2*n)]) N_matrix<-matrix(c(unlist(x)[(n+1):(2*n)]/N_sum),1,n) beta<-N_matrix%*%solve(dat$cov.all)%*%matrix(unlist(x)[1:n])/sqrt(abs(det(solve(dat$cov.all)))) var<-N_matrix%*%solve(dat$cov.all)%*%t(N_matrix)/abs(det(solve(dat$cov.all))) } list(beta=beta,var=var) } ######################################################################################### if (Z_sample_weighted==FALSE){ print("Z method: z statistic is selected to be equally weighted") out$beta <- t(matrix(rep(1/n,n),1,n)%*%solve(dat$cov.all)%*%t(dat$Z[,c(paste("z",1:n,sep=""))]))/sqrt(abs(det(solve(dat$cov.all)))) var <-matrix(rep(1/n,n),1,n)%*%solve(dat$cov.all)%*%matrix(rep(1/n,n),n,1)/abs(det(solve(dat$cov.all))) } else{ print("Z method: z statistic is selected to be sample size weighted") if (is.null(n_total)==T) { stop("Z method is selected to be sample size weighted, n_total cannot be missing!") } else { index1<-which(is.na(rowSums(out[, paste("N",1:n,sep="")])==T)) index2<-which(is.na(rowSums(out[, paste("z",1:n,sep="")])==T)) index<-setdiff(index1, index2) N_miss<-as.character(out[index, "dat.SNP"]) if (length(index)!=0){ warning(paste("N for ", N_miss, " is missing, result for this SNP will be equally weighted \n", sep="")) } else{ } out2<-apply(out[,c(paste("z",1:n,sep=""),paste("N",1:n,sep=""))],1,newz) out3<-unlist(out2) out4<-matrix(out3,nrow(out),2,byrow=TRUE,dimnames=list(NULL,c("beta","var"))) out5<-as.data.frame(out4) out$beta<-out5$beta var<-out5$var } } ######################################################################################### out$SE<-ifelse(!is.na(out$beta),sqrt(var),NA) out$Z.comb <- out$beta/out$SE out$pval<-2*pnorm(abs(out$Z.comb),lower.tail=FALSE) for (i in 1:n){ out[,paste("p",i,sep="")]<-2*pnorm(abs(out[,paste("z",i,sep="")]),lower.tail=FALSE) } for (i in 1:n){ out[,paste("d",i,sep="")]<-ifelse(sign(out[,paste("z",i,sep="")])==-1,"-",ifelse(sign(out[,paste("z",i,sep="")])==1,"+",0)) } merg<-function(x){ direction<-x[1] for (j in 2:length(x)) direction<-paste(direction,x[j],sep="") direction } out$direction<-apply(out[,paste("d",1:n,sep="")],1,merg) out<-out[,!names(out)%in%c("beta", "SE")] out<-out[,!names(out)%in%paste("d",1:n,sep="")] out<-merge(dat$col.keep,out,by.x=snpid, by.y="dat.SNP",all=TRUE) out1<-out[order(out$Z.comb^2, decreasing=TRUE),] ##names(out1)[1]<-"SNPID" write.table(out1, outfile, sep=",",quote=FALSE,na="",row.names=FALSE) write.table(dat$corr,"z_correlation_df.out",sep=" ",quote=FALSE,col.names=traitlist,row.names=traitlist) } #### For chi-square method doN_chisq<-function(){ dat<-CombN_zchisq() outfile<-paste(project,"_",trait,"_chisq.csv",sep="") print(paste("output is in ", outfile)) if (!is.null(n_total)){ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""),"meanN","minN","maxN")] }else{ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""))] } comp_cs<-function(x){ cs<-matrix(unlist(x)[1:n],nrow=1)%*%solve(dat$cov.all)%*%matrix(unlist(x)[1:n]) cs } out$chisq.comb <- apply(out[,c(paste("z",1:n,sep=""))],1,comp_cs) out$pval<-pchisq(out$chisq.comb,df=n,lower.tail=FALSE) for (i in 1:n){ out[,paste("p",i,sep="")]<-2*pnorm(abs(out[,paste("z",i,sep="")]),lower.tail=FALSE) } for (i in 1:n){ out[,paste("d",i,sep="")]<-ifelse(sign(out[,paste("z",i,sep="")])==-1,"-",ifelse(sign(out[,paste("z",i,sep="")])==1,"+",0)) } merg<-function(x){ direction<-x[1] for (j in 2:length(x)) direction<-paste(direction,x[j],sep="") direction } out$direction<-apply(out[,paste("d",1:n,sep="")],1,merg) out<-out[,!names(out)%in%paste("d",1:n,sep="")] out<-merge(dat$col.keep,out,by.x=snpid, by.y="dat.SNP",all=TRUE) out1<-out[order(out$chisq.comb, decreasing=TRUE),] ##names(out1)[1]<-"SNPID" write.table(out1, outfile, sep=",",quote=FALSE,na="",row.names=FALSE) write.table(dat$corr,"chisq_correlation_df.out",sep=" ",quote=FALSE,col.names=traitlist,row.names=traitlist) } #### For sum of square method doN_sumsq<-function(){ dat<-CombN_zchisq() outfile<-paste(project,"_",trait,"_sumsq.csv",sep="") print(paste("output is in ", outfile)) if (!is.null(n_total)){ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""),"meanN","minN","maxN")] }else{ out<-dat$Z[,c("dat.SNP",paste("z",1:n,sep=""))] } comp_cs<-function(x){ cs<-matrix(unlist(x)[1:n],nrow=1)%*%matrix(unlist(x)[1:n]) cs } out$chisq.comb <- apply(out[,c(paste("z",1:n,sep=""))],1,comp_cs) c<-eigen(dat$cov.all)$values a<-sum(c^3)/sum(c^2) b<-sum(c)-((sum(c^2))^2)/sum(c^3) d<-((sum(c^2))^3)/((sum(c^3))^2) out$pval<-pchisq((out$chisq.comb-b)/a,df=d,lower.tail=FALSE) for (i in 1:n){ out[,paste("p",i,sep="")]<-2*pnorm(abs(out[,paste("z",i,sep="")]),lower.tail=FALSE) } for (i in 1:n){ out[,paste("d",i,sep="")]<-ifelse(sign(out[,paste("z",i,sep="")])==-1,"-",ifelse(sign(out[,paste("z",i,sep="")])==1,"+",0)) } merg<-function(x){ direction<-x[1] for (j in 2:length(x)) direction<-paste(direction,x[j],sep="") direction } out$direction<-apply(out[,paste("d",1:n,sep="")],1,merg) out<-out[,!names(out)%in%paste("d",1:n,sep="")] out<-merge(dat$col.keep,out,by.x=snpid, by.y="dat.SNP",all=TRUE) out1<-out[order(out$chisq.comb, decreasing=TRUE),] ##names(out1)[1]<-"SNPID" write.table(out1, outfile, sep=",",quote=FALSE,na="",row.names=FALSE) write.table(dat$corr,"sumsq_correlation_df.out",sep=" ",quote=FALSE,col.names=traitlist,row.names=traitlist) write(paste("sumsq df=",d,sep=""),"sumsq_correlation_df.out",append=TRUE) } #### For beta method CombN_beta<-function(){ Beta<-matrix(0,nrow(dat),n) Se<-matrix(0,nrow(dat),n) Maf<-matrix(0,nrow(dat),n) for (i in 1:n){ Beta[,i]<-dat[,paste("beta",i,sep="")] Se[,i]<-dat[,paste("SE",i,sep="")] Maf[,i]<-pmin(dat[,paste("AF_coded_all",i,sep="")],1-dat[,paste("AF_coded_all",i,sep="")]) } MAF<-rowMeans(Maf) outcol<-names(data0)[!names(data0)%in%c(beta,SE,Z,pvalue,"direction")] col.keep<-data0[,outcol] if (!is.null(n_total)){ meanN<-apply(dat[,c(paste("N",1:n,sep=""))],1,mean,na.rm=TRUE) minN<-apply(dat[,c(paste("N",1:n,sep=""))],1,min,na.rm=TRUE) maxN<-apply(dat[,c(paste("N",1:n,sep=""))],1,max,na.rm=TRUE) Z=data.frame(dat$SNP,MAF,Beta,Se,meanN,minN,maxN) }else{ Z=data.frame(dat$SNP,MAF,Beta,Se) } for (i in 1:n){ names(Z)[names(Z)==paste("X",i,sep="")]<-paste("beta",i,sep="") names(Z)[names(Z)==paste("X",i,".1",sep="")]<-paste("SE",i,sep="") } corr=matrix(0,n,n) corr<-cor(Z[,3:(n+2)],use="complete.obs") if(min(eigen(corr)$values)<0.01){ stop ("The correlation matrix is nearly singular.") } list(col.keep=col.keep,Z=Z,corr=corr) } doN_beta<-function(){ n<-length(traitfile) dat<-CombN_beta() outfile<-paste(project,"_",trait,"_beta.csv",sep="") print(paste("output is in ", outfile)) if (!is.null(n_total)){ out<-dat$Z[,c("dat.SNP",paste("beta",1:n,sep=""),paste("SE",1:n,sep=""),"meanN","minN","maxN")] }else{ out<-dat$Z[,c("dat.SNP",paste("beta",1:n,sep=""),paste("SE",1:n,sep=""))] } newse<-function(x){ cov.mat<-diag(unlist(x)[(n+1):(2*n)])%*%dat$corr%*%diag(unlist(x)[(n+1):(2*n)]) if (any(is.na(unlist(x))) | any(unlist(x)[(n+1):(2*n)]==0)|det(cov.mat)==0){ beta<-NA SE<-NA Z.comb <- NA pval<-NA }else{ beta<-matrix(rep(1/n,n),1,n)%*%solve(cov.mat)%*%matrix(unlist(x)[1:n])/sqrt(abs(det(solve(cov.mat)))) var<-matrix(rep(1/n,n),1,n)%*%solve(cov.mat)%*%matrix(rep(1/n,n),n,1)/abs(det(solve(cov.mat))) SE<-ifelse(!is.na(beta),sqrt(var),NA) Z.comb <- beta/SE pval<-2*pnorm(abs(Z.comb),lower.tail=FALSE) } list(beta=beta,SE=SE,Z.comb=Z.comb,pval=pval) } out2<-apply(out[,c(paste("beta",1:n,sep=""),paste("SE",1:n,sep=""))],1,newse) out3<-unlist(out2) out4<-matrix(out3,nrow(out),4,byrow=TRUE,dimnames=list(NULL,c("beta","SE","Z.comb","pval"))) out5<-as.data.frame(out4) out<-cbind(out,out5) for (i in 1:n){ out[,paste("p",i,sep="")]<-2*pnorm(abs(ifelse(dat$Z[,paste("SE",i,sep="")]>0,dat$Z[,paste("beta",i,sep="")]/dat$Z[,paste("SE",i,sep="")],NA)),lower.tail=FALSE) } for (i in 1:n){ out[,paste("d",i,sep="")]<-ifelse(sign(out[,paste("beta",i,sep="")])==-1,"-",ifelse(sign(out[,paste("beta",i,sep="")])==1,"+",0)) } merg<-function(x){ direction<-x[1] for (j in 2:length(x)) direction<-paste(direction,x[j],sep="") direction } out$direction<-apply(out[,paste("d",1:n,sep="")],1,merg) out<-out[,!names(out)%in%paste("d",1:n,sep="")] out<-merge(dat$col.keep,out,by.x=snpid, by.y="dat.SNP",all=TRUE) ##out<-out[,!names(out)%in%paste("SE",1:n,sep="")] out1<-out[order(out$Z.comb^2, decreasing=TRUE),] ##names(out1)[1]<-"SNPID" write.table(out1, outfile, sep=",",quote=FALSE,na="",row.names=FALSE) write.table(dat$corr,"beta_correlation_df.out",sep=" ",quote=FALSE,col.names=traitlist,row.names=traitlist) } if (FALSE%in%(comb_method%in%c("z","beta","chisq","sumsq"))){ stop("Please check the method name!") } if ("beta"%in%comb_method){ doN_beta() } if ("z"%in%comb_method){ doN_z() } if ("chisq"%in%comb_method){ doN_chisq() } if ("sumsq"%in%comb_method){ doN_sumsq() } }
/scratch/gouwar.j/cran-all/cranData/CUMP/R/combGWAS.R
getARL = function(distr=NULL, K=NULL, H=NULL, Mean=NULL, std=NULL, prob=NULL, Var=NULL, mu=NULL, lambda=NULL, samp.size=NULL, is.upward=NULL, winsrl=NULL, winsru=NULL) { if (is.null(distr)) { cat('1 = Normal location, \n 2 = Normal variance, \n 3 = Poisson, \n 4 = Binomial, \n 5 = Negative binomial, \n 6 = Inv Gaussian mean. \n') stop("Sepcify a distribution.") } distrs = c('Normal location','Normal variance', 'Poisson', 'Binomial', 'Negative binomial', 'Inv Gaussian mean') nonmen = length(distrs) if (!(distr %in% seq(nonmen))) stop ("'distr' is not a valid choice.") # parameter settings eps = 0.001 denrat = 0.0 isint = FALSE plus = 1.0 arg2 = 0.0 ## Winsorizing constants if (is.null(winsrl)) winsrl = -1.0E8 else winsrl = as.double(winsrl) if (is.null(winsru)) winsru = 1.0E8 else winsru = as.double(winsru) ## read parameters for different distributions if (distr == 1) { # Normal location if (is.null(Mean)) stop ("'Mean' is missing.") if (is.null(std)) stop ("Standard deviation 'std' is missing.") if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") amu = as.double(Mean) asig = as.double(std) ref = as.double(K) di = as.double(H) ref = (ref - amu) / asig di = di / asig if (is.upward == TRUE || is.null(is.upward)) cat('The cusum is assumed upward. \n') else cat('Always assume is.upward = TRUE for normal mean. \n') ndis = as.integer(1) } if (distr == 2) { ## Normal variance if (is.null(samp.size)) stop ("Rational group size 'samp.size' is missing.") else nsamp = as.integer(samp.size) if (nsamp < 2) { cat("Charting squared deviations from true mean. \n") nsamp = as.integer(2) } integ = nsamp - as.integer(1) # change the common variable 'ndf' in varup & vardn subroutines .Fortran("cmpar2", integ) if (is.null(std)) stop ("Standard deviation 'std' is missing.") if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") sigma = as.double(std) ref = as.double(K) di = as.double(H) ref = ref / (sigma * sigma) di = di / (sigma * sigma) if (is.null(is.upward)) stop ("Upward or Downward? 'is.upward' is missing.") ndis = as.integer(2) if (is.upward == FALSE) { plus = -1 ndis = as.integer(3) } } if (distr == 3) { ## Poisson if (is.null(Mean)) stop ("Poisson mean 'Mean' is missing.") if (Mean <= 0) stop ("Poisson mean must be positive: Mean > 0.") arg2 = as.double(Mean) if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") ref = as.double(K) di = as.double(H) ndis = as.integer(4) if (is.null(is.upward)) stop ("Upward or Downward? 'is.upward' is missing.") if (is.upward == FALSE) { plus = -1 ndis = as.integer(5) } isint = TRUE } if (distr == 4) { ## Binomial if (is.null(samp.size)) stop ("Sample size 'samp.size' is missing.") if (is.null(prob)) stop ("Success probability 'prob' is missing.") integ = as.integer(samp.size) # change the common variable 'nbig' in binup & bindn subroutines .Fortran("cmpar2", integ) arg2 = as.double(prob) if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") ref = as.double(K) di = as.double(H) ndis = as.integer(6) if (is.null(is.upward)) stop ("Upward or Downward? 'is.upward' is missing.") if (is.upward == FALSE) { plus = -1 ndis = as.integer(7) } isint = TRUE } if (distr == 5) { ## Negative binomial if (is.null(Mean)) stop ("'Mean' is missing.") if (is.null(Var)) stop ("Variance 'Var' is missing.") aver = as.double(Mean) varian = as.double(Var) arg2 = aver / (varian - aver) realno = aver * arg2 if(max(realno, arg2) <= 0) stop("Mean must be > 0 and variance > mean.") # change the common variable 'r' in nbinup & nbindn subroutines .Fortran("cmpar", realno) if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") ref = as.double(K) di = as.double(H) ndis = as.integer(8) if (is.null(is.upward)) stop ("Upward or Downward? 'is.upward' is missing.") if (is.upward == FALSE) { plus = -1 ndis = as.integer(9) } isint = TRUE } if (distr == 6) { ## Inverse Gaussian mean if (is.null(mu)) stop ("Inverse Gaussian mean 'mu' is missing.") if (is.null(lambda)) stop ("Shape parameter 'lambda' is missing.") if(min(mu, lambda) <= 0) stop("All parameters must be strictly positive.") arg2 = as.double(mu) realno = as.double(lambda) # change the common variable 'alam' in gauiup & gauidn subroutines .Fortran("cmpar", realno) if (is.null(K)) stop ("Reference value 'K' is missing.") if (is.null(H)) stop ("Decision interval 'H' is missing.") ref = as.double(K) di = as.double(H) ndis = as.integer(10) if (is.null(is.upward)) stop ("Upward or Downward? 'is.upward' is missing.") if (is.upward == FALSE){ plus = -1 ndis = as.integer(11) } } if (isint) { den = .Fortran('getden', ref=as.double(ref), di=as.double(di), denrat=as.double(denrat)) ref = den$ref di = den$di denrat = den$denrat } # Integer - find rational denominator cat(sprintf("( k = %9.4f, h = %9.4f). \n", ref, di)) winlo = winsrl winhi = winsru if (plus < 0) { winlo = -winsru winhi = -winsrl } cal = .Fortran('calcus', as.double(di), as.double(plus*ref), as.integer(ndis), as.double(denrat), as.double(arg2), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps=eps, esterr=as.double(0), ifault=as.integer(0)) regarl = cal$regarl firarl = cal$firarl ssarl = cal$ssarl esterr = cal$esterr ifault = cal$ifault if (ifault > 0) { cat(sprintf("Error code %5i was returned. \n", ifault)) } cat(sprintf('zero start, FIR, steady state ARLs %10.2f %10.2f %10.2f \n', regarl, firarl, ssarl)) if (ifault != 0) { good = -log10(abs(esterr)) cat(sprintf("I think this answer has only %7.1f accurate digits. \n", good)) } ## Output the result list(ARL_Z = regarl, ARL_F = firarl, ARL_S = ssarl) }
/scratch/gouwar.j/cran-all/cranData/CUSUMdesign/R/getARL.R
getH = function(distr=NULL, ARL=NULL, ICmean=NULL, ICsd=NULL, OOCmean=NULL, OOCsd=NULL, ICprob=NULL, OOCprob=NULL, ICvar=NULL, IClambda=NULL, samp.size=NULL, ref=NULL, winsrl=NULL, winsru=NULL, type=c("fast initial response", "zero start", "steady state")) { if (is.null(distr)) { cat('1 = Normal location, \n 2 = Normal variance, \n 3 = Poisson, \n 4 = Binomial, \n 5 = Negative binomial, \n 6 = Inv Gaussian mean. \n') stop("Sepcify a distribution.") } distrs = c('Normal location','Normal variance', 'Poisson', 'Binomial', 'Negative binomial', 'Inv Gaussian mean') nonmen = length(distrs) if (!(distr %in% seq(nonmen))) stop ("'distr' is not a valid choice.") ## parameter settings eps0 = 0.05 eps = 0.001 int10 = as.integer(10) plus = 1.0 denrat = 0.0 isint = FALSE step0 = 0.25 quar3 = 0.75 quar = 0.25 arg2 = 0.0 intone = as.integer(1) ## Winsorizing constants if (is.null(winsrl)) winsrl = -999 else winsrl = as.double(winsrl) if (is.null(winsru)) winsru = 999 else winsru = as.double(winsru) ## zero-start (Z), steady state (S), or fast initial response (F) if (is.null(type)) { cat ("type is missing. Set type = 'F' (FIR). \n") type = "F" } type = tolower(type) type = match.arg(type) runtype = match(type, c("zero start", "fast initial response", "steady state")) if (is.null(ARL)) stop ("ARL is missing.") else ARL = as.double(ARL) ## read parameters for different distributions if (distr == 1) { # Normal location if (is.null(ICmean)) stop ("In-control mean 'ICmean' is missing.") if (is.null(ICsd)) stop ("In-control sd 'ICsd' is missing.") if (is.null(OOCmean)) stop ("Out-of-control mean 'OOCmean' is missing.") amu = as.double(ICmean) amu1 = as.double(OOCmean) sigma = as.double(ICsd) if (is.null(ref)) ref = 0.5 * abs(amu1 - amu) / sigma else cat("ref is not user-specifed for normal location, \n") offset = 0.5 * (amu + amu1) cat(sprintf("The reference value is %12.3f \n", offset)) ndis = intone } if (distr == 2) { ## Normal variance if (is.null(samp.size)) stop ("Rational group size 'samp.size' is missing.") else nsamp = as.integer(samp.size) if (nsamp < 2) { cat("Using squared deviations from true mean. \n") nsamp = as.integer(2) } integ = nsamp - intone # change the common variable 'ndf' in varup & vardn subroutines .Fortran("cmpar2", integ) if (is.null(ICsd)) stop ("In-control sd 'ICsd' is missing.") if (is.null(OOCsd)) stop ("Out-of-control sd 'OOCsd' is missing.") sigma0 = as.double(ICsd) sigma1 = as.double(OOCsd) varrat = (sigma0 / sigma1) ^ 2 if (is.null(ref)) ref = log(varrat) / (varrat - 1) else cat("ref is not user-specifed for normal variance, \n") offset = ref * sigma0 * sigma0 cat(sprintf("The reference value is %12.3f \n", offset)) ndis = as.integer(2) if (sigma1 < sigma0) { plus = -1 ndis = as.integer(3) } } if (distr == 3) { ## Poisson if (is.null(ICmean)) stop ("In-control mean 'ICmean' is missing.") if (is.null(OOCmean)) stop ("Out-of-control mean 'OOCmean' is missing.") arg2 = as.double(ICmean) amu1 = as.double(OOCmean) if (min(arg2, amu1) <= 0) stop("Invalid - means must be strictly positive.'") if (is.null(ref)) ref = (amu1 - arg2) / log(amu1 / arg2) else ref = as.double(ref) cat(sprintf("The reference value is %12.3f \n", ref)) ndis = as.integer(4) if (amu1 < arg2) { plus = -1 ndis = as.integer(5) } isint = TRUE step0 = as.integer(arg2 * 0.5 + 1) } if (distr == 4) { ## Binomial if (is.null(samp.size)) stop ("Sample size 'samp.size' is missing.") if (is.null(ICprob)) stop ("In-control probability 'ICprob' is missing.") if (is.null(OOCprob)) stop ("Out-of-control probability 'OOCprob' is missing.") integ = as.integer(samp.size) # change the common variable 'nbig' in binup & bindn subroutines .Fortran("cmpar2", integ) arg2 = as.double(ICprob) pi1 = as.double(OOCprob) if(min(pi1, arg2) <= 0 || max(pi1, arg2) > 1) stop("Invalid IC or OOC probability.") if (is.null(ref)) ref = -integ * log((1 - pi1)/(1 - arg2)) / log(pi1 * (1 - arg2)/ (arg2 * ((1 - pi1)))) else ref = as.double(ref) cat(sprintf("The reference value is %12.3f \n", ref)) ndis = as.integer(6) if (pi1 < arg2) { plus = -1 ndis = as.integer(7) } isint = TRUE step0 = as.integer((integ * arg2) * 0.5 + 1) } if (distr == 5) { ## Negative binomial if (is.null(ICmean)) stop ("In-control mean 'ICmean' is missing.") if (is.null(ICvar)) stop ("In-control variance 'ICvar' is missing.") if (is.null(OOCmean)) stop ("Out-of-control mean 'OOCmean' is missing.") aver = as.double(ICmean) varian = as.double(ICvar) aver1 = as.double(OOCmean) if(min(aver, aver1, varian - aver) <= 0) stop("Means must be > 0 and variance > in-control mean.") arg2 = aver / (varian - aver) realno = aver * arg2 # change the common variable 'r' in nbinup & nbindn subroutines .Fortran("cmpar", realno) c1 = arg2 * aver / aver1 if (is.null(ref)) ref = - realno * log((c1*(1+arg2))/(arg2*(1+c1))) / log((1+arg2)/(1+c1)) else ref = as.double(ref) cat(sprintf("The reference value is %12.3f \n", ref)) ndis = as.integer(8) if (aver1 < aver) { plus = -1 ndis = as.integer(9) } isint = TRUE step0 = as.integer(aver * 0.5 + 1) } if (distr == 6) { ## Inverse Gaussian mean if (is.null(ICmean)) stop ("In-control mean 'ICmean' is missing.") if (is.null(IClambda)) stop ("In-control lambda 'IClambda' is missing.") if (is.null(OOCmean)) stop ("Out-of-control mean 'OOCmean' is missing.") arg2 = as.double(ICmean) realno = as.double(IClambda) # change the common variable 'alam' in gauiup & gauidn subroutines .Fortran("cmpar", realno) amu1 = as.double(OOCmean) if (min(arg2, realno, amu1) <= 0.0) stop("All parameters must be strictly positive.") if (is.null(ref)) ref = 2 * arg2 * amu1 / (arg2 + amu1) else ref = as.double(ref) cat(sprintf("The reference value is %12.3f \n", ref)) step0 = min(arg2, realno, amu1) * 0.5 ndis = as.integer(10) if (amu1 < arg2){ plus = -1 ndis = as.integer(11) } } ## Do preliminary ranging maxfau = as.integer(0) hlo = 0 ihlo = as.integer(0) ihhi = as.integer(0) intval = as.integer(0) istep = as.integer(0) alow = 1 step = step0 temp = 1 ## If integer - find rational denominator if (isint) { den = .Fortran('getden', ref=as.double(ref), temp=as.double(temp), denrat=as.double(denrat)) ref = den$ref temp = den$temp denrat = den$denrat istep = step * denrat istep = min(istep, int10) } ## Ranging for (inner in seq(40)) { step = step * 1.2 hhi = hlo + step if (isint) { istep = min(int10, istep + 2) ihhi = ihlo + istep if (ihhi > 256) stop("Can not handle that K. Try a simpler one") hhi = as.double(ihhi) / denrat } winlo = winsrl winhi = winsru if (plus < 0) { winlo = -winsru winhi = -winsrl } cal = .Fortran('calcus', as.double(hhi), as.double(plus*ref), as.integer(ndis), as.double(denrat), as.double(arg2), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps0=eps0, esterr=as.double(0), ifault=as.integer(0)) regarl = cal$regarl firarl = cal$firarl ssarl = cal$ssarl esterr = cal$esterr ifault = cal$ifault maxfau = max(maxfau,ifault) if (ifault != 0) { good = 0 if (esterr > 0) good = -log10(esterr) cat(sprintf(' h %11.4f arls %9.1f %7.1f %7.1f \n', hhi, regarl, firarl, ssarl)) } gotarl = switch(runtype, regarl, firarl, ssarl) ahi = gotarl if (gotarl > ARL) break hlo = hhi ihlo = ihhi alow = gotarl } if (gotarl <= ARL) stop ("Ranging failed. Exit.") ## Refinement logscl = (min(alow, ahi, ARL) > 0) if (logscl) { alowlg = log(alow) ahilg = log(ahi) arllg = log(ARL) } else { alowlg = alow ahilg = ahi arllg = ARL } for (inner in seq(20)) { ratio = (arllg - alowlg) / (ahilg - alowlg) ratio = min(quar3, max(quar, ratio)) test = hlo + ratio * (hhi - hlo) if (isint && ((ihhi - ihlo) == 1)) { cat(sprintf("k %8.4f h %8.4f ARL %10.2f h %8.4f ARL %10.2f \n", ref, hlo, alow, hhi, ahi)) test = hhi gothi = ahi break } if (isint) { intval = as.integer((ihlo + ihhi + intone) / 2) intval = max(ihlo + intone, min(ihhi - intone, intval)) test = as.double(intval) / denrat } cal2 = .Fortran('calcus', as.double(test), as.double(plus*ref), as.integer(ndis), as.double(denrat), as.double(arg2), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps=eps, esterr=as.double(1), ifault=as.integer(0)) regarl = cal2$regarl firarl = cal2$firarl ssarl = cal2$ssarl esterr = cal2$esterr ifault = cal2$ifault maxfau = max(maxfau,ifault) if (ifault == 0) { # cat(sprintf(' h %11.4f arls %9.1f %7.1f %7.1f \n', # test, regarl, firarl, ssarl)) } else { good = -log10(esterr) cat(sprintf(' h %11.4f arls %9.1f %7.1f %7.1f %7.1f estimated good digits \n', test, regarl, firarl, ssarl, good)) } gotarl = switch(runtype, regarl, firarl, ssarl) if (gotarl < ARL) { hlo = test alowlg = gotarl if (logscl) alowlg = log(gotarl) ihlo = intval alow = gotarl } else { hhi = test ahilg = gotarl if (logscl) ahilg = log(gotarl) ihhi = intval ahi = gotarl } if (abs(gotarl / ARL - 1.0) < eps) break } if (inner > 40) { stop(sprintf("Convergence failed. Best guesses. \n k %8.4f h %8.4f ARL %10.2f h %8.4f ARL %10.2f \n", ref, hlo, alow, hhi, ahi)) } if(ndis == 1) { ## Normal location fit = .Fortran('calcus', as.double(test), as.double(-abs(ref)), as.integer(ndis), as.double(denrat), as.double(arg2), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) test = test * sigma cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gotarl, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = offset, IC_ARL = gotarl, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } if(ndis == 2 || ndis == 3) { ## Normal variance fit = .Fortran('calcus', as.double(test*varrat), as.double(plus * ref * varrat), as.integer(ndis), as.double(denrat), as.double(arg2), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) test = test * sigma0 * sigma0 cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gotarl, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = offset, IC_ARL = gotarl, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } if(ndis == 4 || ndis == 5) { ## Poisson fit = .Fortran('calcus', as.double(test), as.double(plus * ref), as.integer(ndis), as.double(denrat), as.double(amu1), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gothi, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = ref, IC_ARL = gothi, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } if(ndis == 6 || ndis == 7) { ## Bionomial fit = .Fortran('calcus', as.double(test), as.double(plus * ref), as.integer(ndis), as.double(denrat), as.double(pi1), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gothi, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = ref, IC_ARL = gothi, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } if(ndis == 8 || ndis == 9) { ## Negative Bionomial fit = .Fortran('calcus', as.double(test), as.double(plus * ref), as.integer(ndis), as.double(denrat), as.double(c1), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gothi, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = ref, IC_ARL = gothi, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } if(ndis == 10 || ndis == 11) { ## Inverse Gaussian mean fit = .Fortran('calcus', as.double(test), as.double(plus * ref), as.integer(ndis), as.double(denrat), as.double(amu1), as.double(winlo), as.double(winhi), regarl=as.double(0), firarl=as.double(0), ssarl=as.double(0), eps, esterr=as.double(1), ifault=as.integer(0)) cat(sprintf("DI %11.3f IC ARL %9.1f OOC ARL Zero start %7.1f FIR %7.1f SS %7.1f \n", test, gotarl, fit$regarl, fit$firarl, fit$ssarl)) res = list(DI = test, ref = ref, IC_ARL = gotarl, OOCARL_Z = fit$regarl, OOCARL_F = fit$firarl, OOCARL_S = fit$ssarl) } ## Output the result res }
/scratch/gouwar.j/cran-all/cranData/CUSUMdesign/R/getH.R
plotConfusionVectors<-function(colorSpace='CIE1931xy'){ neutralPoint<-get("neutralPoint", envir = environment()) dichromaticCopunctalPoint<-get("dichromaticCopunctalPoint", envir = environment()) if (colorSpace=='CIE1931xy'){ segments(neutralPoint['CIE1931xy','u'],neutralPoint['CIE1931xy','v'],dichromaticCopunctalPoint['P','CIE1931xyX'],dichromaticCopunctalPoint['P','CIE1931xyY']) segments(neutralPoint['CIE1931xy','u'],neutralPoint['CIE1931xy','v'],dichromaticCopunctalPoint['D','CIE1931xyX'],dichromaticCopunctalPoint['D','CIE1931xyY']) segments(neutralPoint['CIE1931xy','u'],neutralPoint['CIE1931xy','v'],dichromaticCopunctalPoint['T','CIE1931xyX'],dichromaticCopunctalPoint['T','CIE1931xyY']) } else { if (colorSpace=='CIE1976uv'){ segments(neutralPoint['CIE1976uv','u'],neutralPoint['CIE1976uv','v'],dichromaticCopunctalPoint['P','CIE1976uvU'],dichromaticCopunctalPoint['P','CIE1976uvV']) segments(neutralPoint['CIE1976uv','u'],neutralPoint['CIE1976uv','v'],dichromaticCopunctalPoint['D','CIE1976uvU'],dichromaticCopunctalPoint['D','CIE1976uvV']) segments(neutralPoint['CIE1976uv','u'],neutralPoint['CIE1976uv','v'],dichromaticCopunctalPoint['T','CIE1976uvU'],dichromaticCopunctalPoint['T','CIE1976uvV']) } else { if (colorSpace=='CIE1960uv'){ segments(neutralPoint['CIE1960uv','u'],neutralPoint['CIE1960uv','v'],dichromaticCopunctalPoint['P','CIE1960uvU'],dichromaticCopunctalPoint['P','CIE1960uvV']) segments(neutralPoint['CIE1960uv','u'],neutralPoint['CIE1960uv','v'],dichromaticCopunctalPoint['D','CIE1960uvU'],dichromaticCopunctalPoint['D','CIE1960uvV']) segments(neutralPoint['CIE1960uv','u'],neutralPoint['CIE1960uv','v'],dichromaticCopunctalPoint['T','CIE1960uvU'],dichromaticCopunctalPoint['T','CIE1960uvV']) } } }} vectorPNGbuttons<-function(capsData=get("FarnsworthD15", envir = environment())) {# vector with the PNG button filenames capsData <- data.matrix((capsData[,c('R','G','B')])) apply(capsData,1,function(x) { rgbName <- sprintf('%02x%02x%02x.png',x['R'],x['G'],x['B']) paste(system.file(package='CVD'),'/extdata/',rgbName,sep='') }) } loadPNG<-function(fileIN=NULL, silent=FALSE) {#loads a PNG and shows the dimensions, useful for interactive testing if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist') p<-png::readPNG(fileIN) if (!silent) print(paste('PNG ',dim(p)[1],'x',dim(p)[2],', ',dim(p)[3],' channels.',sep='')) p } createPNGbuttons<-function(capsData=get("FarnsworthD15", envir = environment()), imgLength=44, imgWidth=78) {# creates PNG buttons from a data.frame with RGB values for test caps capsData <- data.matrix((capsData[,c('R','G','B')])) apply(capsData,1,function(x) { rgbName <- sprintf('%02x%02x%02x.png',x['R'],x['G'],x['B']) img.array<-array(rep(c(x),each=imgLength*imgWidth),c(imgLength,imgWidth,3)) png::writePNG(img.array/255, rgbName) }) } approx.scotopic.luminance.LarsonEtAl.XYZ<-function(XYZmatrix) XYZmatrix[,2] * (1.33*(1+(XYZmatrix[,2]+XYZmatrix[,3])/XYZmatrix[,1]) -1.68) approx.scotopic.luminance.LarsonEtAl.RGB<-function(RGBmatrix) RGBmatrix[,1] * 0.062 + RGBmatrix[,2] * 0.608 + RGBmatrix[,3] * 0.330 approx.scotopic.luminance.LarsonEtAl.XYZ.array<-function(XYZarray) { im2 <- matrix(apply(XYZarray,1:2,t),length(XYZarray)/3,3,byrow=TRUE) g1<-approx.scotopic.luminance.LarsonEtAl.XYZ(im2) g2<-array(cbind(g1,g1,g1),dim(XYZarray)) g2 } approx.scotopic.luminance.LarsonEtAl.RGB.array<-function(RGBarray) { im2 <- matrix(apply(RGBarray,1:2,t),length(RGBarray)/3,3,byrow=TRUE) g1<-approx.scotopic.luminance.LarsonEtAl.RGB(im2) g2<-array(cbind(g1,g1,g1),dim(RGBarray)) g2 } # Larson, G. W., H. Rushmeier, and C. Piatko (1997, October - December). A visibility matching tone reproduction operator for high dynamic range scenes. # IEEE Transactions on Visualization and Computer Graphics 3 (4), 291–306. XYZ2scotopic.Rawtran<-function(XYZmatrix) 0.36169*XYZmatrix[,3] + 1.18214*XYZmatrix[,2] - 0.80498*XYZmatrix[,1] XYZ2scotopic.Rawtran.array<-function(XYZarray) { im2 <- matrix(apply(XYZarray,1:2,t),length(XYZarray)/3,3,byrow=TRUE) g1<-XYZ2scotopic.Rawtran(im2) g2<-array(cbind(g1,g1,g1),dim(XYZarray)) g2 } # XYZ to scotopic curve, D65, original code: Rawtran - integral.physics.muni.cz # Masaryk University, http://integral.physics.muni.cz/rawtran/ # Filip Hroch, 1998, Computer Programs for CCD Photometry, # 20th Stellar Conference of the Czech and Slovak Astronomical Institutes, # DusekJ., http://adsabs.harvard.edu/abs/1998stel.conf...30H effectivePupilArea<-function(d) pi*d^2/4*(1-0.085*d^2/8+0.002*d^4/48) # effective area #Smith, VC, Pokorny, J, and Yeh, T: The Farnsworth-Munsell 100-hue test in cone excitation space. Documenta Ophthalmologica Proceedings Series 56:281-291, 1993. luminance2troland<-function(Lv, d=NA) { # convert from luminance (cd/m^2) to troland and effective troland #Smith, VC, Pokorny, J, and Yeh, T: The Farnsworth-Munsell 100-hue test in cone excitation space. Documenta Ophthalmologica Proceedings Series 56:281-291, 1993. cbind(troland=Lv * d^2 * pi/4, effectivetroland=Lv * pi*d^2/4*(1-0.085*d^2/8+0.002*d^4/48)) } illuminance2troland<-function(Ev, lumFactor, d=NA) { # convert from illuminance (lux) to troland and effective troland #Smith, VC, Pokorny, J, and Yeh, T: The Farnsworth-Munsell 100-hue test in cone excitation space. Documenta Ophthalmologica Proceedings Series 56:281-291, 1993. cbind(troland=Ev * lumFactor/pi * d^2 * pi/4, effectivetroland=Ev * lumFactor/pi * pi*d^2/4*(1-0.085*d^2/8+0.002*d^4/48)) } VKSvariantGraphic<-function(VKSdata, xLimit=5, yLimit=4, VKStitle='', VKSxlabel='',VKSylabel=''){ xl<-0:(xLimit) yl<-0:(yLimit*2) x2<-xLimit * 4 # plot the axis z<-lapply(1:(xLimit*2), function(x) { c1<-calculateCircle(xLimit,yLimit,x);plot(c1,xlim=c(0,xLimit*2),ylim=c(0,yLimit*2) ,col='lightgrey',type='l', xaxt='n', yaxt='n',ylab='',xlab='');par(new=TRUE) }) z<-lapply(1:12, function(x) {segments(xLimit, yLimit, xLimit+x2*sin(x*30*pi/180),yLimit+x2*cos(x*30*pi/180), col = ifelse((x %% 3)==0,'black','lightgrey')) }) # plot the data uniqV<-unique(VKSdata[,1]) z<-lapply(1:dim(VKSdata)[1], function(x) { symbV<-which(uniqV==VKSdata[x,1]) angleV<-VKSdata[x,2]*2 indexV<-VKSdata[x,3] par(new=TRUE) plot(cos(angleV*pi/180)*indexV + xLimit, yLimit+sin(angleV*pi/180)*indexV ,xlim=c(0,xLimit*2),ylim=c(0,yLimit*2),type='p',pch=symbV, xaxt='n', yaxt='n',ylab='',xlab='') }) Axis(side=2,at=0:(yLimit*2), labels= c(yLimit:1,0,1:yLimit)) # Y axis Axis(side=1,at=yLimit*tan((0:xLimit*30)*pi/180) + xLimit, labels=0:xLimit*30) # X axis title(main = VKStitle, xlab = VKSxlabel, ylab = VKSylabel) legend("topright",pch=1:length(uniqV), uniqV,bg='white')#,title='Symbols' } VKSgraphic<-function(VKSdata, xLimit=5, yLimit=4, VKStitle='', VKSxlabel='',VKSylabel=''){ xl<-0:(xLimit) yl<-0:(yLimit*2) # plot the axis z<-lapply(1:(xLimit*2), function(x) { c1<-calculateCircle(0,yLimit,x);plot(c1,xlim=c(0,xLimit*2),ylim=c(0,yLimit*2) ,col='lightgrey',type='l', xaxt='n', yaxt='n',ylab='',xlab='');par(new=TRUE) }) abline(h = yLimit, col = 'lightgrey') abline(v = 0, col = 'lightgrey') z<-lapply(-5:5, function(x) { abline(a = yLimit, b = tan(x*15*pi/180), col = 'lightgrey') }) # plot the data uniqV<-unique(VKSdata[,1]) z<-lapply(1:dim(VKSdata)[1], function(x) { symbV<-which(uniqV==VKSdata[x,1]) angleV<-VKSdata[x,2] indexV<-VKSdata[x,3] par(new=TRUE) plot(cos(angleV*pi/180)*indexV, yLimit+sin(angleV*pi/180)*indexV ,xlim=c(0,xLimit*2),ylim=c(0,yLimit*2),type='p',pch=symbV, xaxt='n', yaxt='n',ylab='',xlab='') }) Axis(side=2,at=0:(yLimit*2), labels= c(yLimit:1,0,1:yLimit)) # Y axis Axis(side=1,at=yLimit*tan((0:xLimit*15)*pi/180), labels=0:xLimit*15) # X axis title(main = VKStitle, xlab = VKSxlabel, ylab = VKSylabel) legend("topright",pch=1:length(uniqV), uniqV,bg='white')#,title='Symbols' } showDuplicated<-function(cnum) { # show missing and duplicated cap numbers n <- length(cnum) if (!all(sort(cnum) == 1:n)) { missingC<-which(!(1:n %in% cnum)) repeatedC<-cnum[which(duplicated(cnum))] cat('Missing:',paste(missingC,sep=','),'Repeated:',paste(repeatedC,sep=','),'at position:',paste(which(cnum==repeatedC),sep=',')) } } calculateCircle<-function(x, y, r, steps=50,sector=c(0,360),randomDist=FALSE, randomFun=runif,...) { points = matrix(0,steps,2) if (randomDist) n<-sector[1]+randomFun(steps,...)*(sector[2]-sector[1]) else n<-seq(sector[1],sector[2],length.out=steps) if (randomDist) repeat { n[which(!(n>=sector[1] & n<=sector[2]))]<-sector[1]+randomFun(sum(!(n>=sector[1] & n<=sector[2])),...)*(sector[2]-sector[1]) if (all(n>=sector[1] & n<=sector[2])) break } alpha = n * (pi / 180) sinalpha = sin(alpha) cosalpha = cos(alpha) points[,1]<- x + (r * cosalpha) points[,2]<- y + (r * sinalpha) points } limitScore<-function(x) { # internal function to restrict the plot of scoreFM100Graphic if (x<3) return(14) if (x>15) return(2) 16-x } scoreFM100Graphic<-function(userFM100colors=NULL,userFM100values=NULL, titleGraphic="Farnsworth Munsell 100-Hue test results", okFM100colors=NULL, Kinnear=FALSE) {# plots the graphic to score the Farnsworth Munsell 100-Hue test by default, or a similar test by modifying titleGraphic and okFM100colors FarnsworthMunsell100Hue<-get("FarnsworthMunsell100Hue", envir = environment()) cirC<- round(calculateCircle(550,550,500,86)) cirC2<- round(calculateCircle(550,550,530,86)) circPos<-matrix(c(cirC),ncol=2,byrow=F) NumPos<-matrix(c(cirC2),ncol=2,byrow=F) circPos<-circPos[-1,] # coords for the circles NumPos<-NumPos[-1,] # coords for the numbers if ((is.null(userFM100colors)) & (is.null(userFM100values))) stop('Input either the colors chosen by the user for the Farnsworth Munsell 100-Hue test or the position values') if (is.null(okFM100colors)) { #okFM100colors<-sprintf('#%02x%02x%02x',FarnsworthMunsell100Hue[-1,'R'],FarnsworthMunsell100Hue[-1,'G'],FarnsworthMunsell100Hue[-1,'B']) okFM100colors<-sprintf('#%02x%02x%02x',FarnsworthMunsell100Hue[,'R'],FarnsworthMunsell100Hue[,'G'],FarnsworthMunsell100Hue[,'B']) } if (is.null(userFM100colors)) { pos2<-userFM100values } else { pos2<-c() for (n in 1:85) pos2<-c(pos2,which(userFM100colors[n] == okFM100colors)) } #pos3<-86-pos2 lenBox<-1100 #circPos2<-circPos[pos3,] #symbols(circPos[,1], circPos[,2], circles =rep(5,85) , inches = FALSE, xlim = c(1,lenBox), ylim = c(lenBox,1), xaxt='n', yaxt='n', ann=FALSE) cclockPos<-c(64:1,85:65) # counter-clockwise and with "1" on the top of the circle circPos<-circPos[cclockPos,] NumPos<-NumPos[cclockPos,] colRGB<- sprintf("#%02X%02X%02X", FarnsworthMunsell100Hue[,'R'],FarnsworthMunsell100Hue[,'G'],FarnsworthMunsell100Hue[,'B']) colRGB<- colRGB[cclockPos] plot(circPos[cclockPos,1], circPos[cclockPos,2], col=colRGB, cex=2,pch=19, xlim = c(1,lenBox), ylim = c(lenBox,1), xaxt='n', yaxt='n',xlab='',ylab='') #title and cap numbers par(new=T) if (titleGraphic=="Farnsworth Munsell 100-Hue test results") { titleGraphic <- paste(titleGraphic,ifelse(Kinnear, '(Kinnear score)','Farnsworth score')) } title(main =titleGraphic) par(new=T) zz<-c(1,1:42*2) # the traditional plot has number 1 and then only even numbers text(NumPos[zz,1], NumPos[zz,2], c(zz)) par(new=T) #grid - circles scoreC<-array(0,c(14,2,85)) for (n in 1:14) { circTmp<-calculateCircle(550,550,(500-30*n),86) circTmp<-matrix(c(circTmp),ncol=2,byrow=F) circTmp<-circTmp[-1,] z1<-c(65:1,85:66) circTmp2<-circTmp[z1,] scoreC[n,,]<-t(circTmp2) #plot(scoreC[1,1,],scoreC[1,2,], col= sprintf("#%02X%02X%02X", FarnsworthMunsell100Hue[,'R'],FarnsworthMunsell100Hue[,'G'],FarnsworthMunsell100Hue[,'B']),type='p',pch=19, xlim = c(1,lenBox), ylim = c(lenBox,1)) par(new=T) plot(scoreC[n,1,],scoreC[n,2,],col='lightgrey',type='l', xlim = c(1,lenBox), ylim = c(lenBox,1), xaxt='n', yaxt='n',xlab='',ylab=''); par(new=T) } #grid - lines for (n in 1:85) { segments(scoreC[1,1,n],col='lightgrey',scoreC[1,2,n],scoreC[14,1,n],scoreC[14,2,n]); par(new=T) } # score scoreTES<-abs(calculateTES(pos2,!Kinnear)) #for (n in 1:84) { segments(scoreC[16-scoreTES[n],1,n],scoreC[16-scoreTES[n],2,n],scoreC[16-scoreTES[n+1],1,n+1],scoreC[16-scoreTES[n+1],2,n+1], xlim = c(1,lenBox), ylim = c(lenBox,1)); par(new=T) } for (n in 1:84) { segments(scoreC[limitScore(scoreTES[n]),1,n],scoreC[limitScore(scoreTES[n]),2,n],scoreC[limitScore(scoreTES[n+1]),1,n+1], scoreC[limitScore(scoreTES[n+1]),2,n+1], xlim = c(1,lenBox), ylim = c(lenBox,1)); par(new=T) } } interpretation.VingrysAndKingSmith<-function(VKS,optMethod=88) { #Vingrys, A.J. and King-Smith, P.E. (1988). #A quantitative scoring technique for panel tests of color vision. #Investigative Ophthalmology and Visual Science, 29, 50-63. #VKS<-unlist(VKS) A<-as.numeric(VKS['VKS88','ANGLE']);C<-as.numeric(VKS['VKS88','MAGNITUDE']);S<-as.numeric(VKS['VKS88','SCATTER']) interpAngle<-'';interpMagnitude<-'';interpScatter<-'' if ((A > 3) & (A < 17)) interpAngle<-'Protan' if ((A > -11) & (A < -4)) interpAngle<-'Deutan' if ((A > -90) & (A < -70)) interpAngle<-'Tritan' if (C > 1.78) interpMagnitude<-'Abnormal arrangement' if (C <= 1.78) interpMagnitude<-'Normal arrangement' if (S >= 2) interpScatter<-'Selective' if (S < 2) interpScatter<-'Random' c(Angle=interpAngle,Magnitude=interpMagnitude,Selectivity=interpScatter) } interpretation.Foutch<-function(FLJ) { # A new quantitative technique for grading Farnsworth D-15 color panel tests # Foutch, Brian K.; Stringham, James M.; Lakshminarayanan, Vasuvedan # Journal of Modern Optics, vol. 58, issue 19-20, pp. 1755-1763 # # Evaluation of the new web-based" Colour Assessment and Diagnosis" test # J Seshadri, J Christensen, V Lakshminarayanan, CJ BASSI # Optometry & Vision Science 82 (10), 882-885 #FLJ<-unlist(FLJ) A<-as.numeric(FLJ['VKS88','ANGLE']);C<-as.numeric(FLJ['VKS88','Cindex']);S<-as.numeric(FLJ['VKS88','Sindex']) if ((FLJ['Angle'] > 0) & (FLJ['Angle'] < 30)) interpAngle<-'Protan' if ((FLJ['Angle'] > -30) & (FLJ['Angle'] < 0)) interpAngle<-'Deutan' if ((FLJ['Angle'] > 75) & (FLJ['Angle'] < 90)) interpAngle<-'Tritan' if (FLJ['Cindex'] > 1) interpMagnitude<-'Abnormal arrangement' if (FLJ['Cindex'] <= 1) interpMagnitude<-'Normal arrangement' if (FLJ['Sindex'] >= 1) interpScatter<-'Selective' if (FLJ['Sindex'] < 1) interpScatter<-'Random' c(Angle=interpAngle,Magnitude=interpMagnitude,Selectivity=interpScatter) } D15Foutch<-function(userD15values=NULL,testType='D-15', dataVKS=NA) { #======================================================= #function to quantitatively analyze D15 color panel tests: # code from Dr Brian K. Foutch # Calculates angle, magnitude and scatter (for D-15 panels only) using all four models: # VK-S 88 and VK-S 93 (Vingrys, A.J. and King-Smith, P.E. (1988, 1993)), LSA 05 (Foutch/Bassi '05), and JMO 11 (Foutch/Stringham/Vengu '11). # # A new quantitative technique for grading Farnsworth D-15 color panel tests # Foutch, Brian K.; Stringham, James M.; Lakshminarayanan, Vasuvedan # Journal of Modern Optics, vol. 58, issue 19-20, pp. 1755-1763 # # Evaluation of the new web-based" Colour Assessment and Diagnosis" test # J Seshadri, J Christensen, V Lakshminarayanan, CJ BASSI # Optometry & Vision Science 82 (10), 882-885 # #Vingrys, A.J. and King-Smith, P.E. (1988). #A quantitative scoring technique for panel tests of color vision. #Investigative Ophthalmology and Visual Science, 29, 50-63. #======================================================= #n = # of caps; 15 for D (and DS-) 15s... # dataVKS by default are the CIE Luv data used by Vingrys and King-Smith cnum<-userD15values n <- 15 if (is.null(cnum)) stop('cnum must be defined') if (!is.numeric(cnum)) stop('cnum must be numeric') tType<-which(testType==c('D-15', 'D-15DS', 'FM1OO-Hue', 'Roth28-Hue')) if (length(testType)==0) stop('testType must be "D-15", "D-15DS", "Roth28-Hue" or "FM1OO-Hue"') if (any(trunc(cnum)!=cnum)) stop('cnum must be integers') if (testType %in% c('D-15', 'D-15DS')) { if (length(cnum) != 15) stop('cnum must be a vector of 15 elements for D-15') if (!all(sort(cnum) == 1:15)) showDuplicated(cnum) if (!all(sort(cnum) == 1:15)) stop('cnum must be between 1 and 15, without repetition') } if (testType %in% c('Roth28-Hue')) { if (length(cnum) != 28) stop('cnum must be a vector of 28 elements for Roth28-Hue') if (!all(sort(cnum) == 1:28)) stop('cnum must be between 1 and 28, without repetition') } if (testType == 'FM1OO-Hue') { if (length(cnum) != 85) stop('cnum must be a vector of 85 elements for FM1OO-Hue') if (!all(sort(cnum) == 1:85)) stop('cnum must be between 1 and 85, without repetition') } #============================================= # For all models, initializing U and V vectors #============================================= if (any(is.na(dataVKS))) dataVKS<-list( standardD15=matrix(c(-23.26,-25.56, -22.41,-15.53, -23.11,-7.45,-22.45,1.10, -21.67,7.35, -14.08,18.74, -2.72,28.13, 14.84,31.13, 23.87,26.35,31.82,14.76, 31.42,6.99, 29.79,0.10,26.64,-9.38, 22.92,-18.65, 11.20,-24.61,-21.54, -38.39),16,2,byrow=T) , desaturatedD15=matrix(c(-8.63,-14.65, -12.08,-11.94, -12.86,-6.74,-12.26,-2.67, -11.18,2.01, -7.02,9.12, 1.30,15.78, 9.90,16.46, 15.03,12.05,15.48,2.56, 14.76,-2.24, 13.56,-5.04,11.06,-9.17, 8.95,-12.39, 5.62,-15.20,-4.77,-16.63),16,2,byrow=T) , FM100HUE=matrix(c(43.18,8.03, 44.37,11.34, 44.07,13.62, 44.95,16.04, 44.11,18.52, 42.92,20.64, 42.02,22.49, 42.28,25.15, 40.96,27.78, 37.68,29.55, 37.11,32.95, 35.41,35.94, 33.38,38.03, 30.88,39.59, 28.99,43.07, 25.00,44.12, 22.87,46.44, 18.86,45.87, 15.47,44.97, 13.01,42.12, 10.91,42.85, 8.49,41.35, 3.11,41.70, .68,39.23, -1.70,39.23, -4.14,36.66, -6.57,32.41, -8.53,33.19, -10.98,31.47, -15.07,27.89, -17.13,26.31, -19.39,23.82, -21.93,22.52, -23.40,20.14, -25.32,17.76, -25.10,13.29, -26.58,11.87, -27.35,9.52, -28.41,7.26, -29.54,5.10, -30.37,2.63, -31.07,0.10, -31.72,-2.42, -31.44,-5.13, -32.26,-8.16, -29.86,-9.51, -31.13,-10.59, -31.04,-14.30, -29.10,-17.32, -29.67,-19.59, -28.61,-22.65, -27.76,-26.66, -26.31,-29.24, -23.16,-31.24, -21.31,-32.92, -19.15,-33.17, -16.00,-34.90, -14.10,-35.21, -12.47,-35.84, -10.55,-37.74, -8.49,-34.78, -7.21,-35.44, -5.16,-37.08, -3.00,-35.95, -.31,-33.94, 1.55,-34.50, 3.68,-30.63, 5.88,-31.18, 8.46,-29.46, 9.75,-29.46, 12.24,-27.35, 15.61,-25.68, 19.63,-24.79, 21.20,-22.83, 25.60,-20.51, 26.94,-18.40, 29.39,-16.29, 32.93,-12.30, 34.96,-11.57, 38.24,-8.88, 39.06,-6.81, 39.51,-3.03, 40.90,-1.50, 42.80,0.60, 43.57,4.76,43.57,4.76),86,2,byrow=TRUE) , ROTH28=matrix(c(42.92,40.96,35.41,28.99,18.86,10.91,0.68,-6.57,-15.07, -21.93,-25.10,-28.41,-31.07,-32.26,-31.04,-28.61,-23.16,-16.00,-10.55,-5.16,1.55, 8.46,15.61,25.60,32.93,39.06,42.80,4.76,13.62,20.64,27.78,35.94,43.07,45.87,42.85, 39.23,32.41,27.89,22.52,13.29,7.26,0.10,-8.16,-14.30,-22.65,-31.24,-34.90,-37.74, -37.08,-34.50,-29.46,-25.68,-20.51,-12.30,-6.81,0.60,43.57,44.07),29,2,byrow=TRUE) ) #if (tType==3) cnum<-c(cnum[85],cnum) else cnum<-c(0,cnum) tSize<-c(15,15,85,28)[tType] #CALCULATE SUMS OF SQUARES AND CROSS PRODUCTS #REM COLOR DIFFERENCE VECTORS u <- (dataVKS[[tType]])[,1] v <- (dataVKS[[tType]])[,2] #u<-as.vector(uv[,1]);v<-as.vector(uv[,2]); num_errors=0; #------------------------------------------------------------- #INPUT CAP NUMBERS: REF = Cnum 16, so use actual cap #s: #This code contains "checks" to ensure no cap repeated/skipped #------------------------------------------------------------- cnum<-c(16,cnum) #========================================= #INSERTING VK-s '88 MODEL HERE: #========================================= # CALCULATE COLOR DIFFERENCE VECTORS: u2=0; v2=0; uv=0; d=0; testu<-vector(length=16);testv<-vector(length=16); testu[1]=u[16]; testv[1]=v[16]; #indexing test caps w/reference du=u[cnum[1]]-u[16]; dv=v[cnum[1]]-v[16]; u2=u2 + du*du; v2=v2 + dv*dv; uv=uv + du*dv; # initialize du_plot(16) and dv_plot(16) #---------------------------------------- du_plot<-as.numeric(vector(length=16)) dv_plot<-as.numeric(vector(length=16)) du_plot[1]=du;dv_plot[1]=dv; for (k in 1:15) { testu[k+1]=u[cnum[k+1]];testv[k+1]=v[cnum[k+1]]; du=u[cnum[k+1]]-u[cnum[k]]; du_plot[k+1]=du; dv=v[cnum[k+1]]-v[cnum[k]]; dv_plot[k+1]=dv; u2=u2 + du*du; v2=v2 + dv*dv; uv=uv + du*dv; d1 = d + u2 -v2; } # NEXT--CALCULATE MAJOR AND MINOR RADII AND ANGLE: d = u2-v2; if (d == 0) a0=0.7854 if (d != 0) #Y = atan(X) a0 = atan(2*uv/d)/2; #Major moment #------------ i0=u2*sin(a0)^2+v2*cos(a0)^2-2*uv*sin(a0)*cos(a0); if (a0 < 0) a1 = a0 + 1.5708 if (a0 >= 0) a1 = a0 - 1.5708; #Minor moment #------------ i1=u2*sin(a1)^2+v2*cos(a1)^2-2*uv*sin(a1)*cos(a1); #if minor axis larger, swap angles and minor/major axes: #------------------------------------------------------- if (i1 > i0) { p=a0; a0=a1; a1=p; p=i0; i0 = i1; i1 =p; } #Calculate total error and radii values #-------------------------------------- r0 = (i0/n)^0.5; #n is for 15 possible moments of d-15 r1 = (i1/n)^0.5; r = (r0^2 + r1^2)^0.5;# = TES in algorithm if (n == 15) r2 = 9.234669; # r2 value for standard D-15 c_index=r0/r2;s_index=r0/r1; c_index88=c_index;s_index88=s_index; ANGLE88=180*a1/pi; out88<-c(d,d1,u2,v2,uv,a0,a1,i0,i1,ANGLE88,c_index,s_index,r2) #arr_plot<-plot(testu,testv,type="l",xlim=c(-40,40),ylim=c(-40,40)) #return(out88) # ========================================= # END OF VK-S '88 MODEL #========================================== # NEXT--REINITIALIZE COLOR DIFFERENCE VECTORS: #--------------------------------------------- # ============================================================================= # Now, insert LSA '05 Model HERE # LSA '05 model calculates a best fit line (with y [or dV-]intercept based on: # dV = m*dU + b # The residuals "blow up" if angle is >45 degrees, so this code (and the model) # requires recalculation based on: dU = m* dV + b, if angle is >45 degrees # Publishes as AAO abstract in 2005 (Foutch & Bassi, OVS, eAbstract, 12/05) #=============================================================================== #CALCULATE COLOR DIFFERENCE VECTORS: u2=0; v2=0; uv=0; d=0; testu<-vector(length=16);testv<-vector(length=16); testu[1]=u[16]; testv[1]=v[16]; #indexing test caps w/reference du=u[cnum[1]]-u[16]; dv=v[cnum[1]]-v[16]; u2=u2 + du*du; v2=v2 + dv*dv; uv=uv + du*dv; # initialize du_plot(16) and dv_plot(16) #---------------------------------------- du_plot<-as.numeric(vector(length=16)) dv_plot<-as.numeric(vector(length=16)) du_plot[1]=du;dv_plot[1]=dv; #du_vectors(1)=0.0;dv_vectors(1)=0.0; #du_vectors(2)=du;dv_vectors(2)=dv; mindu=0.0;mindv=0.0;maxdu=0.0;maxdv=0.0; k=0; num_errors = 0;mag_errors2 = 0; num_errors if (cnum[2] != 1) { num_errors = num_errors + 1; num_errors #num_errors du=u[cnum[2]]-u[16]; dv=v[cnum[2]]-v[16]; u2=u2 + du*du; v2=v2 + dv*dv; uv=uv + du*dv; mag=sqrt(abs(du)^2+abs(dv)^2); mag_errors2=mag_errors2+mag; if (du<mindu) mindu=du; end if (du>maxdu) maxdu=du; end if (dv<mindv) mindv=dv; end if (dv>maxdv) maxdv=dv; end } #...WORKS to THIS POINT!!!............. # initialize du_plot(16) and dv_plot(16) #---------------------------------------- du_plot[1]=du;dv_plot[1]=dv; testu[2]=u[cnum[2]];testv[2]=v[cnum[2]]; for (k in 2:15) { #(cnum(k+1)-cnum(k)) #testu[k+1]=u[cnum[k+1]];testv[k+1]=v[cnum[k+1]]; if (abs((cnum[k+1]-cnum[k])) > 1) { num_errors = num_errors + 1; #num_errors k num_errors du=u[cnum[k+1]]-u[cnum[k]]; if (du<mindu) mindu=du if (du>maxdu) maxdu=du du_plot[k]=du; dv=v[cnum[k+1]]-v[cnum[k]]; mag=sqrt(abs(du)^2+abs(dv)^2); mag_errors2=mag_errors2+mag; if (dv<mindv) mindv=dv if (dv>maxdv) maxdv=dv dv_plot[k]=dv; u2=u2 + du*du; v2=v2 + dv*dv; uv=uv + du*dv; } } # Initializing dU and dV vectors uvec<-as.numeric(vector(length=num_errors)) vvec<-as.numeric(vector(length=num_errors)) #dudv<-matrix(ncol=2,nrow=16) #dudv<-data.frame(dudv) #dudv<-cbind(du_plot,dv_plot) kk=0 for (i in 1:16) if(abs(du_plot[i])>0) { kk=kk+1 uvec[kk]<-du_plot[i] vvec[kk]<-dv_plot[i] } #err_plot<-scatterplot(uvec,vvec,xlim=c(-80,80),ylim=c(-80,80),smooth=FALSE) #------------------------------------ # LSA '05 Only works for n > 1 errors #------------------------------------ if (num_errors > 1) { testuv<-summary(lm(vvec~uvec)) testvu<-summary(lm(uvec~vvec)) ssvu<-testvu$res^2 ssuv<-testuv$res^2 ssuvvec<-testuv$res^2 ssvuvec<-testvu$res^2 ssuv=0 ssvu=0 for (i in 1:num_errors) { ssuv<-ssuv+ssuvvec[i] ssvu<-ssvu+ssvuvec[i] } vtv<-ssuv/(num_errors-2) LSA_angle<-as.numeric(testuv$coef[2,1]) LSA_angle<-atan(LSA_angle)*180/pi if(ssvu<ssuv) {#print("SWITCHED MODELS!!!!!!",file="") vtv<-ssvu/(num_errors-2) LSA_angle<-as.numeric(testvu$coef[2,1]) LSA_angle<- -(atan(LSA_angle)*180/pi+90) } if(LSA_angle>90) { LSA_angle<-180-LSA_angle } if(LSA_angle<(-90)) { LSA_angle<-180+LSA_angle } } #======================== # END LSA '05 Model HERE #======================== # # ============================================= # Now, insert JMO '11 Model HERE # JMO '11 model calculates a best fit line (without y [or dV-]intercept based on: # dV = m*dU (see paper in Journ Modern Optics, Foutch et al., 2011) # The residuals "blow up" if angle is >45 degrees, so this code (and the model) # requires recalculation based on: dU = m* dV, if angle is >45 degrees #================================================ # if (num_errors > 0) { testuv11<-summary(lm(vvec~0+uvec)) testvu11<-summary(lm(uvec~0+vvec)) ssvu11<-testvu11$res^2 ssuv11<-testuv11$res^2 ssuvvec11<-testuv11$res^2 ssvuvec11<-testvu11$res^2 ssuv11=0 ssvu11=0 for (i in 1:num_errors) { ssuv11<-ssuv11+ssuvvec11[i] ssvu11<-ssvu11+ssvuvec11[i] } LSA_angle11<-as.numeric(testuv11$coef[1,1]) LSA_angle11<-atan(LSA_angle11)*180/pi #== set JMO11 model equal to LSA05 magnitude==# mag11 = mag_errors2; vtv11<-ssuv11/(num_errors-1) if(ssvu11<ssuv11) {#print("SWITCHED MODELS!!!!!!",file="") vtv11<-ssvu11/(num_errors-1) LSA_angle11<-as.numeric(testvu11$coef[1,1]) LSA_angle11<- -(atan(LSA_angle11)*180/pi+90) } if(LSA_angle11>90) { LSA_angle11<-180-LSA_angle11 } if(LSA_angle11<(-90)) { LSA_angle11<-180+LSA_angle11 } } #======================== #End JMO '11 MODEL HERE #======================== #========== # VK-S 93 #========== #NEXT--CALCULATE MAJOR AND MINOR RADII AND ANGLE: d = u2-v2; #Y = atan(X) a0 = atan(2*uv/d)/2; if (d == 0) a0=0.7854; #Major moment #------------ i0=u2*sin(a0)^2+v2*cos(a0)^2-2*uv*sin(a0)*cos(a0); a1 = a0 - 1.5708; if (a0 < 0) a1 = a0 + 1.5708; #Minor moment #------------ i1=u2*sin(a1)^2+v2*cos(a1)^2-2*uv*sin(a1)*cos(a1); #if minor axis larger, swap angles and minor/major axes: #------------------------------------------------------- if (i1 > i0) { if (i1<0) i1=0 p=a0; a0=a1; a1=p; p=i0; i0 = i1; i1 =p; } #Calculate total error and radii values #-------------------------------------- r0 = sqrt(abs(i0/n)); #n is for 15 possible moments of d-15 r1 = sqrt(abs(i1/n)); r = sqrt(r0^2 + r1^2);# = TES in algorithm if (n == 15) r2 = 9.234669; #r2 value for standard D-15 c_index93=r0/r2; s_index93=(sqrt(r0^2-r1^2))/r2; ANGLE93=a1*180/pi; #============= # END VK-S 93 #============= #=========================================== # Populating vectors and matrices for output #=========================================== # VKS-88 output out88<-cbind(ANGLE88,c_index,s_index) out88 # VKS-93 output out93<-cbind(ANGLE93,c_index93,s_index93) out93 #if "no errors", "blanks" out LSA05 and JMO11 output if (num_errors == 0) { outLSA <- cbind("N/A","N/A","N/A") outJMO <- cbind("N/A","N/A","N/A") } #if only one error, "blanks" out LSA05 output if (num_errors == 1) { outLSA <- cbind("N/A","N/A","N/A") } # Calculates LSA '05 "modeled" output (see original paper) if (num_errors > 1) { outLSA<-cbind(LSA_angle,mag_errors2/83,18.47/sqrt(vtv)) } # ========================================================= # Calculates JMO '11 "modeled" output (see original paper); # Same calculations as LSA '05: # ----------------------------- # magnitude = magnitude / 83; # scatter = 18.47/sqrt(sp^2) if (num_errors > 0) { outJMO<-cbind(LSA_angle11,mag_errors2/83,18.47/sqrt(vtv11)); } #=========================================================== outmat<-matrix(nrow=4,ncol=3) outmat<-data.frame(outmat) names(outmat)<-c("ANGLE","MAGNITUDE","SCATTER") outmat[1,]<-outLSA if(num_errors>1) {outmat[1,]<-round(outLSA,2)} outmat[2,]<-outJMO if(num_errors>0) {outmat[2,]<-round(outJMO,2)} outmat[3,]<-round(out88,2) outmat[4,]<-round(out93,2) row.names(outmat)<-c("LSA05","JMO11","VKS88","VKS93") outmat } calculateTES<-function(fmData, Kinnear=FALSE) { # total error score (TES) using Farnsworth's or Kinnear's method # cap 1 = pilot x<-length(fmData) R<-rep(0,x) for (n in 1:x) R[ifelse(Kinnear,fmData[n],n)]<-ifelse(n==1,abs(fmData[n]-fmData[x]),abs(fmData[n]-fmData[n-1])) + ifelse(n==x,abs(fmData[n]-fmData[1]),abs(fmData[n]-fmData[n+1])) if (x>80) R[R>50]<-R[R>50]-83 R } scoreRoth28Graphic<-function(userR28colors=NULL,userR28values=NULL, titleGraphic="Roth-28 test results", okR28colors=NULL) {# plots the graphic to score the Roth-28 test by default, or a similar test by modifying titleGraphic and okR28colors Roth28<-get("Roth28", envir = environment()) cirC<-c(1050,1037,1000,941,862,767,661,550,439,333,238,159,100,63,50,63,100,159,238,333,439,550,661,767,862,941,1000,1037,1050,550,661,767,862,941,1000,1037,1050,1037,1000,941,862,767,661,550,439,333,238,159,100,63,50,63,100,159,238,333,439,550) cirC2<-c(1080,1067,1028,964,880,780,668,550,432,320,220,136,72,33,20,33,72,136,220,320,432,550,668,780,880,964,1028,1067,1080,550,668,780,880,964,1028,1067,1080,1067,1028,964,880,780,668,550,432,320,220,136,72,33,20,33,72,136,220,320,432,550) circPos<-matrix(c(cirC),ncol=2,byrow=F) NumPos<-matrix(c(cirC2),ncol=2,byrow=F) circPos<-circPos[-1,] NumPos<-NumPos[-1,] circPos<-circPos[c(18:28,1:17),] NumPos<-NumPos[c(18:28,1:17),] # if the user's input was in FM100 indices, convert to 1:28 range if (!is.null(userR28values)) if (is.numeric(userR28values)) if (any(userR28values>28)) userR28values<-userR28values %/% 3+1 if ((is.null(userR28colors)) & (is.null(userR28values))) stop('Input either the colors chosen by the user for the Roth-28 test or the position values') if (is.null(okR28colors)) { okR28colors<-sprintf('#%02x%02x%02x',Roth28[-1,'R'],Roth28[-1,'G'],Roth28[-1,'B']) } if (is.null(userR28colors)) { pos2<-userR28values } else { pos2<-c() for (n in 1:28) pos2<-c(pos2,which(userR28colors[n] == okR28colors)) } pos2<-29-pos2 lenBox<-1100 circPos2<-circPos[pos2,] symbols(circPos[,1], circPos[,2], circles =rep(5,28) , inches = FALSE, xlim = c(1,lenBox), ylim = c(lenBox,1), xaxt='n', yaxt='n', ann=FALSE) par(new=T) title(main =titleGraphic) par(new=T) plot(circPos2[,1], circPos2[,2], xlim = c(1,lenBox), ylim = c(lenBox,1),type='l', xaxt='n', yaxt='n', ann=FALSE) par(new=T) segments(200,200,964, 880 , lty=2,col='red') par(new=T) segments(320, 1028,780, 72 , lty=2,col='green') par(new=T) segments(320,72,780, 1000,lty=2,col='blue') par(new=T) numText<-seq(82,1,-3) text(NumPos[,1], NumPos[,2], c(numText)) par(new=T) text(664,235,"Tritan", srt=60) par(new=T) text(270,230,"Protan", srt=-40) par(new=T) text(420,200,"Deutan", srt=-60) } scoreD15Graphic<-function(userD15colors=NULL,userD15values=NULL, titleGraphic="Farnsworth dichotomous test (D-15) results", okD15colors=NULL) {# plots the graphic to score the Farnsworth dichotomous test (D-15) by default, or a similar test by modifying titleGraphic and okD15colors FarnsworthD15<-get("FarnsworthD15", envir = environment()) circPos<-matrix(c(22,125,44,82,76,50,118,28,150,28,193,28,246,50,278,92,289,167,278,230,246,263,204,284,172,284,118,274,86,252,44,209),ncol=2,byrow=TRUE) NumPos<-matrix(c(22,135,44,82-15,76,50-15,118,28-15,150,28-15,193,28-15,246,50-15,278+15,92,289+15,167,278+15,230,246,263+15,204,284+15,172,284+15,118,274+15,86,252+15,44,209+15),ncol=2,byrow=TRUE) if ((is.null(userD15colors)) & (is.null(userD15values))) stop('Input either the colors chosen by the user for the D-15 test or the position values') if (is.null(okD15colors)) { okD15colors<-sprintf('#%02x%02x%02x',FarnsworthD15[-1,'R'],FarnsworthD15[-1,'G'],FarnsworthD15[-1,'B'])#c('#3583B4', '#3B84A7', '#39859C', '#3B8690', '#3F8782', '#588473', '#6C8164', '#837B5D', '#907660', '#9E6E6F', '#9F6D7C', '#9C6D89', '#927099', '#8F6FA4','#8073B2') } if (is.null(userD15colors)) { pos2<-userD15values } else { pos2<-c() for (n in 1:15) pos2<-c(pos2,which(userD15colors[n] == okD15colors) ) } pos2<-c(1,pos2+1) circPos2<-circPos[pos2,] symbols(circPos[,1], circPos[,2], circles =rep(5,16) , inches = FALSE, xlim = c(1,300), ylim = c(300,1), xaxt='n', yaxt='n', ann=FALSE) par(new=T) title(main =titleGraphic) par(new=T) plot(circPos2[,1], circPos2[,2], xlim = c(1,300), ylim = c(300,1),type='l', xaxt='n', yaxt='n', ann=FALSE) par(new=T) lines(c(96,138),c(27,267),type = 'l', lty=2,col='red') par(new=T) lines(c(133,102),c(14,290),type = 'l', lty=2,col='green') par(new=T) lines(c(58,293),c(210,131),type = 'l', lty=2,col='blue') par(new=T) text(NumPos[,1], NumPos[,2], c('Reference',1:15)) par(new=T) text(195,145,"Tritan", srt=20) par(new=T) text(94,80,"P\nr\no\nt\na\nn") par(new=T) text(137,83,"D\ne\nu\nt\na\nn") } scoreD15TCDS<-function(userD15colors=NULL,userD15values=NULL, distTable=get("BowmanTCDS", envir = environment()), D15colors=get("FarnsworthD15", envir = environment())) {# Compute the Total Color Difference Score (TCDS) for the D-15 colors or for their positions # Bowman's (1982) Total Color Difference Score (TCDS) for congenitally defective observers on the D-15 with enlarged tests. # K.J. Bowman, A method for quantitative scoring of the Farnsworth Panel D-15, Acta Ophthalmologica, 60 (1982), pp. 907–916 # userD15colors RGB colors chosen by tester # userD15values position values chosen by tester # distTable a distance table, for example GellerTCDS for scoring D15d with Geller's method # D15colors contains the D15 colors in columns 'R', 'G' and 'B' if ((is.null(userD15colors)) & (is.null(userD15values))) stop('Input either the colors chosen by the user for the D-15 test or the position values') if (is.null(userD15colors)) { pos2<-userD15values } else { lColorsOK<-sprintf('#%02x%02x%02x',D15colors[-1,'R'],D15colors[-1,'G'],D15colors[-1,'B']) pos2<-c() for (n in 1:15) pos2<-c(pos2,which(userD15colors[n] == lColorsOK) ) } posRow<-c(1,pos2+1) posRow<-posRow[1:15] posColumn<- pos2+1 posValue<-c() posValueNormal<-c() for (n in 1:15) { posValue<-c(posValue,distTable[posRow[n],posColumn[n]]) posValueNormal<-c(posValueNormal,distTable[n+1,n]) } TCDS<-sum(posValue)# TCDS # Color Confusion Index (CCI = TCDSactual / TCDSnormal) CCI<-TCDS/sum(posValueNormal) c(TCDS=TCDS,CCI=CCI) } lightAdaptedPupilSize.Holladay<-function(L=NULL){ # pupil diameter ranges, formula "for a probable average healthy young eye" - Holladay, L. (1926) # L=luminance in cd m^-2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Holladay, L. (1926). The fundamentals of glare and visibility. Journal of the Optical Society of America, 12(4), 271–319. if (is.null(L)) stop('Please enter the luminance in candels per square meter (cd m^-2)') if (is.na(L)) stop('Please enter a numeric value for the luminance') if (!is.numeric(L)) stop('Please enter a numeric value for the luminance') return(7*exp(-0.1007*L^0.4)) } lightAdaptedPupilSize.Crawford<-function(L=NULL){ # pupil diameter ranges - Crawford 1936 # L=luminance in cd m^-2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Crawford, B. H. (1936). The dependence of pupil size upon external light stimulus under static and variable conditions. Proceedings of the Royal # Society of London, Series B, Biological Sciences, 121(823), 376–395. 5-2.2*tanh(0.61151+0.447*log(L)) } lightAdaptedPupilSize.MoonAndSpencer<-function(L=NULL){ # pupil diameter ranges Moon and Spencer 1944 # L=luminance in cd m^-2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Moon, P., & Spencer, D. E. (1944). On the Stiles-Crawford effect. Journal of the Optical Society of # America, 34(6), 319–329, http://www.opticsinfobase. org/abstract.cfm?URI1⁄4josa-34-6-319. 4.9-3*tanh(0.4*log(L)-0.00114) } lightAdaptedPupilSize.DeGrootAndGebhard<-function(L=NULL){ # pupil diameter ranges De Groot and Gebhard 1952 # L=luminance in cd m^-2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # De Groot, S. G., & Gebhard, J. W. (1952). Pupil size as determined by adapting luminance. Journal of the Optical Society of America A, 42(7), 492–495. 7.175*exp(-0.00092*(7.597+log(L))^3) } lightAdaptedPupilSize.LeGrand<-function(L=NULL){ # pupil diameter ranges Le Grand 1992 # L=luminance in cd m^-2 # Vision, Pierre A. Buser, Michel Imbert, MIT Press, 1992 5 - 3 * tanh(0.4 * log10(L)) } lightAdaptedPupilSize.StanleyAndDavies<-function(L=NULL, a=NULL){ # pupil diameter ranges Stanley and Davies 1995 # L=luminance in cd m^-2, a = area in deg^2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Stanley, P. A., & Davies, A. K. (1995). The effect of field of view size on steady-state pupil diameter. Ophthalmic & Physiological Optics, 15(6), 601–603. 7.75 - 5.75*((L*a/846)^0.41/((L*a/846)^0.41+2)) } lightAdaptedPupilSize.Barten<-function(L=NULL, a=NULL){ # pupil diameter ranges Barten 1999 # L=luminance in cd m^-2, a = area in deg^2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Barten, P. G. J. (1999). Contrast sensitivity of the human eye and its effects on image quality. Bellingham, WA: SPIE Optical Engineering Press. 5-3*tanh(0.4*log(L*a/40^2)) } lightAdaptedPupilSize.BlackieAndHowland<-function(L=NULL){ # pupil diameter ranges Blackie and Howland 1999 # L=luminance in cd m^-2 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Blackie, C. A., & Howland, H. C. (1999). An extension of an accommodation and convergence model of emmetropization to include the effects of illumination intensity. Ophthalmic and Physiological Optics, 19(2), 112–125. 5.697 - 0.658* log(L) + 0.07*(log(L))^2 } lightAdaptedPupilSize.WinnEtAl<-function(L=NULL, y=NULL){ # pupil diameter ranges Winn, Whitaker, Elliott, and Phillips 1994 # L=luminance in cd m^-2, age y in years # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. # Winn, B., Whitaker, D., Elliott, D. B., & Phillips, N. J. (1994). Factors affecting light-adapted pupil size in # normal human subjects. Investigative Ophthalmology & Visual Science, 35(3):1132–1137, http://www.iovs.org/content/35/3/1132. s <- c( -0.024501, -0.0368073, 0.0210892, 0.00281557) b <- c( 6.9039, 2.7765, -1.909, 0.25599) (sum(s* (log(min(4400,max(9,L))))^(0:3) ))*y+sum(b* (log(min(4400,max(9,L))))^(0:3) ) } attenuationNumberOfEyes<-function(e) ifelse(e==1,0.1,ifelse(e==2,1,0)) # attenuation as a function M(e) of number of eyes e (1 or 2) # M(1) = 0.1, M(2) = 1, otherwise 0 # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. effectiveCornealFluxDensity<-function(L=NULL,a=NULL,e=NULL){ # effective Corneal Flux Density = product of luminance, area, and the monocular effect, F = Lae # L=luminance, a = field area in deg^2, e = number of eyes (1 or 2) # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. L*a*attenuationNumberOfEyes(e) } lightAdaptedPupilSize.WatsonAndYellott<-function(L=NULL, a=NULL, y=NULL, y0=NULL, e=NULL){ # pupil diameter ranges Watson & Yellott 2012 # L=luminance in cd m^-2, a = field area in deg^2, y = age in years, y0 = reference age, e = number of eyes (1 or 2) # Watson A. B., Yellott J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10):12, 1–16. http://journalofvision.org/12/10/12/, doi:10.1167/5.9.6. F <- effectiveCornealFluxDensity(L,a,e) Dsd <- lightAdaptedPupilSize.StanleyAndDavies(F,1) Dsd+(y-y0)*(0.02132 - 0.009562*Dsd) } greyscale.avg<-function(colorArray){# average RGB values - grayscale algorithm if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,mean) else p3<-apply(colorArray,1:2,mean) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } greyscale.Y<-function(colorArray){# YIQ/NTSC - RGB colors in a gamma 2.2 color space - grayscale algorithm colorArray[,,1]<-colorArray[,,1]*0.299 colorArray[,,2]<-colorArray[,,2]*0.587 colorArray[,,3]<-colorArray[,,3]*0.114 if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,sum) else p3<-apply(colorArray,1:2,sum) #p3<-colorArray #if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,sum) else p3<-apply(colorArray,1:2,sum) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } greyscale.Linear<-function(colorArray){# linear RGB colors - grayscale algorithm colorArray[,,1]<-colorArray[,,1]*0.3086 colorArray[,,2]<-colorArray[,,2]*0.6094 colorArray[,,3]<-colorArray[,,3]*0.0820 if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,sum) else p3<-apply(colorArray,1:2,sum) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } greyscale.RMY<-function(colorArray){# RMY - grayscale algorithm colorArray[,,1]<-colorArray[,,1]*0.5 colorArray[,,2]<-colorArray[,,2]*0.419 colorArray[,,3]<-colorArray[,,3]*0.081 if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,sum) else p3<-apply(colorArray,1:2,sum) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } greyscale.BT709<-function(colorArray){# BT709 - grayscale algorithm colorArray[,,1]<-colorArray[,,1]*0.2125 colorArray[,,2]<-colorArray[,,2]*0.7154 colorArray[,,3]<-colorArray[,,3]*0.0721 if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,sum) else p3<-apply(colorArray,1:2,sum) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } greyscale.Luminosity<-function(colorArray){# Luminosity - grayscale algorithm if (dim(colorArray)[3]>3) p3<-apply(colorArray[,,-4],1:2,function(x) (max(x)+min(x))/2) else p3<-apply(colorArray,1:2,function(x) (max(x)+min(x))/2) p3<-array(p3,dim(colorArray)) if (dim(colorArray)[3]>3) p3[,,4]<-colorArray[,,4] p3 } RGBtoHSL<-function(R,G,B){ # RGB to HSL function to assist Color.Vision.c2g R2 = R/255 G2 = G/255 B2 = B/255 if (length(R)==1 & length(G)==1 & length(B)==1){ Cmax = max(R2, G2, B2) Cmin = min(R2, G2, B2) D = Cmax - Cmin if (Cmax==R2) H<-60*(((G2-B2)/D) %% 6) if (Cmax==G2) H<-60*((B2-R2)/D+2) if (Cmax==B2) H<-60*((R2-G2)/D+4) L<-(Cmax+Cmin)/2 if (D==0) S<-0 else S<-D/(1-abs(2*L-1)) } else { Tmp<-cbind(R2,G2,B2) Cmax = apply(Tmp,1,max) Cmin = apply(Tmp,1,min) D = Cmax - Cmin H<-S<-rep(0,length(R)) w<-which(Cmax==R2) H[w]<-60*(((G2[w]-B2[w])/D[w]) %% 6) w<-which(Cmax==G2) H[w]<-60*((B2[w]-R2[w])/D[w]+2) w<-which(Cmax==B2) H[w]<-60*((R2[w]-G2[w])/D[w]+4) L<-(Cmax+Cmin)/2 w<-which(D!=0) S[w]<-D[w]/(1-abs(2*L[w]-1)) } list(H=H,S=S,L=L) } Color.Vision.c2g<-function(fileIN=NULL, fileOUT=NULL, CorrectBrightness=FALSE){ #Color Image to Grayscale Conversion #Original work by Martin Faust 2008 #http://www.e56.de/c2g.php #Translated to R by Jose Gama 2013 #fileIN='ars_puzzlefighter_normal_vision.png'; fileOUT='ars_puzzlefighter_c2g.png';CorrectBrightness=FALSE if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist' ) if (is.null(fileOUT)) stop('A file output must be defined') if (is.null(CorrectBrightness)) stop('CorrectBrightness must be defined') if (!is.logical(CorrectBrightness)) stop('CorrectBrightness must be logical') p<-png::readPNG(fileIN) p<-p*255 r<-c(p[,,1]) g<-c(p[,,2]) b<-c(p[,,3]) grayMat<-rep(0,length(r)) h2<-RGBtoHSL(r,g,b) HSVmat<-rbind(h=h2$H,s=h2$S,l=h2$L) wSat0<-which(HSVmat['s',] == 0.0) grayMat[wSat0] = 1.5 * HSVmat['l',wSat0] if (length(wSat0)==0) grayMat = HSVmat['l',] + HSVmat['l',] * HSVmat['s',] else grayMat[-wSat0] = HSVmat['l',-wSat0] + HSVmat['l',-wSat0] * HSVmat['s',-wSat0] minC = min(grayMat) maxC = max(grayMat) meanC = mean(grayMat) cat('Grey values: min',minC,', mean',meanC,', max',maxC) minC = 0.0; maxC = (meanC + maxC) * 0.5 if (CorrectBrightness){ HSVmat['l',] <- 0.9 * (grayMat - minC) / (maxC - minC) } else { HSVmat['l',] <- (grayMat - minC) / (maxC - minC) } HSVmat['l',which(HSVmat['l',] > 1.0)] <- 1.0 HSVmat['l',which(HSVmat['l',] < 0.0)] <- 0.0 p2<-HSVmat['l',] p3<-p[,,-4] p3[,,1]<-array(t(p2),dim(p)[1:2]) p3[,,2]<-p3[,,1] p3[,,3]<-p3[,,1] png::writePNG(p3, fileOUT) } Color.Vision.Daltonize<-function(fileIN=NULL, fileOUT=NULL, myoptions=NULL, amount=1.0){ # converts images so that the most problematic colors are more visible to people with CVD # Based on: # Michael Deal Daltonize.org http://mudcu.be/labs/Color/Vision http://www.daltonize.org/p/about.html #"Analysis of Color Blindness" by Onur Fidaner, Poliang Lin and Nevran Ozguven. #http://scien.stanford.edu/class/psych221/projects/05/ofidaner/project_report.pdf #"Digital Video Colourmaps for Checking the Legibility of Displays by Dichromats" by Francoise Vienot, Hans Brettel and John D. Mollon #http://vision.psychol.cam.ac.uk/jdmollon/papers/colourmaps.pdf if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist' ) if (is.null(fileOUT)) stop('A file output must be defined') if (is.null(myoptions)) stop('Options must be defined') if ((amount>1.0)|(amount<0.0)) stop('Amount must be between 0.0 and 1.0') if (!is.character(myoptions)) stop('Options must be "Protanope","Deuteranope" or "Tritanope"') if (!(myoptions %in% c("Protanope","Deuteranope", "Tritanope"))) stop('Wrong option, must be: Protanope, Deuteranope or Tritanope.') CVDMatrix <- array(c(0.000000,0.000000,0.000000,2.023440,1.000000,0.000000,-2.525810, 0.000000,1.000000,1.000000,0.494207,0.000000,0.000000,0.000000, 0.000000,0.000000,1.248270,1.000000,1.000000,0.000000,-0.395913, 0.000000,1.000000,0.801109,0.000000,0.000000,0.000000),c(3,3,3)) #Protanope, Deuteranope, Tritanope p<-png::readPNG(fileIN) r<-p[,,1] g<-p[,,2] b<-p[,,3] x<-which(c("Protanope","Deuteranope", "Tritanope")==myoptions) cvd_a = CVDMatrix[1,1,x] cvd_b = CVDMatrix[1,2,x] cvd_c = CVDMatrix[1,3,x] cvd_d = CVDMatrix[2,1,x] cvd_e = CVDMatrix[2,2,x] cvd_f = CVDMatrix[2,3,x] cvd_g = CVDMatrix[3,1,x] cvd_h = CVDMatrix[3,2,x] cvd_i = CVDMatrix[3,3,x] L = (17.8824 * r) + (43.5161 * g) + (4.11935 * b) M = (3.45565 * r) + (27.1554 * g) + (3.86714 * b) S = (0.0299566 * r) + (0.184309 * g) + (1.46709 * b) l = (cvd_a * L) + (cvd_b * M) + (cvd_c * S) m = (cvd_d * L) + (cvd_e * M) + (cvd_f * S) s = (cvd_g * L) + (cvd_h * M) + (cvd_i * S) R = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s) G = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s) B = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s) R = r - R G = g - G B = b - B RR = (0.0 * R) + (0.0 * G) + (0.0 * B) GG = (0.7 * R) + (1.0 * G) + (0.0 * B) BB = (0.7 * R) + (0.0 * G) + (1.0 * B) R = RR + r G = GG + g B = BB + b # Return values R[which(R>1.0)]<-1.0 R[which(R<0.0)]<-0.0 G[which(G>1.0)]<-1.0 G[which(G<0.0)]<-0.0 B[which(B>1.0)]<-1.0 B[which(B<0.0)]<-0.0 p[,,1]<-R p[,,2]<-G p[,,3]<-B png::writePNG(p, fileOUT) } Color.Vision.Simulate<-function(fileIN=NULL, fileOUT=NULL, myoptions=NULL, amount=1.0){ # converts images so that the colors look similar to how they are seen by people with CVD # Based on: # Michael Deal Daltonize.org http://mudcu.be/labs/Color/Vision http://www.daltonize.org/p/about.html #"Analysis of Color Blindness" by Onur Fidaner, Poliang Lin and Nevran Ozguven. #http://scien.stanford.edu/class/psych221/projects/05/ofidaner/project_report.pdf #"Digital Video Colourmaps for Checking the Legibility of Displays by Dichromats" by Francoise Vienot, Hans Brettel and John D. Mollon #http://vision.psychol.cam.ac.uk/jdmollon/papers/colourmaps.pdf if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist' ) if (is.null(fileOUT)) stop('A file output must be defined') if (is.null(myoptions)) stop('Options must be defined') if ((amount>1.0)|(amount<0.0)) stop('Amount must be between 0.0 and 1.0') ConfusionLines <- data.frame(name=c("Protanope","Deuteranope","Tritanope","Achromatope"),x=c(0.7465,1.4,0.1748,0), y=c(0.2535,-0.4,0.0,0), m=c(1.273463,0.968437,0.062921,0), yint=c(-0.073894,0.003331,0.292119,0)) if (is.character(myoptions)) if (!(myoptions %in% as.vector(ConfusionLines[["name"]]))) stop('Wrong option, must be: Protanope, Deuteranope, Tritanope or Achromatope.') #library('png', character.only=TRUE) if (is.character(myoptions)) { if (myoptions %in% as.vector(ConfusionLines[["name"]])) { if (myoptions=="Achromatope") { p<-png::readPNG(fileIN) numrows<-dim(p)[1] numcols<-dim(p)[2] p0=0.212656*p[,,1] + 0.715158*p[,,2] + 0.072186*p[,,3] p0=p0*amount a0<-1.0 - amount p[,,1]<-p[,,1] * a0 + p0 p[,,2]<-p[,,2] * a0 + p0 p[,,3]<-p[,,3] * a0 + p0 png::writePNG(p, fileOUT) return() } if (myoptions %in% as.vector(ConfusionLines[["name"]])) { tmp<-ConfusionLines[which(ConfusionLines[["name"]]==myoptions),] confuse_x<-tmp[["x"]] confuse_y<-tmp[["y"]] confuse_m<-tmp[["m"]] confuse_yint<-tmp[["yint"]] opName<-myoptions } } } else { if (!is.numeric(myoptions)) stop('Options must be "Protanope","Deuteranope","Tritanope","Achromatope" or a numeric vector with 4 custom parameters for the confusion lines') if (is.numeric(myoptions)) if(length(myoptions)!=4) stop('Options must be a numeric vector with 4 parameters') if (is.numeric(myoptions)) if(length(myoptions)==4) { confuse_x<-myoptions[1];confuse_y<-myoptions[2];confuse_m<-myoptions[3];confuse_yint<-myoptions[4];opName<-'Custom' } } #Simulate: Protanope, Deuteranope, or Tritanope p<-png::readPNG(fileIN) sr<-p[,,1] sg<-p[,,2] sb<-p[,,3] dr = sr # destination-pixel dg = sg db = sb # Convert source color into XYZ color space pow_r = sr^2.2 pow_g = sg^2.2 pow_b = sb^2.2 X = pow_r * 0.412424 + pow_g * 0.357579 + pow_b * 0.180464 # RGB->XYZ (sRGB:D65) Y = pow_r * 0.212656 + pow_g * 0.715158 + pow_b * 0.0721856 Z = pow_r * 0.0193324 + pow_g * 0.119193 + pow_b * 0.950444 # Convert XYZ into xyY Chromacity Coordinates (xy) and Luminance (Y) chroma_x = X / (X + Y + Z) chroma_y = Y / (X + Y + Z) chroma_x[which(is.na(chroma_x))]<-0#X[which(is.na(chroma_x))] chroma_y[which(is.na(chroma_y))]<-0#Y[which(is.na(chroma_y))] # Generate the “Confusion Line" between the source color and the Confusion Point m = (chroma_y - confuse_y) / (chroma_x - confuse_x) # slope of Confusion Line yint = chroma_y - chroma_x * m # y-intercept of confusion line (x-intercept = 0.0) # How far the xy coords deviate from the simulation deviate_x = (confuse_yint - yint) / (m - confuse_m) deviate_y = (m * deviate_x) + yint # Compute the simulated color’s XYZ coords X = deviate_x * Y / deviate_y Z = (1.0 - (deviate_x + deviate_y)) * Y / deviate_y # Neutral grey calculated from luminance (in D65) neutral_X = 0.312713 * Y / 0.329016 neutral_Z = 0.358271 * Y / 0.329016 # Difference between simulated color and neutral grey diff_X = neutral_X - X diff_Z = neutral_Z - Z diff_r = diff_X * 3.24071 + diff_Z * -0.498571 # XYZ->RGB (sRGB:D65) diff_g = diff_X * -0.969258 + diff_Z * 0.0415557 diff_b = diff_X * 0.0556352 + diff_Z * 1.05707 # Convert to RGB color space dr = X * 3.24071 + Y * -1.53726 + Z * -0.498571 # XYZ->RGB (sRGB:D65) dg = X * -0.969258 + Y * 1.87599 + Z * 0.0415557 db = X * 0.0556352 + Y * -0.203996 + Z * 1.05707 # Compensate simulated color towards a neutral fit in RGB space fit_r2 = (ifelse(dr < 0.0, 0.0,1.0) - dr) / diff_r fit_g2 = (ifelse(dg < 0.0,0.0,1.0) - dg) / diff_g fit_b2 = (ifelse(db < 0.0,0.0,1.0) - db) / diff_b fit_r=fit_r2 fit_g=fit_g2 fit_b=fit_b2 fit_r[which(is.infinite(fit_r2))]<-(ifelse(dr[which(is.infinite(fit_r2))] < 0.0, 0.0,1.0) - dr[which(is.infinite(fit_r2))]) fit_g[which(is.infinite(fit_g2))]<-(ifelse(dg[which(is.infinite(fit_g2))] < 0.0, 0.0,1.0) - dg[which(is.infinite(fit_g2))]) fit_b[which(is.infinite(fit_b2))]<-(ifelse(db[which(is.infinite(fit_b2))] < 0.0, 0.0,1.0) - db[which(is.infinite(fit_b2))]) fit_r2 = fit_r fit_g2 = fit_g fit_b2 = fit_b fit_r2[which((fit_r > 1.0) | (fit_r < 0.0))]<-0.0 fit_g2[which((fit_g > 1.0) | (fit_g < 0.0))]<-0.0 fit_b2[which((fit_b > 1.0) | (fit_b < 0.0))]<-0.0 # highest value adjust2 = fit_r2 - fit_g2 w<-which(adjust2<0) adjust2[w]<-fit_g2[w] adjust2[-w]<-fit_r2[-w] adjust = adjust2 - fit_b2 w<-which(adjust<0) adjust[w]<-fit_b2[w] adjust[-w]<-adjust2[-w] # Shift proportional to the greatest shift dr = dr + (adjust * diff_r) dg = dg + (adjust * diff_g) db = db + (adjust * diff_b) # Apply gamma correction dr = dr^(1.0 / 2.2) dg = dg^(1.0 / 2.2) db = db^(1.0 / 2.2) # Anomylize colors dr = sr * (1.0 - amount) + dr * amount dg = sg * (1.0 - amount) + dg * amount db = sb * (1.0 - amount) + db * amount # Return values dr[which(dr>1.0)]<-1.0 dr[which(dr<0.0)]<-0.0 dg[which(dg>1.0)]<-1.0 dg[which(dg<0.0)]<-0.0 db[which(db>1.0)]<-1.0 db[which(db<0.0)]<-0.0 p[,,1]<-(dr) p[,,2]<-(dg) p[,,3]<-(db) png::writePNG(p, fileOUT) } Color.Vision.VingrysAndKingSmith <-function(capnumbers=NULL,testType='D-15',silent=TRUE){ #method of scoring the results of the "D-15", "D-15DS", "Roth28-Hue" or "FM1OO-Hue" tests #translated to R by Jose Gama 2013 #Implementation of the Vingrys and King-Smith method (1988) #Vingrys, A.J. and King-Smith, P.E. (1988). #A quantitative scoring technique for panel tests of color vision. #Investigative Ophthalmology and Visual Science, 29, 50-63. # added "Roth28-Hue" test if (is.null(capnumbers)) stop('capnumbers must be defined') if (!is.numeric(capnumbers)) stop('capnumbers must be numeric') tType<-which(testType==c('D-15', 'D-15DS', 'FM1OO-Hue', "Roth28-Hue")) if (length(testType)==0) stop('testType must be "D-15", "D-15DS", "Roth28-Hue" or "FM1OO-Hue"') if (any(trunc(capnumbers)!=capnumbers)) stop('capnumbers must be integers') if (testType %in% c('D-15', 'D-15DS')) { if (length(capnumbers) != 15) stop('capnumbers must be a vector of 15 elements for D-15') if (!all(sort(capnumbers) == 1:15)) stop('capnumbers must be between 1 and 15, without repetition') } if (testType %in% c('Roth28-Hue')) { if (length(capnumbers) != 28) stop('capnumbers must be a vector of 28 elements for Roth28-Hue') if (!all(sort(capnumbers) == 1:28)) stop('capnumbers must be between 1 and 28, without repetition') } if (testType == 'FM1OO-Hue') { if (length(capnumbers) != 85) stop('capnumbers must be a vector of 85 elements for FM1OO-Hue') if (!all(sort(capnumbers) == 1:85)) stop('capnumbers must be between 1 and 85, without repetition') } dataVKS<-list( standardD15=matrix(c(-21.54, -38.39,-23.26,-25.56, -22.41,-15.53, -23.11,-7.45,-22.45,1.10, -21.67,7.35, -14.08,18.74, -2.72,28.13, 14.84,31.13, 23.87,26.35,31.82,14.76, 31.42,6.99, 29.79,0.10,26.64,-9.38, 22.92,-18.65, 11.20,-24.61),16,2,byrow=T) , desaturatedD15=matrix(c(-4.77,-16.63,-8.63,-14.65, -12.08,-11.94, -12.86,-6.74,-12.26,-2.67, -11.18,2.01, -7.02,9.12, 1.30,15.78, 9.90,16.46, 15.03,12.05,15.48,2.56, 14.76,-2.24, 13.56,-5.04,11.06,-9.17, 8.95,-12.39, 5.62,-15.20),16,2,byrow=T) , FM100HUE=matrix(c(43.57,4.76,43.18,8.03, 44.37,11.34, 44.07,13.62, 44.95,16.04, 44.11,18.52, 42.92,20.64, 42.02,22.49, 42.28,25.15, 40.96,27.78, 37.68,29.55, 37.11,32.95, 35.41,35.94, 33.38,38.03, 30.88,39.59, 28.99,43.07, 25.00,44.12, 22.87,46.44, 18.86,45.87, 15.47,44.97, 13.01,42.12, 10.91,42.85, 8.49,41.35, 3.11,41.70, .68,39.23, -1.70,39.23, -4.14,36.66, -6.57,32.41, -8.53,33.19, -10.98,31.47, -15.07,27.89, -17.13,26.31, -19.39,23.82, -21.93,22.52, -23.40,20.14, -25.32,17.76, -25.10,13.29, -26.58,11.87, -27.35,9.52, -28.41,7.26, -29.54,5.10, -30.37,2.63, -31.07,0.10, -31.72,-2.42, -31.44,-5.13, -32.26,-8.16, -29.86,-9.51, -31.13,-10.59, -31.04,-14.30, -29.10,-17.32, -29.67,-19.59, -28.61,-22.65, -27.76,-26.66, -26.31,-29.24, -23.16,-31.24, -21.31,-32.92, -19.15,-33.17, -16.00,-34.90, -14.10,-35.21, -12.47,-35.84, -10.55,-37.74, -8.49,-34.78, -7.21,-35.44, -5.16,-37.08, -3.00,-35.95, -.31,-33.94, 1.55,-34.50, 3.68,-30.63, 5.88,-31.18, 8.46,-29.46, 9.75,-29.46, 12.24,-27.35, 15.61,-25.68, 19.63,-24.79, 21.20,-22.83, 25.60,-20.51, 26.94,-18.40, 29.39,-16.29, 32.93,-12.30, 34.96,-11.57, 38.24,-8.88, 39.06,-6.81, 39.51,-3.03, 40.90,-1.50, 42.80,0.60, 43.57,4.76),86,2,byrow=TRUE) , ROTH28=matrix(c(43.57,44.07,42.92,40.96,35.41,28.99,18.86,10.91,0.68,-6.57,-15.07,-21.93,-25.10,-28.41,-31.07,-32.26,-31.04,-28.61,-23.16,-16.00,-10.55,-5.16,1.55,8.46,15.61,25.60,32.93,39.06,42.80,4.76,13.62,20.64,27.78,35.94,43.07,45.87,42.85,39.23,32.41,27.89,22.52,13.29,7.26,0.10,-8.16,-14.30,-22.65,-31.24,-34.90,-37.74,-37.08,-34.50,-29.46,-25.68,-20.51,-12.30,-6.81,0.60),29,2,byrow=TRUE) ) if (!silent) print("SUMS OF U AND V") if (!silent) cat(sum(dataVKS[[tType]][,1]),sum(dataVKS[[tType]][,2]),'\n') #CHOOSE FIRST CAP NUMBER if (tType==3) capnumbers<-c(capnumbers[85],capnumbers) else capnumbers<-c(0,capnumbers) tSize<-c(16,16,86,29)[tType] #CALCULATE SUMS OF SQUARES AND CROSS PRODUCTS #REM COLOR DIFFERENCE VECTORS DU = dataVKS[[tType]][capnumbers[2:(tSize)]+1,1]-dataVKS[[tType]][capnumbers[1:(tSize-1)]+1,1] DV = dataVKS[[tType]][capnumbers[2:(tSize)]+1,2]-dataVKS[[tType]][capnumbers[1:(tSize-1)]+1,2] U2 = sum(DU^2) V2 = sum(DV^2) UV = sum(DU * DV) # CALCULATE MAJOR AND MINOR RADII AND ANGLE D = U2 - V2 #ANGLE if (D == 0) A0 = 0.7854 else A0 = atan(2 * UV / D) / 2 #MAJOR MOMENT I0 = U2 * sin(A0)^2 + V2 * cos(A0)^2 - 2 * UV * sin(A0) * cos(A0) #PERPENDICULAR ANGLE if (A0 < 0) A1 = A0 + 1.5708 else A1 = A0 - 1.5708 #MINOR MOMENT I1 = U2 * sin(A1)^2 + V2 * cos(A1)^2 - 2 * UV * sin(A1) * cos(A1) #CHECK THAT MAJOR MOMENT GREATER THAN MINOR if (!(I0 > I1)) { #SWAP ANGLES & MOMENTS P = A0 A0 = A1 A1 = P P = I0 I0 = I1 I1 = P } #RADII & TOTAL ERROR R0 = sqrt(I0 / (tSize-1)) R1 = sqrt(I1 / (tSize-1)) R = sqrt(R0^2 + R1^2) if (tType == 1) { R2 = 9.234669; if (!silent) print ("STANDARD D-15")} if (tType == 2) { R2 = 5.121259; if (!silent) print ("DESATURATED D-15")} if (tType == 3) { R2 = 2.525249; if (!silent) print ("FM-100 HUE")} if (tType == 4) { R2 = 2.525249; if (!silent) print ("Roth-28 HUE")} if (!silent) cat ("ANGLE\tMAJ RAD\tMIN RAD\tTOT ERR\tS-INDEX\tC-INDEX\n") if (!silent) cat('\t',57.3 * A1,'\t', R0,'\t', R1,'\t', R,'\t', R0 / R1,'\t', R0 / R2) list(Angle=57.3 * A1,MajRad=R0,MinRad=R1,TotErr=R,Sindex=R0 / R1,Cindex=R0 / R2) } decolorize<-function(fileIN=NULL,effect=0.5,scale=NULL,noise=0.001,recolor=FALSE){ #Color Image to Grayscale Conversion #Original work by Mark Grundland and Neil A. Dodgson # Mark Grundland and Neil A. Dodgson, "Decolorize: Fast, Contrast Enhancing, Color to Grayscale Conversion", # Pattern Recognition, vol. 40, no. 11, pp. 2891-2896, (2007). # http://www.Eyemaginary.com/Portfolio/Publications.html if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist') p<-png::readPNG(fileIN) p<-p*255 frameP<-dim(p)[1:2] pixelsP<-prod(frameP) if (is.null(scale)) scale<-sqrt(2*min(frameP)) tolerance=100 * .Machine$double.eps#2^(-52) # Define the YPQ color space colorconvert<-matrix(c(0.2989360212937753847527155, 0.5870430744511212909351327, 0.1140209042551033243121518, 0.5, 0.5, -1, 1, -1, 0),3,3,byrow=F) colorrevert<-matrix(c(1, 0.1140209042551033243121518, 0.6440535265786729530912086, 1, 0.1140209042551033243121518, -0.3559464734213270469087914, 1, -0.8859790957448966756878482, 0.1440535265786729530912086),3,3,byrow=F) colorspan<-matrix(c(0, 1, -1, 1, -1, 1),3,2,byrow=F) maxluminance=1.0 scaleluminance=0.66856793424088827189 maxsaturation=1.1180339887498948482 alterP=effect*(maxluminance/maxsaturation) # Convert picture to the YPQ color space p2=array(p,c(pixelsP,3)) imageP=p2 %*% colorconvert originalP=imageP chromaP=sqrt(imageP[,2] * imageP[,2] + imageP[,3] * imageP[,3]) # Pair each pixel with a randomly chosen sample site meshP=cbind(rep(1:frameP[1],frameP[2]),rep(1:frameP[2],each=frameP[1])) displaceP=(scale * sqrt(2/pi)) * matrix(rnorm(pixelsP*2),pixelsP,2)# lookP=round(meshP+displaceP) redoP=which((lookP[,1]<1)) lookP[redoP,1]=2-sign(lookP[redoP,1])*(lookP[redoP,1] %% (frameP[1]-1))# redoP=which((lookP[,2]<2)) lookP[redoP,2]=2-sign(lookP[redoP,2])*(lookP[redoP,2] %% (frameP[2]-1))# redoP=which((lookP[,1]>frameP[1])) lookP[redoP,1]=frameP[1]-1-sign(lookP[redoP,1])*((lookP[redoP,1]-2) %% (frameP[1]-1))# redoP=which((lookP[,2]>frameP[2])) lookP[redoP,2]=frameP[2]-1-sign(lookP[redoP,2])*((lookP[redoP,2]-2) %% (frameP[2]-1))# lookP=lookP[,1]+frameP[1] * (lookP[,2]-1)# # Calculate the color differences between the paired pixels deltaP=imageP-imageP[lookP,] contrastchange=abs(deltaP[,1]) contrastdirection=sign(deltaP[,1]) colordifference=p2-p2[lookP,] colordifference=sqrt(apply(colordifference * colordifference,1,sum))+2^(-52) # Derive a chromatic axis from the weighted sum of chromatic differences between paired pixels weightP=1-((contrastchange/scaleluminance)/colordifference) weightP[which(colordifference<tolerance)]=0 axisP=weightP * contrastdirection axisP=deltaP[,2:3] * c(axisP, axisP) axisP=apply(axisP,2,sum) # Project the chromatic content of the picture onto the chromatic axis projection=imageP[,2] * axisP[1] + imageP[,3] * axisP[2] quantile(abs(projection),1-noise) projection=projection / (quantile(abs(projection),1-noise)+tolerance) # Combine the achromatic tones with the projected chromatic colors and adjust the dynamic range imageP[,1]=imageP[,1]+effect*projection imagerange=quantile(imageP[,1],c(noise, 1-noise)) imageP[,1]=(imageP[,1]-imagerange[1])/(imagerange[2]-imagerange[1]+tolerance) targetrange=effect*c(0.0, maxluminance)+(1-effect)*quantile(originalP[,1],c(noise, 1-noise)) imageP[,1]=targetrange[1]+(imageP[,1]*(targetrange[2]-targetrange[1]+tolerance)) iP1<-imageP[,1] w<-which(imageP[,1]<(originalP[,1]-alterP*chromaP)) iP1[w]<-originalP[w,1]-alterP*chromaP[w] w<-which(iP1>(originalP[,1]+alterP*chromaP)) iP1[w]<-originalP[w,1]+alterP*chromaP imageP[,1]=iP1/255.0 imageP[which(imageP<0.0)]=0.0 imageP[which(imageP>maxluminance)]=maxluminance # Return the results tones=imageP[,1] / maxluminance tones=array(tones,dim(p)) if (recolor){ recolorP=imageP %*% colorrevert recolorP=array(c(array(recolorP[,1],frameP),array(recolorP[,2],frameP),array(recolorP[,3],frameP)),dim(p)) recolorP[which(recolorP<0)]=0.0 recolorP[which(recolorP>1)]=1.0 return(list(tones=tones,recolor=recolorP)) } else return(list(tones=tones,recolor=NULL)) } decolorizeFile<-function(fileIN=NULL,fileOUT=NULL,effect=0.5,scale=NULL,noise=0.001,fileRecolorOUT=NULL){ #Color Image to Grayscale Conversion #Original work by Mark Grundland and Neil A. Dodgson # Mark Grundland and Neil A. Dodgson, "Decolorize: Fast, Contrast Enhancing, Color to Grayscale Conversion", # Pattern Recognition, vol. 40, no. 11, pp. 2891-2896, (2007). # http://www.Eyemaginary.com/Portfolio/Publications.html if (is.null(fileIN)) stop('A file input must be defined') if (!file.exists(fileIN)) stop('Error! File does not exist') if (is.null(fileOUT)) stop('A file output must be defined') if (!is.null(fileRecolorOUT)) { if (!is.character(fileRecolorOUT)) stop('A file output for recolor must have a valid name') if (fileRecolorOUT=='') stop('A file output for recolor must have a valid name') } if (is.null(fileRecolorOUT)) recolor<-FALSE else recolor<-TRUE decF<-decolorize(fileIN,effect,scale,noise,recolor) png::writePNG(decF$tones, fileOUT) if (recolor) png::writePNG(decF$recolor, fileRecolorOUT) }
/scratch/gouwar.j/cran-all/cranData/CVD/R/CVD.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-9*60 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test dispose(w) scoreFM100Graphic(userFM100values=lColors) lColorsOK<-sprintf('#%02x%02x%02x',FarnsworthMunsell100Hue[-1,'R'],FarnsworthMunsell100Hue[-1,'G'],FarnsworthMunsell100Hue[-1,'B']) pos2<-c() for (n in 1:85) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('total error score (TES) using Farnsworth\'s method:',paste(sum(calculateTES(pos2,FALSE)-2*85),collapse='\t',sep=' '), 'total error score (TES) using Kinnear\'s method:',paste(sum(calculateTES(pos2,TRUE)-2*85),collapse='\t',sep=' '), '\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2,testType='Farnsworth Munsell 100-Hue')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:85))) return(FALSE) rangeRow<-c(1:20,85) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(22:42) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(43:63) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(64:84) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) ndxs<-1:85 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI %in% c(1,22,43,64)) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons[1:85], lColors) tmpv<<-'' } modify_button <- function(b, col) { col <- as.GdkColor(col) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) } # instructions #gmessage('', title="Farnsworth Munsell 100-Hue color vision test - instructions",icon = "info") # prepare variables for the colors to be displayed and the sequence from the user data(FarnsworthMunsell100Hue) # list of colors lColorsStart<-sprintf('#%02x%02x%02x',FarnsworthMunsell100Hue[,'R'],FarnsworthMunsell100Hue[,'G'],FarnsworthMunsell100Hue[,'B']) #color1st<-lColorsStart[c(84,21,21,42,42,63,63,83)] #lColorsStart<-sample(lColorsStart,85) # mix them # corner color1st<-lColorsStart[c(84,21,42,63,22,43,64,85)] # mix them lColorsStart<-c(sample(lColorsStart[c(1:21,85)],22),sample(lColorsStart[c(22:42)],21), sample(lColorsStart[c(43:63)],21), sample(lColorsStart[c(64:84)],21)) lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Farnsworth-Munsell100-hue test") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) scrPos<-matrix( c(rbind( cbind(1,2:23), cbind(3,2:22), cbind(5,2:22), cbind(7,2:22) )),85,2,byrow=F) buttons <- lapply(1:93, function(x) gbutton('\n', cont=wlayout)) for (n in 1:85) wlayout[scrPos[n,1],scrPos[n,2], expand=TRUE] <- buttons[[n]] scrPos2<-matrix(c(rbind(cbind(1:4*2-1,1),c(1,24), cbind(2:4*2-1,23))) ,8,2,byrow=F) for (n in 1:8) wlayout[scrPos2[n,1],scrPos2[n,2], expand=TRUE] <- buttons[[85+n]] wlayout[2,1, expand=TRUE] <- gbutton('\n', cont=wlayout) wlayout[4,1, expand=TRUE] <- gbutton('\n', cont=wlayout) wlayout[6,1, expand=TRUE] <- gbutton('\n', cont=wlayout) modify_button(wlayout[2,1],'#000000') modify_button(wlayout[4,1],'#000000') modify_button(wlayout[6,1],'#000000') mapply(modify_button, buttons, c(lColors, color1st)) lTimer<-glabel('Time left 9:00', cont = g0) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") for (n in 1:85 ) { b<-wlayout[scrPos[n,1],scrPos[n,2]] eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) } gtimer(9000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/FM100.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-9*60 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test lColors <- paste('#',substr(lColors,nchar(lColors)-9,nchar(lColors)-4),sep='') dispose(w) scoreFM100Graphic(userFM100colors=lColors) lColorsOK<-sprintf('#%02x%02x%02x',FarnsworthMunsell100Hue[-1,'R'],FarnsworthMunsell100Hue[-1,'G'],FarnsworthMunsell100Hue[-1,'B']) pos2<-c() for (n in 1:85) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('total error score (TES) using Farnsworth\'s method:',paste(sum(calculateTES(pos2,FALSE)-2*85),collapse='\t',sep=' '), 'total error score (TES) using Kinnear\'s method:',paste(sum(calculateTES(pos2,TRUE)-2*85),collapse='\t',sep=' '), '\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2,testType='Farnsworth Munsell 100-Hue')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:85))) return(FALSE) rangeRow<-c(1:20,85) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(22:42) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(43:63) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) rangeRow<-c(64:84) if (!(tmpv %in% as.character(rangeRow)) & (strToB %in% as.character(rangeRow))) return(FALSE) ndxs<-1:85 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI %in% c(1,22,43,64)) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons[1:85], lColors) tmpv<<-'' } modify_button <- function(b, colX) { svalue(b) <- colX } # instructions # prepare variables for the colors to be displayed and the sequence from the user data(FarnsworthMunsell100Hue) # list of colors lColorsStart<-vectorPNGbuttons(FarnsworthMunsell100Hue) blackPNG <- vectorPNGbuttons(data.frame(R=0,G=0,B=0)) # corner color1st<-lColorsStart[c(84,21,42,63,22,43,64,85)] # mix them lColorsStart<-c(sample(lColorsStart[c(1:21,85)],22),sample(lColorsStart[c(22:42)],21), sample(lColorsStart[c(43:63)],21), sample(lColorsStart[c(64:84)],21)) lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Farnsworth-Munsell100-hue test") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) scrPos<-matrix( c(rbind( cbind(1,2:23), cbind(3,2:22), cbind(5,2:22), cbind(7,2:22) )),85,2,byrow=F) buttons <- lapply(1:93, function(x) gimage(c(color1st,lColors)[x], cont = wlayout)) for (n in 1:85) wlayout[scrPos[n,1],scrPos[n,2], expand=TRUE] <- buttons[[n]] scrPos2<-matrix(c(rbind(cbind(1:4*2-1,1),c(1,24), cbind(2:4*2-1,23))) ,8,2,byrow=F) for (n in 1:8) wlayout[scrPos2[n,1],scrPos2[n,2], expand=TRUE] <- buttons[[85+n]] wlayout[2,1, expand=TRUE] <- gimage(blackPNG, cont = wlayout)#gbutton('\n', cont=wlayout) wlayout[4,1, expand=TRUE] <- gimage(blackPNG, cont = wlayout)#gbutton('\n', cont=wlayout) wlayout[6,1, expand=TRUE] <- gimage(blackPNG, cont = wlayout)#gbutton('\n', cont=wlayout) # modify_button(wlayout[2,1],'#000000') # modify_button(wlayout[4,1],'#000000') # modify_button(wlayout[6,1],'#000000') #mapply(modify_button, buttons, c(lColors, color1st)) lTimer<-glabel('Time left 9:00', cont = g0) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") for (n in 1:85 ) { b<-wlayout[scrPos[n,1],scrPos[n,2]] eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/FM100.Windows.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test dispose(w) scoreD15Graphic(lColors) lColorsOK<-sprintf('#%02x%02x%02x',FarnsworthD15[-1,'R'],FarnsworthD15[-1,'G'],FarnsworthD15[-1,'B']) pos2<-c() for (n in 1:15) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('Bowman\'s (1982) Total Color Difference Score (TCDS) and Color Confusion Index (CCI)\nTCDS\tCCCI', paste(unlist(scoreD15TCDS(lColors)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2)),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } colorgBtn<-function(allButtons,allColors) {# assign colors to the buttons n<-1 for (b in allButtons) { col<-as.GdkColor(allColors[n]) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) n<-n+1 } } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:15) )) return(FALSE) ndxs<-1:15 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] #colorgBtn(wlayout[1,2:16],lColors) mapply(modify_button, buttons, c(color1st,lColors)) tmpv<<-'' } # instructions gmessage('General Description.\n\nThe Farnsworth Dichotomous Test for Color Blindness (Panel D-15) is designed to select those observers with severe discrimination loss. In addition to indicating red-green discrimination loss, the test also indicates blue-yellow dicrimination loss and detects monochromacy. The test consists of 15 colored caps placed in a box, with one reference cap at a fixed location. The samples are chosen to represent approximately equal hue steps in the natural color circle and are similar in chroma to those of the FM 100-hue test. They are set in plastic caps and subtend 1.5 degrees at 50 cm. The movable caps are numbered on the back according to the correct color circle. An instruction manual and scoring sheets are provided. Additional scoring sheets are available.\n\nQuoted from:\nProcedures for Testing Color Vision: Report of Working Group 41\nCommittee on Vision, National Research Council\nISBN: 0-309-58883-9, 128 pages, 8.5 x 11, (1981)', title="Farnsworth D-15 color vision test - General Description",icon = "info") gmessage('Administration.\n\nThe examiner prearranges the caps in random order on the upper lid of the open box. The subject is instructed to "arrange the caps in order according to color" in the lower tray, starting with the cap closest in color to the fixed reference cap. The box is presented at a comfortable distance under daylight illumination of at least 270 lux. The majority of individuals with normal color vision can complete the test within one minute. The observer is allowed as long as is necessary to complete the task. People with poor coordination may have difficulty in handling the caps.\n\nQuoted from:\nProcedures for Testing Color Vision: Report of Working Group 41\nCommittee on Vision, National Research Council\nISBN: 0-309-58883-9, 128 pages, 8.5 x 11, (1981)', title="Farnsworth D-15 color vision test - Administration",icon = "info") # The Farnsworth dichotomous test (D-15) classifies subjects into Strongly/Medium color deficient or Mildly color deficient/normal. # # The test should be administered on a black background, to prevent any interference from background colors. # # The recommended illumination is approximately 6700 deg. Kelvin at 25 foot-candles or greater (Illuminant C) or daylight. # # The working distance is about 50 cm (20 inches). There are 15 colored caps to be sorted, the most common sizes are 12 mm (0.5 inches) and 33 mm (1.3 inches). # # The first colored cap (from the left) is the "reference cap", this is the first color from the sequence of colors and it can\'t be moved. # The test taker has two minutes to move the caps to form a sequence of colors. The test will finish after two minutes or after pressing the button "Done". # # # Instructions based on: # Farnsworth D-15 and Lanthony Test Instructions # Rev 1.7 (05/06) # Richmond Products Inc. # prepare variables for the colors to be displayed and the sequence from the user data(FarnsworthD15) # list of colors lColorsStart<-sprintf('#%02x%02x%02x',FarnsworthD15[,'R'],FarnsworthD15[,'G'],FarnsworthD15[,'B']) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,15) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Farnsworth dichotomous test (D-15)") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) #wlayout[1,1, expand=TRUE] = gbutton('\n', cont=wlayout) #for (n in 1:15) wlayout[1,n+1, expand=TRUE] = gbutton('\n', cont=wlayout) buttons <- lapply(1:16, function(x) gbutton('\n', cont=wlayout)) for (n in 1:16) wlayout[1,n, expand=TRUE] = buttons[[n]] # #sapply( lColors, as.GdkColor) modify_button <- function(b, col) { col <- as.GdkColor(col) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) } mapply(modify_button, buttons, c(color1st,lColors)) #colorgBtn(wlayout[1,],c(color1st,lColors)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") n<-1 for (b in wlayout[1,2:16]) { eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) n<-n+1 } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/FarnsworthD15.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test lColors <- paste('#',substr(lColors,nchar(lColors)-9,nchar(lColors)-4),sep='') dispose(w) scoreD15Graphic(lColors) lColorsOK<-sprintf('#%02x%02x%02x',FarnsworthD15[-1,'R'],FarnsworthD15[-1,'G'],FarnsworthD15[-1,'B']) pos2<-c() for (n in 1:15) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('Bowman\'s (1982) Total Color Difference Score (TCDS) and Color Confusion Index (CCI)\nTCDS\tCCCI', paste(unlist(scoreD15TCDS(lColors)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2)),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } modify_button <- function(b, colX) { svalue(b) <- colX } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:15) )) return(FALSE) ndxs<-1:15 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons, c(color1st,lColors)) tmpv<<-'' } # instructions gmessage('General Description.\n\nThe Farnsworth Dichotomous Test for Color Blindness (Panel D-15) is designed to select those observers with severe discrimination loss. In addition to indicating red-green discrimination loss, the test also indicates blue-yellow dicrimination loss and detects monochromacy. The test consists of 15 colored caps placed in a box, with one reference cap at a fixed location. The samples are chosen to represent approximately equal hue steps in the natural color circle and are similar in chroma to those of the FM 100-hue test. They are set in plastic caps and subtend 1.5 degrees at 50 cm. The movable caps are numbered on the back according to the correct color circle. An instruction manual and scoring sheets are provided. Additional scoring sheets are available.\n\nQuoted from:\nProcedures for Testing Color Vision: Report of Working Group 41\nCommittee on Vision, National Research Council\nISBN: 0-309-58883-9, 128 pages, 8.5 x 11, (1981)', title="Farnsworth D-15 color vision test - General Description",icon = "info") gmessage('Administration.\n\nThe examiner prearranges the caps in random order on the upper lid of the open box. The subject is instructed to "arrange the caps in order according to color" in the lower tray, starting with the cap closest in color to the fixed reference cap. The box is presented at a comfortable distance under daylight illumination of at least 270 lux. The majority of individuals with normal color vision can complete the test within one minute. The observer is allowed as long as is necessary to complete the task. People with poor coordination may have difficulty in handling the caps.\n\nQuoted from:\nProcedures for Testing Color Vision: Report of Working Group 41\nCommittee on Vision, National Research Council\nISBN: 0-309-58883-9, 128 pages, 8.5 x 11, (1981)', title="Farnsworth D-15 color vision test - Administration",icon = "info") # The Farnsworth dichotomous test (D-15) classifies subjects into Strongly/Medium color deficient or Mildly color deficient/normal. # # The test should be administered on a black background, to prevent any interference from background colors. # # The recommended illumination is approximately 6700 deg. Kelvin at 25 foot-candles or greater (Illuminant C) or daylight. # # The working distance is about 50 cm (20 inches). There are 15 colored caps to be sorted, the most common sizes are 12 mm (0.5 inches) and 33 mm (1.3 inches). # # The first colored cap (from the left) is the "reference cap", this is the first color from the sequence of colors and it can\'t be moved. # The test taker has two minutes to move the caps to form a sequence of colors. The test will finish after two minutes or after pressing the button "Done". # # # Instructions based on: # Farnsworth D-15 and Lanthony Test Instructions # Rev 1.7 (05/06) # Richmond Products Inc. # prepare variables for the colors to be displayed and the sequence from the user data(FarnsworthD15) # list of colors lColorsStart<-vectorPNGbuttons(FarnsworthD15) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,15) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Farnsworth dichotomous test (D-15)") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) buttons <- lapply(1:16, function(x) gimage(c(color1st,lColors)[x], cont = wlayout)) for (n in 1:16) wlayout[1,n, expand=TRUE] = buttons[[n]] ###mapply(modify_button, buttons, c(color1st,lColors)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") n<-1 for (b in wlayout[1,2:16]) { eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) n<-n+1 } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/FarnsworthD15.Windows.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test dispose(w) scoreD15Graphic(lColors, titleGraphic="Lanthony desaturated D-15 test (D-15d) results", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) lColorsOK<-sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B']) pos2<-c() for (n in 1:15) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('Bowman\'s (1982) Total Color Difference Score (TCDS) and Color Confusion Index (CCI)\nTCDS\tCCCI', paste(unlist(scoreD15TCDS(lColors, distTable=GellerTCDS, D15colors=LanthonyD15)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2, testType='D-15DS')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } colorgBtn<-function(allButtons,allColors) {# assign colors to the buttons n<-1 for (b in allButtons) { col<-as.GdkColor(allColors[n]) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) n<-n+1 } } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:15) )) return(FALSE) ndxs<-1:15 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons, c(color1st,lColors)) tmpv<<-'' } # prepare variables for the colors to be displayed and the sequence from the user data(LanthonyD15) # list of colors lColorsStart<-sprintf('#%02x%02x%02x',LanthonyD15[,'R'],LanthonyD15[,'G'],LanthonyD15[,'B']) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,15) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Lanthony desaturated D-15 test (D-15d)") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) buttons <- lapply(1:16, function(x) gbutton('\n', cont=wlayout)) for (n in 1:16) wlayout[1,n, expand=TRUE] = buttons[[n]] modify_button <- function(b, col) { col <- as.GdkColor(col) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) } mapply(modify_button, buttons, c(color1st,lColors)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") n<-1 for (b in wlayout[1,2:16]) { eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) n<-n+1 } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/LanthonyD15.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test lColors <- paste('#',substr(lColors,nchar(lColors)-9,nchar(lColors)-4),sep='') dispose(w) scoreD15Graphic(lColors, titleGraphic="Lanthony desaturated D-15 test (D-15d) results", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) lColorsOK<-sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B']) pos2<-c() for (n in 1:15) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('Bowman\'s (1982) Total Color Difference Score (TCDS) and Color Confusion Index (CCI)\nTCDS\tCCCI', paste(unlist(scoreD15TCDS(lColors, distTable=GellerTCDS, D15colors=LanthonyD15)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2, testType='D-15DS')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:15) )) return(FALSE) ndxs<-1:15 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons, c(color1st,lColors)) tmpv<<-'' } modify_button <- function(b, colX) { svalue(b) <- colX } # prepare variables for the colors to be displayed and the sequence from the user data(LanthonyD15) # list of colors lColorsStart<-vectorPNGbuttons(LanthonyD15) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,15) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Lanthony desaturated D-15 test (D-15d)") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) buttons <- lapply(1:16, function(x) gimage(c(color1st,lColors)[x], cont = wlayout)) for (n in 1:16) wlayout[1,n, expand=TRUE] = buttons[[n]] #mapply(modify_button, buttons, c(color1st,lColors)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") n<-1 for (b in wlayout[1,2:16]) { eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) n<-n+1 } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/LanthonyD15.Windows.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) #round(calculateCircle(550,550,500,29)) #round(calculateCircle(550,550,530,29)) #paste(cirC2,sep='',collapse=',') #scoreRoth28Graphic(userR28values=c(1,4,7,34,37,40,43,46,79,76,73,52,49,55,58,61,64,67,70)) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test dispose(w) scoreRoth28Graphic(lColors) lColorsOK<-sprintf('#%02x%02x%02x',Roth28[-1,'R'],Roth28[-1,'G'],Roth28[-1,'B']) pos2<-c() for (n in 1:28) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('total error score (TES) using Farnsworth\'s method:', paste(sum(calculateTES(pos2)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2,testType='Roth28-Hue')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:28) )) return(FALSE) ndxs<-1:28 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] #colorgBtn(wlayout[1,2:16],lColors) mapply(modify_button, buttons[1:28], lColors) tmpv<<-'' } # instructions #gmessage('', title="Roth28-hues color vision test - instructions",icon = "info") # prepare variables for the colors to be displayed and the sequence from the user data(Roth28) # list of colors lColorsStart<-sprintf('#%02x%02x%02x',Roth28[,'R'],Roth28[,'G'],Roth28[,'B']) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,28) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Roth 28 test") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) #wlayout[1,1, expand=TRUE] = gbutton('\n', cont=wlayout) #for (n in 1:15) wlayout[1,n+1, expand=TRUE] = gbutton('\n', cont=wlayout) scrPos<-matrix(c(5,1,4,1,3,2,2,3,1,4,1,5,1,6,1,7,1,8,2,9,3,10,4,11,5,11,6,11,7,11,8,11,9,11,10,10,11,9,12,8,12,7,12,6,12,5,12,4,11,3,10,2,9,1,8,1),28,2,byrow=TRUE) buttons <- lapply(1:29, function(x) gbutton('\n', cont=wlayout)) for (n in 1:28) wlayout[scrPos[n,1],scrPos[n,2], expand=TRUE] = buttons[[n]] wlayout[6,1, expand=TRUE] = buttons[[29]] #sapply( lColors, as.GdkColor) modify_button <- function(b, col) { col <- as.GdkColor(col) getToolkitWidget(b)$modifyBg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyBg(GtkStateType["active"], col) getToolkitWidget(b)$modifyBg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyBg(GtkStateType["selected"], col) getToolkitWidget(b)$modifyFg(GtkStateType["normal"], col) getToolkitWidget(b)$modifyFg(GtkStateType["active"], col) getToolkitWidget(b)$modifyFg(GtkStateType["prelight"], col) getToolkitWidget(b)$modifyFg(GtkStateType["selected"], col) } mapply(modify_button, buttons, c(lColors, color1st)) #colorgBtn(wlayout[1,],c(color1st,lColors)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") for (n in 1:28 ) { b<-wlayout[scrPos[n,1],scrPos[n,2]] eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/Roth28.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) incTimer<-function( h , ... ) {# timer event - decrease timer and validate at the end if (is.na(timeC)) timeC<<-120 else { timeC<<-timeC - 1 svalue(lTimer) <- paste('Time left ',trunc(timeC/60),':',(timeC-60*trunc(timeC/60)),sep='') } if (timeC<0) validate(h) } validate<-function( h , ... ) {# close the window and score the test lColors <- paste('#',substr(lColors,nchar(lColors)-9,nchar(lColors)-4),sep='') dispose(w) scoreRoth28Graphic(lColors) lColorsOK<-sprintf('#%02x%02x%02x',Roth28[-1,'R'],Roth28[-1,'G'],Roth28[-1,'B']) pos2<-c() for (n in 1:28) pos2<-c(pos2,which(lColors[n] == lColorsOK) ) tmpR<-paste('total error score (TES) using Farnsworth\'s method:', paste(sum(calculateTES(pos2)),collapse='\t',sep=' '),'\nANGLE\tMAJ\tRAD\tMIN\tRAD\tTOT\tERR\tS-INDEX\tC-INDEX', 'Vingrys and King-Smith method (1988)', paste(round(unlist(Color.Vision.VingrysAndKingSmith(pos2,testType='Roth28-Hue')),2),collapse='\t',sep=' '),sep='\n') gmessage(tmpR) } dropF<-function(h,strToB) {# function to assist the drop event if (!(tmpv %in% as.character(1:28) )) return(FALSE) ndxs<-1:28 ndxs[as.numeric(tmpv)]<-NA posI<-(as.numeric(strToB)) if ((posI== as.numeric(tmpv)+1) ) posI<-posI+1 if (posI==1) ndxs<-c(as.numeric(tmpv),ndxs) else ndxs<-append(ndxs, as.numeric(tmpv), after=posI-1) ndxs<-ndxs[-which(is.na(ndxs))] lColors<<-lColors[ndxs] mapply(modify_button, buttons[1:28], lColors) tmpv<<-'' } # instructions # prepare variables for the colors to be displayed and the sequence from the user data(Roth28) # list of colors lColorsStart<-vectorPNGbuttons(Roth28) color1st<-lColorsStart[1] lColorsStart<-lColorsStart[-1] lColorsStart<-sample(lColorsStart,28) # mix them lColors<-lColorsStart # create GUI tmpv<-'' timeC<-NA w <- gwindow("Roth 28 test") getToolkitWidget(w)$maximize() g0 <- ggroup(cont=w, expand=TRUE, horizontal=F, spacing =0) g <- ggroup(cont=g0, expand=TRUE, horizontal=T, spacing =0) wlayout = glayout(visible=TRUE,container=g0, expand=TRUE, spacing =0) #wlayout[1,1, expand=TRUE] = gbutton('\n', cont=wlayout) #for (n in 1:15) wlayout[1,n+1, expand=TRUE] = gbutton('\n', cont=wlayout) scrPos<-matrix(c(5,1,4,1,3,2,2,3,1,4,1,5,1,6,1,7,1,8,2,9,3,10,4,11,5,11,6,11,7,11,8,11,9,11,10,10,11,9,12,8,12,7,12,6,12,5,12,4,11,3,10,2,9,1,8,1),28,2,byrow=TRUE) buttons <- lapply(1:29, function(x) gimage(c(color1st,lColors)[x], cont = wlayout))# for (n in 1:28) wlayout[scrPos[n,1],scrPos[n,2], expand=TRUE] = buttons[[n]] wlayout[6,1, expand=TRUE] = buttons[[29]] #sapply( lColors, as.GdkColor) modify_button <- function(b, colX) { svalue(b) <- colX } #mapply(modify_button, buttons, c(lColors, color1st)) lTimer<-glabel('Time left 2:00', cont = g0 ) font(lTimer) <- c(color="red", weight = 'bold', scale = "xx-large") bDONE<-gbutton("Done", cont=g0,handler = validate) font(bDONE) <- c(color="red", weight = 'bold', scale = "xx-large") getToolkitWidget(w)$modifyBg(GtkStateType["normal"], "black") for (n in 1:28 ) { b<-wlayout[scrPos[n,1],scrPos[n,2]] eval(parse( text=paste('addDropSource(b, handler = function(h,...) tmpv<<-',as.character(n),')',sep='') )) eval(parse( text=paste('addDropTarget(b,targetType="object", handler = function(h,...) dropF(h,',as.character(n),'))',sep='') )) } gtimer(2000, incTimer, lTimer )
/scratch/gouwar.j/cran-all/cranData/CVD/demo/Roth28.Windows.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to Fig. 1 from\nThe Desaturated Panel D-15 P. Lanthony Documenta Ophthalmologica 46,1: 185-189, 1978') data(LanthonyD15) data(example1Lanthony1978) .pardefault <- par(no.readonly = T) #png('example1Lanthony1978.png') par(mfrow=c(2,2),mar=c(1,1,3,1),oma=c(0, 0, 2, 0)) scoreD15Graphic(userD15values=example1Lanthony1978[,1], titleGraphic="Test standard") scoreD15Graphic(userD15values=example1Lanthony1978[,2], titleGraphic="Test desaturated", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) scoreD15Graphic(userD15values=example1Lanthony1978[,3], titleGraphic="Test standard") scoreD15Graphic(userD15values=example1Lanthony1978[,4], titleGraphic="Test desaturated", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) mtext('Simple Anomalous Trichromacy', side = 3, line = 0, outer = TRUE,cex=1.5) mtext('Extreme Anomalous Trichromacy', side = 3, line = -20, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/example1Lanthony1978.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to Fig. 2 from\nThe Desaturated Panel D-15 P. Lanthony Documenta Ophthalmologica 46,1: 185-189, 1978') data(LanthonyD15) data(example2Lanthony1978) .pardefault <- par(no.readonly = T) #png('example2Lanthony1978.png') par(mfrow=c(3,2),mar=c(1,1,3,1),oma=c(0, 0, 2, 0)) scoreD15Graphic(userD15values=example2Lanthony1978[,1], titleGraphic="Test standard") scoreD15Graphic(userD15values=example2Lanthony1978[,2], titleGraphic="Test desaturated", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) scoreD15Graphic(userD15values=example2Lanthony1978[,3], titleGraphic="Test standard") scoreD15Graphic(userD15values=example2Lanthony1978[,4], titleGraphic="Test desaturated", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) scoreD15Graphic(userD15values=example2Lanthony1978[,5], titleGraphic="Test standard") scoreD15Graphic(userD15values=example2Lanthony1978[,6], titleGraphic="Test desaturated", okD15colors=sprintf('#%02x%02x%02x',LanthonyD15[-1,'R'],LanthonyD15[-1,'G'],LanthonyD15[-1,'B'])) mtext('Central Serous Choroidopathy', side = 3, line = 0, outer = TRUE,cex=1.5) mtext('Optic Neuritis', side = 3, line = -18, outer = TRUE,cex=1.5) mtext('Autosomal Dominant Optic Atrophy', side = 3, line = -33, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/example2Lanthony1978.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) #gmessage('Example identical to A Method For Quantitative Scoring Of The Farnsworth Panel D-15 K.J. Bowman 1982') data(FarnsworthD15) data(exampleBowman1982) .pardefault <- par(no.readonly = T) #png('exampleBowman1982.png') par(mfrow=c(3,2),mar=c(1,1,1,1),oma=c(0, 0, 2, 0),cex=1) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,1]) scoreD15Graphic(userD15values=exampleBowman1982[,1], titleGraphic=paste('A ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,2]) scoreD15Graphic(userD15values=exampleBowman1982[,2], titleGraphic=paste('B ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,3]) scoreD15Graphic(userD15values=exampleBowman1982[,3], titleGraphic=paste('C ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,4]) scoreD15Graphic(userD15values=exampleBowman1982[,4], titleGraphic=paste('D ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,5]) scoreD15Graphic(userD15values=exampleBowman1982[,5], titleGraphic=paste('E ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) scoreTCDS <-scoreD15TCDS(userD15values=exampleBowman1982[,6]) scoreD15Graphic(userD15values=exampleBowman1982[,6], titleGraphic=paste('F ( TCDS = ',scoreTCDS[1],', CCI = ',round(scoreTCDS[2],3),' )',sep='')) mtext('Panel D-15 with Bowman\'s TCDS', side = 3, line = 0, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleBowman.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to proceedings of the New Zealand Generating fast automated reports for the Farnsworth-Munsell 100-hue colour vision test Ray Hidayat, Computer Science Research Student Conference 2008') data(FarnsworthMunsell100Hue) data(exampleFM100) allFM100data <- data.matrix(exampleFM100) fig3data <- allFM100data[1:4*3-2,] fig3data <- c(t(fig3data)) fig3data <- fig3data[-which(is.na(fig3data))] scoreFM100Graphic(userFM100values=fig3data)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleFM100.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to Farnsworth D. The Farnsworth Dichotomous Test for Color Blindness Panel D-15 Manual. New York, The Psychological Corp., 1947, pp. 1-8.') data(FarnsworthD15) data(exampleFarnsworth1974) .pardefault <- par(no.readonly = T) #png('exampleFarnsworth1974.png') par(mfrow=c(1,3),mar=c(1,1,3,1),oma=c(0, 0, 2, 0)) scoreD15Graphic(userD15values=exampleFarnsworth1974[,1], titleGraphic="Deuteranope") scoreD15Graphic(userD15values=exampleFarnsworth1974[,2], titleGraphic="Protanope") scoreD15Graphic(userD15values=exampleFarnsworth1974[,3], titleGraphic="Tritanope") mtext('The Farnsworth Dichotomous Test', side = 3, line = 0, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleFarnsworth.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to Procedures for Testing Color Vision: Report of Working Group 41, 1981, Committee on Vision, National Research Council') data(exampleNRC1981) # this is an example of a typo in data from a publication #the "monochromat" data has "16" instead of "6" showDuplicated(exampleNRC1981[,3]) fixedData <- exampleNRC1981[,3] fixedData[7] <- 6 # double check: showDuplicated(fixedData) # OK! .pardefault <- par(no.readonly = T) #png('exampleNRC1981.png') par(mfrow=c(1,3),mar=c(1,1,3,1),oma=c(0, 0, 2, 0)) scoreD15Graphic(userD15values=exampleNRC1981[,1], titleGraphic="Protanope") scoreD15Graphic(userD15values=exampleNRC1981[,2], titleGraphic="Deuteranope") scoreD15Graphic(userD15values=fixedData, titleGraphic="Achromat") mtext('The Farnsworth Dichotomous Test', side = 3, line = 0, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleNRC1981.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example identical to Cone dystrophies Part 2 Cone dysfunction syndromes, Matthew P Simunovic') data(exampleSimunovic2004) .pardefault <- par(no.readonly = T) #png('exampleSimunovic2004.png') par(mfrow=c(1,2),mar=c(1,1,3,1),oma=c(0, 0, 2, 0)) scoreD15Graphic(userD15values=exampleSimunovic2004[,1], titleGraphic="Rod Monochromat") scoreD15Graphic(userD15values=exampleSimunovic2004[,2], titleGraphic="Blue Cone Monochromat") mtext('The Farnsworth Dichotomous Test', side = 3, line = 0, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleSimunovic2004.R
library(gWidgets2) options(guiToolkit="RGtk2") library(RGtk2) library(CVD) gmessage('Example similar to Vingrys, A.J. and King-Smith, P.E. (1988). A quantitative scoring technique for panel tests of color vision. Investigative Ophthalmology and Visual Science, 29, 50-63.') data(VKStable2) .pardefault <- par(no.readonly = T) #png('exampleVKS91.png') par(mfrow=c(1,2),mar=c(2,2,3,1),oma=c(0, 0, 2, 0)) VKSdata<-VKStable2[,c(1,3:5)] VKSdata[1,1]<-'Normal no error' VKSdata[2:9,1]<-'Normal' VKSdata[10:13,1]<-'Acquired CVD' # the graphics are similar but not identical because the data used in the plots is the average of the values instead of all the values VKSgraphic(VKSdata[,1:3],5,4,'D-15 angle vs C-index (Average)','Angle','C-index') # Fig. 6 VKSgraphic(VKSdata[,c(1,2,4)],5,4,'D-15 angle vs S-index (Average)','Angle','S-index') # Fig. 7 mtext('The Vingrys and King-Smith score', side = 3, line = 0, outer = TRUE,cex=1.5) #dev.off() par(.pardefault)
/scratch/gouwar.j/cran-all/cranData/CVD/demo/exampleVKS91.R
# same plot as: # Transformed Up-Down Method (1 up/2 down rule) # using the simple up/down rule until the first (neglected) reversal # Reference: www.Bedienhaptik.de # Dr. Manuel Kuehner stimulusIntensity<-c(11,9,7,5,3:6,6,5,5,4,5,6,6,5,6,7,7,6,6,5,5,4,4) stimulusDetected<-c('Right','Right','Right','Right','Wrong','Wrong','Wrong','Right','Right','Right','Right','Wrong','Wrong','Right','Right','Wrong','Wrong','Right','Right','Right','Right','Right','Right','Right','Wrong') rvrslsN<-CountReversals(stimulusDetected) rvrsls<-MarkReversalsUD(rvrslsN, stimulusIntensity) xl<-c(1, 25);yl<-c(0,12) plot(1:25, answers, type='b',xlim=xl,ylim=yl, pch=as.character(rvrslsN),xlab='Trial Number',ylab='Stimulus Intensity x', main='Transformed Up-Down Method (1 up/2 down rule)') dev.new() plot(1:25, answers, type='b',xlim=xl,ylim=yl, pch=ifelse(stimulus=='Right',15,0),xlab='Trial Number',ylab='Stimulus Intensity', main='Transformed Up-Down Method (1 up/2 down rule)') par(new=TRUE) plot(1:25, answers, type='p',xlim=xl,ylim=yl, pch=ifelse(rvrsls,1,NA),cex=1.75,xlab='',ylab='') par(new=TRUE) plot(1:25, (answers+0.5)*ifelse(rvrsls,1,-1), type='p',xlim=xl,ylim=yl, pch=ifelse(rvrsls,as.character(rvrslsN-1),NA),cex=.75,xlab='',ylab='') legend("topright",c('Answers','Stimulus detected','Stimulus not detected','Reversal Ri'),pch=c(NA,15,0,1))
/scratch/gouwar.j/cran-all/cranData/CVD/demo/transformedUpDown.R
#' Estimating Ensemble Kernel Matrices #' #' Give the ensemble projection matrix and weights of the kernels in the #' library. #' #' There are three ensemble strategies available here: #' #' \bold{Empirical Risk Minimization (Stacking)} #' #' After obtaining the estimated errors \eqn{\{\hat{\epsilon}_d\}_{d=1}^D}, we #' estimate the ensemble weights \eqn{u=\{u_d\}_{d=1}^D} such that it minimizes #' the overall error \deqn{\hat{u}={argmin}_{u \in \Delta}\parallel #' \sum_{d=1}^Du_d\hat{\epsilon}_d\parallel^2 \quad where\; \Delta=\{u | u \geq #' 0, \parallel u \parallel_1=1\}} Then produce the final ensemble prediction: #' \deqn{\hat{h}=\sum_{d=1}^D \hat{u}_d h_d=\sum_{d=1}^D \hat{u}_d #' A_{d,\hat{\lambda}_d}y=\hat{A}y} where \eqn{\hat{A}=\sum_{d=1}^D \hat{u}_d #' A_{d,\hat{\lambda}_d}} is the ensemble matrix. #' #' \bold{Simple Averaging} #' #' Motivated by existing literature in omnibus kernel, we propose another way #' to obtain the ensemble matrix by simply choosing unsupervised weights #' \eqn{u_d=1/D} for \eqn{d=1,2,...D}. #' #' \bold{Exponential Weighting} #' #' Additionally, another scholar gives a new strategy to calculate weights #' based on the estimated errors \eqn{\{\hat{\epsilon}_d\}_{d=1}^D}. #' \deqn{u_d(\beta)=\frac{exp(-\parallel \hat{\epsilon}_d #' \parallel_2^2/\beta)}{\sum_{d=1}^Dexp(-\parallel \hat{\epsilon}_d #' \parallel_2^2/\beta)}} #' #' @param strategy (character) A character string indicating which ensemble #' strategy is to be used. #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp" \code{\link{ensemble_exp}}. #' @param error_mat (matrix, n*K) A n\*K matrix indicating errors. #' @param A_hat (list of length K) A list of projection matrices to kernel space #' for each kernel in the kernel library. #' @return \item{A_est}{(matrix, n*n) The ensemble projection matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' @author Wenying Deng #' @seealso mode: \code{\link{tuning}} #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017. #' #' Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample #' kernel independence test for microbiome community-level association #' analysis. December 2017. #' #' Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential #' Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes #' in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. #' #' @export ensemble ensemble <- function(strategy, beta_exp, error_mat, A_hat) { strategy <- match.arg(strategy, c("avg", "exp", "stack")) func_name <- paste0("ensemble_", strategy) do.call(func_name, list(beta_exp = beta_exp, error_mat = error_mat, A_hat = A_hat)) } #' Estimating Ensemble Kernel Matrices Using Stack #' #' Give the ensemble projection matrix and weights of the kernels in the #' library using stacking. #' #' \bold{Empirical Risk Minimization (Stacking)} #' #' After obtaining the estimated errors \eqn{\{\hat{\epsilon}_d\}_{d=1}^D}, we #' estimate the ensemble weights \eqn{u=\{u_d\}_{d=1}^D} such that it minimizes #' the overall error \deqn{\hat{u}={argmin}_{u \in \Delta}\parallel #' \sum_{d=1}^Du_d\hat{\epsilon}_d\parallel^2 \quad where\; \Delta=\{u | u \geq #' 0, \parallel u \parallel_1=1\}} Then produce the final ensemble prediction: #' \deqn{\hat{h}=\sum_{d=1}^D \hat{u}_d h_d=\sum_{d=1}^D \hat{u}_d #' A_{d,\hat{\lambda}_d}y=\hat{A}y} where \eqn{\hat{A}=\sum_{d=1}^D \hat{u}_d #' A_{d,\hat{\lambda}_d}} is the ensemble matrix. #' #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp" \code{\link{ensemble_exp}}. #' @param error_mat (matrix, n*K) A n\*K matrix indicating errors. #' @param A_hat (list of length K) A list of projection matrices to kernel space #' for each kernel in the kernel library. #' @return \item{A_est}{(matrix, n*n) The ensemble projection matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' @author Wenying Deng #' @seealso mode: \code{\link{tuning}} #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017. #' #' Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample #' kernel inde- pendence test for microbiome community-level association #' analysis. December 2017. #' #' Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential #' Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes #' in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. ensemble_stack <- function(beta_exp, error_mat, A_hat) { n <- nrow(error_mat) kern_size <- ncol(error_mat) A <- error_mat B <- rep(0, n) E <- rep(1, kern_size) F <- 1 G <- diag(kern_size) H <- rep(0, kern_size) u_hat <- lsei(A, B, E = E, F = F, G = G, H = H)$X A_est <- u_hat[1] * A_hat[[1]] if (kern_size != 1) { for (d in 2:kern_size) { A_est <- A_est + u_hat[d] * A_hat[[d]] } } list(A_est = A_est, u_hat = u_hat) } #' Estimating Ensemble Kernel Matrices Using AVG #' #' Give the ensemble projection matrix and weights of the kernels in the #' library using simple averaging. #' #' \bold{Simple Averaging} #' #' Motivated by existing literature in omnibus kernel, we propose another way #' to obtain the ensemble matrix by simply choosing unsupervised weights #' \eqn{u_d=1/D} for \eqn{d=1,2,...D}. #' #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp" \code{\link{ensemble_exp}}. #' @param error_mat (matrix, n*K) A n\*K matrix indicating errors. #' @param A_hat (list of length K) A list of projection matrices to kernel space #' for each kernel in the kernel library. #' @return \item{A_est}{(matrix, n*n) The ensemble projection matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' @author Wenying Deng #' @seealso mode: \code{\link{tuning}} #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017. #' #' Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample #' kernel inde- pendence test for microbiome community-level association #' analysis. December 2017. #' #' Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential #' Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes #' in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. ensemble_avg <- function(beta_exp, error_mat, A_hat) { n <- nrow(error_mat) kern_size <- ncol(error_mat) u_hat <- rep(1 / kern_size, kern_size) A_est <- (1 / kern_size) * A_hat[[1]] if (kern_size != 1) { for (d in 2:kern_size) { A_est <- A_est + (1 / kern_size) * A_hat[[d]] } } list(A_est = A_est, u_hat = u_hat) } #' Estimating Ensemble Kernel Matrices Using EXP #' #' Give the ensemble projection matrix and weights of the kernels in the #' library using exponential weighting. #' #' \bold{Exponential Weighting} #' #' Additionally, another scholar gives a new strategy to calculate weights #' based on the estimated errors \eqn{\{\hat{\epsilon}_d\}_{d=1}^D}. #' \deqn{u_d(\beta)=\frac{exp(-\parallel \hat{\epsilon}_d #' \parallel_2^2/\beta)}{\sum_{d=1}^Dexp(-\parallel \hat{\epsilon}_d #' \parallel_2^2/\beta)}} #' #' \bold{beta_exp} #' #' The value of beta_exp can be "min"=\eqn{min\{RSS\}_{d=1}^D/10}, #' "med"=\eqn{median\{RSS\}_{d=1}^D}, "max"=\eqn{max\{RSS\}_{d=1}^D*2} and any #' other positive numeric number, where \eqn{\{RSS\} _{d=1}^D} are the set of #' residual sum of squares of \eqn{D} base kernels. #' #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp". See Details. #' @param error_mat (matrix, n*K) A n\*K matrix indicating errors. #' @param A_hat (list of length K) A list of projection matrices to kernel space #' for each kernel in the kernel library. #' @return \item{A_est}{(matrix, n*n) The ensemble projection matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' @author Wenying Deng #' @seealso mode: \code{\link{tuning}} #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017. #' #' Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample #' kernel inde- pendence test for microbiome community-level association #' analysis. December 2017. #' #' Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential #' Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes #' in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. ensemble_exp <- function(beta_exp, error_mat, A_hat) { n <- nrow(error_mat) kern_size <- ncol(error_mat) A <- error_mat if (beta_exp == "med") { beta_exp <- median(apply(A, 2, function(x) sum(x ^ 2))) } else if (beta_exp == "min") { beta_exp <- min(apply(A, 2, function(x) sum(x ^ 2))) / 10 } else if (beta_exp == "max") { beta_exp <- max(apply(A, 2, function(x) sum(x ^ 2))) * 2 } beta <- as.numeric(beta_exp) u_hat <- apply(A, 2, function(x) { exp(sum(-x ^ 2 / beta)) }) u_hat <- u_hat / sum(u_hat) A_est <- u_hat[1] * A_hat[[1]] if (kern_size != 1) { for (d in 2:kern_size) { A_est <- A_est + u_hat[d] * A_hat[[d]] } } list(A_est = A_est, u_hat = u_hat) }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/ensemble.R
#' Conducting Gaussian Process Regression #' #' Conduct Gaussian process regression based on the estimated ensemble kernel #' matrix. #' #' After obtaining the ensemble kernel matrix, we can calculate the output of #' Gaussian process regression. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_list (list of matrices) A nested list of kernel term matrices. #' The first level corresponds to each base kernel function in kern_func_list, #' the second level corresponds to each kernel term specified in the formula. #' @param mode (character) A character string indicating which tuning parameter #' criteria is to be used. #' @param strategy (character) A character string indicating which ensemble #' strategy is to be used. #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp" \code{\link{ensemble_exp}}. #' @param lambda (numeric) A numeric string specifying the range of tuning #' parameter to be chosen. The lower limit of lambda must be above 0. #' @param ... Additional parameters to pass to estimate_ridge. #' #' @return \item{lambda}{(numeric) The selected tuning parameter based on the #' estimated ensemble kernel matrix.} #' #' \item{beta}{(matrix, d_fixed*1) Fixed effect estimates.} #' #' \item{alpha}{(matrix, n*1) Kernel effect estimates.} #' #' \item{K}{(matrix, n*n) Estimated ensemble kernel matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' #' \item{kern_term_effect}{(matrix, n*n) Estimated ensemble kernel effect matrix.} #' #' \item{base_est}{(list) The detailed estimation results of K kernels.} #' #' @author Wenying Deng #' @seealso strategy: \code{\link{ensemble}} #' #' @export estimation estimation <- function(Y, X, K_list = NULL, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), ...) { # base model estimate n <- length(Y) if(sum(X[, 1] == 1) != n) { X <- cbind(matrix(1, nrow = n, ncol = 1), X) } kern_size <- length(K_list) if (kern_size == 0) { # if K_list is empty, estimate only fixed effect # 'assemble' fake ensemble kernel matrix base_est <- NULL K_ens <- NULL # final estimate lambda_ens <- tuning(Y, X, K_ens, mode, lambda) ens_est <- estimate_ridge(Y = Y, X = X, K = K_ens, lambda = lambda_ens, ...) # kernel terms estimates u_weight <- 1 kern_term_effect <- NULL } else { # if K_list is not empty, estimate full ensemble base_est <- estimate_base(Y, X, K_list, mode, lambda, ...) P_K_hat <- base_est$P_K_hat error_mat <- base_est$error_mat ens_res <- ensemble(strategy, beta_exp, error_mat, P_K_hat) # assemble ensemble kernel matrix K_ens <- ensemble_kernel_matrix(ens_res$A_est) K_ens <- list(K_ens) # final estimate lambda_ens <- tuning(Y, X, K_ens, mode, lambda) ens_est <- estimate_ridge(Y = Y, X = X, K = K_ens, lambda = lambda_ens, ...) # kernel terms estimates u_weight <- ens_res$u_hat kern_term_effect <- 0 for (k in seq(kern_size)) { kern_term_effect <- kern_term_effect + u_weight[k] * base_est$kern_term_list[[k]] } } list(lambda = lambda_ens, beta = ens_est$beta, alpha = ens_est$alpha, K = K_ens[[1]], u_hat = u_weight, kern_term_effect = kern_term_effect, base_est = base_est) } #' Estimating Projection Matrices #' #' Calculate the estimated projection matrices for every kernels in the kernel #' library. #' #' For a given mode, this function returns a list of projection matrices for #' every kernel in the kernel library and a n*K matrix indicating errors. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_list (list of matrices) A nested list of kernel term matrices. #' The first level corresponds to each base kernel function in kern_func_list, #' the second level corresponds to each kernel term specified in the formula. #' @param mode (character) A character string indicating which tuning parameter #' criteria is to be used. #' @param lambda (numeric) A numeric string specifying the range of tuning #' parameter to be chosen. The lower limit of lambda must be above 0. #' @param ... Additional parameters to pass to estimate_ridge. #' #' @return \item{A_hat}{(list of length K) A list of projection matrices for #' each kernel in the kernel library.} #' #' \item{P_K_hat}{(list of length K) A list of projection matrices to kernel #' space for each kernel in the kernel library.} #' #' \item{beta_list}{(list of length K) A list of fixed effect estimators for #' each kernel in the kernel library.} #' #' \item{alpha_list}{(list of length K) A list of kernel effect estimates for #' each kernel in the kernel library.} #' #' \item{kern_term_list}{(list of length K) A list of kernel effects for #' each kernel in the kernel library.} #' #' \item{A_proc_list}{(list of length K) A list of projection matrices for #' each kernel in the kernel library.} #' #' \item{lambda_list}{(list of length K) A list of selected tuning parameters for #' each kernel in the kernel library.} #' #' \item{error_mat}{(matrix, n*K) A n\*K matrix indicating errors.} #' #' @author Wenying Deng #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017. #' @keywords internal #' @export estimate_base estimate_base <- function(Y, X, K_list, mode, lambda, ...) { A_hat <- list() P_K_hat <- list() beta_list <- list() alpha_list <- list() lambda_list <- list() kern_term_list <- list() A_proc_list <- list() n <- length(Y) kern_size <- length(K_list) error_mat <- matrix(0, nrow = n, ncol = kern_size) for (k in seq(kern_size)) { lambda0 <- tuning(Y, X, K_list[[k]], mode, lambda) estimate <- estimate_ridge(Y = Y, X = X, K = K_list[[k]], lambda = lambda0, ...) A <- estimate$proj_matrix$total # produce loocv error matrix error_mat[, k] <- (diag(n) - A) %*% Y / (1 - diag(A)) A_hat[[k]] <- A P_K_hat[[k]] <- estimate$proj_matrix$P_K0 beta_list[[k]] <- estimate$beta alpha_list[[k]] <- estimate$alpha kern_term_list[[k]] <- estimate$kern_term_mat lambda_list[[k]] <- lambda0 A_proc_list[[k]] <- estimate$A_list } list(A_hat = A_hat, P_K_hat = P_K_hat, beta_list = beta_list, alpha_list = alpha_list, kern_term_list = kern_term_list, A_proc_list = A_proc_list, lambda_list = lambda_list, error_mat = error_mat) } #' Estimating a Single Model #' #' Estimating projection matrices and parameter estimates for a single model. #' #' For a single model, we can calculate the output of gaussian process #' regression, the solution is given by \deqn{\hat{\beta}=[X^T(K+\lambda #' I)^{-1}X]^{-1}X^T(K+\lambda I)^{-1}y} \deqn{\hat{\alpha}=(K+\lambda #' I)^{-1}(y-\hat{\beta}X)}. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @param compute_kernel_terms (logic) Whether to computing effect for each individual terms. #' If FALSE then only compute the overall effect. #' @param converge_thres (numeric) The convergence threshold for computing kernel terms. #' #' @return \item{beta}{(matrix, d_fixed*1) Fixed effect estimates.} #' #' \item{alpha}{(matrix, n*k_terms) Kernel effect estimates for each kernel term.} #' #' \item{kern_term_mat}{(matrix, n*k_terms) Kernel effect for each kernel term.} #' #' \item{A_list}{(list of length k_terms) Projection matrices for each kernel term.} #' #' \item{proj_matrix}{(list of length 4) Estimated projection matrices, combined #' across kernel terms.} #' @author Wenying Deng #' @references Andreas Buja, Trevor Hastie, and Robert Tibshirani. (1989) #' Linear Smoothers and Additive Models. Ann. Statist. Volume 17, Number 2, 453-510. #' @export estimate_ridge estimate_ridge <- function(Y, X, K, lambda, compute_kernel_terms=TRUE, converge_thres=1e-4){ # standardize kernel matrix n <- length(Y) if(sum(X[, 1] == 1) != n) { X <- cbind(matrix(1, nrow = n, ncol = 1), X) } # initialize parameters and calculate projection matrices X_mat <- ginv(t(X) %*% X) %*% t(X) beta <- X_mat %*% Y P_K <- 0 P_X <- X %*% X_mat A_list <- NULL P_K0 <- NULL alpha_mat <- NULL kern_term_mat <- NULL if (!is.null(K)) { # prepare matrices needed for computing project alpha_mat <- matrix(0, nrow = n, ncol = length(K)) A <- 0 H <- X %*% X_mat V_inv_list <- list() A_list <- list() for (d in seq(length(K))) { K[[d]] <- K[[d]] / sum(diag(K[[d]])) V_inv_list[[d]] <- ginv(K[[d]] + lambda * diag(n)) alpha_mat[, d] <- V_inv_list[[d]] %*% (Y - X %*% beta) S_d <- K[[d]] %*% V_inv_list[[d]] A_list[[d]] <- (diag(n) + K[[d]] / lambda) %*% S_d A <- A + A_list[[d]] } B <- ginv(diag(n) + A) %*% A # project matrices # residual projection to kernel space P_K <- ginv(diag(n) - B %*% H) %*% B %*% (diag(n) - H) # projection to fixed-effect space P_X <- H %*% (diag(n) - P_K) # projection to kernel space # P_K0 <- P_K %*% ginv(diag(n) - P_X) P_K0 <- B # compute kernel term effects if (!compute_kernel_terms) { # compute overall effect beta <- X_mat %*% (diag(n) - P_K) %*% Y kern_term_mat <- P_K %*% Y } else { # compute individual terms by iterative update using backfitting algorithm alpha_temp <- 1e3 * alpha_mat beta <- X_mat %*% (diag(n) - P_K) %*% Y while (euc_dist(alpha_mat, alpha_temp) > converge_thres) { alpha_temp <- alpha_mat kernel_effect <- 0 for (d in seq(length(K))) { kernel_effect <- kernel_effect + K[[d]] %*% alpha_mat[, d] } for (d in seq(length(K))) { alpha_mat[, d] <- V_inv_list[[d]] %*% (Y - X %*% beta - kernel_effect + K[[d]] %*% alpha_mat[, d]) } } # kernel terms estimates kern_term_mat <- matrix(0, nrow = n, ncol = length(K)) for (d in seq(length(K))) { kern_term_mat[, d] <- K[[d]] %*% alpha_mat[, d] } } } proj_matrix_list <- list(total = P_X + P_K, P_X = P_X, P_K = P_K, P_K0 = P_K0) list(beta = beta, alpha = alpha_mat, kern_term_mat = kern_term_mat, A_list = A_list, proj_matrix = proj_matrix_list) } #' Calculating Ensemble Kernel Matrix #' #' Calculating ensemble kernel matrix and truncating those columns whose #' eigenvalues are smaller than the given threshold. #' #' After we obtain the ensemble projection matrix, we can calculate the #' ensemble kernel matrix. #' #' @param A_est (matrix) Ensemble projection matrix. #' @param eig_thres (numeric) Threshold to truncate the kernel matrix. #' @return \item{K_hat}{(matrix, n*n) Estimated ensemble kernel matrix.} #' @author Wenying Deng #' @keywords internal #' @export ensemble_kernel_matrix ensemble_kernel_matrix <- function(A_est, eig_thres = 1e-11) { As <- svd(A_est) U <- As$u d <- As$d # produce spectral components for ensemble kernel matrix ensemble_dim <- sum(d > eig_thres) U_ens <- U[, 1:ensemble_dim] d_ens <- d[1:ensemble_dim] / (1 - d[1:ensemble_dim]) # assemble ensemble matrix and return K_hat <- U_ens %*% diag(d_ens) %*% t(U_ens) K_hat / sum(diag(K_hat)) }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/estimation.R
#' Generating A Single Kernel #' #' Generate kernels for the kernel library. #' #' There are seven kinds of kernel available here. For convenience, we define #' \eqn{r=\mid x-x'\mid}. #' #' \bold{Gaussian RBF Kernels} \deqn{k_{SE}(r)=exp\Big(-\frac{r^2}{2l^2}\Big)} #' #' \bold{Matern Kernels} #' \deqn{k_{Matern}(r)=\frac{2^{1-\nu}}{\Gamma(\nu)}\Big(\frac{\sqrt{2\nu #' r}}{l}\Big)^\nu K_\nu \Big(\frac{\sqrt{2\nu r}}{l}\Big)} #' #' \bold{Rational Quadratic Kernels} \deqn{k_{RQ}(r)=\Big(1+\frac{r^2}{2\alpha #' l^2}\Big)^{-\alpha}} #' #' \bold{Polynomial Kernels} \deqn{k(x, x')=(x \cdot x')^p} We have intercept #' kernel when \eqn{p=0}, and linear kernel when \eqn{p=1}. #' #' \bold{Neural Network Kernels} \deqn{k_{NN}(x, #' x')=\frac{2}{\pi}sin^{-1}\Big(\frac{2\sigma \tilde{x}^T #' \tilde{x}'}{\sqrt{(1+2\sigma \tilde{x}^T \tilde{x})(1+2\sigma \tilde{x}'^T #' \tilde{x}')}}\Big)} where \eqn{\tilde{x}} is the vector \eqn{x} prepending #' with \eqn{1}. #' #' @param method (character) A character string indicating which kernel #' is to be computed. #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / 2; for #' rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{kern}{(function) A function indicating the generated kernel.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. #' @examples #' #' kern_par <- data.frame(method = c("rbf", "polynomial", "matern"), #' l = c(.5, 1, 1.5), p = 1:3, sigma = rep(1, 3), stringsAsFactors = FALSE) #' #' kern_func_list <- list() #' for (j in 1:nrow(kern_par)) { #' kern_func_list[[j]] <- generate_kernel(kern_par[j, ]$method, #' kern_par[j, ]$l, #' kern_par[j, ]$p, #' kern_par[j, ]$sigma) #' } #' #' #' @export generate_kernel #' #' @import MASS limSolve stats generate_kernel <- function(method = "rbf", l = 1, p = 2, sigma = 1) { method <- match.arg(method, c("intercept", "linear", "polynomial", "rbf", "matern", "rational", "nn")) func_name <- paste0("kernel_", method) matrix_wise <- do.call(func_name, list(l = l, p = p, sigma = sigma)) kern <- function(X1, X2) { matrix_wise(X1, X2, l, p, sigma) } kern } #' Generating A Single Matrix-wise Function Using Intercept #' #' Generate matrix-wise functions for two matrices using intercept kernel. #' #' \bold{Polynomial Kernels} \deqn{k(x, x')=(x \cdot x')^p} We have intercept #' kernel when \eqn{p=0}, and linear kernel when \eqn{p=1}. #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_intercept <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma) { matrix(1, nrow = nrow(X1), ncol = nrow(X2)) } matrix_wise } #' Generating A Single Matrix-wise Function Using Linear #' #' Generate matrix-wise functions for two matrices using linear kernel. #' #' \bold{Polynomial Kernels} \deqn{k(x, x')=(x \cdot x')^p} We have intercept #' kernel when \eqn{p=0}, and linear kernel when \eqn{p=1}. #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_linear <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma) { X1 %*% t(X2) } matrix_wise } #' Generating A Single Matrix-wise Function Using Polynomial #' #' Generate matrix-wise functions for two matrices using polynomial kernel. #' #' \bold{Polynomial Kernels} \deqn{k(x, x')=(x \cdot x')^p} We have intercept #' kernel when \eqn{p=0}, and linear kernel when \eqn{p=1}. #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_polynomial <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma) { (X1 %*% t(X2) + 1) ^ p } matrix_wise } #' Generating A Single Matrix-wise Function Using RBF #' #' Generate matrix-wise functions for two matrices using rbf kernel. #' #' \bold{Gaussian RBF Kernels} \deqn{k_{SE}(r)=exp\Big(-\frac{r^2}{2l^2}\Big)} #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_rbf <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma) { exp(-square_dist(X1, X2, l = sqrt(2) * l)) } matrix_wise } #' Generating A Single Matrix-wise Function Using Matern #' #' Generate matrix-wise functions for two matrices using matern kernel. #' #' \bold{Matern Kernels} #' \deqn{k_{Matern}(r)=\frac{2^{1-\nu}}{\Gamma(\nu)}\Big(\frac{\sqrt{2\nu #' r}}{l}\Big)^\nu K_\nu \Big(\frac{\sqrt{2\nu r}}{l}\Big)} #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_matern <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma){ r <- sqrt(square_dist(X1, X2)) v <- p + 1 / 2 s <- 0 for (i in 0:p) { s <- s + factorial(p + i) / (factorial(i) * factorial(p - i)) * (sqrt(8 * v) * r / l) ^ (p - i) } exp(-sqrt(2 * v) * r / l) * gamma(p + 1) / gamma(2 * p + 1) * s } matrix_wise } #' Generating A Single Matrix-wise Function Using Rational Quadratic #' #' Generate matrix-wise functions for two matrices using rational kernel. #' #' \bold{Rational Quadratic Kernels} \deqn{k_{RQ}(r)=\Big(1+\frac{r^2}{2\alpha #' l^2}\Big)^{-\alpha}} #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_rational <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma){ r <- sqrt(square_dist(X1, X2)) (1 + r ^ 2 / (2 * p * l ^ 2)) ^ (-p) } matrix_wise } #' Generating A Single Matrix-wise Function Using Neural Network #' #' Generate matrix-wise functions for two matrices using neural network kernel. #' #' \bold{Neural Network Kernels} \deqn{k_{NN}(x, #' x')=\frac{2}{\pi}sin^{-1}\Big(\frac{2\tilde{x}^T #' \tilde{x}'}{\sqrt{(1+2\tilde{x}^T \tilde{x})(1+2\tilde{x}'^T #' \tilde{x}')}}\Big)} #' #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @param p (integer) For polynomial, p is the power; for matern, v = p + 1 / #' 2; for rational, alpha = p. #' @param sigma (numeric) The covariance coefficient for neural network kernel. #' @return \item{matrix_wise}{(function) A function calculating the relevance #' of two matrices.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. kernel_nn <- function(l, p, sigma) { matrix_wise <- function(X1, X2, l, p, sigma){ X1 <- cbind(1, X1) X2 <- cbind(1, X2) X1s <- apply(X1, 1, crossprod) X2s <- apply(X2, 1, crossprod) X1m <- matrix(X1s, nrow = length(X1s), ncol = nrow(X2), byrow = FALSE) X2m <- matrix(X2s, nrow = nrow(X1), ncol = length(X2s), byrow = TRUE) s <- 2 * sigma * (X1 %*% t(X2)) / (sqrt((1 + 2 * sigma * X1m) * (1 + 2 * sigma * X2m))) 2 / pi * asin(s) } matrix_wise } #' Computing Square Distance between Two Sets of Variables #' #' Compute Squared Euclidean distance between two sets of variables with the #' same dimension. #' #' #' @param X1 (matrix, n1*p0) The first set of variables. #' @param X2 (matrix, n2*p0) The second set of variables. #' @param l (numeric) A numeric number indicating the hyperparameter #' (flexibility) of a specific kernel. #' @return \item{dist_sq}{(matrix, n1*n2) The computed squared Euclidean distance.} #' @author Wenying Deng #' @references The MIT Press. Gaussian Processes for Machine Learning, 2006. #' @keywords internal #' @export square_dist square_dist <- function(X1, X2 = NULL, l = 1) { X1 <- X1 / l X1s <- apply(X1, 1, crossprod) if (is.null(X2)) { X2 <- X1 X2s <- X1s } else { if (ncol(X1) != ncol(X2)) { stop("dimensions of X1 and X2 do not match!") } X2 <- X2 / l X2s <- apply(X2, 1, crossprod) } dist <- -2 * X1 %*% t(X2) X1m <- matrix(X1s, nrow = length(X1s), ncol = nrow(X2), byrow = FALSE) X2m <- matrix(X2s, nrow = nrow(X1), ncol = length(X2s), byrow = TRUE) dist_sq <- dist + X1m + X2m dist_sq[which(abs(dist_sq) < 1e-12)] <- 0 dist_sq }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/generate_kernel.R
#' Conducting Cross-validated Kernel Ensemble #' #' Conducting Cross-validated Kernel Ensemble based on user-specified formula. #' #' Perform Cross-validated Kernel Ensemble and optionally test for kernel effect #' based on user-specified formula. #' #' @param formula (formula) A user-supplied formula for the null model. Should #' contain at least one kernel term. #' @param kern_func_list (list) A list of kernel functions in the kernel library. #' @param data (data.frame, n*d) A data.frame, list or environment (or object #' coercible by as.data.frame to a data.frame), containing the variables in #' formula. Neither a matrix nor an array will be accepted. #' @param formula_test (formula) A user-supplied formula indicating the alternative #' effect to test. All terms in the alternative mode must be specified as kernel terms. #' @param mode (character) A character string indicating which tuning parameter #' criteria is to be used. #' @param strategy (character) A character string indicating which ensemble #' strategy is to be used. #' @param beta_exp (numeric/character) A numeric value specifying the parameter #' when strategy = "exp" \code{\link{ensemble_exp}}. #' @param lambda (numeric) A numeric string specifying the range of #' tuning parameter to be chosen. The lower limit of lambda must be above 0. #' @param test (character) Type of hypothesis test to conduct. Must be either #' 'asymp' or 'boot'. #' @param alt_kernel_type (character) Type of alternative kernel effect to consider. #' Must be either "linear" or "ensemble". #' @param B (numeric) Number of bootstrap samples. #' @param verbose (logical) Whether to print additional messages. #' #' @return \item{lambda}{(numeric) The selected tuning parameter based on the #' estimated ensemble kernel matrix.} #' #' \item{beta}{(matrix, d_fixed*1) Fixed effect estimates.} #' #' \item{alpha}{(matrix, n*1) Kernel effect estimates.} #' #' \item{K}{(matrix, n*n) Estimated ensemble kernel matrix.} #' #' \item{u_hat}{(vector of length K) A vector of weights of the kernels in the #' library.} #' #' \item{base_est}{(list) The detailed estimation results of K kernels.} #' #' \item{pvalue}{(numeric) If formula_test is given, p-value of the test is returned.} #' #' @author Jeremiah Zhe Liu #' @seealso \code{\link{estimation}} #' #' method: \code{\link{generate_kernel}} #' #' mode: \code{\link{tuning}} #' #' strategy: \code{\link{ensemble}} #' @references Xihong Lin. Variance component testing in generalised linear #' models with random effects. June 1997. #' #' Arnab Maity and Xihong Lin. Powerful tests for detecting a gene effect in #' the presence of possible gene-gene interactions using garrote kernel #' machines. December 2011. #' #' Petra Bu z kova, Thomas Lumley, and Kenneth Rice. Permutation and #' parametric bootstrap tests for gene-gene and gene-environment interactions. #' January 2011. #' #' @examples #' #' kern_par <- data.frame(method = rep("rbf", 3), #' l = rep(3, 3), p = rep(2, 3), #' stringsAsFactors = FALSE) #' # define kernel library #' kern_func_list <- define_library(kern_par) #' #' n <- 10 #' d <- 4 #' formula <- y ~ x1 + x2 + k(x3, x4) #' formula_test <- y ~ k(x1, x2) * k(x3, x4) #' set.seed(1118) #' data <- as.data.frame(matrix( #' rnorm(n * d), #' ncol = d, #' dimnames = list(NULL, paste0("x", 1:d)) #' )) #' beta_true <- c(1, .41, 2.37) #' lnr_kern_func <- generate_kernel(method = "rbf", l = 3) #' kern_effect_lnr <- #' parse_kernel_variable("k(x3, x4)", lnr_kern_func, data) #' alpha_lnr_true <- rnorm(n) #' #' data$y <- as.matrix(cbind(1, data[, c("x1", "x2")])) %*% beta_true + #' kern_effect_lnr %*% alpha_lnr_true #' #' data_train <- data #' #' pvalue <- cvek(formula, #' kern_func_list, #' data_train, #' formula_test, #' mode = "loocv", #' strategy = "stack", #' beta_exp = 1, #' lambda = exp(seq(-2, 2)), #' test = "asymp", #' alt_kernel_type = "linear", #' verbose = FALSE)$pvalue #' #' @export cvek cvek <- function(formula, kern_func_list, data, formula_test = NULL, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "boot", alt_kernel_type = "linear", B = 100, verbose = FALSE) { # specify model matrices for main model model_matrices <- parse_cvek_formula( formula, kern_func_list = kern_func_list, data = data, verbose = verbose ) # conduct estimation est_res <- estimation( Y = model_matrices$y, X = model_matrices$X, K_list = model_matrices$K, mode = mode, strategy = strategy, beta_exp = beta_exp, lambda = lambda ) est_res$model_matrices <- model_matrices est_res$kern_func_list <- kern_func_list est_res$formula <- formula est_res$data <- data # conduct hypothesis test if formula_test is given. if (class(formula_test) == "formula") { est_res$pvalue <- cvek_test(est_res, formula_test, kern_func_list, data, test = test, alt_kernel_type = alt_kernel_type, B = B, verbose = verbose ) } class(est_res) <- "cvek" est_res } #' Conduct Hypothesis Testing #' #' Conduct hypothesis testing based on CVEK estimation result. #' #' Conduct score tests comparing a fitted model and a more general alternative #' model. #' #' There are two tests available here: #' #' \bold{Asymptotic Test} #' #' This is based on the classical variance component test to construct a #' testing procedure for the hypothesis about Gaussian process function. #' #' \bold{Bootstrap Test} #' #' When it comes to small sample size, we can use bootstrap test instead, which #' can give valid tests with moderate sample sizes and requires similar #' computational effort to a permutation test. In the case of bootstrap test, #' we can specify the form of the null derivative kernel (alt_kernel_type) to be #' linear or ensemble. The bootstrap test allows the null derivative #' kernel to be estimated adaptively from data using the same corresponding #' ensemble weights to better represent the alternative hypothesis space. #' #' @param est_res (list) Estimation results returned by estimation() procedure. #' @param formula_test (formula) A user-supplied formula indicating the alternative #' effect to test. All terms in the alternative mode must be specified as kernel terms. #' @param kern_func_list (list) A list of kernel functions in the kernel library #' @param data (data.frame, n*d) A data.frame, list or environment (or object #' coercible by as.data.frame to a data.frame), containing the variables in #' formula. Neither a matrix nor an array will be accepted. #' @param test (character) Type of hypothesis test to conduct. #' Must be either 'asymp' or 'boot'. #' @param alt_kernel_type (character) Type of alternative kernel effect to consider. #' Must be either 'linear' or 'ensemble' #' @param B (integer) A numeric value indicating times of resampling when test #' = "boot". #' @param verbose (logical) Whether to print additional messages. #' #' @return \item{pvalue}{(numeric) p-value of the test.} #' #' @keywords internal #' @export cvek_test cvek_test <- function(est_res, formula_test, kern_func_list, data, test = "boot", alt_kernel_type = "linear", B = 100, verbose = FALSE) { alt_kernel_type <- match.arg(alt_kernel_type, c("linear", "ensemble")) # define kernel functions for alternative effect if (alt_kernel_type == "linear") { lnr_kern_func <- generate_kernel(method = "linear") alt_kern_func_list <- list(lnr_kern_func) } else if (alt_kernel_type == "ensemble") { alt_kern_func_list <- kern_func_list } # parse alternative effect formula to get kernel matrices test_matrices <- parse_cvek_formula( formula_test, kern_func_list = alt_kern_func_list, data = data, verbose = verbose ) # check if alternative effect contains linear terms linear_terms <- setdiff(colnames(test_matrices$X), "(Intercept)") if (length(linear_terms) > 0) { stop( gettextf( "'formula_test' should contain only kernel terms. Linear terms found: %s", paste0(linear_terms, collapse = ", ") ) ) } # compute alternative kernel effect if (alt_kernel_type == "linear") { K_std_list <- lapply(test_matrices$K[[1]], function(K) K / sum(diag(K))) K_int <- Reduce("+", K_std_list) } else { u_weight <- est_res$u_hat K_int <- 0 for (k in seq(length(kern_func_list))) { K_std_list <- lapply(test_matrices$K[[k]], function(K) K / sum(diag(K))) K_temp <- Reduce("+", K_std_list) K_int <- K_int + u_weight[k] * K_temp } } model_matrices <- est_res$model_matrices # estimate variance component parameters y_fixed <- model_matrices$X %*% est_res$beta sigma2_hat <- estimate_sigma2( Y = model_matrices$y, X = model_matrices$X, lambda_hat = est_res$lambda, y_fixed_hat = y_fixed, alpha_hat = est_res$alpha, K_hat = est_res$K ) tau_hat <- sigma2_hat / est_res$lambda # compute p-value func_name <- paste0("test_", test) do.call( func_name, list(Y = model_matrices$y, X = model_matrices$X, y_fixed = y_fixed, alpha0 = est_res$alpha, K_ens = est_res$K, K_int = K_int, sigma2_hat = sigma2_hat, tau_hat = tau_hat, B = B ) ) } #' Parsing User-supplied Formula #' #' Parsing user-supplied formula to fixed-effect and kernel matrices. #' #' @param formula (formula) A user-supplied formula. #' @param kern_func_list (list) A list of kernel functions in the kernel library #' @param data (data.frame, n*d) A data.frame, list or environment (or object #' coercible by as.data.frame to a data.frame), containing the variables in #' formula. Neither a matrix nor an array will be accepted. #' @param data_new (data.frame, n_new*d) New data for computing predictions. #' @param verbose (logical) Whether to print additional messages. #' #' @return A list of three slots: #' \item{Y}{(matrix, n*1) The vector of response variable.} #' \item{X}{(matrix, n*d_fix) The fixed effect matrix.} #' \item{K}{(list of matrices) A nested list of kernel term matrices. #' The first level corresponds to each base kernel function in #' kern_func_list, the second level corresponds to each kernel term #' specified in the formula.} #' #' @details #' The formula object is exactly like the formula for a GLM except that user can #' use k() to specify kernel terms. #' Additionally, user can specify interaction between kernel terms (using either '*' and ':'), #' and exclude interaction term by including -1 on the RHS of formula. #' #' @author Jeremiah Zhe Liu #' @export parse_cvek_formula parse_cvek_formula <- function(formula, kern_func_list, data, data_new = NULL, verbose = FALSE) { # extract dependent variables and terms tf <- terms.formula(formula, specials = c("k")) term_names <- attr(tf, "term.labels") num_terms <- length(term_names) var_table <- attr(tf, "factors") # extract dependent variables and intercept intercept <- attr(tf, "intercept") response_vector <- NULL if ((attr(tf, "response") > 0) & is.null(data_new)) { response_name <- as.character(attr(tf, "variables")[2]) response_vector <- data[, response_name] } # identify fixed-effect and kernel-effect terms kern_var_idx <- attr(tf, "specials")$k kern_term_idx <- NULL fixd_term_idx <- NULL if (length(kern_var_idx) > 0) { # if the formula contains kernel terms, identify their locations kern_term_idx <- which(colSums(var_table[kern_var_idx, , drop = FALSE]) > 0) fixd_term_idx <- setdiff(1:num_terms, kern_term_idx) if (length(fixd_term_idx) == 0) { # set fixd_term_idx back to NULL if it is an empty set fixd_term_idx <- NULL } } else { fixd_term_idx <- 1:num_terms } # assemble fixed-effect and kernel-effect formula kern_effect_formula <- NULL fixed_effect_formula <- NULL if (!is.null(kern_term_idx)) { kern_effect_formula <- as.formula(paste("~", paste(term_names[kern_term_idx], collapse = " + "))) } if (!is.null(fixd_term_idx)) { fixed_effect_formula <- paste("~", paste(term_names[fixd_term_idx], collapse = " + ")) if (intercept == 0) fixed_effect_formula <- paste0(fixed_effect_formula, " -1") fixed_effect_formula <- as.formula(fixed_effect_formula) } else if (intercept > 0) { # intercept only fixed_effect_formula <- ~ 1 } # produce fixed-effect matrix X using model.frame fixed_effect_matrix <- NULL if (!is.null(fixed_effect_formula)) { fixed_effect_data <- data if (!is.null(data_new)) { fixed_effect_data <- data_new } mm <- model.frame(fixed_effect_formula, data = data) xlevels <- .getXlevels(terms.formula(fixed_effect_formula), mm) m <- model.frame(fixed_effect_formula, data = fixed_effect_data, xlev = xlevels) fixed_effect_matrix <- model.matrix(fixed_effect_formula, data = m) } # produce kernel-effect matrices Ks # (list of kernel terms, one for each kernel in library) kernel_effect_matrix_list <- vector("list", length = length(kern_func_list)) names(kernel_effect_matrix_list) <- names(kern_func_list) if (!is.null(kern_effect_formula)) { if (verbose) print("Preparing Kernels...") for (kern_func_id in 1:length(kern_func_list)) { # prepare kernel function kern_func <- kern_func_list[[kern_func_id]] # compute kernel terms using the kern_func, then store to list kernel_effect_matrix_list[[kern_func_id]] <- parse_kernel_terms(kern_effect_formula, kern_func, data = data, data_new = data_new) } if (verbose) print("Done!") } # combine and return list(y = response_vector, X = fixed_effect_matrix, K = kernel_effect_matrix_list) } #' Compute Kernel Matrix #' #' Compute kernel matrix for each kernel term in the formula. #' #' @param kern_effect_formula (character) A term in the formula. #' @param kern_func (function) A kernel function. Will be overwritten to linear #' kernel if the variable doesn't contain 'k()'. #' @param data (data.frame, n*d) A data.frame, list or environment (or object #' coercible by as.data.frame to a data.frame), containing the variables in #' formula. Neither a matrix nor an array will be accepted. #' @param data_new (data.frame, n_new*d) New data for computing predictions. #' #' @return \item{kern_term_list}{(list) A list of kernel matrices for each term #' in the formula.} #' #' @author Jeremiah Zhe Liu #' @keywords internal #' @export parse_kernel_terms parse_kernel_terms <- function(kern_effect_formula, kern_func, data, data_new = NULL) { kern_var_table <- attr(terms(kern_effect_formula), "factors") kern_var_names <- rownames(kern_var_table) kern_term_names <- colnames(kern_var_table) # prepare kernel variables kern_var_list <- vector("list", length = length(kern_var_names)) names(kern_var_list) <- kern_var_names for (var_name in kern_var_names) { # compute individual kernel variables for each base kernel kern_var_list[[var_name]] <- parse_kernel_variable(var_name, kern_func = kern_func, data = data, data_new = data_new) } # assemble kernel terms (for interaction terms) kern_term_list <- vector("list", length = length(kern_term_names)) names(kern_term_list) <- kern_term_names for (term_id in 1:length(kern_term_names)) { term_name <- kern_term_names[term_id] kern_term_var_idx <- which(kern_var_table[, term_id] > 0) # compute interaction term kern_term_list[[term_name]] <- Reduce("*", kern_var_list[kern_term_var_idx]) } kern_term_list } #' Create Kernel Matrix #' #' Create kernel matrix for each variable in the formula. #' #' @param kern_var_name (vector of characters) Names of variables in data to #' create the kernel matrix from. Must be a single term that is either of the form #' \eqn{x} (a single linear term) or \eqn{k(x1, x2, \dots)} (a kernel term that may #' contain multiple variables). #' @param kern_func (function) A kernel function. Will be overwritten to linear #' kernel if the variable doesn't contain 'k()'. #' @param data (data.frame, n*d) A data.frame, list or environment (or object #' coercible by as.data.frame to a data.frame), containing the variables in #' formula. Neither a matrix nor an array will be accepted. #' @param data_new (data.frame, n_new*d) New data for computing predictions. #' #' @return \item{kernel_mat}{(matrix, n*n) The kernel matrix corresponding to #' the variable being computed.} #' #' @author Jeremiah Zhe Liu #' @keywords internal #' @export parse_kernel_variable parse_kernel_variable <- function(kern_var_name, kern_func, data, data_new=NULL) { # parse kernel term kern_term_formula <- terms.formula(formula(paste("~", kern_var_name)), specials = c("k")) is_fixed_eff <- is.null(attr(kern_term_formula, "specials")$k) input_var_names <- all.vars(kern_term_formula) # sets kern_func to linear kernel if kern_var is a fixed-effect term if (is_fixed_eff) { kern_func <- generate_kernel(method = "linear") } # extract data Z_extract_command <- gettextf("cbind(%s)", paste(input_var_names, collapse = ", ")) Z_mat <- eval(parse(text = Z_extract_command), envir = data) Z_mat_new <- Z_mat if (!is.null(data_new)){ Z_mat_new <- eval(parse(text = Z_extract_command), envir = data_new) } # compute kernel matrix and return kernel_mat <- kern_func(Z_mat_new, Z_mat) kernel_mat }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/interface.R
#' Predicting New Response #' #' Predicting new response based on given design matrix and #' the estimation result. #' #' After we obtain the estimation result, we can predict new response. #' #' @param object (list) Estimation results returned by cvek() procedure. #' @param newdata (dataframe) The new set of predictors, whose name is #' the same as those of formula in cvek(). #' @param ... Further arguments passed to or from other methods. #' @return \item{y_pred}{(matrix, n*1) Predicted new response.} #' @author Wenying Deng #' @examples #' #' kern_par <- data.frame(method = rep("rbf", 3), #' l = rep(3, 3), p = rep(2, 3), #' stringsAsFactors = FALSE) #' # define kernel library #' kern_func_list <- define_library(kern_par) #' #' n <- 10 #' d <- 4 #' formula <- y ~ x1 + x2 + k(x3, x4) #' set.seed(1118) #' data <- as.data.frame(matrix( #' rnorm(n * d), #' ncol = d, #' dimnames = list(NULL, paste0("x", 1:d)) #' )) #' beta_true <- c(1, .41, 2.37) #' lnr_kern_func <- generate_kernel(method = "rbf", l = 3) #' kern_effect_lnr <- #' parse_kernel_variable("k(x3, x4)", lnr_kern_func, data) #' alpha_lnr_true <- rnorm(n) #' #' data$y <- as.matrix(cbind(1, data[, c("x1", "x2")])) %*% beta_true + #' kern_effect_lnr %*% alpha_lnr_true #' #' data_train <- data[1:6, ] #' data_test <- data[7:10, ] #' #' result <- cvek(formula, #' kern_func_list, #' data_train, #' mode = "loocv", #' strategy = "stack", #' beta_exp = 1, #' lambda = exp(seq(-2, 2)), #' test = "asymp", #' alt_kernel_type = "linear", #' verbose = FALSE) #' #' predict(result, data_test) #' #' @importFrom utils data #' @export predict.cvek #' @export predict.cvek <- function(object, newdata, ...) { model_matrices <- object$model_matrices kern_func_list <- object$kern_func_list new_matrices <- parse_cvek_formula(object$formula, kern_func_list, data = object$data, data_new = newdata) X <- new_matrices$X A <- 0 Xmat <- ginv(t(model_matrices$X) %*% model_matrices$X) %*% t(model_matrices$X) H <- model_matrices$X %*% Xmat H_star <- X %*% Xmat n <- length(object$alpha) P_K_star <- list() P_X_star <- list() y_pred <- 0 for (k in seq(length(kern_func_list))) { B_temp <- 0 for (d in seq(length(new_matrices$K[[k]]))) { S_d_star <- new_matrices$K[[k]][[d]] %*% ginv(model_matrices$K[[k]][[d]] + object$base_est$lambda_list[[k]] * diag(n)) B_temp <- B_temp + S_d_star %*% (diag(n) + object$base_est$A_proc_list[[k]][[d]]) } B_star <- B_temp %*% (diag(n) - object$base_est$P_K_hat[[k]]) P_K <- ginv(diag(n) - object$base_est$P_K_hat[[k]] %*% H) %*% object$base_est$P_K_hat[[k]] %*% (diag(n) - H) P_K_star[[k]] <- B_star %*% (diag(n) - H + H %*% object$base_est$P_K_hat[[k]]) P_X_star[[k]] <- H_star %*% (diag(n) - P_K) y_pred <- y_pred + object$u_hat[k] * (P_K_star[[k]] + P_X_star[[k]]) %*% object$model_matrices$y } y_pred }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/predict.R
#' Conducting Score Tests for Interaction Using Asymptotic Test #' #' Conduct score tests comparing a fitted model and a more general alternative #' model using asymptotic test. #' #' \bold{Asymptotic Test} #' #' This is based on the classical variance component test to construct a #' testing procedure for the hypothesis about Gaussian process function. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param y_fixed (vector of length n) Estimated fixed effect of the #' response. #' @param alpha0 (vector of length n) Kernel effect estimator of the estimated #' ensemble kernel matrix. #' @param K_ens (matrix, n*n) Estimated ensemble kernel matrix. #' @param K_int (matrix, n*n) The kernel matrix to be tested. #' @param sigma2_hat (numeric) The estimated noise of the fixed effect. #' @param tau_hat (numeric) The estimated noise of the kernel effect. #' @param B (integer) A numeric value indicating times of resampling when test #' = "boot". #' @return \item{pvalue}{(numeric) p-value of the test.} #' @author Wenying Deng #' @seealso method: \code{\link{generate_kernel}} #' #' mode: \code{\link{tuning}} #' #' strategy: \code{\link{ensemble}} #' @references Xihong Lin. Variance component testing in generalised linear #' models with random effects. June 1997. #' #' Arnab Maity and Xihong Lin. Powerful tests for detecting a gene effect in #' the presence of possible gene-gene interactions using garrote kernel #' machines. December 2011. #' #' Petra Bu z kova, Thomas Lumley, and Kenneth Rice. Permutation and #' parametric bootstrap tests for gene-gene and gene-environment interactions. #' January 2011. test_asymp <- function(Y, X, y_fixed, alpha0, K_ens, K_int, sigma2_hat, tau_hat, B) { n <- length(Y) score_chi <- compute_stat(Y, K_int, y_fixed, K_ens, sigma2_hat, tau_hat) K0 <- K_ens V0_inv <- ginv(tau_hat * K0 + sigma2_hat * diag(n)) P0_mat <- V0_inv - V0_inv %*% X %*% ginv(t(X) %*% V0_inv %*% X) %*% t(X) %*% V0_inv drV0_tau <- K0 drV0_sigma2 <- diag(n) drV0_del <- tau_hat * K_int I0 <- compute_info(P0_mat, mat_del = drV0_del, mat_sigma2 = drV0_sigma2, mat_tau = drV0_tau) tot_dim <- ncol(I0) I_deldel <- I0[1, 1] - I0[1, 2:tot_dim] %*% ginv(I0[2:tot_dim, 2:tot_dim]) %*% I0[2:tot_dim, 1] md <- tau_hat * sum(diag(K_int %*% P0_mat)) / 2 m_chi <- I_deldel / (2 * md) d_chi <- md / m_chi pvalue <- 1 - pchisq(score_chi / m_chi, d_chi) pvalue } #' Conducting Score Tests for Interaction Using Bootstrap Test #' #' Conduct score tests comparing a fitted model and a more general alternative #' model using bootstrap test. #' #' \bold{Bootstrap Test} #' #' When it comes to small sample size, we can use bootstrap test instead, which #' can give valid tests with moderate sample sizes and requires similar #' computational effort to a permutation test. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param y_fixed (vector of length n) Estimated fixed effect of the #' response. #' @param alpha0 (vector of length n) Kernel effect estimator of the estimated #' ensemble kernel matrix. #' @param K_ens (matrix, n*n) Estimated ensemble kernel matrix. #' @param K_int (matrix, n*n) The kernel matrix to be tested. #' @param sigma2_hat (numeric) The estimated noise of the fixed effect. #' @param tau_hat (numeric) The estimated noise of the kernel effect. #' @param B (integer) A numeric value indicating times of resampling when test #' = "boot". #' @return \item{pvalue}{(numeric) p-value of the test.} #' @author Wenying Deng #' @seealso method: \code{\link{generate_kernel}} #' #' mode: \code{\link{tuning}} #' #' strategy: \code{\link{ensemble}} #' @references Xihong Lin. Variance component testing in generalised linear #' models with random effects. June 1997. #' #' Arnab Maity and Xihong Lin. Powerful tests for detecting a gene effect in #' the presence of possible gene-gene interactions using garrote kernel #' machines. December 2011. #' #' Petra Bu z kova, Thomas Lumley, and Kenneth Rice. Permutation and #' parametric bootstrap tests for gene-gene and gene-environment interactions. #' January 2011. test_boot <- function(Y, X, y_fixed, alpha0, K_ens, K_int, sigma2_hat, tau_hat, B) { n <- length(Y) meanY <- K_ens %*% alpha0 + y_fixed bs_test <- sapply(1:B, function(k) { Ystar <- meanY + rnorm(n, sd = sqrt(sigma2_hat)) compute_stat(Ystar, K_int, y_fixed, K_ens, sigma2_hat, tau_hat) }) original_test <- compute_stat(Y, K_int, y_fixed, K_ens, sigma2_hat, tau_hat) pvalue <- mean(as.numeric(original_test) <= bs_test) pvalue }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/testing.R
#' Calculating Tuning Parameters #' #' Calculate tuning parameters based on given criteria. #' #' There are seven tuning parameter selections here: #' #' \bold{leave-one-out Cross Validation} #' #' \deqn{\lambda_{n-CV}={argmin}_{\lambda \in #' \Lambda}\;\Big\{log\;y^{\star #' T}[I-diag(A_\lambda)-\frac{1}{n}I]^{-1}(I-A_\lambda)^2[I-diag(A_\lambda)- #' \frac{1}{n}I]^{-1}y^\star \Big\}} #' #' \bold{Akaike Information Criteria} #' #' \deqn{\lambda_{AIC}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)^2y^\star+\frac{2[tr(A_\lambda)+2]}{n}\Big\}} #' #' \bold{Akaike Information Criteria (small-sample variant)} #' #' \deqn{\lambda_{AICc}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star+\frac{2[tr(A_\lambda)+2]}{n-tr(A_\lambda)-3}\Big\}} #' #' \bold{Bayesian Information Criteria} #' #' \deqn{\lambda_{BIC}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)^2y^\star+\frac{log(n)[tr(A_\lambda)+2]}{n}\Big\}} #' #' \bold{Generalized Cross Validation} #' #' \deqn{\lambda_{GCV}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star-2log[1-\frac{tr(A_\lambda)}{n}-\frac{1}{n}]_+\Big\}} #' #' \bold{Generalized Cross Validation (small-sample variant)} #' #' \deqn{\lambda_{GCVc}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star-2log[1-\frac{tr(A_\lambda)}{n}-\frac{2}{n}]_+\Big\}} #' #' \bold{Generalized Maximum Profile Marginal Likelihood} #' #' \deqn{\lambda_{GMPML}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)y^\star-\frac{1}{n-1}log \mid I-A_\lambda \mid #' \Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param mode (character) A character string indicating which tuning parameter #' criteria is to be used. #' @param lambda (numeric) A numeric string specifying the range of tuning #' parameter to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The selected tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. #' #' @export tuning tuning <- function(Y, X, K_mat, mode, lambda) { mode <- match.arg(mode, c("AIC", "AICc", "BIC", "GCV", "GCVc", "gmpml", "loocv")) func_name <- paste0("tuning_", mode) lambda_selected <- do.call(func_name, list(Y = Y, X = X, K_mat = K_mat, lambda = lambda)) if (length(lambda_selected) != 1) { warning(paste0("Multiple (", length(lambda_selected), ") optimal lambda's found, returning the smallest one.")) } min(lambda_selected) } #' Calculating Tuning Parameters Using AIC #' #' Calculate tuning parameters based on AIC. #' #' \bold{Akaike Information Criteria} #' #' \deqn{\lambda_{AIC}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)^2y^\star+\frac{2[tr(A_\lambda)+2]}{n}\Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_AIC <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total trace_A <- sum(diag(A)) log(t(Y) %*% (diag(n) - A) %*% (diag(n) - A) %*% Y) + 2 * (trace_A + 2) / n }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using AICc #' #' Calculate tuning parameters based on AICc. #' #' \bold{Akaike Information Criteria (small sample size)} #' #' \deqn{\lambda_{AICc}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star+\frac{2[tr(A_\lambda)+2]}{n-tr(A_\lambda)-3}\Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_AICc <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total trace_A <- sum(diag(A)) log(t(Y) %*% (diag(n) - A) %*% (diag(n) - A) %*% Y) + 2 * (trace_A + 2) / (n - trace_A - 3) }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using BIC #' #' Calculate tuning parameters based on BIC. #' #' \bold{Bayesian Information Criteria} #' #' \deqn{\lambda_{BIC}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)^2y^\star+\frac{log(n)[tr(A_\lambda)+2]}{n}\Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_BIC <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total trace_A <- sum(diag(A)) log(t(Y) %*% (diag(n) - A) %*% (diag(n) - A) %*% Y) + log(n) * (trace_A + 2) / n }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using GCV #' #' Calculate tuning parameters based on GCV. #' #' \bold{Generalized Cross Validation} #' #' \deqn{\lambda_{GCV}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star-2log[1-\frac{tr(A_\lambda)}{n}-\frac{1}{n}]_+\Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_GCV <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total trace_A <- sum(diag(A)) log(t(Y) %*% (diag(n) - A) %*% (diag(n) - A) %*% Y) - 2 * log(1 - trace_A / n - 1 / n) }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using GCVc #' #' Calculate tuning parameters based on GCVc. #' #' \bold{Generalized Cross Validation (small sample size)} #' #' \deqn{\lambda_{GCVc}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star #' T}(I-A_\lambda)^2y^\star-2log[1-\frac{tr(A_\lambda)}{n}-\frac{2}{n}]_+\Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_GCVc <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total trace_A <- sum(diag(A)) log(t(Y) %*% (diag(n) - A) %*% (diag(n) - A) %*% Y) - 2 * log(max(0, 1 - trace_A / n - 2 / n)) }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using GMPML #' #' Calculate tuning parameters based on Generalized Maximum Profile Marginal #' Likelihood. #' #' \bold{Generalized Maximum Profile Marginal Likelihood} #' #' \deqn{\lambda_{GMPML}={argmin}_{\lambda \in \Lambda}\Big\{log\; #' y^{\star T}(I-A_\lambda)y^\star-\frac{1}{n-1}log \mid I-A_\lambda \mid #' \Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_gmpml <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k){ proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total log_det <- unlist(determinant(diag(n) - A), use.names = FALSE)[1] log(t(Y) %*% (diag(n) - A) %*% Y) - 1 / (n - 1) * log_det }) lambda[which(CV == min(CV))] } #' Calculating Tuning Parameters Using looCV #' #' Calculate tuning parameters based on given leave-one-out Cross Validation. #' #' \bold{leave-one-out Cross Validation} #' #' \deqn{\lambda_{n-CV}={argmin}_{\lambda \in #' \Lambda}\;\Big\{log\;y^{\star #' T}[I-diag(A_\lambda)-\frac{1}{n}I]^{-1}(I-A_\lambda)^2[I-diag(A_\lambda)- #' \frac{1}{n}I]^{-1}y^\star \Big\}} #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param K_mat (list of matrices) A nested list of kernel term matrices, #' corresponding to each kernel term specified in the formula for #' a base kernel function in kern_func_list. #' @param lambda (numeric) A numeric string specifying the range of tuning parameter #' to be chosen. The lower limit of lambda must be above 0. #' @return \item{lambda0}{(numeric) The estimated tuning parameter.} #' @author Wenying Deng #' @references Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. #' A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July #' 2015. #' #' Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of #' Statistical Learning: Data Mining, Inference, and Prediction, Second #' Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 #' edition, 2009. #' #' Hirotogu Akaike. Information Theory and an Extension of the Maximum #' Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer #' Series in Statistics, pages 199–213. Springer, New York, NY, 1998. #' #' Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model #' selection in small samples. June 1989. #' #' Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing #' parameter selection in nonparametric regression using an improved Akaike #' information criterion. January 2002. tuning_loocv <- function(Y, X, K_mat, lambda) { n <- length(Y) CV <- sapply(lambda, function(k) { proj_matrix <- estimate_ridge(Y = Y, X = X, K = K_mat, lambda = k)$proj_matrix A <- proj_matrix$total sum(((diag(n) - A) %*% Y / diag(diag(n) - A)) ^ 2) }) lambda[which(CV == min(CV))] }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/tuning.R
#' Defining Kernel Library #' #' Generate the expected kernel library based on user-specified dataframe. #' #' It creates a kernel library according to the parameters given in kern_par. #' #' * kern_par: for a library of K kernels, the dimension of this dataframe is #' K*3. Each row represents a kernel. The first column is method, with entries #' of character class. The second and the third are l and p respectively, both #' with entries of numeric class. #' #' @param kern_par (dataframe, K*3) A dataframe indicating the parameters of #' base kernels to fit kernel effect. See Details. #' @return \item{kern_func_list}{(list of length K) A list of kernel functions #' given by user. Will be overwritten to linear kernel if kern_par is NULL.} #' @author Wenying Deng #' @seealso method: \code{\link{generate_kernel}} #' #' @export define_library define_library <- function(kern_par = NULL) { if (is.null(kern_par)){ lnr_func <- generate_kernel(method = "linear") kern_func_list <- list(lnr_func) } else { kern_func_list <- list() for (d in 1:nrow(kern_par)) { kern_func_list[[d]] <- generate_kernel(kern_par[d,]$method, kern_par[d,]$l, kern_par[d,]$p, kern_par[d,]$sigma) } } kern_func_list } #' Estimating Noise #' #' An implementation of Gaussian processes for estimating noise. #' #' #' @param Y (matrix, n*1) The vector of response variable. #' @param X (matrix, n*d_fix) The fixed effect matrix. #' @param lambda_hat (numeric) The selected tuning parameter based on the #' estimated ensemble kernel matrix. #' @param y_fixed_hat (vector of length n) Estimated fixed effect of the #' response. #' @param alpha_hat (vector of length n) Kernel effect estimators of the #' estimated ensemble kernel matrix. #' @param K_hat (matrix, n*n) Estimated ensemble kernel matrix. #' @return \item{sigma2_hat}{(numeric) The estimated noise of the fixed #' effect.} #' @author Wenying Deng #' @references Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for #' Nonlinear Effect with Gaussian Processes. October 2017.s #' @keywords internal #' @export estimate_sigma2 estimate_sigma2 <- function(Y, X, lambda_hat, y_fixed_hat, alpha_hat, K_hat) { n <- length(Y) V_inv <- ginv(K_hat + lambda_hat * diag(n)) B_mat <- ginv(t(X) %*% V_inv %*% X) %*% t(X) %*% V_inv P_X <- X %*% B_mat P_K <- K_hat %*% V_inv %*% (diag(n) - P_X) A <- P_X + P_K sigma2_hat <- sum((Y - y_fixed_hat - K_hat %*% alpha_hat) ^ 2) / (n - sum(diag(A)) - 1) sigma2_hat } #' Computing Score Test Statistics. #' #' Compute score test statistics. #' #' The test statistic is distributed as a scaled Chi-squared distribution. #' #' @param Y (matrix, n*1) The vector of response variable. #' @param K_int (matrix, n*n) The kernel matrix to be tested. #' @param y_fixed (vector of length n) Estimated fixed effect of the #' response. #' @param K_0 (matrix, n*n) Estimated ensemble kernel matrix. #' @param sigma2_hat (numeric) The estimated noise of the fixed effect. #' @param tau_hat (numeric) The estimated noise of the kernel effect. #' @return \item{test_stat}{(numeric) The computed test statistic.} #' @author Wenying Deng #' @references Arnab Maity and Xihong Lin. Powerful tests for detecting a gene #' effect in the presence of possible gene-gene interactions using garrote #' kernel machines. December 2011. #' @keywords internal #' @export compute_stat compute_stat <- function(Y, K_int, y_fixed, K0, sigma2_hat, tau_hat) { n <- length(Y) V0_inv <- ginv(tau_hat * K0 + sigma2_hat * diag(n)) test_stat <- tau_hat * t(Y - y_fixed) %*% V0_inv %*% K_int %*% V0_inv %*% (Y - y_fixed) / 2 test_stat } #' Computing Information Matrices #' #' Compute information matrices based on block matrices. #' #' This function gives the information value of the interaction strength. #' #' @param P0_mat (matrix, n*n) Scale projection matrix under REML. #' @param mat_del (matrix, n*n) Derivative of the scale covariance matrix of Y #' with respect to delta. #' @param mat_sigma2 (matrix, n*n) Derivative of the scale covariance matrix of #' Y with respect to sigma2. #' @param mat_tau (matrix, n*n) Derivative of the scale covariance matrix of Y #' with respect to tau. #' @return \item{I0}{(matrix, n*n) The computed information value.} #' @author Wenying Deng #' @references Arnab Maity and Xihong Lin. Powerful tests for detecting a gene #' effect in the presence of possible gene-gene interactions using garrote #' kernel machines. December 2011. #' @keywords internal #' @export compute_info compute_info <- function(P0_mat, mat_del = NULL, mat_sigma2 = NULL, mat_tau = NULL) { I0 <- matrix(NA, 3, 3) I0[1, 1] <- sum(diag(P0_mat %*% mat_del %*% P0_mat %*% mat_del)) / 2 I0[1, 2] <- sum(diag(P0_mat %*% mat_del %*% P0_mat %*% mat_sigma2)) / 2 I0[2, 1] <- I0[1, 2] I0[1, 3] <- sum(diag(P0_mat %*% mat_del %*% P0_mat %*% mat_tau)) / 2 I0[3, 1] <- I0[1, 3] I0[2, 2] <- sum(diag(P0_mat %*% mat_sigma2 %*% P0_mat %*% mat_sigma2)) / 2 I0[2, 3] <- sum(diag(P0_mat %*% mat_sigma2 %*% P0_mat %*% mat_tau)) / 2 I0[3, 2] <- I0[2, 3] I0[3, 3] <- sum(diag(P0_mat %*% mat_tau %*% P0_mat %*% mat_tau)) / 2 I0 } #' Standardizing Matrix #' #' Center and scale the data matrix into mean zero and standard deviation one. #' #' This function gives the standardized data matrix. #' #' @param X (matrix) Original data matrix. #' @return \item{X}{(matrix) Standardized data matrix.} #' @author Wenying Deng #' @keywords internal #' @export standardize standardize <- function(X) { Xm <- colMeans(X) n <- nrow(X) p <- ncol(X) X <- X - rep(Xm, rep(n, p)) Xscale <- drop(rep(1 / n, n) %*% X ^ 2) ^ .5 X <- X / rep(Xscale, rep(n, p)) X } #' Computing Euclidean Distance between Two Vectors (Matrices) #' #' Compute the L2 distance between two vectors or matrices. #' #' This function gives the Euclidean distance between two #' vectors or matrices. #' #' @param x1 (vector/matrix) The first vector/matrix. #' @param x2 (vector/matrix, the same dimension as x1) #' The second vector/matrix. #' @return \item{dist}{(numeric) Euclidean distance.} #' @author Wenying Deng #' @keywords internal #' @export euc_dist euc_dist <- function(x1, x2 = NULL) { if (is.null(x2)) { dist <- sqrt(sum(x1 ^ 2)) } else { dist <- sqrt(sum((x1 - x2) ^ 2)) } dist }
/scratch/gouwar.j/cran-all/cranData/CVEK/R/util.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ---- message = FALSE--------------------------------------------------------- library(CVEK) library(ggplot2) library(ggrepel) ## ----------------------------------------------------------------------------- set.seed(0726) n <- 60 # including training and test d <- 4 int_effect <- 0.2 data <- matrix(rnorm(n * d), ncol = d) Z1 <- data[, 1:2] Z2 <- data[, 3:4] kern <- generate_kernel(method = "linear") w <- rnorm(n) w12 <- rnorm(n) K1 <- kern(Z1, Z1) K2 <- kern(Z2, Z2) K1 <- K1 / sum(diag(K1)) # standardize kernel K2 <- K2 / sum(diag(K2)) h0 <- K1 %*% w + K2 %*% w h0 <- h0 / sqrt(sum(h0 ^ 2)) # standardize main effect h1_prime <- (K1 * K2) %*% w12 # interaction effect # standardize sampled functions to have unit norm, so that 0.2 # represents the interaction strength relative to main effect Ks <- svd(K1 + K2) len <- length(Ks$d[Ks$d / sum(Ks$d) > .001]) U0 <- Ks$u[, 1:len] h1_prime_hat <- fitted(lm(h1_prime ~ U0)) h1 <- h1_prime - h1_prime_hat h1 <- h1 / sqrt(sum(h1 ^ 2)) # standardize interaction effect Y <- h0 + int_effect * h1 + rnorm(1) + rnorm(n, 0, 0.01) data <- as.data.frame(cbind(Y, Z1, Z2)) colnames(data) <- c("y", paste0("z", 1:d)) data_train <- data[1:40, ] data_test <- data[41:60, ] ## ---- results='asis'---------------------------------------------------------- knitr::kable(head(data_train, 5)) ## ---- fig.width=14, fig.height=11--------------------------------------------- knitr::include_graphics("table1.pdf", auto_pdf = TRUE) ## ----------------------------------------------------------------------------- kern_par <- data.frame(method = c("linear", "polynomial", "rbf"), l = rep(1, 3), p = 1:3, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ## ----------------------------------------------------------------------------- formula <- y ~ z1 + z2 + k(z3, z4) ## ----------------------------------------------------------------------------- est_res <- cvek(formula, kern_func_list = kern_func_list, data = data_train) est_res$lambda est_res$u_hat ## ----------------------------------------------------------------------------- formula_test <- y ~ k(z1, z2):k(z3, z4) cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "asymp", alt_kernel_type = "ensemble", verbose = FALSE)$pvalue cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "boot", alt_kernel_type = "ensemble", B = 200, verbose = FALSE)$pvalue ## ----------------------------------------------------------------------------- y_pred <- predict(est_res, data_test[, 2:5]) data_test_pred <- cbind(y_pred, data_test) ## ---- echo=FALSE, results='asis'---------------------------------------------- knitr::kable(head(data_test_pred, 5)) ## ---- fig.width=14, fig.height=3---------------------------------------------- knitr::include_graphics("table2.pdf", auto_pdf = TRUE) ## ----------------------------------------------------------------------------- kern_par <- data.frame(method = c("linear", "rbf"), l = rep(1, 2), p = 1:2, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ## ----------------------------------------------------------------------------- formula <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim) + k(lstat) formula_test <- medv ~ k(crim):k(lstat) fit_bos <- cvek(formula, kern_func_list = kern_func_list, data = Boston, formula_test = formula_test, lambda = exp(seq(-3, 5)), test = "asymp") ## ----------------------------------------------------------------------------- fit_bos$pvalue ## ----message=FALSE, fig.width=7, fig.height=5--------------------------------- # first fit the alternative model formula_alt <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim):k(lstat) fit_bos_alt <- cvek(formula = formula_alt, kern_func_list = kern_func_list, data = Boston, lambda = exp(seq(-3, 5))) # mean-center all confounding variables not involved in the interaction # so that the predicted values are more easily interpreted pred_name <- c("zn", "indus", "chas", "nox", "rm", "age", "dis", "rad", "tax", "ptratio", "black") covar_mean <- apply(Boston, 2, mean) pred_cov <- covar_mean[pred_name] pred_cov_df <- t(as.data.frame(pred_cov)) lstat_list <- seq(12.5, 17.5, length.out = 100) crim_quantiles <- quantile(Boston$crim, probs = c(.05, .25, .5, .75, .95)) # crim is set to its 5% quantile data_test1 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[1]) data_test1_pred <- predict(fit_bos_alt, data_test1) # crim is set to its 25% quantile data_test2 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[2]) data_test2_pred <- predict(fit_bos_alt, data_test2) # crim is set to its 50% quantile data_test3 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[3]) data_test3_pred <- predict(fit_bos_alt, data_test3) # crim is set to its 75% quantile data_test4 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[4]) data_test4_pred <- predict(fit_bos_alt, data_test4) # crim is set to its 95% quantile data_test5 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[5]) data_test5_pred <- predict(fit_bos_alt, data_test5) # combine five sets of prediction data together medv <- rbind(data_test1_pred, data_test2_pred, data_test3_pred, data_test4_pred, data_test5_pred) data_pred <- data.frame(lstat = rep(lstat_list, 5), medv = medv, crim = rep(c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile"), each = 100)) data_pred$crim <- factor(data_pred$crim, levels = c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile")) data_label <- data_pred[which(data_pred$lstat == 17.5), ] data_label$value <- c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%") data_label$value <- factor(data_label$value, levels = c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%")) ggplot(data = data_pred, aes(x = lstat, y = medv, color = crim)) + geom_point(size = 0.1) + geom_text_repel(aes(label = value), data = data_label, color = "black", size = 3.6) + scale_colour_manual(values = c("firebrick1", "chocolate2", "darkolivegreen3", "skyblue2", "purple2")) + geom_line() + theme_set(theme_bw()) + theme(panel.grid = element_blank(), axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12), legend.title = element_text(size = 12, face = "bold"), legend.text = element_text(size = 12)) + labs(x = "percentage of lower status", y = "median value of owner-occupied homes ($1000)", col = "per capita crime rate")
/scratch/gouwar.j/cran-all/cranData/CVEK/inst/doc/vignette.R
--- title: "Using the CVEK R package" author: "Wenying Deng" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using the CVEK R package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Short Description Using a library of base kernels, **CVEK** learns the generating function from data by directly minimizing the ensemble model's error, and tests whether the data is generated by the RKHS under the null hypothesis. Part I presents a simple example to conduct Gaussian process regression and hypothesis testing using *cvek* function on simulated data. Part II shows a real-world application where we use **CVEK** to understand whether the per capita crime rate impacts the relationship between the local socioeconomic status and the housing price at Boston, MA, U.S.A. Finally, Part III provides code showing how to visualize the interaction effect from a *cvek* model. Download the package from CRAN or [GitHub](https://github.com/IrisTeng/CVEK-1) and then install and load it. ```{r, message = FALSE} library(CVEK) library(ggplot2) library(ggrepel) ``` ## Tutorial using simulated dataset ### Generate Data and Define Model We generate a simulated dataset using the $"linear"$ kernel, and set the relative interaction strength to be $0.2$. The outcome $y_i$ is generated as, \begin{align*} y_i=h_1(\mathbf{x}_{i, 1})+h_2(\mathbf{x}_{i, 2})+0.2 * h_{12}(\mathbf{x}_{i, 1}, \mathbf{x}_{i, 2})+\epsilon_i, \end{align*} where $h_1$, $h_2$, $h_{12}$ are sampled from RKHSs $\textit{H}_1$, $\textit{H}_2$, $\textit{H}_{12}$, generated using the corresponding *linear* kernel. We standardize all sampled functions to have unit form, so that $0.2$ represents the strength of interaction relative to the main effect. ```{r} set.seed(0726) n <- 60 # including training and test d <- 4 int_effect <- 0.2 data <- matrix(rnorm(n * d), ncol = d) Z1 <- data[, 1:2] Z2 <- data[, 3:4] kern <- generate_kernel(method = "linear") w <- rnorm(n) w12 <- rnorm(n) K1 <- kern(Z1, Z1) K2 <- kern(Z2, Z2) K1 <- K1 / sum(diag(K1)) # standardize kernel K2 <- K2 / sum(diag(K2)) h0 <- K1 %*% w + K2 %*% w h0 <- h0 / sqrt(sum(h0 ^ 2)) # standardize main effect h1_prime <- (K1 * K2) %*% w12 # interaction effect # standardize sampled functions to have unit norm, so that 0.2 # represents the interaction strength relative to main effect Ks <- svd(K1 + K2) len <- length(Ks$d[Ks$d / sum(Ks$d) > .001]) U0 <- Ks$u[, 1:len] h1_prime_hat <- fitted(lm(h1_prime ~ U0)) h1 <- h1_prime - h1_prime_hat h1 <- h1 / sqrt(sum(h1 ^ 2)) # standardize interaction effect Y <- h0 + int_effect * h1 + rnorm(1) + rnorm(n, 0, 0.01) data <- as.data.frame(cbind(Y, Z1, Z2)) colnames(data) <- c("y", paste0("z", 1:d)) data_train <- data[1:40, ] data_test <- data[41:60, ] ``` The resulting data look as follows. ```{r, results='asis'} knitr::kable(head(data_train, 5)) ``` Now we can apply the *cvek* function to conduct Gaussian process regression. Below table is a detailed list of all the arguments of the function *cvek*. ```{r, fig.width=14, fig.height=11} knitr::include_graphics("table1.pdf", auto_pdf = TRUE) ``` Suppose we want our kernel library to contain three kernels: $"linear"$, $"polynomial"$ with $p=2$, and $"rbf"$ with $l=1$ (the effective parameter for $"polynomial"$ is $p$ and the effective parameter for $"rbf"$ is $l$, so we can set anything to $l$ for $"polynomial"$ kernel and $p$ for $"rbf"$ kernel). We then first apply *define_library*. ```{r} kern_par <- data.frame(method = c("linear", "polynomial", "rbf"), l = rep(1, 3), p = 1:3, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ``` The null model is then $y \sim z1 + z2 + k(z3, z4)$. ```{r} formula <- y ~ z1 + z2 + k(z3, z4) ``` ### Estimation and Testing With all these parameters specified, we can conduct Gaussian process regression. ```{r} est_res <- cvek(formula, kern_func_list = kern_func_list, data = data_train) est_res$lambda est_res$u_hat ``` We can see that the ensemble weight assigns $0.99$ to the $"linear"$ kernel, which is the true kernel. This illustrates the accuracy and efficiency of the CVEK method. We next specify the testing procedure. Note that we can use the same function *cvek* to perform hypothesis testing, as we did for estimation, but we need to provide $formula\_test$, which is the user-supplied formula indicating the additional alternative effect (e.g., interactions) to test for. Specifically, we will first show how to conduct the classic score test by specifying $test="asymp"$, followed by a bootstrap test where we specify $test="boot"$, and the number of bootstrap samples $B=200$. ```{r} formula_test <- y ~ k(z1, z2):k(z3, z4) cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "asymp", alt_kernel_type = "ensemble", verbose = FALSE)$pvalue cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "boot", alt_kernel_type = "ensemble", B = 200, verbose = FALSE)$pvalue ``` Both tests come to the same conclusion. At the significance level $0.05$, we reject the null hypothesis that there's no interaction effect, which matches our data generation mechanism. Additionally, we can prediction new outcomes based on estimation result *est_res*. ```{r} y_pred <- predict(est_res, data_test[, 2:5]) data_test_pred <- cbind(y_pred, data_test) ``` ```{r, echo=FALSE, results='asis'} knitr::kable(head(data_test_pred, 5)) ``` ## Detecting Nonlinear Interaction in Boston Housing Price In this part, we show an example of using *cvek* test to detect nonlinear interactions between socioeconomic factors that contribute to housing price in the city of Boston, Massachusetts, USA. We consider the *Boston* dataset (available in the **MASS** package), which is collected by the U.S Census Service about the median housing price ($medv$) in Boston, along with additional variables describing local socioeconomic information such as per capita crime rate, proportion of non-retail business, number of rooms per household, etc. Below table lists the $14$ variables. ```{r, fig.width=14, fig.height=3} knitr::include_graphics("table2.pdf", auto_pdf = TRUE) ``` Here we use *cvek* to study whether the per capita crime rate ($crim$) impacts the relationship between the local socioeconomic status ($lstat$) and the housing price. The null model is, \begin{align*} medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat), \end{align*} where $\mathbf{x}^\top=(1, zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black)$, and $k()$ is specified as a semi-parametric model with a model library that includes *linear* and *rbf* kernels with $l=1$. This inclusion of nonlinearity (i.e., the *rbf* kernel) is important, since per classic results in the macroeconmics literature, the crime rates and socioeconomic status of local community are known to have nonlinear association with the local housing price [harrison_hedonic_1978](https://doi.org/10.1016/0095-0696(78)90006-2). ```{r} kern_par <- data.frame(method = c("linear", "rbf"), l = rep(1, 2), p = 1:2, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ``` To this end, the hypothesis regarding whether the crime rate ($crim$) impacts the association between local socioeconomic status ($lstat$) and the housing price ($medv$) is equivalent to testing whether there exists a nonlinear interaction between $crim$ and $lstat$ in predicting $medv$, i.e., \begin{align*} \mathcal{H}_0: &\; medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat), \\ \mathcal{H}_a: &\; medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat) + k(crim):k(lstat). \end{align*} To test this hypothesis using *cvek*, we specify the null model using *formula*, and specify the additional interaction term ($k(crim):k(lstat)$) in the alternative model using *formula\_test*, as shown below: ```{r} formula <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim) + k(lstat) formula_test <- medv ~ k(crim):k(lstat) fit_bos <- cvek(formula, kern_func_list = kern_func_list, data = Boston, formula_test = formula_test, lambda = exp(seq(-3, 5)), test = "asymp") ``` Given the fitted object (*fit_bos*), the p-value of the *cvek* test can be extracted as below: ```{r} fit_bos$pvalue ``` Since $p<0.05$, we reject the null hypothesis that there's no $crim:lstat$ interaction, and conclude that the data does suggest an impact of the crime rate on the relationship between the local socioeconomic status and the housing price. ## Visualizing Nonlinear Interaction in Boston Housing Price A versatile and sometimes the most intepretable method for understanding interaction effects is via plotting. Next we show the *Boston* example of how to visualize the fitted interaction from a *cvek* model. We visualize the interaction effects by creating five datasets: Fix all confounding variables to their means, vary $lstat$ in a reasonable range (i.e., from $12.5$ to $17.5$, since the original range of $lstat$ in *Boston* dataset is $(1.73, 37.97)$), and respectively set $crim$ value to its $5\%, 25\%, 50\%, 75\%$ and $95\%$ quantiles. ```{r message=FALSE, fig.width=7, fig.height=5} # first fit the alternative model formula_alt <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim):k(lstat) fit_bos_alt <- cvek(formula = formula_alt, kern_func_list = kern_func_list, data = Boston, lambda = exp(seq(-3, 5))) # mean-center all confounding variables not involved in the interaction # so that the predicted values are more easily interpreted pred_name <- c("zn", "indus", "chas", "nox", "rm", "age", "dis", "rad", "tax", "ptratio", "black") covar_mean <- apply(Boston, 2, mean) pred_cov <- covar_mean[pred_name] pred_cov_df <- t(as.data.frame(pred_cov)) lstat_list <- seq(12.5, 17.5, length.out = 100) crim_quantiles <- quantile(Boston$crim, probs = c(.05, .25, .5, .75, .95)) # crim is set to its 5% quantile data_test1 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[1]) data_test1_pred <- predict(fit_bos_alt, data_test1) # crim is set to its 25% quantile data_test2 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[2]) data_test2_pred <- predict(fit_bos_alt, data_test2) # crim is set to its 50% quantile data_test3 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[3]) data_test3_pred <- predict(fit_bos_alt, data_test3) # crim is set to its 75% quantile data_test4 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[4]) data_test4_pred <- predict(fit_bos_alt, data_test4) # crim is set to its 95% quantile data_test5 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[5]) data_test5_pred <- predict(fit_bos_alt, data_test5) # combine five sets of prediction data together medv <- rbind(data_test1_pred, data_test2_pred, data_test3_pred, data_test4_pred, data_test5_pred) data_pred <- data.frame(lstat = rep(lstat_list, 5), medv = medv, crim = rep(c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile"), each = 100)) data_pred$crim <- factor(data_pred$crim, levels = c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile")) data_label <- data_pred[which(data_pred$lstat == 17.5), ] data_label$value <- c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%") data_label$value <- factor(data_label$value, levels = c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%")) ggplot(data = data_pred, aes(x = lstat, y = medv, color = crim)) + geom_point(size = 0.1) + geom_text_repel(aes(label = value), data = data_label, color = "black", size = 3.6) + scale_colour_manual(values = c("firebrick1", "chocolate2", "darkolivegreen3", "skyblue2", "purple2")) + geom_line() + theme_set(theme_bw()) + theme(panel.grid = element_blank(), axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12), legend.title = element_text(size = 12, face = "bold"), legend.text = element_text(size = 12)) + labs(x = "percentage of lower status", y = "median value of owner-occupied homes ($1000)", col = "per capita crime rate") ``` The figure above shows the $medv$ - $lstat$ relationship under different levels of $crim$. Numbers at the end of each curves indicate the actual values of $crim$ rate (per capita crime rate by town) at the corresponding quantiles. From the figure we see that crime rate does impact the relationship between the local socioeconomic status v.s. housing price. Building on this code, user can continue to refine the visualization (e.g., by adding in confidence levels) and use it to improve the the model fit based on domain knowledge (e.g., by experimenting different kernels / hyper-parameters). ## References 1. Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for Nonlinear Effect with Gaussian Processes. October 2017. 1. Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample kernel independence test for microbiome community-level association analysis. December 2017. 1. Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. 1. Arnab Maity and Xihong Lin. Powerful tests for detecting a gene effect in the presence of possible gene-gene interactions using garrote kernel machines. December 2011. 1. The MIT Press. Gaussian Processes for Machine Learning, 2006. 1. Xihong Lin. Variance component testing in generalised linear models with random effects. June 1997. 1. Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July 2015. 1. Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of Statistical Learning: Data Mining, Inference, and Prediction, Second Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 edition, 2009. 1. Hirotogu Akaike. Information Theory and an Extension of the Maximum Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer Series in Statistics, pages 199–213. Springer, New York, NY, 1998. 1. Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model selection in small samples. June 1989. 1. Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing parameter selection in nonparametric regression using an improved Akaike information criterion. January 2002.
/scratch/gouwar.j/cran-all/cranData/CVEK/inst/doc/vignette.Rmd
--- title: "Using the CVEK R package" author: "Wenying Deng" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using the CVEK R package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Short Description Using a library of base kernels, **CVEK** learns the generating function from data by directly minimizing the ensemble model's error, and tests whether the data is generated by the RKHS under the null hypothesis. Part I presents a simple example to conduct Gaussian process regression and hypothesis testing using *cvek* function on simulated data. Part II shows a real-world application where we use **CVEK** to understand whether the per capita crime rate impacts the relationship between the local socioeconomic status and the housing price at Boston, MA, U.S.A. Finally, Part III provides code showing how to visualize the interaction effect from a *cvek* model. Download the package from CRAN or [GitHub](https://github.com/IrisTeng/CVEK-1) and then install and load it. ```{r, message = FALSE} library(CVEK) library(ggplot2) library(ggrepel) ``` ## Tutorial using simulated dataset ### Generate Data and Define Model We generate a simulated dataset using the $"linear"$ kernel, and set the relative interaction strength to be $0.2$. The outcome $y_i$ is generated as, \begin{align*} y_i=h_1(\mathbf{x}_{i, 1})+h_2(\mathbf{x}_{i, 2})+0.2 * h_{12}(\mathbf{x}_{i, 1}, \mathbf{x}_{i, 2})+\epsilon_i, \end{align*} where $h_1$, $h_2$, $h_{12}$ are sampled from RKHSs $\textit{H}_1$, $\textit{H}_2$, $\textit{H}_{12}$, generated using the corresponding *linear* kernel. We standardize all sampled functions to have unit form, so that $0.2$ represents the strength of interaction relative to the main effect. ```{r} set.seed(0726) n <- 60 # including training and test d <- 4 int_effect <- 0.2 data <- matrix(rnorm(n * d), ncol = d) Z1 <- data[, 1:2] Z2 <- data[, 3:4] kern <- generate_kernel(method = "linear") w <- rnorm(n) w12 <- rnorm(n) K1 <- kern(Z1, Z1) K2 <- kern(Z2, Z2) K1 <- K1 / sum(diag(K1)) # standardize kernel K2 <- K2 / sum(diag(K2)) h0 <- K1 %*% w + K2 %*% w h0 <- h0 / sqrt(sum(h0 ^ 2)) # standardize main effect h1_prime <- (K1 * K2) %*% w12 # interaction effect # standardize sampled functions to have unit norm, so that 0.2 # represents the interaction strength relative to main effect Ks <- svd(K1 + K2) len <- length(Ks$d[Ks$d / sum(Ks$d) > .001]) U0 <- Ks$u[, 1:len] h1_prime_hat <- fitted(lm(h1_prime ~ U0)) h1 <- h1_prime - h1_prime_hat h1 <- h1 / sqrt(sum(h1 ^ 2)) # standardize interaction effect Y <- h0 + int_effect * h1 + rnorm(1) + rnorm(n, 0, 0.01) data <- as.data.frame(cbind(Y, Z1, Z2)) colnames(data) <- c("y", paste0("z", 1:d)) data_train <- data[1:40, ] data_test <- data[41:60, ] ``` The resulting data look as follows. ```{r, results='asis'} knitr::kable(head(data_train, 5)) ``` Now we can apply the *cvek* function to conduct Gaussian process regression. Below table is a detailed list of all the arguments of the function *cvek*. ```{r, fig.width=14, fig.height=11} knitr::include_graphics("table1.pdf", auto_pdf = TRUE) ``` Suppose we want our kernel library to contain three kernels: $"linear"$, $"polynomial"$ with $p=2$, and $"rbf"$ with $l=1$ (the effective parameter for $"polynomial"$ is $p$ and the effective parameter for $"rbf"$ is $l$, so we can set anything to $l$ for $"polynomial"$ kernel and $p$ for $"rbf"$ kernel). We then first apply *define_library*. ```{r} kern_par <- data.frame(method = c("linear", "polynomial", "rbf"), l = rep(1, 3), p = 1:3, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ``` The null model is then $y \sim z1 + z2 + k(z3, z4)$. ```{r} formula <- y ~ z1 + z2 + k(z3, z4) ``` ### Estimation and Testing With all these parameters specified, we can conduct Gaussian process regression. ```{r} est_res <- cvek(formula, kern_func_list = kern_func_list, data = data_train) est_res$lambda est_res$u_hat ``` We can see that the ensemble weight assigns $0.99$ to the $"linear"$ kernel, which is the true kernel. This illustrates the accuracy and efficiency of the CVEK method. We next specify the testing procedure. Note that we can use the same function *cvek* to perform hypothesis testing, as we did for estimation, but we need to provide $formula\_test$, which is the user-supplied formula indicating the additional alternative effect (e.g., interactions) to test for. Specifically, we will first show how to conduct the classic score test by specifying $test="asymp"$, followed by a bootstrap test where we specify $test="boot"$, and the number of bootstrap samples $B=200$. ```{r} formula_test <- y ~ k(z1, z2):k(z3, z4) cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "asymp", alt_kernel_type = "ensemble", verbose = FALSE)$pvalue cvek(formula, kern_func_list = kern_func_list, data = data_train, formula_test = formula_test, mode = "loocv", strategy = "stack", beta_exp = 1, lambda = exp(seq(-10, 5)), test = "boot", alt_kernel_type = "ensemble", B = 200, verbose = FALSE)$pvalue ``` Both tests come to the same conclusion. At the significance level $0.05$, we reject the null hypothesis that there's no interaction effect, which matches our data generation mechanism. Additionally, we can prediction new outcomes based on estimation result *est_res*. ```{r} y_pred <- predict(est_res, data_test[, 2:5]) data_test_pred <- cbind(y_pred, data_test) ``` ```{r, echo=FALSE, results='asis'} knitr::kable(head(data_test_pred, 5)) ``` ## Detecting Nonlinear Interaction in Boston Housing Price In this part, we show an example of using *cvek* test to detect nonlinear interactions between socioeconomic factors that contribute to housing price in the city of Boston, Massachusetts, USA. We consider the *Boston* dataset (available in the **MASS** package), which is collected by the U.S Census Service about the median housing price ($medv$) in Boston, along with additional variables describing local socioeconomic information such as per capita crime rate, proportion of non-retail business, number of rooms per household, etc. Below table lists the $14$ variables. ```{r, fig.width=14, fig.height=3} knitr::include_graphics("table2.pdf", auto_pdf = TRUE) ``` Here we use *cvek* to study whether the per capita crime rate ($crim$) impacts the relationship between the local socioeconomic status ($lstat$) and the housing price. The null model is, \begin{align*} medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat), \end{align*} where $\mathbf{x}^\top=(1, zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black)$, and $k()$ is specified as a semi-parametric model with a model library that includes *linear* and *rbf* kernels with $l=1$. This inclusion of nonlinearity (i.e., the *rbf* kernel) is important, since per classic results in the macroeconmics literature, the crime rates and socioeconomic status of local community are known to have nonlinear association with the local housing price [harrison_hedonic_1978](https://doi.org/10.1016/0095-0696(78)90006-2). ```{r} kern_par <- data.frame(method = c("linear", "rbf"), l = rep(1, 2), p = 1:2, stringsAsFactors = FALSE) # define kernel library kern_func_list <- define_library(kern_par) ``` To this end, the hypothesis regarding whether the crime rate ($crim$) impacts the association between local socioeconomic status ($lstat$) and the housing price ($medv$) is equivalent to testing whether there exists a nonlinear interaction between $crim$ and $lstat$ in predicting $medv$, i.e., \begin{align*} \mathcal{H}_0: &\; medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat), \\ \mathcal{H}_a: &\; medv \sim \mathbf{x}^\top \boldsymbol{\beta} + k(crim) + k(lstat) + k(crim):k(lstat). \end{align*} To test this hypothesis using *cvek*, we specify the null model using *formula*, and specify the additional interaction term ($k(crim):k(lstat)$) in the alternative model using *formula\_test*, as shown below: ```{r} formula <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim) + k(lstat) formula_test <- medv ~ k(crim):k(lstat) fit_bos <- cvek(formula, kern_func_list = kern_func_list, data = Boston, formula_test = formula_test, lambda = exp(seq(-3, 5)), test = "asymp") ``` Given the fitted object (*fit_bos*), the p-value of the *cvek* test can be extracted as below: ```{r} fit_bos$pvalue ``` Since $p<0.05$, we reject the null hypothesis that there's no $crim:lstat$ interaction, and conclude that the data does suggest an impact of the crime rate on the relationship between the local socioeconomic status and the housing price. ## Visualizing Nonlinear Interaction in Boston Housing Price A versatile and sometimes the most intepretable method for understanding interaction effects is via plotting. Next we show the *Boston* example of how to visualize the fitted interaction from a *cvek* model. We visualize the interaction effects by creating five datasets: Fix all confounding variables to their means, vary $lstat$ in a reasonable range (i.e., from $12.5$ to $17.5$, since the original range of $lstat$ in *Boston* dataset is $(1.73, 37.97)$), and respectively set $crim$ value to its $5\%, 25\%, 50\%, 75\%$ and $95\%$ quantiles. ```{r message=FALSE, fig.width=7, fig.height=5} # first fit the alternative model formula_alt <- medv ~ zn + indus + chas + nox + rm + age + dis + rad + tax + ptratio + black + k(crim):k(lstat) fit_bos_alt <- cvek(formula = formula_alt, kern_func_list = kern_func_list, data = Boston, lambda = exp(seq(-3, 5))) # mean-center all confounding variables not involved in the interaction # so that the predicted values are more easily interpreted pred_name <- c("zn", "indus", "chas", "nox", "rm", "age", "dis", "rad", "tax", "ptratio", "black") covar_mean <- apply(Boston, 2, mean) pred_cov <- covar_mean[pred_name] pred_cov_df <- t(as.data.frame(pred_cov)) lstat_list <- seq(12.5, 17.5, length.out = 100) crim_quantiles <- quantile(Boston$crim, probs = c(.05, .25, .5, .75, .95)) # crim is set to its 5% quantile data_test1 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[1]) data_test1_pred <- predict(fit_bos_alt, data_test1) # crim is set to its 25% quantile data_test2 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[2]) data_test2_pred <- predict(fit_bos_alt, data_test2) # crim is set to its 50% quantile data_test3 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[3]) data_test3_pred <- predict(fit_bos_alt, data_test3) # crim is set to its 75% quantile data_test4 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[4]) data_test4_pred <- predict(fit_bos_alt, data_test4) # crim is set to its 95% quantile data_test5 <- data.frame(pred_cov_df, lstat = lstat_list, crim = crim_quantiles[5]) data_test5_pred <- predict(fit_bos_alt, data_test5) # combine five sets of prediction data together medv <- rbind(data_test1_pred, data_test2_pred, data_test3_pred, data_test4_pred, data_test5_pred) data_pred <- data.frame(lstat = rep(lstat_list, 5), medv = medv, crim = rep(c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile"), each = 100)) data_pred$crim <- factor(data_pred$crim, levels = c("5% quantile", "25% quantile", "50% quantile", "75% quantile", "95% quantile")) data_label <- data_pred[which(data_pred$lstat == 17.5), ] data_label$value <- c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%") data_label$value <- factor(data_label$value, levels = c("0.028%", "0.082%", "0.257%", "3.677%", "15.789%")) ggplot(data = data_pred, aes(x = lstat, y = medv, color = crim)) + geom_point(size = 0.1) + geom_text_repel(aes(label = value), data = data_label, color = "black", size = 3.6) + scale_colour_manual(values = c("firebrick1", "chocolate2", "darkolivegreen3", "skyblue2", "purple2")) + geom_line() + theme_set(theme_bw()) + theme(panel.grid = element_blank(), axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12), legend.title = element_text(size = 12, face = "bold"), legend.text = element_text(size = 12)) + labs(x = "percentage of lower status", y = "median value of owner-occupied homes ($1000)", col = "per capita crime rate") ``` The figure above shows the $medv$ - $lstat$ relationship under different levels of $crim$. Numbers at the end of each curves indicate the actual values of $crim$ rate (per capita crime rate by town) at the corresponding quantiles. From the figure we see that crime rate does impact the relationship between the local socioeconomic status v.s. housing price. Building on this code, user can continue to refine the visualization (e.g., by adding in confidence levels) and use it to improve the the model fit based on domain knowledge (e.g., by experimenting different kernels / hyper-parameters). ## References 1. Jeremiah Zhe Liu and Brent Coull. Robust Hypothesis Test for Nonlinear Effect with Gaussian Processes. October 2017. 1. Xiang Zhan, Anna Plantinga, Ni Zhao, and Michael C. Wu. A fast small-sample kernel independence test for microbiome community-level association analysis. December 2017. 1. Arnak S. Dalalyan and Alexandre B. Tsybakov. Aggregation by Exponential Weighting and Sharp Oracle Inequalities. In Learning Theory, Lecture Notes in Computer Science, pages 97– 111. Springer, Berlin, Heidelberg, June 2007. 1. Arnab Maity and Xihong Lin. Powerful tests for detecting a gene effect in the presence of possible gene-gene interactions using garrote kernel machines. December 2011. 1. The MIT Press. Gaussian Processes for Machine Learning, 2006. 1. Xihong Lin. Variance component testing in generalised linear models with random effects. June 1997. 1. Philip S. Boonstra, Bhramar Mukherjee, and Jeremy M. G. Taylor. A Small-Sample Choice of the Tuning Parameter in Ridge Regression. July 2015. 1. Trevor Hastie, Robert Tibshirani, and Jerome Friedman. The Elements of Statistical Learning: Data Mining, Inference, and Prediction, Second Edition. Springer Series in Statistics. Springer- Verlag, New York, 2 edition, 2009. 1. Hirotogu Akaike. Information Theory and an Extension of the Maximum Likelihood Principle. In Selected Papers of Hirotugu Akaike, Springer Series in Statistics, pages 199–213. Springer, New York, NY, 1998. 1. Clifford M. Hurvich and Chih-Ling Tsai. Regression and time series model selection in small samples. June 1989. 1. Hurvich Clifford M., Simonoff Jeffrey S., and Tsai Chih-Ling. Smoothing parameter selection in nonparametric regression using an improved Akaike information criterion. January 2002.
/scratch/gouwar.j/cran-all/cranData/CVEK/vignettes/vignette.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' @title Canonical Variate Regression. #' #' @description Perform canonical variate regression with a set of fixed tuning parameters. #' #' @usage cvrsolver(Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) #' #' @param Y A response matrix. The response can be continuous, binary or Poisson. #' @param Xlist A list of covariate matrices. Cannot contain missing values. #' @param rank Number of pairs of canonical variates. #' @param eta Weight parameter between 0 and 1. #' @param Lam A vector of penalty parameters \eqn{\lambda} for regularizing the loading matrices #' corresponding to the covariate matrices in \code{Xlist}. #' @param family Type of response. \code{"gaussian"} if Y is continuous, \code{"binomial"} if Y is binary, and \code{"poisson"} if Y is Poisson. #' @param Wini A list of initial loading matrices W's. It must be provided. See \code{cvr} and \code{scca} for using sCCA solution as the default. #' @param penalty Type of penalty on W's. "GL1" for rowwise sparsity and #' "L1" for entrywise sparsity. #' @param opts A list of options for controlling the algorithm. Some of the options are: #' #' \code{standardization}: need to standardize the data? Default is TRUE. #' #' \code{maxIters}: maximum number of iterations allowed in the algorithm. The default is 300. #' #' \code{tol}: convergence criterion. Stop iteration if the relative change in the objective is less than \code{tol}. #' #' @details CVR is used for extracting canonical variates and also predicting the response #' for multiple sets of covariates (Xlist = list(X1, X2)) and response (Y). #' The covariates can be, for instance, gene expression, SNPs or DNA methylation data. #' The response can be, for instance, quantitative measurement or binary phenotype. #' The criterion minimizes the objective function #' #' \deqn{(\eta/2)\sum_{k < j} ||X_kW_k - X_jW_j||_F^2 + (1-\eta)\sum_{k} l_k(\alpha, \beta, Y,X_kW_k) #' + \sum_k \rho_k(\lambda_k, W_k),}{% #' (\eta/2) \Sigma_\{k<j\}||X_kW_k - X_jW_j||_F^2 + (1 - \eta) \Sigma_k l_k(\alpha, \beta, Y, X_kW_k) + \Sigma_k \rho_k(\lambda_k, W_k),} #' s.t. \eqn{W_k'X_k'X_kW_k = I_r,} for \eqn{k = 1, 2, \ldots, K}. #' \eqn{l_k()} are general loss functions with intercept \eqn{\alpha} and coefficients \eqn{\beta}. \eqn{\eta} is the weight parameter and #' \eqn{\lambda_k} are the regularization parameters. \eqn{r} is the rank, i.e. the number of canonical pairs. #' By adjusting \eqn{\eta}, one can change the weight of the first correlation term and the second prediction term. #' \eqn{\eta=0} is reduced rank regression and \eqn{\eta=1} is sparse CCA (with orthogonal constrained W's). By choosing appropriate \eqn{\lambda_k} #' one can induce sparsity of \eqn{W_k}'s to select useful variables for predicting Y. #' \eqn{W_k}'s with \eqn{B_k}'s and (\eqn{\alpha, \beta}) are iterated using an ADMM algorithm. See the reference for details. #' #' @return An object containing the following components #' \item{iter}{The number of iterations the algorithm takes.} #' @return \item{W}{A list of fitted loading matrices.} #' @return \item{B}{A list of fitted \eqn{B_k}'s.} #' @return \item{Z}{A list of fitted \eqn{B_kW_k}'s.} #' @return \item{alpha}{Fitted intercept term in the general loss term.} #' @return \item{beta}{Fitted regression coefficients in the general loss term.} #' @return \item{objvals}{A sequence of the objective values.} #' @author Chongliang Luo, Kun Chen. #' @references Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @examples ## see SimulateCVR for simulation examples, see CVR for parameter tuning. #' @seealso \code{\link{SimulateCVR}}, \code{\link{CVR}}. #' @export cvrsolver <- function(Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) { .Call('CVR_cvrsolver', PACKAGE = 'CVR', Y, Xlist, rank, eta, Lam, family, Wini, penalty, opts) }
/scratch/gouwar.j/cran-all/cranData/CVR/R/RcppExports.R
#' Data sets for the alcohol dependence example #' #' A list of 3 data frames that contains the gene expression, #' DNA methylation and AUD (alcohol use disorder) of 46 human subjects. #' The data is already screened for quality control. #' For the raw data see the link below. For more details see the reference. #' #' @format A list of 3 data frames: #' \describe{ #' \item{gene}{Human gene expression. A data frame of 46 rows and 300 columns.} #' \item{meth}{Human DNA methylation. A data frame of 46 rows and 500 columns.} #' \item{disorder}{Human AUD indicator. A data frame of 46 rows and 1 column. #' The first 23 subjects are AUDs and the others are matched controls.} #' } #' #' @examples #' ############## Alcohol dependence example ###################### #' data(alcohol) #' gene <- scale(as.matrix(alcohol$gene)) #' meth <- scale(as.matrix(alcohol$meth)) #' disorder <- as.matrix(alcohol$disorder) #' alcohol.X <- list(X1 = gene, X2 = meth) #' \dontrun{ #' foldid <- c(rep(1:5, 4), c(3,4,5), rep(1:5, 4), c(1,2,5)) #' ## table(foldid, disorder) #' ## there maybe warnings due to the glm refitting with small sample size #' alcohol.cvr <- CVR(disorder, alcohol.X, rankseq = 2, etaseq = 0.02, #' family = "b", penalty = "L1", foldid = foldid ) #' plot(alcohol.cvr) #' plot(gene %*% alcohol.cvr$solution$W[[1]][, 1], meth %*% alcohol.cvr$solution$W[[2]][, 1]) #' cor(gene %*% alcohol.cvr$solution$W[[1]], meth %*% alcohol.cvr$solution$W[[2]]) #' } #' #' @references Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @source Alcohol dependence: \url{http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE49393}. "alcohol"
/scratch/gouwar.j/cran-all/cranData/CVR/R/alcohol.R
#' Data sets for the mouse body weight example #' #' A list of 3 data frames that contains the genotype, gene expression and body-mass index of #' 294 mice. The data is already screened for quality control. #' For the raw data see the links below. For more details see the reference. #' #' @format A list of 3 data frames: #' \describe{ #' \item{geno}{Mouse genotype. A data frame of 294 rows and 163 columns.} #' \item{expr}{Mouse gene expression. A data frame of 294 rows and 215 columns.} #' \item{bmi}{Mouse body-mass index. A data frame of 294 rows and 1 column.} #' } #' #' @examples #' ############## Mouse body weight example ###################### #' data(mouse) #' expr <- scale(as.matrix(mouse$expr)) #' geno <- scale(as.matrix(mouse$geno)) #' bmi <- as.matrix(mouse$bmi) #' mouse.X <- list(X1 = expr, X2 = geno) #' \dontrun{ #' mouse.cvr <- CVR(bmi, mouse.X, rankseq = 2, etaseq = 0.04, family = "g", penalty = "L1") #' plot(mouse.cvr) #' plot(expr %*% mouse.cvr$solution$W[[1]][, 2], geno %*% mouse.cvr$solution$W[[2]][, 2]) #' cor(expr %*% mouse.cvr$solution$W[[1]], geno %*% mouse.cvr$solution$W[[2]]) #' } #' #' @references Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @source Mouse genotype: \url{http://www.genetics.org/cgi/content/full/genetics.110.116087/DC1} #' Mouse gene expression: \url{ftp://ftp.ncbi.nlm.nih.gov/pub/geo/DATA/SeriesMatrix/GSE2814/} #' Mouse body-mass index: \url{http://labs.genetics.ucla.edu/horvath/CoexpressionNetwork/MouseWeight/}. "mouse"
/scratch/gouwar.j/cran-all/cranData/CVR/R/mouse.R
## PMA package is needed to install CVR ## PMA depends on impute, which is removed from CRAN to bioconuctor ## Use the following to install impute ## (try http:// if https:// URLs are not supported) ## source("https://bioconductor.org/biocLite.R") ## biocLite("impute") ## useDynLib(CVR, .registration = TRUE) #' @useDynLib CVR #' @import Rcpp #' @import graphics #' @import stats #' @title Sparse canonical correlation analysis. #' #' @description Get sparse CCA solutions of X1 and X2. Use \code{CCA} and \code{CCA.permute} from PMA package. #' See PMA package for details. #' #' @usage SparseCCA(X1, X2, rank = 2, penaltyx1 = NULL, penaltyx2 = NULL, #' nperms = 25, ifplot = 0) #' @param X1,X2 Numeric matrices representing the two sets of covariates. They should have the same number of rows and #' cannot contain missing values. #' @param rank The number of canonical variate pairs wanted. The default is 2. #' @param penaltyx1,penaltyx2 Numeric vectors as the penalties to be applied to X1 and X2. The defaults are seq(0.1, 0.7, len = 20). #' See PMA package for details. #' @param nperms Number of times the data should be permuted. The default is 25. Don't use too small value. See PMA package for details. #' @param ifplot 0 or 1. The default is 0 which means don't plot the result. See PMA package for details. #' @details This function is generally used for tuning the penalties in sparse CCA if \code{penaltyx1} and \code{penaltyx2} are supplied as vectors. #' The CCA solution is based on PMD algorithm and the tuning is based on permutation. #' The fitted W1 and W2 are scaled so that the diagonals of W1'X1'X1W1 and W2'X2'X2W2 are all 1's. #' #' Specifically, if a single value of mild penalty is provided for both \code{penaltyx1} and \code{penaltyx2}, the result can be used as #' initial values of W's in CVR. For instance, with \code{penaltyx1 = 0.7} and \code{penaltyx2 = 0.7}, #' the fitted W1 and W2 are only shrinked, but mostly not zero yet. #' @return \item{W1}{Loading matrix corresponding to X1. X1*W1 gives the canonical variates from X1.} #' @return \item{W2}{Loading matrix corresponding to X2. X2*W2 gives the canonical variates from X2.} #' @author Chongliang Luo, Kun Chen. #' @references Daniela M. Witten, Robert Tibshirani and Trevor Hastie (2009) A penalized matrix decomposition, with applications to #' sparse principal components and canonical correlation analysis. Biostatistics 10(3), 515-534. #' #' Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{CVR}}, \code{\link{CCA}}, \code{\link{CCA.permute}}. #' @import PMA #' @export SparseCCA <- function(X1, X2, rank = 2, penaltyx1 = NULL, penaltyx2 = NULL, nperms = 25, ifplot = 0){ if (nrow(X1) != nrow(X2)) stop("X1 and X2 should have the same row number!") if (ncol(X1) == 1 | ncol(X2) == 1) stop("X1 and X2 should have at least 2 columns!") if (is.null(penaltyx1) | is.null(penaltyx2)){ penaltyx1 <- seq(0.1, 0.7, len = 20) penaltyx2 <- seq(0.1, 0.7, len = 20) } if (length(penaltyx1) > 1){ perm.out <- CCA.permute(X1, X2, "standard", "standard", penaltyx1, penaltyx2, nperms = nperms) if (ifplot == 1 ) { print(c(perm.out$bestpenaltyx, perm.out$bestpenaltyz)) plot(perm.out) } SparseCCA_X12 <- CCA(X1, X2, typex = "standard", typez = "standard", K = rank, penaltyx = perm.out$bestpenaltyx, penaltyz = perm.out$bestpenaltyz, v = perm.out$v.init, trace = FALSE) } else { SparseCCA_X12 <- CCA(X1, X2, typex = "standard", typez = "standard", K = rank, penaltyx = penaltyx1, penaltyz = penaltyx2, trace = FALSE) } D1 <- diag(diag(t(X1 %*% SparseCCA_X12$u) %*% X1 %*% SparseCCA_X12$u)^(-0.5), rank, rank) D2 <- diag(diag(t(X2 %*% SparseCCA_X12$v) %*% X2 %*% SparseCCA_X12$v)^(-0.5), rank, rank) W1 <- SparseCCA_X12$u %*% D1 W2 <- SparseCCA_X12$v %*% D2 ## to make X1 %*% W1 orthogonal return(list(W1 = W1, W2 = W2)) } #' @title Generate simulation data. #' #' @description Generate two sets of covariates and an univariate response driven by several latent factors. #' #' @usage SimulateCVR(family = c("gaussian", "binomial", "poisson"), n = 100, #' rank = 4, p1 = 50, p2 = 70, pnz = 10, sigmax = 0.2, #' sigmay = 0.5, beta = c(2, 1, 0, 0), standardization = TRUE) #' #' @param family Type of response. \code{"gaussian"} for continuous response, \code{"binomial"} #' for binary response, and \code{"poisson"} for Poisson response. The default is \code{"gaussian"}. #' @param n Number of rows. The default is 100. #' @param rank Number of latent factors generating the covariates. The default is 4. #' @param p1 Number of variables in X1. The default is 50. #' @param p2 Number of variables in X2. The default is 70. #' @param pnz Number of variables in X1 and X2 related to the signal. The default is 10. #' @param sigmax Standard deviation of normal noise in X1 and X2. The default is 0.2. #' @param sigmay Standard deviation of normal noise in Y. Only used when the response is Gaussian. The default is 0.5. #' @param beta Numeric vector, the coefficients used to generate respose from the latent factors. The default is c(2, 1, 0, 0). #' @param standardization Logical. If TRUE, standardize X1 and X2 before output. The default is TRUE. #' #' @details The latent factors in U are randomly generated normal vectors, #' #' \eqn{X_1 = U*V_1 + \sigma_x*E_1, X_2 = U*V_2 + \sigma_x*E_2, E_1, E_2}{% #' X1 = U*V1 + sigmax*E1, X2 = U*V2 + sigmax*E2, E1, E2} are N(0,1) noise matrices. #' #' The nonzero entries of \eqn{V_1}{% #' V1} and \eqn{V_2}{% #' V2} are generated from Uniform([-1,-0.5]U[0.5,1]). #' #' For Gaussian response, #' #' \eqn{y = U*\beta + \sigma_y*e_y, e_y}{% #' y = U*\beta + sigmay*ey, ey} is N(0,1) noise vector, #' #' for binary response, #' #' \eqn{y \sim rbinom(n, 1, 1/(1 + \exp(-U*\beta)))}, #' #' and for Poisson response, #' #' \eqn{y \sim rpois(n, \exp(U*\beta))}. #' #' See the reference for more details. #' #' @return \item{X1, X2}{The two sets of covariates with dimensions n*p1 and n*p2 respectively.} #' @return \item{y}{The response vector with length n.} #' @return \item{U}{The true latent factor matrix with dimension n*rank.} #' @return \item{beta}{The coefficients used to generate response from \code{U}. The length is rank.} #' @return \item{V1, V2}{The true loading matrices for X1 and X2 with dimensions p1*rank and p2*rank. The first \code{pnz} rows are nonzero.} #' @author Chongliang Luo, Kun Chen. #' @references Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{CVR}}, \code{\link{cvrsolver}}. #' @examples #' set.seed(42) #' mydata <- SimulateCVR(family = "g", n = 100, rank = 4, p1 = 50, p2 = 70, #' pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1 #' X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' opts <- list(standardization = FALSE, maxIters = 300, tol = 0.005) #' ## use sparse CCA solution as initial values, see SparseCCA() #' Wini <- SparseCCA(X1, X2, 4, 0.7, 0.7) #' ## perform CVR with fixed eta and lambda, see cvrsolver() #' fit <- cvrsolver(Y, Xlist, rank = 4, eta = 0.5, Lam = c(1, 1), #' family = "gaussian", Wini, penalty = "GL1", opts) #' ## check sparsity recovery #' fit$W[[1]]; #' fit$W[[2]]; #' ## check orthogonality #' X1W1 <- X1 %*% fit$W[[1]]; #' t(X1W1) %*% X1W1 #' @export SimulateCVR <- function(family = c("gaussian", "binomial", "poisson"), n = 100, rank = 4, p1 = 50, p2 = 70, pnz = 10, sigmax = 0.2, sigmay = 0.5, beta = c(2, 1, 0, 0), standardization = TRUE){ family <- match.arg(family) U <- matrix(rnorm(2 * n * rank), 2 * n, rank); ## U = svd(U)$u*sqrt(n); # n by r V1 <- matrix(0, p1, rank); V11 <- matrix(runif(rank * pnz) * (rbinom(rank * pnz, 1, 0.5) * 2-1), ncol = rank); V2 <- matrix(0, p2, rank); V21 <- matrix(runif(rank * pnz) * (rbinom(rank * pnz, 1, 0.5) * 2 - 1), ncol = rank); V1[1:pnz, ] <- svd(V11)$u; V2[1:pnz, ] <- svd(V21)$u; x1 <- U %*% t(V1); x2 <- U %*% t(V2); lp <- U %*% beta; e1 <- matrix(rnorm(2 * n * p1), 2 * n, p1) * sigmax; e2 <- matrix(rnorm(2 * n * p2), 2 * n, p2) * sigmax; X1 <- x1[1:n, ] + e1[1:n, ]; X2 <- x2[1:n, ] + e2[1:n, ]; X1test <- x1[(n + 1):(2 * n), ] + e1[(n + 1):(2 * n), ]; X2test <- x2[(n + 1):(2 * n), ] + e2[(n + 1):(2 * n), ]; U <- U[1:n, ] if (family == "gaussian") { e <- rnorm(2 * n) * sigmay; y <- lp[1:n] + e[1:n]; ytest <- lp[(n + 1):(2 * n)] + e[(n + 1):(2 * n)]; if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1) V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); y <- scale(y); X1 <- scale(X1); X2 <- scale(X2);#/sqrt(n-1) ytest <- scale(ytest); X1test <- scale(X1test); X2test <- scale(X2test);#/sqrt(n-1) } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr.y <- sd(lp) / sd(e); snr <- c(snr.x1, snr.x2, snr.y) } else if (family == "binomial") { px <- 1 / (1 + exp(-lp)); y <- rbinom(n, 1, px[1:n]) ytest <- rbinom(n, 1, px[(n + 1):(2 * n)]) if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1); V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); X1 <- scale(X1); X2 <- scale(X2); X1test <- scale(X1test); X2test <- scale(X2test); } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr <- c(snr.x1, snr.x2, 0) } else if (family == "poisson") { px <- exp(lp); y <- rpois(n, px[1:n]) ytest <- rpois(n, px[(n + 1):(2 * n)]) if (standardization) { V1 <- diag(apply(X1, 2, sd)) %*% V1 / sqrt(n - 1); V2 <- diag(apply(X2, 2, sd)) %*% V2 / sqrt(n - 1); X1 <- scale(X1); X2 <- scale(X2); X1test <- scale(X1test); X2test <- scale(X2test); } snr.x1 <- sd(x1) / sd(e1) snr.x2 <- sd(x2) / sd(e2) snr <- c(snr.x1, snr.x2, 0) } ## X1test = X1test, X2test = X2test, ytest = as.matrix(ytest), x1 = x1, x2 = x2, lp = lp, snr = snr return(list(X1 = X1, X2 = X2, y = as.matrix(y), U = U, beta = beta, V1 = V1, V2 = V2)) } ## calculate area under ROC curve (AUC) and deviance in binomial case CalcROC <- function(y, px, ifplot = 0){ ## predict binomial response with given fitted prob px, ## compute AUC of ROC / (neg) deviance (use it instead of AUC, for small sample size) ## input: ## y: real response ## px: fitted prob seq ## output: ## list(spec = spec, sens = sens, auc = auc, dev = dev) n <- length(px); np <- sum(y == 1); nn <- n - np; sens <- c(); spec <- c(); if (np == 0) { auc <- sum(px < 0.5) / nn; } else if (nn == 0) { auc <- sum(px > 0.5) / np; } else { for (i in 1:n) { sens[i] <- (sum(px > px[i] & y == 1) + 0.5 * sum(px == px[i] & y == 1)) / np; spec[i] <- (sum(px < px[i] & y == 0) + 0.5 * sum(px == px[i] & y == 0)) / nn; } } if (ifplot == 1) plot(1 - spec, sens); ##auc = trapz(sort(1-spec),sort(sens)); xx <- sort(1 - spec, index.return = TRUE) yy <- c(0, sens[xx$ix], 1) xx <- c(0, xx$x, 1) auc <- sum((xx[-1] - xx[-(n + 2)]) * (yy[-1] + yy[-(n + 2)])) / 2 dev <- -2 * sum(y * log(px + 0.00001) + (1 - y) * log(1 - px + 0.0001)) return(list(spec = spec, sens = sens, auc = auc, dev = dev)) } ## calculate the error of testing data (mse, auc or deviance) using fitted W1, W2, alpha, beta PredCVR <- function(Ytest, X1test, X2test, W1, W2, alpha = 0, beta = 0, Y, X1, X2, family = "gaussian", refit = TRUE, combine = TRUE, type.measure = NULL){ ## compute the pred mse/AUC(deviance) of testing data X1testW1 <- X1test %*% W1; X2testW2 <- X2test %*% W2; if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if(length(Ytest) > 10 & is.null(type.measure)) type.measure <- "auc"; if(length(Ytest) < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure <- "deviance"; } if (refit) { X1W1 <- X1 %*% W1; X2W2 <- X2 %*% W2; XW <- cbind(X1W1, X2W2) XtestW <- cbind(X1testW1, X2testW2) if (family == "gaussian") { ## mse is the average of two predictions from X1testW1 and X2testW2 if (combine) { ab <- coef(lm(Y ~ XW)); ab[is.na(ab)] <- 0 mse <- sum((Ytest - ab[1] - XtestW %*% ab[-1])^2) / length(Ytest) } else { ab1 <- coef(lm(Y ~ X1W1)) ab2 <- coef(lm(Y ~ X2W2)) ab1[is.na(ab1)] <- 0; ab2[is.na(ab2)] <- 0; mse <- (sum((Ytest - ab1[1] - X1testW1 %*% ab1[-1])^2) + sum((Ytest - ab2[1] - X2testW2 %*% ab2[-1])^2)) / length(Ytest) / 2 } if (is.na(mse)) mse <- sum(Ytest^2) / length(Ytest) # for empty W1 and W2 return(mse) } else if (family == "binomial") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { ## avoid fitting glm with zero predictors if (type.measure == "auc") { return(0) } else if (type.measure == "deviance") { dev <- -2 * length(Ytest) * log(0.00001) return(dev) } } else { if (combine) { refit12 <- glm(Y ~ XW, family = "binomial") ab <- coef(refit12) ab[is.na(ab)] <- 0 px <- 1 / (1 + exp(-XtestW %*% ab[-1] - ab[1])) if (type.measure == "auc") { auc <- CalcROC(Ytest, px)$auc; return(auc) } else if (type.measure == "deviance") { dev <- CalcROC(Ytest, px)$dev; return(dev) } } else { refit1 <- glm(Y ~ X1W1, family = "binomial") refit2 <- glm(Y ~ X2W2, family = "binomial") ab1 <- coef(refit1) ab2 <- coef(refit2) ab1[is.na(ab1)] <- 0 ab2[is.na(ab2)] <- 0 px1 <- 1 / (1 + exp(-X1testW1 %*% ab1[-1] - ab1[1])) px2 <- 1 / (1 + exp(-X2testW2 %*% ab2[-1] - ab2[1])) if (type.measure == "auc") { auc <- (CalcROC(Ytest, px1)$auc + CalcROC(Ytest, px2)$auc) / 2 return(auc) } else if (type.measure == "deviance") { dev <- (CalcROC(Ytest, px1)$dev + CalcROC(Ytest, px2)$dev) / 2 return(dev) } } } } else if (family == "poisson") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { dev <- -2 * length(Ytest) * log(0.000001) return(dev) } else { if (combine) { refit12 <- glm(Y ~ XW, family = "poisson") ab <- coef(refit12) ab[is.na(ab)] <- 0 px <- exp(XtestW %*% ab[-1] + ab[1]) dev <- -2 * sum(Ytest * log(px) - px) return(dev) } else { refit1 <- glm(Y ~ X1W1, family = "poisson") refit2 <- glm(Y ~ X2W2, family = "poisson") ab1 <- coef(refit1); ab2 <- coef(refit2) ab1[is.na(ab1)] <- 0; ab2[is.na(ab2)] <- 0 px1 <- exp(X1testW1 %*% ab1[-1] + ab1[1]) px2 <- exp(X2testW2 %*% ab2[-1] + ab2[1]) dev <- -sum(Ytest * log(px1) - px1) - sum(Ytest * log(px2) - px2) return(dev) } } } } else { if (family == "gaussian") { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta mse <- sum((Ytest - lp1)^2 + (Ytest - lp2)^2) / length(Ytest) / 2 return(mse) } else if (family == "binomial") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { if (type.measure == "auc") { return(0) } else if (type.measure == "deviance") { dev <- -2 * length(Ytest) * log(0.00001) return(dev) } } else { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta px1 <- 1 / (1 + exp(-lp1)) px2 <- 1 / (1 + exp(-lp2)) if (type.measure == "auc") { auc <- (CalcROC(Ytest, px1)$auc + CalcROC(Ytest, px2)$auc) / 2 return(auc) } else if (type.measure == "deviance") { dev <- (CalcROC(Ytest, px1)$dev + CalcROC(Ytest, px2)$dev) / 2 return(dev) } } } else if (family == "poisson") { if (sum(abs(W1)) == 0 | sum(abs(W2)) == 0) { dev <- -2 * length(Ytest) * log(0.000001) return(dev) } else { lp1 <- alpha + X1testW1 %*% beta lp2 <- alpha + X2testW2 %*% beta px1 <- exp(lp1) px2 <- exp(lp2) dev <- -sum(Ytest * log(px1) - px1) - sum(Ytest * log(px2) - px2) return(dev) } } } } ## calculate solution path of CVR (along the sequence of lambda) CVRPath <- function(Y, Xlist, rank = 2, eta = 0.5, Lamseq, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), opts){ family <- match.arg(family) penalty <- match.arg(penalty) Y <- as.matrix(Y) K <- length(Xlist) if (dim(Lamseq)[2] != K) stop("The length of Lambda is not the same to K!"); nlam <- dim(Lamseq)[1] family <- match.arg(family) penalty <- match.arg(penalty) if (is.null(Wini)) Wini <- SparseCCA(Xlist[[1]], Xlist[[2]], rank, 0.7, 0.7) p <- c() WPath <- list() for (k in 1:K) { p[k] <- dim(Xlist[[k]])[2] WPath[[k]] <- array(0, c(nlam, p[k], rank)); } betaPath <- matrix(0, nlam, rank) alphaPath <- rep(0, nlam) iterPath <- rep(0, nlam) fitwork <- list() warm <- TRUE Wwork <- Wini for (i in 1:nlam){ if (i == 1) { optswork <- opts; optswork$maxIters <- 2 * opts$maxIters; } else { optswork <- opts; if (warm) Wwork <- fitwork$W; ## warm start } fitwork <- cvrsolver(Y, Xlist, rank, eta, as.vector(Lamseq[i, ]), family, Wwork, penalty, optswork); Wzero <- 0 for (k in 1:K) Wzero <- Wzero + sum(fitwork$W[[k]]!=0); if (Wzero == 0) break; for (k in 1:K) WPath[[k]][i, , ] <- fitwork$W[[k]]; betaPath[i, ] <- fitwork$beta; alphaPath[i] <- fitwork$alpha; iterPath[i] <- fitwork$iter } return(list(WPath = WPath, betaPath = betaPath, alphaPath = alphaPath, iterPath = iterPath)) } ## cross validate to select lambda, with fixed rank and eta TuneCVR <- function(Y, Xlist, rank, eta, Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, type.measure = NULL, opts){ ## cross-validate to select lam's ## input: Lamseq: nlam by K, K=2 ## output: list(Lamseq = Lamseq, cverror = pred, cvm = mpred, msparse = msparse, ## Lamhat = Lamhat, W1trace = W1trace, W2trace = W2trace, cvr.fit = fit, ## alpha = alpha.refit, beta = beta.refit, type.measure = type.measure) ## cvr.fit: Refit all the data using the selected parameters, ## see the output of cvrsolver(). Also output the coefficients of regressing ## the response to the combined fitted canonical variates (Y ~ cbind(X1W1, X2W2)). ## family <- match.arg(family) penalty <- match.arg(penalty) Y <- as.matrix(Y) n <- dim(Y)[1] K <- length(Xlist) X1 <- as.matrix(Xlist[[1]]) X2 <- as.matrix(Xlist[[2]]) p1 <- ncol(X1) p2 <- ncol(X2) if (is.null(Wini)) Wini <- SparseCCA(X1, X2, rank, 0.7, 0.7) if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if (n / nfold > 10 & is.null(type.measure)) type.measure <- "auc"; if (n / nfold < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure <- "deviance"; } warm <- TRUE; opts$nrank <- rank opts$family <- family opts$penalty <- penalty Lamseq <- as.matrix(Lamseq) if (dim(Lamseq)[2] != K) { lamseq <- 10^(seq(-2, 1.3, len = 50)) Lamseq <- cbind(lamseq, lamseq * p2 / p1) } nlam <- dim(Lamseq)[1]; pred <- matrix(0, nlam, nfold); itertrace <- matrix(0, nlam, nfold) W1trace <- array(0, c(nlam, nfold, p1, rank)) W2trace <- array(0, c(nlam, nfold, p2, rank)) sparse <- matrix(0, nlam, nfold) # monitor sparsity if (is.null(foldid)) { tmp <- ceiling(c(1:n) / (n / nfold)); foldid <- sample(tmp, n) } for (i in 1:nfold) { X1train <- Xlist[[1]][foldid != i, ]; X2train <- Xlist[[2]][foldid != i, ]; Xtrain <- list(X1 = X1train, X2 = X2train); Ytrain <- as.matrix(Y[foldid != i, ]); X1test <- Xlist[[1]][foldid == i, ]; X2test <- Xlist[[2]][foldid == i, ]; Ytest <- as.matrix(Y[foldid == i, ]); if (is.null(opts$W)) opts$W = SparseCCA(X1train, X2train, rank, 0.7, 0.7) obj <- CVRPath(Ytrain, Xtrain, rank, eta, Lamseq, family, opts$W, penalty, opts); W1trace[, i, , ] <- obj$WPath[[1]] W2trace[, i, , ] <- obj$WPath[[2]] itertrace[, i] <- obj$iterPath for (j in 1:nlam){ W1 <- obj$WPath[[1]][j, , ] W2 <- obj$WPath[[2]][j, , ] ## sparse = proportion of nonzero elements among W1 and W2 sparse[j, i] <- (sum(W1 != 0) + sum(W2 != 0)) / (length(W1) + length(W2)) alpha <- as.numeric(obj$alphaPath[j]) beta <- obj$betaPath[j, ] pred[j, i] <- PredCVR(Ytest, X1test, X2test, W1, W2, alpha, beta, Ytrain, X1train, X2train, family = family, refit = TRUE, type.measure = type.measure) } } mpred <- apply(pred, 1, mean) msparse <- apply(sparse, 1, mean) spthresh <- opts$spthresh if (type.measure == "mse" | type.measure == "deviance") { ## search the best lam only among sparse models ilam <- which.min(mpred[msparse <= spthresh]) + min(which(msparse <= spthresh)) - 1 ifold <- which.min(pred[ilam, ]) mmpred <- min(mpred[msparse <= spthresh]) } else if (type.measure == "auc") { ilam <- which.max(mpred[msparse <= spthresh]) + min(which(msparse <= spthresh)) - 1 ifold <- which.max(pred[ilam, ]) mmpred <- max(mpred[msparse <= spthresh]) } Lamhat <- Lamseq[ilam, ] ## refit all the data with Lamhat if (warm) { Wini <- list(W1 = as.matrix(W1trace[max(ilam - 1, 1), ifold, , ]), W2 = as.matrix(W2trace[max(ilam - 1, 1), ifold, , ])) } fit <- cvrsolver(Y, Xlist, rank, eta, Lamhat, family, Wini, penalty, opts) XW <- cbind(X1 %*% fit$W[[1]], X2 %*% fit$W[[2]]) if (family == "gaussian") { ab <- coef(lm(Y ~ XW)); ab[is.na(ab)] <- 0 alpha.refit <- ab[1] beta.refit <- ab[-1] } else { ab <- coef(glm(Y ~ XW, family = family)) ab[is.na(ab)] <- 0 alpha.refit <- ab[1] beta.refit <- ab[-1] } refit <- list(alpha = alpha.refit, beta = beta.refit, W = fit$W) cv.out <- list(Lamseq = Lamseq, eta = eta, rank = rank, cverror = pred, cvm = mpred, mmpred = mmpred, msparse = msparse, Lamhat = Lamhat, W1trace = W1trace, W2trace = W2trace, cvr.fit = fit, refit = refit, type.measure = type.measure, spthresh = spthresh) class(cv.out) <- "TuneCVR" return(cv.out) } ## plot mean cv error and sparsity of the solution path from TuneCVR objects plot.TuneCVR <- function(x) { par(mfrow = c(2, 1)) plot(log(x$Lamseq[, 1]), x$cvm, xlab="", ylab = x$type.measure, type = "l", col = "red", main = paste("CVR(eta = ", round(x$eta, 5), ", rank = ", x$rank, ")", sep="")) abline(v = log(x$Lamhat[1])) plot(log(x$Lamseq[, 1]), x$msparse, xlab = expression(log ~ lambda), ylab = "sparsity", type = "l") abline(h = x$spthresh) } #' @title Fit canonical variate regression with tuning parameters selected by cross validation. #' #' @description This function fits the solution path of canonical variate regression, #' with tuning parameters selected by cross validation. The tuning parameters #' include the rank, the \eqn{\eta} and the \eqn{\lambda}. #' @usage #' CVR(Y, Xlist, rankseq = 2, neta = 10, etaseq = NULL, nlam = 50, #' Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), #' Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, #' opts = list(), type.measure = NULL) #' #' @param Y A univariate response variable. #' @param Xlist A list of two covariate matrices as in \code{cvrsolver}. #' @param rankseq A sequence of candidate ranks. The default is a single value 2. #' @param neta Number of \eqn{\eta} values. The default is 10. #' @param etaseq A sequence of length \code{neta} containing candidate \eqn{\eta} values between 0 and 1. #' The default is 10^seq(-2, log10(0.9), length = neta). #' @param nlam Number of \eqn{\lambda} values. The default is 50. #' @param Lamseq A matrix of \eqn{\lambda} values. The column number is the number of sets in \code{Xlist}, #' and the row number is \code{nlam}. The default is 10^(seq(-2, 2, length = nlam)) for each column. #' @param family Type of response as in \code{cvrsolver}. The default is \code{"gaussian"}. #' @param Wini A list of initial loading W's. The default is from the SparseCCA solution. See \code{SparseCCA}. #' @param penalty Type of penalty on loading matrices W's as in \code{cvrsolver}. The default is \code{"GL1"}. #' @param nfold Number of folds in cross validation. The default is 10. #' @param foldid Specifying training and testing sets in cross validation; random generated if not supplied. #' It remains the same across different rank and \eqn{\eta}. #' @param opts A list of options for controlling the algorithm. The default of \code{opts$spthresh} is 0.4, which means #' we only search sparse models with at most 40\% nonzero entries in W1 and W2. See the other options #' (\code{standardization}, \code{maxIters} and \code{tol}) in \code{cvrsolver}. #' @param type.measure Type of measurement used in cross validation. \code{"mse"} for Gaussian, \code{"auc"} for binomial, #' and \code{"deviance"} for binomial and Poisson. #' #' @details In this function, the rank, \eqn{\eta} and \eqn{\lambda} are tuned by cross validation. CVR then is refitted with #' all data using the selected tuning parameters. The \code{plot} function shows the tuning of \eqn{\lambda}, #' with selected rank and \eqn{\eta}. #' #' @return An object with S3 class "CVR" containing the following components #' @return \item{cverror}{A matrix containing the CV errors. The number of rows is the length #' of \code{etaseq} and the number of columns is the length of \code{rankseq}.} #' @return \item{etahat}{Selected \eqn{\eta}.} #' @return \item{rankhat}{Selected rank.} #' @return \item{Lamhat}{Selected \eqn{\lambda}'s.} #' @return \item{Alphapath}{An array containing the fitted paths of the intercept term \eqn{\alpha}.} #' @return \item{Betapath}{An array containing the fitted paths of the regression coefficient \eqn{\beta}.} #' @return \item{W1path, W2path}{Arrays containing the fitted paths of W1 and W2.} #' @return \item{foldid}{\code{foldid} used in cross validation.} #' @return \item{cvout}{Cross validation results using selected \eqn{\eta} and rank.} #' @return \item{solution}{A list including the solutions of \eqn{\alpha}, \eqn{\beta}, W1 and W2, by refitting all the data #' using selected tuning parameters.} #' #' @author Chongliang Luo, Kun Chen. #' #' @references Chongliang Luo, Jin Liu, Dipak D. Dey and Kun Chen (2016) Canonical variate regression. #' Biostatistics, doi: 10.1093/biostatistics/kxw001. #' @seealso \code{\link{cvrsolver}}, \code{\link{SparseCCA}}, \code{\link{SimulateCVR}}. #' @examples #' ############## Gaussian response ###################### #' set.seed(42) #' mydata <- SimulateCVR(family = "g", n = 100, rank = 4, p1 = 50, p2 = 70, #' pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1; #' X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## fix rank = 4, tune eta and lambda #' ##out_cvr <- CVR(Y, Xlist, rankseq = 4, neta = 5, nlam = 25, #' ## family = "g", nfold = 5) #' ## out_cvr$solution$W[[1]]; #' ## out_cvr$solution$W[[2]]; #' ### uncomment to see plots #' ## plot.CVR(out_cvr) #' ## #' ## Distance of subspaces #' ##U <- mydata$U #' ##Pj <- function(U) U %*% solve(t(U) %*% U, t(U)) #' ##sum((Pj(U) - (Pj(X1 %*% out_cvr$sol$W[[1]]) + Pj(X2 %*% out_cvr$sol$W[[2]]))/2)^2) #' ## Precision/Recall rate #' ## the first 10 rows of the true W1 and W2 are set to be nonzero #' ##W12 <- rbind(out_cvr$sol$W[[1]], out_cvr$sol$W[[1]]) #' ##W12norm <- apply(W12, 1, function(a)sqrt(sum(a^2))) #' ##prec <- sum(W12norm[c(1:10, 51:60)] != 0)/sum(W12norm != 0); prec #' ##rec <- sum(W12norm[c(1:10, 51:60)] != 0)/20; rec #' ## sequential SparseCCA, compare the Distance of subspaces and Prec/Rec #' ##W12s <- SparseCCA(X1, X2, 4) #' ## Distance larger than CVR's #' ##sum((Pj(U) - (Pj(X1 %*% W12s$W1) + Pj(X2 %*% W12s$W2))/2)^2) #' ##W12snorm <- apply(rbind(W12s$W1, W12s$W2), 1, function(a)sqrt(sum(a^2))) #' ## compare Prec/Rec #' ##sum(W12snorm[c(1:10, 51:60)] != 0)/sum(W12snorm != 0); #' ##sum(W12snorm[c(1:10, 51:60)] != 0)/20; #' #' ############## binary response ######################## #' set.seed(12) #' mydata <- SimulateCVR(family = "binomial", n = 300, rank = 4, p1 = 50, #' p2 = 70, pnz = 10, beta = c(2, 1, 0, 0)) #' X1 <- mydata$X1; X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## out_cvr <- CVR(Y, Xlist, 4, neta = 5, nlam=25, family = "b", nfold = 5) #' ## out_cvr$sol$W[[1]]; #' ## out_cvr$sol$W[[2]]; #' ## plot.CVR(out_cvr) #' #' ############## Poisson response ###################### #' set.seed(34) #' mydata <- SimulateCVR(family = "p", n = 100, rank = 4, p1 = 50, #' p2 = 70, pnz = 10, beta = c(0.2, 0.1, 0, 0)) #' X1 <- mydata$X1; X2 <- mydata$X2 #' Xlist <- list(X1 = X1, X2 = X2); #' Y <- mydata$y #' ## etaseq <- 10^seq(-3, log10(0.95), len = 10) #' ## out_cvr <- CVR(Y, Xlist, 4, neta = 5, nlam = 25, family = "p", nfold = 5) #' ## out_cvr$sol$W[[1]]; #' ## out_cvr$sol$W[[2]]; #' ## plot.CVR(out_cvr) #' @export CVR <- function(Y, Xlist, rankseq = 2, neta = 10, etaseq = NULL, nlam = 50, Lamseq = NULL, family = c("gaussian", "binomial", "poisson"), Wini = NULL, penalty = c("GL1", "L1"), nfold = 10, foldid = NULL, opts = list(), type.measure = NULL){ family <- match.arg(family) penalty <- match.arg(penalty) if(is.null(family)) stop('Must specify family of the response!') if(is.null(penalty)) { penalty = "GL1"; cat('Use default: penalty = "GL1".\n') } Y <- as.matrix(Y) X1 <- as.matrix(Xlist[[1]]) X2 <- as.matrix(Xlist[[2]]) Xlist <- list(X1 = X1, X2 = X2) n <- dim(Y)[1] p1 <- ncol(X1) p2 <- ncol(X2) if(p1 == 1 | p2 == 1) stop("X1 and X2 should have at least 2 columns!") if(nrow(X1) != nrow(X2)) stop("X1 and X2 should have the same row number!") if(n != nrow(X1)) stop("Y and X1, X2 should have the same row number!") opts$n <- n opts$p1 <- p1 opts$p2 <- p2 mrank <- max(rankseq) if (is.null(Wini)) { Wini <- SparseCCA(X1, X2, mrank, 0.7, 0.7); cat('Use default: initial W = SparseCCA(X1, X2, rank, 0.7, 0.7).\n') } if (is.null(opts$standardization)) { opts$standardization <- TRUE; #cat('Use default: standardization = TRUE.\n') } if (is.null(opts$maxIters)) { opts$maxIters <- 300; #cat('Use default: maxIters = 300.\n') } if (is.null(opts$tol)) { opts$tol <- 0.01; #cat('Use default: tol = 0.01.\n') } if (is.null(opts$spthresh)) { spthresh <- 0.4 opts$spthresh = spthresh; #cat('Use default: spthresh = 0.4.\n') } if (is.null(etaseq)) { if(is.null(neta)) neta <- 10 etaseq <- 10^seq(-2, log10(0.9), len = neta) } if (is.null(Lamseq)) { if (is.null(nlam)) nlam <- 50 lamseq <- 10^(seq(-2, 2, len = nlam)) Lamseq <- cbind(lamseq, lamseq) } if (is.null(foldid)) { if(is.null(nfold)) nfold <- 10 tmp <- ceiling(c(1:n)/(n/nfold)); foldid <- sample(tmp, n) } else { if(nfold != length(unique(foldid))){ #warning("nfold not equal to no. unique values in foldid") nfold <- length(unique(foldid)) } } if (family == "gaussian") { type.measure <- "mse"; } else if (family == "binomial") { if (n / nfold > 10 & is.null(type.measure)) type.measure <- "auc"; if (n / nfold < 11 & is.null(type.measure)) type.measure <- "deviance"; } else if (family == "poisson") { type.measure = "deviance"; } Lr <- length(rankseq) Leta <- length(etaseq) pred <- matrix(0, Leta, Lr) Lamhat <- matrix(0, Leta, Lr) Alphapath <- matrix(0, Leta, Lr) Betapath <- array(0, c(Leta, Lr, mrank)) W1path <- array(0, c(Leta, Lr, p1, mrank)) W2path <- array(0, c(Leta, Lr, p2, mrank)) for (ir in 1:Lr) { for (ieta in 1:Leta) { obj_cv <- TuneCVR(Y, Xlist, rankseq[ir], etaseq[ieta], Lamseq, family, Wini, penalty, nfold = nfold, foldid = foldid, type.measure = type.measure, opts) pred[ieta, ir] <- obj_cv$mmpred Lamhat[ieta, ir] <- obj_cv$Lamhat[1] Alphapath[ieta, ir] <- obj_cv$cvr.fit$alpha Betapath[ieta, ir, 1:rankseq[ir]] <- obj_cv$cvr.fit$beta W1path[ieta, ir, , 1:rankseq[ir]] <- obj_cv$cvr.fit$W[[1]] W2path[ieta, ir, , 1:rankseq[ir]] <- obj_cv$cvr.fit$W[[2]] } } if (type.measure == "mse" | type.measure == "deviance") { ind <- apply(pred, 2, which.min) ind2 <- which.min(apply(pred, 2, min)) mmpred <- min(pred) } else if (type.measure == "auc") { ind <- apply(pred, 2, which.max) ind2 <- which.max(apply(pred, 2, max)) mmpred <- max(pred) } etahat <- etaseq[ind[ind2]] rankhat <- rankseq[ind2] cvout <- TuneCVR(Y, Xlist, rankhat, etahat, Lamseq, family, Wini, penalty, nfold, foldid = foldid, type.measure, opts) cvrout <- list(cverror = pred, etahat = etahat, rankhat = rankhat, Lamhat = Lamhat, Alphapath = Alphapath, Betapath = Betapath, W1path = W1path, W2path = W2path, foldid = foldid, cvout = cvout, solution = append(cvout$refit, list(rankseq = rankseq, etaseq = etaseq, Lamseq = Lamseq))) class(cvrout) <- "CVR" return(cvrout) } #' @title Plot a CVR object. #' #' @description Plot the tuning of CVR #' #' @usage #' \method{plot}{CVR}(x, ...) #' #' @param x A CVR object. #' @param ... Other graphical parameters used in plot. #' #' @details The first plot is mean cv error vs log(\eqn{\lambda}). The type of mean cv error is #' decided by \code{type.measure} (see parameters of \code{CVR}). The selected \eqn{\lambda} is marked #' by a vertical line in the plot. The second plot is sparsity vs log(\eqn{\lambda}). #' Sparsity is the proportion of non-zero elements in fitted W1 and W2. #' The threshold is marked by a horizontal line. #' Press ENTER to see the second plot, which shows the tuning of \eqn{\eta}. #' @export plot.CVR <- function(x, ...) { plot.TuneCVR(x$cvout) cat ("Press [enter] to continue") line <- readline() par(mfrow = c(1, 1)) plot(x$cverror[, which(x$solution$rankseq == x$rankhat)] ~ log10(x$solution$etaseq), xlab = "log10(etaseq)", ylab = x$cvout$type.measure, main = "CVR(tune eta)") }
/scratch/gouwar.j/cran-all/cranData/CVR/R/myfunctions.R
CV = function(data, learner, params, fold=5, verbose=TRUE) { stopifnot(inherits(learner, "CVST.learner") && inherits(data, "CVST.data") && inherits(params, "CVST.params")) nParams = length(params) dimnames = list(as.character(1:fold), names(params)) results = matrix(0, fold, nParams, dimnames=dimnames) size = getN(data) / fold for (ind in 1:nParams) { p = params[[ind]] for (f in 1:fold) { validationIndex = seq((f-1)*size + 1, f*size) curTrain = getSubset(data, -validationIndex) curTest = getSubset(data, validationIndex) # either mean squared error or mean classification error results[f, ind] = mean(.getResult(curTrain, curTest, learner, p)) } if (verbose) { cat(names(params)[ind], "(", mean(results[, ind]), ")\n") } } winner = which.min(apply(results, 2, mean)) if (length(winner) == 0) { return(NULL) } else { return(params[winner]) } } # the function to perform fastcrossvalidation: # # train: training data CVST.data # # learner: the learner as CVST.learner # # params: list of parameters for the learner as CVST.params # # setup: setup of the CVST as CVST.setup # # test: either the test data for fixed test error setting or NULL, if # the adjusted test error setting should be used fastCV = function(train, learner, params, setup, test=NULL, verbose=TRUE) { stopifnot(inherits(learner, "CVST.learner") && inherits(train, "CVST.data") && inherits(params, "CVST.params") && inherits(setup, "CVST.setup") && (is.null(test) || inherits(test, "CVST.data"))) isClassificationTask = isClassification(train) regressionSimilarityViaOutliers = setup$regressionSimilarityViaOutliers earlyStopping = setup$earlyStoppingSignificance similarity = setup$similaritySignificance # use nested modeling, i.e. we start with the first minimalModel number of # data points and in each step subsequently add minimalModel data points to it nestModel = TRUE earlyStoppingWindow = setup$earlyStoppingWindow if (is.null(test)) { # we are in the adjusted test error setting, therefore we have to keep # an additional slice of the data for the last test minimalModel = getN(train) / (setup$steps + 1) n = getN(train) - minimalModel } else { minimalModel = getN(train) / setup$steps n = getN(train) } N = seq(minimalModel, n, by=minimalModel) st = getCVSTTest(setup$steps, setup$beta, setup$alpha) nParams = length(params) if (verbose) { cat("Total number of params:", nParams, "\n") } dimnames = list(names(params), as.character(N)) traces = matrix(0, nParams, length(N), dimnames=dimnames) success = matrix(0, nParams, length(N), dimnames=dimnames) skipCalculation = rep(FALSE, nParams) isEarlyStopping = FALSE stoppedAt = length(N) activeConfigurations = matrix(FALSE, nParams, length(N), dimnames=dimnames) configurationsLeft = nParams for (ind in 1:length(N)) { n = N[ind] if (!isClassificationTask && regressionSimilarityViaOutliers) { err = .calculateErrors(train, test, n, learner, params, skipCalculation, squared=FALSE) success[, ind] = apply(err^2, 1, mean) } else { err = .calculateErrors(train, test, n, learner, params, skipCalculation) success[, ind] = apply(err, 1, mean) } success[, ind] = apply(err, 1, mean) indByError = sort.list(success[, ind], decreasing=FALSE, na.last=TRUE) traces[indByError[1], ind] = 1 sortedErrors = t(err[indByError, ]) if (!isClassificationTask && regressionSimilarityViaOutliers) { s = apply(sortedErrors, 2, sd) sortedErrors = t(abs(t(sortedErrors)) > s * qnorm(1 - (similarity / 2))) } adjustedSignificance = similarity / (configurationsLeft - 1) for (k in 2:length(indByError)) { if (is.na(success[indByError[k], ind])) { # we either have an unsufficient model, which gives us NA as result... # ... or reached the skipCalculation, so we can stop our procedure break } if (isClassificationTask) { pvalue = cochranq.test(sortedErrors[, 1:k])$p.value } else { if (regressionSimilarityViaOutliers) { pvalue = cochranq.test(sortedErrors[, 1:k])$p.value } else { pvalue = friedman.test(sortedErrors[, 1:k])$p.value } } if (!is.nan(pvalue) && pvalue <= adjustedSignificance) { break } traces[indByError[k], ind] = 1 } if (verbose) { cat("(sim:", sum(traces[, ind]), "alpha:", similarity, "left:", configurationsLeft, ")") } # do the testing here... # check for loosers if (ind > 1) { testResults = apply(traces[, 1:ind], 1, testSequence, st=st) # check for loosers skipCalculation = (testResults == -1) if (verbose) { cat("Skipped configurations:", sum(skipCalculation), " ") } } configurationsLeft = nParams - sum(skipCalculation) activeConfigurations[, ind] = !skipCalculation # check for early stopping if (earlyStoppingWindow >= 2 && ind > earlyStoppingWindow && earlyStopping < 1.0) { # check, whether all remaining parameters perform similar if (sum(!skipCalculation) > 1) pvalue = cochranq.test(t(traces[!skipCalculation, (ind-earlyStoppingWindow+1):ind]))$p.value else { pvalue = 1.0 } if (!is.nan(pvalue) && pvalue > earlyStopping) { if (verbose) { cat("EARLY STOPPING!") } isEarlyStopping = TRUE stoppedAt = ind break } # just go on, if they are signifcantly dissimilar! } } if (verbose) { cat("\n") } theWinners = !skipCalculation ret = list(traces=traces, success=success) ret$numberOfPotentialWinners = sum(theWinners) ret$isEarlyStopping = isEarlyStopping ret$stoppedAt = stoppedAt ret$activeConfigurations = activeConfigurations ret$earlyStoppingWindow = earlyStoppingWindow winningConfiguration = .getOptimalSolution(ret) ret$param = params[winningConfiguration] ret$winningConfiguration = winningConfiguration return(params[winningConfiguration]) } # returns a (# configuration) X (# testsamples) matrix containing 0/1 or squared error at # position i, j if the model learned on N data points of traindata # with configuration i labeled point j of the testdata # correctly or not. skipCalculation controls, which confguration should be # skipped. A NA in the returned matrix corresponds to skipped configuration. .calculateErrors = function(traindata, testdata, N, learner, params, skipCalculation, squared=TRUE) { nestModel = TRUE nPars = length(params) if (nestModel) { sampleIndex = 1:N } else { sampleIndex = sample.int(getN(traindata), N) } # if no test data is available, we have the adjusted test error settings, # i.e. we use the rest of the train data, which is not used for model building # to determine the test error if (is.null(testdata)) { testdata = getSubset(traindata, -sampleIndex) } # initialize results results = matrix(NA, nPars, getN(testdata)) # calculate results curTrain = getSubset(traindata, sampleIndex) for (ind in 1:nPars) { param = params[[ind]] if (!is.null(skipCalculation) && skipCalculation[ind]) { next } results[ind, ] = as.vector(.getResult(curTrain, testdata, learner, param, squared=squared)) } return(results) } .getOptimalSolution = function(paramRace) { remainingConfs = paramRace$activeConfigurations[, paramRace$stoppedAt] if (sum(remainingConfs) == 1) { return(remainingConfs) } # pick the race, which has the smallest mean rank inside # the earlyStoppingWindow: lastSuccess = paramRace$success[remainingConfs, (paramRace$stoppedAt - paramRace$earlyStoppingWindow + 1):paramRace$stoppedAt] meanRank = apply(apply(lastSuccess, 2, rank), 1, mean) # breaks ties at random overallWinner = which(remainingConfs)[.which.is.min(meanRank)] ret = rep(FALSE, nrow(paramRace$traces)) names(ret) = rownames(paramRace$traces) ret[overallWinner] = TRUE return(ret) } .which.is.min = function (x) { y = seq_along(x)[x == min(x)] if (length(y) > 1) { y = sample(y, 1) } return(y) } getCVSTTest = function(steps, beta=.1, alpha=.01) { pi1 = .5 * ((1 - beta) / alpha)^(1/steps) sst = constructSequentialTest(.5, pi1, beta, alpha) sst$steps = steps return(sst) }
/scratch/gouwar.j/cran-all/cranData/CVST/R/CV.R
constructSVRLearner = function() { learn.svr = function(data, params) { #require(kernlab) stopifnot(isRegression(data)) kpar=params[setdiff(names(params), c("kernel", "nu", "C"))] return(ksvm(data$x, data$y, kernel=params$kernel, kpar=kpar, type="nu-svr", nu=params$nu, C=params$C / getN(data), scale=FALSE)) } predict.svr = function(model, newData) { stopifnot(isRegression(newData)) return(predict(model, newData$x)) } return(constructLearner(learn.svr, predict.svr)) } constructSVMLearner = function() { learn.svm = function(data, params) { #require(kernlab) stopifnot(isClassification(data)) kpar=params[setdiff(names(params), c("kernel", "nu"))] return(ksvm(data$x, data$y, kernel=params$kernel, kpar=kpar, type="nu-svc", nu=params$nu, scale=FALSE)) } predict.svm = function(model, newData) { stopifnot(isClassification(newData)) return(predict(model, newData$x)) } return(constructLearner(learn.svm, predict.svm)) } constructKlogRegLearner = function() { learn.klogreg = function(data, params) { #require(kernlab) stopifnot(isClassification(data)) # convert the factor to numeric 0/1 if (nlevels(data$y) > 2) { stop("klogreg does not support multiclass experiments") } y = (data$y != levels(data$y)[1]) + 0 kpar = params[setdiff(names(params), c("kernel", "lambda", "tol", "maxiter"))] kernel = do.call(params$kernel, kpar) model = .klogreg(data$x, kernel, y, getN(data) * params$lambda, params$tol, params$maxiter) model$yLevels = levels(data$y) return(model) } predict.klogreg = function(model, newData) { stopifnot(isClassification(newData)) pred = .klogreg.predict(model, newData$x) f = factor(pred, c("0", "1"), model$yLevels, ordered=FALSE) return(f) } return(constructLearner(learn.klogreg, predict.klogreg)) } constructKRRLearner = function() { learn.krr = function(data, params) { #require(kernlab) stopifnot(isRegression(data)) kpar = params[setdiff(names(params), c("kernel", "lambda"))] kernel = do.call(params$kernel, kpar) return(.krr(data$x, kernel, data$y, getN(data) * params$lambda)) } predict.krr = function(model, newData) { stopifnot(isRegression(newData)) return(as.matrix(.krr.predict(newData$x, model))) } return(constructLearner(learn.krr, predict.krr)) } .krr = function(data, kernel, y, lambda) { #require(kernlab) #require(Matrix) K = kernelMatrix(kernel, data) N = nrow(K) alpha = solve(Matrix(K + diag(lambda, N))) %*% y return(list(data=data, kernel=kernel, alpha=alpha)) } .krr.predict = function(newData, krr) { #require(kernlab) k = kernelMatrix(krr$kernel, newData, krr$data) return(k %*% krr$alpha) } .klogreg = function(data, kernel, labels, lambda, tol, maxiter) { # labels should be 0/1 #require(kernlab) #require(Matrix) K = Matrix(kernelMatrix(kernel, data)@.Data) N = nrow(K) alpha = rep(1/N, N) iter = 1 while (TRUE) { Kalpha = as.vector(K %*% alpha) spec = 1 + exp(-Kalpha) pi = 1 / spec diagW = pi * (1 - pi) e = (labels - pi) / diagW q = Kalpha + e theSol = try(solve(K + lambda * Diagonal(x=1/diagW), q)) if (inherits(theSol, "try-error")) { break } alphan = as.vector(theSol) if (any(is.nan(alphan)) || all(abs(alphan - alpha) <= tol)) { break } else if (iter > maxiter) { cat("klogreg:maxiter!") break } else { alpha = alphan iter = iter + 1 } } return(list(data=data, kernel=kernel, alpha=as.vector(alpha), pi=pi)) } .klogreg.predict = function(klogreg, newData) { #require(kernlab) K = kernelMult(klogreg$kernel, newData, klogreg$data, klogreg$alpha) pi = 1 / (1 + exp(-as.vector(K))) return((pi >= .5) + 0) }
/scratch/gouwar.j/cran-all/cranData/CVST/R/methods.R
# data is a list # x: either a list or a matrix containing the data rowwise # y: vector of labels/values constructData = function(x, y) { stopifnot(is.list(x) || is.vector(x) || is.matrix(x)) stopifnot(is.list(y) || is.vector(y) || is.factor(y)) data = list(x=x, y=y) class(data) = "CVST.data" return(data) } getN = function(data) { stopifnot(inherits(data, "CVST.data")) if (is.list(data$x) || is.vector(data$x)) { N = length(data$x) } else { N = nrow(data$x) } return(N) } shuffleData = function(data) { stopifnot(inherits(data, "CVST.data")) shuffle = sample.int(getN(data)) return(getSubset(data, shuffle)) } getSubset = function(data, subset) { stopifnot(inherits(data, "CVST.data")) x = getX(data, subset) y = data$y[subset] ret = constructData(x=x, y=y) return(ret) } getX = function(data, subset=NULL) { stopifnot(inherits(data, "CVST.data")) if (is.null(subset)) { ret = data$x } else { if (is.list(data$x) || is.vector(data$x)) { ret = data$x[subset] } else { ret = data$x[subset, ,drop=FALSE] } } return(ret) } isClassification = function(data) { stopifnot(inherits(data, "CVST.data")) return(is.factor(data$y)) } isRegression = function(data) { stopifnot(inherits(data, "CVST.data")) return(!isClassification(data)) } constructLearner = function(learn, predict) { stopifnot(is.function(learn) && is.function(predict)) learner = list(learn=learn, predict=predict) class(learner) = "CVST.learner" return(learner) } constructCVSTModel = function(steps=10, beta=.1, alpha=.01, similaritySignificance=.05, earlyStoppingSignificance=.05, earlyStoppingWindow=3, regressionSimilarityViaOutliers=FALSE) { ret = list(steps=steps, beta=beta, alpha=alpha, similaritySignificance=similaritySignificance, earlyStoppingSignificance=earlyStoppingSignificance, earlyStoppingWindow=earlyStoppingWindow, regressionSimilarityViaOutliers=regressionSimilarityViaOutliers) class(ret) = "CVST.setup" return(ret) } constructParams = function(...) { pn = names(substitute(c(...)))[-1] ret = expand.grid(..., stringsAsFactors=FALSE, KEEP.OUT.ATTRS = FALSE) params = lapply(1:nrow(ret), function(ind) as.list(ret[ind, ])) paramNames = lapply(1:nrow(ret), function(ind) paste(pn, ret[ind, ], sep="=", collapse=" ")) names(params) = paramNames class(params) = "CVST.params" return(params) } .getResult = function(train, test, learner, param, squared=TRUE) { stopifnot(inherits(learner, "CVST.learner") && inherits(train, "CVST.data") && inherits(test, "CVST.data")) model = try(learner$learn(train, param)) if (inherits(model, "try-error")) { pred = rep(NA, length(test$y)) } else { pred = try(learner$predict(model, test)) if (inherits(pred, "try-error")) { pred = rep(NA, length(test$y)) } } if (isClassification(test)) { res = (test$y != pred) } else { if (squared) { res = (pred - test$y)^2 } else { res = (pred - test$y) } } return(res) } cochranq.test = function(mat) { cochransQtest = list(statistic = 0, parameter = 0, p.value = 1, method = "Cochran's Q Test", data.name = deparse(substitute(mat))) class(cochransQtest) = "htest" if (is.vector(mat) || any(dim(mat) <= 1)) { return(cochransQtest) } # we expect the individuals in the rows, repetitions/treatments in the columns m = ncol(mat) df = m - 1 L = apply(mat, 1, sum) index = (L > 0 & L < m) if (sum(index) <= 1) { # all rows are either one or zero... no effect! return(cochransQtest) } if (sum(index) * m <= 24) { return(.perm.cochranq.test(mat[index, ])) } L = L[index] T = apply(mat[index, ], 2, sum) Q = ((m-1) * (m * sum(T^2) - sum(T)^2)) / (m * sum(L) - sum(L^2)) names(df) = "df" names(Q) = "Cochran's Q" if (is.nan(Q)) { p.val = 1.0 } else { p.val = pchisq(Q, df, lower.tail=FALSE) } cochransQtest$statistic = Q cochransQtest$parameter = df cochransQtest$p.value = p.val return(cochransQtest) } .perm.cochranq.test = function(mat, nperm=1000) { if (is.vector(mat) || any(dim(mat) <= 1)) { cochransQtest = list(statistic = 0, parameter = 0, p.value = 1, method = "Cochran's Q Test", data.name = deparse(substitute(mat))) class(cochransQtest) = "htest" return(cochransQtest) } # we expect no straight zero or one-rows in mat m = ncol(mat) df = m - 1 L = apply(mat, 1, sum) T = apply(mat, 2, sum) quot = (m * sum(L) - sum(L^2)) Q = ((m-1) * (m * sum(T^2) - sum(T)^2)) / quot names(df) = "df" names(Q) = "Cochran's Q" permFun = function() { newPerm = mat for (i in 1:nrow(mat)) { newPerm[i, ] = mat[i, sample(m)] } T = apply(newPerm, 2, sum) Q = ((m-1) * (m * sum(T^2) - sum(T)^2)) / quot return(Q) } QS = replicate(nperm, permFun()) p.value = mean(QS >= Q) cochransQtest = list(statistic = Q, parameter = df, p.value = p.value, method = "Cochran's Q Test (monte-carlo)", data.name = deparse(substitute(mat))) class(cochransQtest) = "htest" return(cochransQtest) } constructSequentialTest = function(piH0=.5, piH1=.9, beta, alpha) { a1 = log((1 - beta) / alpha) / (log(piH1 / piH0) + log((1 - piH0) / (1 - piH1))) a0 = -log(beta / (1 - alpha)) / (log(piH1 / piH0) + log((1 - piH0) / (1 - piH1))) b = log((1 - piH0) / (1 - piH1)) / (log(piH1 / piH0) + log((1 - piH0) / (1 - piH1))) ret = list(a1=a1, a0=a0, b=b, piH0=piH0, piH1=piH1, alpha=alpha, beta=beta) class(ret) = "CVST.sequentialTest" return(ret) } plotSequence = function(st, s) { y = cumsum(s) if (!is.null(st$steps)) { plot(y, xlim=c(1, st$steps), ylim=c(1, st$steps)) } else { plot(y) } abline(a=st$a1, b=st$b, col="red") abline(a=-st$a0, b=st$b, col="red", lty=2) abline(h=0) abline(a=0, b=1) title(sprintf("one-sided H0:%0.2f; H1:%0.2f", st$piH0, st$piH1)) } testSequence = function(st, s) { stopifnot(inherits(st, "CVST.sequentialTest")) n = length(s) y = cumsum(s) ret = 0 if (y[n] >= st$b * n + st$a1) { ret = 1 } else if (y[n] <= st$b * n - st$a0) { ret = -1 } return(ret) } noisySinc = function(n, dim=2, sigma=0.1) { if (length(n) > 1) { x = n } else { x = runif(n, -pi, pi) } sinc = function(d) sin(d) / (d) y = sinc(4 * x) + 0.2 * sin(15 * x * dim) + sigma*rnorm(n) y[is.nan(y)] = 1 return(constructData(x=as.matrix(x), y=y)) } noisySine = function(n, dim=5, sigma=.25) { x = runif(n, 0, 2 * pi * dim) y = sin(x) if (!is.null(sigma) && sigma > 0) { y = y + rnorm(n, sd=sigma) } label = factor(y == abs(y)) return(constructData(x=as.matrix(x), y=label)) } noisyDonoho = function(n, fun=doppler, sigma=1) { x = matrix(runif(n, 0, 1), n, 1) y = as.vector(fun(x)) + rnorm(n, sd=sigma) return(constructData(x=x, y=y)) } blocks = function(x, scale=3.656993) { t = c(0.1, 0.13, 0.15, 0.23, 0.25, 0.40, 0.44, 0.65, 0.76, 0.78, 0.81) h = c(4, -5, 3, -4, 5, -4.2, 2.1, 4.3, -3.1, 2.1, -4.2) ret = t(sapply(x, function(xx) (1 + sign(xx - t)) / 2)) %*% h ret = ret * scale return(ret) } bumps = function(x, scale=10.52884) { t = c(0.1, 0.13, 0.15, 0.23, 0.25, 0.40, 0.44, 0.65, 0.76, 0.78, 0.81) h = c(4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2) w = c(0.005, 0.005, 0.006, 0.01, 0.01, 0.03, 0.01, 0.01, 0.005, 0.008, 0.005) ret = t(sapply(x, function(xx) (1 + abs((xx - t) / w))^-4 )) %*% h ret = ret * scale return(ret) } heavisine = function(x, scale=2.356934) { ret = 4 * sin(4 * pi * x) - sign(x - 0.3) - sign(0.72 - x) ret = ret * scale return(ret) } doppler = function(x, scale=24.22172) { ret = sqrt(x * (1 - x)) * sin((2.1 * pi) / (x + 0.05)) ret = ret * scale return(ret) }
/scratch/gouwar.j/cran-all/cranData/CVST/R/util.R
cvwavelet <- function( y=y, ywd=ywd, cv.optlevel, cv.bsize=1, cv.kfold, cv.random=TRUE, cv.tol=0.1^3, cv.maxiter=100, impute.vscale="independent", impute.tol=0.1^3, impute.maxiter=100, filter.number=10, family="DaubLeAsymm", thresh.type ="soft", ll=3) { if (impute.vscale != "independent" && impute.vscale != "level") stop("impute.vscale must be one of independent or level.") cv.index <- cvtype(n=length(y), cv.bsize=cv.bsize, cv.kfold=cv.kfold, cv.random=cv.random)$cv.index yimpute <- cvimpute.by.wavelet(y=y, impute.index=cv.index, impute.tol=impute.tol, impute.maxiter=impute.maxiter, impute.vscale=impute.vscale, filter.number=10, family="DaubLeAsymm", ll=3)$yimpute tmpout <- cvwavelet.after.impute(y=y, ywd=ywd, yimpute=yimpute, cv.index=cv.index, cv.optlevel=cv.optlevel, cv.tol=cv.tol, cv.maxiter=cv.maxiter, filter.number=10, family="DaubLeAsymm", thresh.type="soft", ll=3) return(list(y=y, yimpute=yimpute, yc=tmpout$yc, cvthresh=tmpout$cvthresh)) } cvtype <- function(n, cv.bsize=1, cv.kfold, cv.random=TRUE) { if(n < cv.bsize * cv.kfold) stop("Block size or no. of fold is too large.") if(n <= 0) stop("The number of data must be greater than 0.") cv.index <- tmp.index <- NULL if(cv.random) { cv.nblock <- trunc(n / (cv.bsize * cv.kfold)) for (k in 1:cv.kfold) tmp.index <- rbind(tmp.index, sort(sample(seq(sample(1:cv.bsize, 1), n-cv.bsize+1, by=cv.bsize), cv.nblock))) } else { for (k in 1:cv.kfold) tmp.index <- rbind(tmp.index, seq(1, n-cv.bsize*(cv.kfold-1), by=cv.bsize*cv.kfold)+ cv.bsize * (k-1)) } if(cv.bsize > 1) { cv.index <- tmp.index for (i in 1:(cv.bsize-1)) cv.index <- cbind(cv.index, tmp.index + i) cv.index <- t(apply(cv.index, 1, sort)) } else { cv.index <- tmp.index } list(cv.index=cv.index) } cvimpute.by.wavelet <- function( y, impute.index, impute.tol=0.1^3, impute.maxiter=100, impute.vscale="independent", filter.number=10, family="DaubLeAsymm", ll=3) { if (impute.vscale != "independent" && impute.vscale != "level") stop("impute.vscale must be one of independent or level.") n <- length(y) sdy <- sd(y) impute.nrep <- nrow(impute.index) fracmiss <- ncol(impute.index) / n yimpute <- y slevel <- log2(n) - ll nlevelm1 <- log2(n) - 1 ll.nlevelm1 <- ll:nlevelm1 for (k in 1:impute.nrep) { tmpyimpute <- y tmpyimputewd <- wd(tmpyimpute, filter.number=filter.number, family=family) if(impute.vscale=="independent") { sdev0 <- mad(accessD(tmpyimputewd, nlevelm1)) tmpyimpute[impute.index[k,]] <- wr(ebayesthresh.wavelet(tmpyimputewd, vscale=sdev0, smooth.levels=slevel))[impute.index[k,]] } if(impute.vscale=="level") { sdev0 <- NULL for (i in ll.nlevelm1) { tmpsdev0 <- mad(accessD(tmpyimputewd, i)) tmpyimputewd <- putD(tmpyimputewd, i, ebayesthresh(accessD(tmpyimputewd, i), sdev=tmpsdev0)) sdev0 <- c(sdev0, tmpsdev0) } tmpyimpute[impute.index[k,]] <- wr(tmpyimputewd)[impute.index[k,]] } j <- 0 repeat{ tmpyimputewd <- wd(tmpyimpute, filter.number=filter.number, family=family) if(impute.vscale=="independent") { sdev1 <- mad(accessD(tmpyimputewd, nlevelm1)) sdev1 <- sqrt(sdev1^2 + fracmiss * sdev0^2) tmpyimputewr <- wr(ebayesthresh.wavelet(tmpyimputewd, vscale=sdev1, smooth.levels=slevel)) } if(impute.vscale=="level") { sdev1 <- NULL for (i in ll.nlevelm1) { tmpsdev1 <- mad(accessD(tmpyimputewd, i)) tmpsdev1 <- sqrt(tmpsdev1^2 + fracmiss * sdev0[i-ll+1]^2) tmpyimputewd <- putD(tmpyimputewd, i, ebayesthresh(accessD(tmpyimputewd, i), sdev=tmpsdev1)) sdev1 <- c(sdev1, tmpsdev1) } tmpyimputewr <- wr(tmpyimputewd) } ydiff <- mean(abs(tmpyimpute[impute.index[k,]] - tmpyimputewr[impute.index[k,]])) / sdy if (ydiff < impute.tol || j > impute.maxiter) { tmpyimpute[impute.index[k,]] <- tmpyimputewr[impute.index[k,]] break } tmpyimpute[impute.index[k,]] <- tmpyimputewr[impute.index[k,]] sdev0 <- sdev1 j <- j + 1 } # End of repeat loop yimpute[impute.index[k,]] <- tmpyimpute[impute.index[k,]] } # End of k-th impute loop return(list(yimpute=yimpute)) } cvwavelet.after.impute <- function( y, ywd, yimpute, cv.index, cv.optlevel, cv.tol=0.1^3, cv.maxiter=100, filter.number=10, family="DaubLeAsymm", thresh.type="soft", ll=3) { ### We adapt grid search algorithm of R function "WaveletCV" in WaveThresh3 of Nason (1998). ### This algorithm is a special form of grid search algorithm called golden section search. ### When bisectioning the interval containing solution, the golden number is used to keep ### the ratio of two sectioned subinterval fixed. if (length(y) != length(yimpute)) stop("The length of data and imputed values must be the same.") n <- length(y) cd.kfold <- nrow(cv.index) nlevel <- log2(n) ll.nlevelm1 <- ll:(nlevel - 1) cv.ndim <- length(cv.optlevel) R <- (sqrt(5)-1)/2 # R is the golden number 0.61803399000000003 C <- 1 - R lambda <- matrix(0, 4, cv.ndim) if(cv.ndim != 1) { ethresh <- NULL for (i in ll.nlevelm1) ethresh <- c(ethresh, ebayesthresh(accessD(ywd, i), verbose=TRUE)$threshold.origscale) lambda.range <- 2 * ethresh[cv.optlevel + diff(c(cv.optlevel, nlevel))-ll] } else { lambda.range <- threshold(ywd, policy="universal", type=thresh.type, return.threshold=TRUE, lev=ll.nlevelm1)[1] } lambda[1, ] <- rep(0, cv.ndim) lambda[4, ] <- lambda.range lambda[2, ] <- lambda[4, ]/2 lambda[3, ] <- lambda[2, ] + C * (lambda[4, ] - lambda[2, ]) optlambda <- lambda[3, ] tmpyimputewr <- y for (k in 1:cd.kfold) { yimpute2 <- y yimpute2[cv.index[k,]] <- yimpute[cv.index[k,]] tmpyimputewr[cv.index[k,]] <- wr(threshold(wd(yimpute2, filter.number=filter.number, family=family), policy="manual", value=rep(optlambda, diff(c(cv.optlevel, nlevel))), by.level=TRUE, type=thresh.type, lev=ll.nlevelm1))[cv.index[k,]] } perr <- mean((tmpyimputewr - y)^2) j <- 0 repeat{ for (i in 1:cv.ndim) { optlambda[i] <- lambda[2, i] for (k in 1:cd.kfold) { yimpute2 <- y yimpute2[cv.index[k,]] <- yimpute[cv.index[k,]] tmpyimputewr[cv.index[k,]] <- wr(threshold(wd(yimpute2, filter.number=filter.number, family=family), policy="manual", value=rep(optlambda, diff(c(cv.optlevel, nlevel))), by.level=TRUE, type=thresh.type, lev=ll.nlevelm1))[cv.index[k,]] } f2 <- mean((tmpyimputewr - y)^2) optlambda[i] <- lambda[3, i] for (k in 1:cd.kfold) { yimpute2 <- y yimpute2[cv.index[k,]] <- yimpute[cv.index[k,]] tmpyimputewr[cv.index[k,]] <- wr(threshold(wd(yimpute2, filter.number=filter.number, family=family), policy="manual", value=rep(optlambda, diff(c(cv.optlevel, nlevel))), by.level=TRUE, type=thresh.type, lev=ll.nlevelm1))[cv.index[k,]] } f3 <- mean((tmpyimputewr - y)^2) if(f3 < f2) { optlambda[i] <- lambda[3, i] optf <- f3 lambda[1, i] <- lambda[2, i] lambda[2, i] <- lambda[3, i] lambda[3, i] <- R * lambda[2, i] + C * lambda[4, i] } else { optlambda[i] <- lambda[2, i] optf <- f2 lambda[4, i] <- lambda[3, i] lambda[3, i] <- lambda[2, i] lambda[2, i] <- R * lambda[3, i] + C * lambda[1, i] } perr <- c(perr, optf) } stopping <- NULL for (i in 1:cv.ndim) stopping <- c(stopping, abs(lambda[4, i] - lambda[1, i]) / (abs(lambda[2, i]) + abs(lambda[3, i]))) if (all(stopping < cv.tol) || abs(perr[cv.ndim*(j+1)+1]-perr[cv.ndim*j+1])/perr[cv.ndim*j+1] < cv.tol || j > cv.maxiter) break j <- j + 1 } yc <- wr(threshold(ywd, policy="manual", value=rep(optlambda, diff(c(cv.optlevel, nlevel))), by.level=TRUE, type=thresh.type, lev=ll.nlevelm1)) if(cv.ndim !=1) list(yc=yc, cvthresh=rep(optlambda, diff(c(cv.optlevel, nlevel)))) else list(yc=yc, cvthresh=optlambda) } cvwavelet.image <- function( images, imagewd, cv.optlevel, cv.bsize=c(1,1), cv.kfold, cv.tol=0.1^3, cv.maxiter=100, impute.tol=0.1^3, impute.maxiter=100, filter.number=2, ll=3) { if(!is.matrix(images)) stop("images must be a matrix format.") tmp <- cvtype.image(n=c(nrow(images), ncol(images)), cv.bsize=cv.bsize, cv.kfold=cv.kfold) cv.index1 <- tmp$cv.index1 cv.index2 <- tmp$cv.index2 imageimpute <- cvimpute.image.by.wavelet(images=images, impute.index1=cv.index1, impute.index2=cv.index2, impute.tol=impute.tol, impute.maxiter=impute.maxiter, filter.number=filter.number, ll=ll)$imageimpute tmpout <- cvwavelet.image.after.impute(images=images, imagewd=imagewd, imageimpute=imageimpute, cv.index1=cv.index1, cv.index2=cv.index2, cv.optlevel=cv.optlevel, cv.tol=cv.tol, cv.maxiter=cv.maxiter, filter.number=2, ll=ll) list(imagecv=tmpout$imagecv, cvthresh=tmpout$optlambda) } cvtype.image <- function(n, cv.bsize=c(1,1), cv.kfold) { if(length(n) != 2 || length(cv.bsize) != 2) stop("Two dimension") if(n[1]*n[2] < cv.bsize[1] * cv.bsize[2] * cv.kfold) stop("Block size or no. of fold is too large.") cv.perc <- 1 / cv.kfold cv.nblock <- trunc(n * sqrt(cv.perc) / cv.bsize) for (j in 1:2) { cv.index <- tmp.index <- NULL for (k in 1:cv.kfold) tmp.index <- rbind(tmp.index, sort(sample(seq(sample(1:cv.bsize[j], 1), n[j]-cv.bsize[j]+1, by=cv.bsize[j]), cv.nblock[j]))) if(cv.bsize[j] > 1) { cv.index <- tmp.index for (i in 1:(cv.bsize[j]-1)) cv.index <- cbind(cv.index, tmp.index + i) cv.index <- t(apply(cv.index, 1, sort)) } else { cv.index <- tmp.index } #assign(paste("cv.index", j, sep=""), cv.index) if(j==1) cv.index1 <- cv.index if(j==2) cv.index2 <- cv.index } list(cv.index1=cv.index1, cv.index2=cv.index2) } cvimpute.image.by.wavelet <- function( images, impute.index1, impute.index2, impute.tol=0.1^3, impute.maxiter=100, filter.number=2, ll=3) { if(!is.matrix(images)) stop("images must be a matrix format.") fracmiss <- (ncol(impute.index1) * ncol(impute.index2)) / (nrow(images) * ncol(images)) sdimage <- sd(as.numeric(images)) tmp <- c(8,9,10) slevel <- NULL for (k in 1:(log2(nrow(images))-ll)) slevel <- c(slevel, tmp+4*(k-1)) slevel <- slevel[length(slevel):1] yimpute <- images for (k in 1:nrow(impute.index1)) { ym <- images ymwd <- imwd(ym, filter.number=filter.number) sdev0 <- mad(c(ymwd[[8]], ymwd[[9]], ymwd[[10]])) for (i in 1:length(slevel)) ymwd[[slevel[i]]] <- ebayesthresh(ymwd[[slevel[i]]], sdev=sdev0) ym[impute.index1[k, ], impute.index2[k, ]] <- imwr(ymwd)[impute.index1[k, ], impute.index2[k, ]] j <- 0 repeat{ ymwd <- imwd(ym, filter.number=filter.number) sdev1 <- mad(c(ymwd[[8]], ymwd[[9]], ymwd[[10]])) sdev1 <- sqrt(sdev1^2 + fracmiss * sdev0^2) for (i in 1:length(slevel)) ymwd[[slevel[i]]] <- ebayesthresh(ymwd[[slevel[i]]], sdev=sdev1) tmpymwr <- imwr(ymwd) ydiff <- mean(abs(ym[impute.index1[k, ], impute.index2[k, ]] - tmpymwr[impute.index1[k, ], impute.index2[k, ]])) / sdimage if (ydiff < impute.tol || j > impute.maxiter) { ym[impute.index1[k, ], impute.index2[k, ]] <- tmpymwr[impute.index1[k, ], impute.index2[k, ]] break } sdev0 <- sdev1 ym[impute.index1[k, ], impute.index2[k, ]] <- tmpymwr[impute.index1[k, ], impute.index2[k, ]] j <- j + 1 } yimpute[impute.index1[k, ], impute.index2[k, ]] <- ym[impute.index1[k, ], impute.index2[k, ]] } list(imageimpute=yimpute) } cvwavelet.image.after.impute <- function( images, imagewd, imageimpute, cv.index1=cv.index1, cv.index2=cv.index2, cv.optlevel=cv.optlevel, cv.tol=cv.tol, cv.maxiter=cv.maxiter, filter.number=2, ll=3) { ### We adapt grid search algorithm of R function "WaveletCV" in WaveThresh3 of Nason (1998). ### This algorithm is a special form of grid search algorithm called golden section search. ### When bisectioning the interval containing solution, the golden number is used to keep ### the ratio of two sectioned subinterval fixed. if(!is.matrix(images)) stop("images must be a matrix format.") sdimage <- sd(as.numeric(images)) cv.kfold <- nrow(cv.index1) tmp <- c(8,9,10) slevel <- NULL for (i in 1:(diff(range(cv.optlevel))+1)) slevel <- c(slevel, tmp+4*(i-1)) slevel <- slevel[length(slevel):1] sdev <- mad(c(imagewd[[8]], imagewd[[9]], imagewd[[10]])) lambda.range <- NULL for (i in slevel) lambda.range <- c(lambda.range, ebayesthresh(imagewd[[i]], sdev=sdev, verbose=TRUE)$threshold.origscale) R <- (sqrt(5)-1)/2 # R is the golden number 0.61803399000000003 C <- 1 - R ndim <- (diff(range(cv.optlevel))+1) * 3 lambda <- matrix(0, 4, ndim) lambda[1, ] <- rep(0, ndim) lambda[4, ] <- 2.0 * lambda.range lambda[2, ] <- lambda[4, ]/2 lambda[3, ] <- lambda[2, ] + C * (lambda[4, ] - lambda[2, ]) optlambda <- lambda[3, ] tmpyimputewr <- images for (k in 1:cv.kfold) { yimpute2 <- images yimpute2[cv.index1[k, ], cv.index2[k, ]] <- imageimpute[cv.index1[k, ], cv.index2[k, ]] ywdth <- imwd(yimpute2, filter.number=filter.number) for (j in 1:ndim) ywdth[[slevel[j]]] <- threshld(ywdth[[slevel[j]]], optlambda[j], hard=FALSE) tmpyimputewr[cv.index1[k, ], cv.index2[k, ]] <- imwr(ywdth)[cv.index1[k, ], cv.index2[k, ]] } perr <- mean((tmpyimputewr - images)^2) j <- 0 repeat{ for (i in 1:ndim) { optlambda[i] <- lambda[2, i] for (k in 1:cv.kfold) { yimpute2 <- images yimpute2[cv.index1[k, ], cv.index2[k, ]] <- imageimpute[cv.index1[k, ], cv.index2[k, ]] ywdth <- imwd(yimpute2, filter.number=filter.number) for (m in 1:ndim) ywdth[[slevel[m]]] <- threshld(ywdth[[slevel[m]]], optlambda[m], hard=FALSE) tmpyimputewr[cv.index1[k, ], cv.index2[k, ]] <- imwr(ywdth)[cv.index1[k, ], cv.index2[k, ]] } f2 <- mean((tmpyimputewr - images)^2) optlambda[i] <- lambda[3, i] for (k in 1:cv.kfold) { yimpute2 <- images yimpute2[cv.index1[k, ], cv.index2[k, ]] <- imageimpute[cv.index1[k, ], cv.index2[k, ]] ywdth <- imwd(yimpute2, filter.number=filter.number) for (m in 1:ndim) ywdth[[slevel[m]]] <- threshld(ywdth[[slevel[m]]], optlambda[m], hard=FALSE) tmpyimputewr[cv.index1[k, ], cv.index2[k, ]] <- imwr(ywdth)[cv.index1[k, ], cv.index2[k, ]] } f3 <- mean((tmpyimputewr - images)^2) if(f3 < f2) { optlambda[i] <- lambda[3, i] optf <- f3 lambda[1, i] <- lambda[2, i] lambda[2, i] <- lambda[3, i] lambda[3, i] <- R * lambda[2, i] + C * lambda[4, i] } else { optlambda[i] <- lambda[2, i] optf <- f2 lambda[4, i] <- lambda[3, i] lambda[3, i] <- lambda[2, i] lambda[2, i] <- R * lambda[3, i] + C * lambda[1, i] } perr <- c(perr, optf) } stopping <- NULL for (i in 1:ndim) stopping <- c(stopping, abs(lambda[4, i] - lambda[1, i]) / (abs(lambda[2, i]) + abs(lambda[3, i]))) if (all(stopping < cv.tol) || abs(perr[ndim*(j+1)+1]-perr[ndim*j+1]) < (cv.tol * sdimage) || j > cv.maxiter) break j <- j + 1 } for (j in 1:ndim) imagewd[[slevel[j]]] <- threshld(imagewd[[slevel[j]]], optlambda[j], hard=FALSE) imagecv <- imwr(imagewd) list(imagecv=imagecv, cvthresh=optlambda) } heav <- function(norx = 1024) { if (length(norx) == 1) { if(norx <= 0) stop("The number of data must be greater than 0.") x <- seq(0, 1, length = norx + 1)[1:norx] } else x <- norx meanf <- 4 * sin(4*pi*x) - sign(x-0.3)-sign(0.72-x) list(x = x, meanf = meanf, sdf=2.969959) } dopp <- function(norx = 1024) { if (length(norx) == 1) { if(norx <= 0) stop("The number of data must be greater than 0.") x <- seq(0, 1, length = norx + 1)[1:norx] } else x <- norx meanf <- (x*(1-x))^0.5 * sin(2*pi*1.05/(x+0.05)) list(x = x, meanf = meanf, sdf=0.2889965) } ppoly <- function(norx = 1024) { if (length(norx) == 1) { if(norx <= 0) stop("The number of data must be greater than 0.") x <- seq(0, 1, length = norx + 1)[1:norx] } else x <- norx meanf <- rep(0, length(x)) xsv <- (x <= 0.5) # Left hand end meanf[xsv] <- -16 * x[xsv]^3 + 12 * x[xsv]^2 xsv <- (x > 0.5) & (x <= 0.75) # Middle section meanf[xsv] <- (x[xsv] * (16 * x[xsv]^2 - 40 * x[xsv] + 28))/3 - 1.5 xsv <- x > 0.75 # Right hand end meanf[xsv] <- (x[xsv] * (16 * x[xsv]^2 - 32 * x[xsv] + 16))/3 list(x = x, meanf = meanf, sdf=0.3033111) } fg1 <- function(norx = 1024) { if (length(norx) == 1) { if(norx <= 0) stop("The number of data must be greater than 0.") x <- seq(0, 1, length = norx + 1)[1:norx] } else x <- norx meanf <- 0.25 * ((4 * x - 2.0) + 2 * exp(-16 * (4 * x - 2.0)^2)) list(x = x, meanf = meanf, sdf=0.3159882) }
/scratch/gouwar.j/cran-all/cranData/CVThresh/R/CVThresh.R
#' CVXR: Disciplined Convex Optimization in R #' #' CVXR is an R package that provides an object-oriented modeling #' language for convex optimization, similar to CVX, CVXPY, YALMIP, #' and Convex.jl. This domain specific language (DSL) allows the user #' to formulate convex optimization problems in a natural mathematical #' syntax rather than the restrictive standard form required by most #' solvers. The user specifies an objective and set of constraints by #' combining constants, variables, and parameters using a library of #' functions with known mathematical properties. CVXR then applies #' signed disciplined convex programming (DCP) to verify the problem's #' convexity. Once verified, the problem is converted into standard #' conic form using graph implementations and passed to a cone solver #' such as ECOS or SCS. #' #' @name CVXR-package #' @useDynLib CVXR #' @importFrom Rcpp evalCpp #' @import methods #' @import Matrix #' @importFrom stats rnorm runif #' @aliases CVXR-package CVXR #' @docType package #' @author Anqi Fu, Balasubramanian Narasimhan, John Miller, Steven Diamond, Stephen Boyd #' #' Maintainer: Anqi Fu<[email protected]> #' @keywords package NULL
/scratch/gouwar.j/cran-all/cranData/CVXR/R/CVXR.R
## CVXcanon class shadowing CVXcannon.cpp code, exposing merely the two ## build_matrix methods CVXcanon <- R6::R6Class("CVXcanon", private = list( ptr = NA ) , active = list( ) , public = list( initialize = function() { } , getXPtr = function() { private$ptr } , build_matrix = function(constraints, id_to_col, constr_offsets) { ## constraints is a vector of Linops (LinOpVector-R6 in R) ## id_to_col is an integer vector with names that are ## integers converted to chacracters ## constr_offsets is a standard integer vector in R ## cat("Linvec\n") ## constraints$print() ## cat("id_to_col\n") ## print(id_to_col) if (missing(constr_offsets)) { objPtr <- .Call('_CVXR_build_matrix_0', constraints$getXPtr(), id_to_col, PACKAGE = 'CVXR') } else { objPtr <- .Call('_CVXR_build_matrix_1', constraints$getXPtr(), id_to_col, constr_offsets, PACKAGE = 'CVXR') } ##cat("Instantiating ProblemData-R6", "\n") CVXcanon.ProblemData$new(objPtr) } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/CVXcanon-R6.R
Deque <- R6::R6Class("Deque", private = list( queue = NA ), public = list( initialize = function(init = list()) { private$queue <- init }, ## popleft, remove and return an element from the left side of the queue, ## raise error if no element. popleft = function() { if (length(private$queue) > 0) { result <- private$queue[[1]] private$queue <- private$queue[-1] result } else { stop("Deque: empty queue") } }, ## append, adds to the right end of the queue ## append = function(what) { n <- length(private$queue) private$queue[[n+1]] <- what invisible(private$queue) }, length = function() { length(private$queue) }, getQ = function() private$queue, print = function() { print(private$queue) } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/Deque.R
## LinOp class shadowing CPP class CVXcanon.LinOp <- R6::R6Class("CVXcanon.LinOp", private = list( operatorType = c( ## from LinOp.hpp "VARIABLE", "PROMOTE", "MUL_EXPR", "RMUL_EXPR", "MUL_ELEM", "DIV", "SUM", "NEG", "INDEX", "TRANSPOSE", "SUM_ENTRIES", "TRACE", "RESHAPE_EXPR", "DIAG_VEC", "DIAG_MAT", "UPPER_TRI", "CONV", "HSTACK", "VSTACK", "SCALAR_CONST", "DENSE_CONST", "SPARSE_CONST", "NO_OP", "KRON"), args = NA, ptr = NA ), active = list( sparse = function(value) { if (missing(value)) { .Call("_CVXR_LinOp__get_sparse", private$ptr, PACKAGE = "CVXR") } else { ## value should be a boolean .Call("_CVXR_LinOp__set_sparse", private$ptr, value, PACKAGE = "CVXR") } } , sparse_data = function(value) { if (missing(value)) { .Call("_CVXR_LinOp__get_sparse_data", private$ptr, PACKAGE = "CVXR") } else { ## value should be a dgCMatrix-class .Call("_CVXR_LinOp__set_sparse_data", private$ptr, value, PACKAGE = "CVXR") } } , dense_data = function(value) { if (missing(value)) { .Call("_CVXR_LinOp__get_dense_data", private$ptr, PACKAGE = "CVXR") } else { ## value should be a matrix .Call("_CVXR_LinOp__set_dense_data", private$ptr, value, PACKAGE = "CVXR") } } , type = function(value) { if (missing(value)) { index <- .Call("_CVXR_LinOp__get_type", private$ptr, PACKAGE = "CVXR") ## make 1-based index private$operatorType[index + 1] } else { ##value <- match.arg(value, private$operatorType) ## Make zero based index! index <- match(value, private$operatorType) - 1 .Call("_CVXR_LinOp__set_type", private$ptr, index, PACKAGE = "CVXR") } } , size = function(value) { if (missing(value)) { .Call("_CVXR_LinOp__get_size", private$ptr, PACKAGE = "CVXR") } else { ## value is an integer vector .Call("_CVXR_LinOp__set_size", private$ptr, value, PACKAGE = "CVXR") } } , slice = function(value) { if (missing(value)) { .Call("_CVXR_LinOp__get_slice", private$ptr, PACKAGE = "CVXR") } else { ## value is a list of integer vectors .Call("_CVXR_LinOp__set_slice", private$ptr, value, PACKAGE = "CVXR") } } ), public = list( initialize = function(type = NULL, size = NULL, args = NULL, data = NULL) { private$args = R6List$new() ## Create a new LinOp on the C side private$ptr <- .Call("_CVXR_LinOp__new", PACKAGE = "CVXR") ## Associate args on R side with the args on the C side. if (!is.null(type)) { self$type <- type } if (!is.null(size)) { self$size <- size } if (!is.null(args)) { for (x in args) self$args_push_back(x) } if (!is.null(data)) { self$dense_data <- data } } , args_push_back = function(R6LinOp) { private$args$append(R6LinOp) .Call("_CVXR_LinOp__args_push_back", private$ptr, R6LinOp$getXPtr(), PACKAGE = "CVXR") } , slice_push_back = function(anIntVector) { .Call("_CVXR_LinOp__slice_push_back", private$ptr, anIntVector, PACKAGE = "CVXR") } , getXPtr = function() { private$ptr } , getArgs = function() { private$args } , get_id = function() { .Call("_CVXR_LinOp__get_id", private$ptr, PACKAGE = "CVXR") } , size_push_back = function(value) { .Call("_CVXR_LinOp__size_push_back", private$ptr, value, PACKAGE = "CVXR") } , toString = function() { sparse <- self$sparse if (sparse) { data <- paste(self$sparse_data, collapse=", ") } else { data <- paste(self$dense_data, collapse=", ") } sprintf("LinOp(id=%s, type=%s, size=[%s], args=%s, sparse=%s, data=[%s])", self$get_id(), self$type, paste(self$size, collapse=", "), private$args$toString(), sparse, data) } , print = function() { print(self$toString()) } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/LinOp-R6.R
## LinOpVector class shadowing CPP class CVXcanon.LinOpVector <- R6::R6Class("CVXcanon.LinOpVector", private = list( linOps = NA, ptr = NA ## the rcpp XPtr ), active = list( ), public = list( initialize = function() { private$linOps <- list() private$ptr <- .Call("_CVXR_LinOpVector__new", PACKAGE = "CVXR") } , getXPtr = function() { private$ptr } , getList = function() { private$linOps } , push_back = function(R6LinOp) { n <- length(private$linOps) private$linOps[[n+1]] <- R6LinOp ## Needs modification by hand for arguments .Call("_CVXR_LinOpVector__push_back", private$ptr , R6LinOp$getXPtr(), PACKAGE = "CVXR") } , toString = function() { result <- sapply(private$linOps, function(x) x$toString()) result <- paste(result, collapse = ", ") sprintf("[ %s ]", result) } , print = function() { print(self$toString()) } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/LinOpVector-R6.R
## CVXcanon.ProblemData class shadowing CPP class CVXcanon.ProblemData <- R6::R6Class("CVXcanon.ProblemData", private = list( ptr = NA ), active = list( V = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_V', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_V', private$ptr, value, PACKAGE = "CVXR") } } , I = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_I', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_I', private$ptr, value, PACKAGE = "CVXR") } } , J = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_J', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_J', private$ptr, value, PACKAGE = "CVXR") } } , const_vec = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_const_vec', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_const_vec', private$ptr, value, PACKAGE = "CVXR") } } , id_to_col = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_id_to_col', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_id_to_col', private$ptr, value, PACKAGE = "CVXR") } } , const_to_row = function(value) { if (missing(value)) { .Call('_CVXR_ProblemData__get_const_to_row', private$ptr, PACKAGE = "CVXR") } else { .Call('_CVXR_ProblemData__set_const_to_row', private$ptr, value, PACKAGE = "CVXR") } } ), public = list( initialize = function(ptr = NULL) { private$ptr <- if (is.null(ptr)) { .Call('_CVXR_ProblemData__new', PACKAGE = 'CVXR') } else { ptr } } , getV = function() { .Call('_CVXR_ProblemData__get_V', private$ptr, PACKAGE = "CVXR") } , getI = function() { .Call('_CVXR_ProblemData__get_I', private$ptr, PACKAGE = "CVXR") } , getJ = function() { .Call('_CVXR_ProblemData__get_J', private$ptr, PACKAGE = "CVXR") } , getConstVec = function() { .Call('_CVXR_ProblemData__get_const_vec', private$ptr, PACKAGE = "CVXR") } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/ProblemData-R6.R
## An R6 List class with reference semantics mainly for keeping objects in scope #' @importFrom R6 R6Class R6List <- R6::R6Class("R6List", private = list( r6list = NA ) , public = list( initialize = function() { private$r6list <- list() } , getList = function() { private$r6list } , append = function(what) { n <- length(private$r6list) private$r6list[[n+1]] <- what } , toString = function() { result <- sapply(private$r6list, function(x) x$toString()) result <- paste(result, collapse = ", ") sprintf("[ %s ]", result) } , print = function() { print(self$toString()) } ))
/scratch/gouwar.j/cran-all/cranData/CVXR/R/R6List.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' Get the \code{sparse} flag field for the LinOp object #' #' @param xp the LinOpVector Object XPtr #' @param v the \code{id_to_col} named int vector in R with integer names #' @return a XPtr to ProblemData Object .build_matrix_0 <- function(xp, v) { .Call('_CVXR_build_matrix_0', PACKAGE = 'CVXR', xp, v) } #' Get the \code{sparse} flag field for the LinOp object #' #' @param xp the LinOpVector Object XPtr #' @param v1 the \code{id_to_col} named int vector in R with integer names #' @param v2 the \code{constr_offsets} vector of offsets (an int vector in R) #' @return a XPtr to ProblemData Object .build_matrix_1 <- function(xp, v1, v2) { .Call('_CVXR_build_matrix_1', PACKAGE = 'CVXR', xp, v1, v2) } .cpp_convolve <- function(xa, xb) { .Call('_CVXR_cpp_convolve', PACKAGE = 'CVXR', xa, xb) } #' Create a new LinOp object. #' #' @return an external ptr (Rcpp::XPtr) to a LinOp object instance. .LinOp__new <- function() { .Call('_CVXR_LinOp__new', PACKAGE = 'CVXR') } #' Get the \code{sparse} flag field for the LinOp object #' #' @param xp the LinOp Object XPtr #' @return TRUE or FALSE .LinOp__get_sparse <- function(xp) { .Call('_CVXR_LinOp__get_sparse', PACKAGE = 'CVXR', xp) } #' Set the flag \code{sparse} of the LinOp object #' #' @param xp the LinOp Object XPtr #' @param sparseSEXP an R boolean .LinOp__set_sparse <- function(xp, sparseSEXP) { invisible(.Call('_CVXR_LinOp__set_sparse', PACKAGE = 'CVXR', xp, sparseSEXP)) } #' Get the field named \code{sparse_data} from the LinOp object #' #' @param xp the LinOp Object XPtr #' @return a \link[Matrix]{dgCMatrix-class} object .LinOp__get_sparse_data <- function(xp) { .Call('_CVXR_LinOp__get_sparse_data', PACKAGE = 'CVXR', xp) } #' Set the field named \code{sparse_data} of the LinOp object #' #' @param xp the LinOp Object XPtr #' @param sparseMat a \link[Matrix]{dgCMatrix-class} object .LinOp__set_sparse_data <- function(xp, sparseMat) { invisible(.Call('_CVXR_LinOp__set_sparse_data', PACKAGE = 'CVXR', xp, sparseMat)) } #' Get the field \code{dense_data} for the LinOp object #' #' @param xp the LinOp Object XPtr #' @return a MatrixXd object .LinOp__get_dense_data <- function(xp) { .Call('_CVXR_LinOp__get_dense_data', PACKAGE = 'CVXR', xp) } #' Set the field \code{dense_data} of the LinOp object #' #' @param xp the LinOp Object XPtr #' @param denseMat a standard matrix object in R .LinOp__set_dense_data <- function(xp, denseMat) { invisible(.Call('_CVXR_LinOp__set_dense_data', PACKAGE = 'CVXR', xp, denseMat)) } #' Get the field \code{size} for the LinOp object #' #' @param xp the LinOp Object XPtr #' @return an integer vector .LinOp__get_size <- function(xp) { .Call('_CVXR_LinOp__get_size', PACKAGE = 'CVXR', xp) } #' Set the field \code{size} of the LinOp object #' #' @param xp the LinOp Object XPtr #' @param value an integer vector object in R .LinOp__set_size <- function(xp, value) { invisible(.Call('_CVXR_LinOp__set_size', PACKAGE = 'CVXR', xp, value)) } #' Perform a push back operation on the \code{args} field of LinOp #' #' @param xp the LinOp Object XPtr #' @param yp the LinOp Object XPtr to push .LinOp__args_push_back <- function(xp, yp) { invisible(.Call('_CVXR_LinOp__args_push_back', PACKAGE = 'CVXR', xp, yp)) } #' Perform a push back operation on the \code{size} field of LinOp #' #' @param xp the LinOp Object XPtr #' @param intVal the integer value to push back .LinOp__size_push_back <- function(xp, intVal) { invisible(.Call('_CVXR_LinOp__size_push_back', PACKAGE = 'CVXR', xp, intVal)) } #' Set the field named \code{type} for the LinOp object #' #' @param xp the LinOp Object XPtr #' @param typeValue an integer value .LinOp__set_type <- function(xp, typeValue) { invisible(.Call('_CVXR_LinOp__set_type', PACKAGE = 'CVXR', xp, typeValue)) } #' Get the field named \code{type} for the LinOp object #' #' @param xp the LinOp Object XPtr #' @return an integer value for type .LinOp__get_type <- function(xp) { .Call('_CVXR_LinOp__get_type', PACKAGE = 'CVXR', xp) } #' Perform a push back operation on the \code{slice} field of LinOp #' #' @param xp the LinOp Object XPtr #' @param intVec an integer vector to push back .LinOp__slice_push_back <- function(xp, intVec) { invisible(.Call('_CVXR_LinOp__slice_push_back', PACKAGE = 'CVXR', xp, intVec)) } #' Get the slice field of the LinOp Object #' #' @param xp the LinOp Object XPtr #' @return the value of the slice field of the LinOp Object .LinOp__get_slice <- function(xp) { .Call('_CVXR_LinOp__get_slice', PACKAGE = 'CVXR', xp) } #' Set the slice field of the LinOp Object #' #' @param xp the LinOp Object XPtr #' @param value a list of integer vectors, e.g. \code{list(1:10, 2L, 11:15)} #' @return the value of the slice field of the LinOp Object .LinOp__set_slice <- function(xp, value) { invisible(.Call('_CVXR_LinOp__set_slice', PACKAGE = 'CVXR', xp, value)) } #' Get the id field of the LinOp Object #' #' @param xp the LinOp Object XPtr #' @return the value of the id field of the LinOp Object .LinOp__get_id <- function(xp) { .Call('_CVXR_LinOp__get_id', PACKAGE = 'CVXR', xp) } #' Create a new LinOpVector object. #' #' @return an external ptr (Rcpp::XPtr) to a LinOp object instance. .LinOpVector__new <- function() { .Call('_CVXR_LinOpVector__new', PACKAGE = 'CVXR') } #' Perform a push back operation on the \code{args} field of LinOp #' #' @param xp the LinOpVector Object XPtr #' @param yp the LinOp Object XPtr to push .LinOpVector__push_back <- function(xp, yp) { invisible(.Call('_CVXR_LinOpVector__push_back', PACKAGE = 'CVXR', xp, yp)) } #' Return the LinOp element at index i (0-based) #' #' @param lvec the LinOpVector Object XPtr #' @param i the index .LinOp_at_index <- function(lvec, i) { .Call('_CVXR_LinOp_at_index', PACKAGE = 'CVXR', lvec, i) } #' Create a new ProblemData object. #' #' @return an external ptr (Rcpp::XPtr) to a ProblemData object instance. .ProblemData__new <- function() { .Call('_CVXR_ProblemData__new', PACKAGE = 'CVXR') } #' Get the V field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return a numeric vector of doubles (the field V) from the ProblemData Object .ProblemData__get_V <- function(xp) { .Call('_CVXR_ProblemData__get_V', PACKAGE = 'CVXR', xp) } #' Set the V field in the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param vp a numeric vector of values for field V .ProblemData__set_V <- function(xp, vp) { invisible(.Call('_CVXR_ProblemData__set_V', PACKAGE = 'CVXR', xp, vp)) } #' Get the I field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return an integer vector of the field I from the ProblemData Object .ProblemData__get_I <- function(xp) { .Call('_CVXR_ProblemData__get_I', PACKAGE = 'CVXR', xp) } #' Set the I field in the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param ip an integer vector of values for field I of the ProblemData object .ProblemData__set_I <- function(xp, ip) { invisible(.Call('_CVXR_ProblemData__set_I', PACKAGE = 'CVXR', xp, ip)) } #' Get the J field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return an integer vector of the field J from the ProblemData Object .ProblemData__get_J <- function(xp) { .Call('_CVXR_ProblemData__get_J', PACKAGE = 'CVXR', xp) } #' Set the J field in the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param jp an integer vector of the values for field J of the ProblemData object .ProblemData__set_J <- function(xp, jp) { invisible(.Call('_CVXR_ProblemData__set_J', PACKAGE = 'CVXR', xp, jp)) } #' Get the const_vec field from the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return a numeric vector of the field const_vec from the ProblemData Object .ProblemData__get_const_vec <- function(xp) { .Call('_CVXR_ProblemData__get_const_vec', PACKAGE = 'CVXR', xp) } #' Set the const_vec field in the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param cvp a numeric vector of values for const_vec field of the ProblemData object .ProblemData__set_const_vec <- function(xp, cvp) { invisible(.Call('_CVXR_ProblemData__set_const_vec', PACKAGE = 'CVXR', xp, cvp)) } #' Get the id_to_col field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return the id_to_col field as a named integer vector where the names are integers converted to characters .ProblemData__get_id_to_col <- function(xp) { .Call('_CVXR_ProblemData__get_id_to_col', PACKAGE = 'CVXR', xp) } #' Set the id_to_col field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param iv a named integer vector with names being integers converted to characters .ProblemData__set_id_to_col <- function(xp, iv) { invisible(.Call('_CVXR_ProblemData__set_id_to_col', PACKAGE = 'CVXR', xp, iv)) } #' Get the const_to_row field of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @return the const_to_row field as a named integer vector where the names are integers converted to characters .ProblemData__get_const_to_row <- function(xp) { .Call('_CVXR_ProblemData__get_const_to_row', PACKAGE = 'CVXR', xp) } #' Set the const_to_row map of the ProblemData Object #' #' @param xp the ProblemData Object XPtr #' @param iv a named integer vector with names being integers converted to characters .ProblemData__set_const_to_row <- function(xp, iv) { invisible(.Call('_CVXR_ProblemData__set_const_to_row', PACKAGE = 'CVXR', xp, iv)) }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/RcppExports.R
#' #' The AffAtom class. #' #' This virtual class represents an affine atomic expression. #' #' @name AffAtom-class #' @aliases AffAtom #' @rdname AffAtom-class AffAtom <- setClass("AffAtom", contains = c("VIRTUAL", "Atom")) #' @param object An \linkS4class{AffAtom} object. #' @describeIn AffAtom Does the atom handle complex numbers? setMethod("allow_complex", "AffAtom", function(object) { TRUE }) #' @describeIn AffAtom The sign of the atom. setMethod("sign_from_args", "AffAtom", function(object) { sum_signs(object@args) }) #' @describeIn AffAtom Is the atom imaginary? setMethod("is_imag", "AffAtom", function(object) { all(sapply(object@args, is_imag)) }) #' @describeIn AffAtom Is the atom complex valued? setMethod("is_complex", "AffAtom", function(object) { any(sapply(object@args, is_complex)) }) #' @describeIn AffAtom The atom is convex. setMethod("is_atom_convex", "AffAtom", function(object) { TRUE }) #' @describeIn AffAtom The atom is concave. setMethod("is_atom_concave", "AffAtom", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn AffAtom The atom is weakly increasing in every argument. setMethod("is_incr", "AffAtom", function(object, idx) { TRUE }) #' @describeIn AffAtom The atom is not weakly decreasing in any argument. setMethod("is_decr", "AffAtom", function(object, idx) { FALSE }) #' @describeIn AffAtom Is every argument quadratic? setMethod("is_quadratic", "AffAtom", function(object) { all(sapply(object@args, is_quadratic)) }) #' @describeIn AffAtom Is every argument quadratic of piecewise affine? setMethod("is_qpwa", "AffAtom", function(object) { all(sapply(object@args, is_qpwa)) }) #' @describeIn AffAtom Is every argument piecewise linear? setMethod("is_pwl", "AffAtom", function(object) { all(sapply(object@args, is_pwl)) }) #' @describeIn AffAtom Is the atom a positive semidefinite matrix? setMethod("is_psd", "AffAtom", function(object) { for(idx in seq_len(length(object@args))) { arg <- object@args[[idx]] if(!((is_incr(object, idx) && is_psd(arg)) || (is_decr(object, idx) && is_nsd(arg)))) return(FALSE) } return(TRUE) }) #' @describeIn AffAtom Is the atom a negative semidefinite matrix? setMethod("is_nsd", "AffAtom", function(object) { for(idx in seq_len(length(object@args))) { arg <- object@args[[1]] if(!((is_decr(object, idx) && is_psd(arg)) || (is_incr(object, idx) && is_nsd(arg)))) return(FALSE) } return(TRUE) }) #' @param values A list of numeric values for the arguments #' @describeIn AffAtom Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "AffAtom", function(object, values) { # TODO: Should be a simple function in CVXcore for this. # Make a fake LinOp tree for the function fake_args <- list() var_offsets <- c() var_names <- c() offset <- 0 for(idx in seq_len(length(object@args))) { arg <- object@args[[idx]] if(is_constant(arg)) fake_args <- c(fake_args, list(canonical_form(Constant(value(arg)))[[1]])) else { fake_args <- c(fake_args, list(create_var(dim(arg), idx))) var_offsets <- c(var_offsets, offset) var_names <- c(var_names, idx) offset <- offset + size(arg) } } names(var_offsets) <- var_names graph <- graph_implementation(object, fake_args, dim(object), get_data(object)) fake_expr <- graph[[1]] # Get the matrix representation of the function. prob_mat <- get_problem_matrix(list(fake_expr), var_offsets) V <- prob_mat[[1]] I <- prob_mat[[2]] + 1 # TODO: R uses 1-indexing, but get_problem_matrix returns with 0-indexing J <- prob_mat[[3]] + 1 dims <- c(offset, size(object)) stacked_grad <- sparseMatrix(i = J, j = I, x = V, dims = dims) # Break up into per argument matrices. grad_list <- list() start <- 1 for(arg in object@args) { if(is_constant(arg)) { grad_dim <- c(size(arg), dims[2]) if(all(grad_dim == c(1,1))) grad_list <- c(grad_list, list(0)) else grad_list <- c(grad_list, list(sparseMatrix(i = c(), j = c(), dims = grad_dim))) } else { stop <- start + size(arg) if(stop == start) grad_list <- c(grad_list, list(sparseMatrix(i = c(), j = c(), dims = c(0, dim[2])))) else grad_list <- c(grad_list, list(stacked_grad[start:(stop-1),])) start <- stop } } return(grad_list) }) #' #' The AddExpression class. #' #' This class represents the sum of any number of expressions. #' #' @slot arg_groups A \code{list} of \linkS4class{Expression}s and numeric data.frame, matrix, or vector objects. #' @name AddExpression-class #' @aliases AddExpression #' @rdname AddExpression-class .AddExpression <- setClass("AddExpression", representation(arg_groups = "list"), prototype(arg_groups = list()), contains = "AffAtom") AddExpression <- function(arg_groups = list()) { .AddExpression(arg_groups = arg_groups) } setMethod("initialize", "AddExpression", function(.Object, ..., arg_groups = list()) { .Object@arg_groups <- arg_groups .Object <- callNextMethod(.Object, ..., atom_args = arg_groups) # Casts R values to Constant objects .Object@args <- lapply(.Object@args, function(group) { if(is(group,"AddExpression")) group@args else group }) .Object@args <- flatten_list(.Object@args) # Need to flatten list of expressions .Object }) #' @param x,object An \linkS4class{AddExpression} object. #' @describeIn AddExpression The dimensions of the expression. setMethod("dim_from_args", "AddExpression", function(object) { sum_dims(lapply(object@args, dim)) }) #' @describeIn AddExpression The string form of the expression. setMethod("name", "AddExpression", function(x) { paste(sapply(x@args, name), collapse = " + ") }) #' @param values A list of arguments to the atom. #' @describeIn AddExpression Sum all the values. setMethod("to_numeric", "AddExpression", function(object, values) { values <- lapply(values, intf_convert_if_scalar) Reduce("+", values) }) #' @describeIn AddExpression Is the atom log-log convex? setMethod("is_atom_log_log_convex", "AddExpression", function(object) { TRUE }) #' @describeIn AddExpression Is the atom log-log convex? setMethod("is_atom_log_log_concave", "AddExpression", function(object) { FALSE }) #' @describeIn AddExpression Is the atom symmetric? setMethod("is_symmetric", "AddExpression", function(object) { symm_args <- all(sapply(object@args, is_symmetric)) return(dim(object)[1] == dim(object)[2] && symm_args) }) #' @describeIn AddExpression Is the atom hermitian? setMethod("is_hermitian", "AddExpression", function(object) { herm_args <- all(sapply(object@args, is_hermitian)) return(dim(object)[1] == dim(object)[2] && herm_args) }) # As initialize takes in the arg_groups instead of args, we need a special copy function. #' @param args An optional list of arguments to reconstruct the atom. Default is to use current args of the atom. #' @param id_objects Currently unused. #' @describeIn AddExpression Returns a shallow copy of the AddExpression atom setMethod("copy", "AddExpression", function(object, args = NULL, id_objects = list()) { if(is.null(args)) args <- object@arg_groups do.call(class(object), list(arg_groups = args)) }) AddExpression.graph_implementation <- function(arg_objs, dim, data = NA_real_) { arg_objs <- lapply(arg_objs, function(arg) { if(!all(arg$dim == dim) && lo.is_scalar(arg)) lo.promote(arg, dim) else arg }) list(lo.sum_expr(arg_objs), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn AddExpression The graph implementation of the expression. setMethod("graph_implementation", "AddExpression", function(object, arg_objs, dim, data = NA_real_) { AddExpression.graph_implementation(arg_objs, dim, data) }) #' #' The UnaryOperator class. #' #' This base class represents expressions involving unary operators. #' #' @slot expr The \linkS4class{Expression} that is being operated upon. #' @slot op_name A \code{character} string indicating the unary operation. #' @name UnaryOperator-class #' @aliases UnaryOperator #' @rdname UnaryOperator-class UnaryOperator <- setClass("UnaryOperator", representation(expr = "Expression"), contains = "AffAtom") setMethod("initialize", "UnaryOperator", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) setMethod("op_name", "UnaryOperator", function(object) { stop("Unimplemented") }) setMethod("op_func", "UnaryOperator", function(object) { stop("Unimplemented") }) #' @param x,object A \linkS4class{UnaryOperator} object. #' @describeIn UnaryOperator Returns the expression in string form. setMethod("name", "UnaryOperator", function(x) { paste(op_name(x), name(x@args[[1]]), sep = "") }) #' @param values A list of arguments to the atom. #' @describeIn UnaryOperator Applies the unary operator to the value. setMethod("to_numeric", "UnaryOperator", function(object, values) { op_func(object)(values[[1]]) }) #' #' The NegExpression class. #' #' This class represents the negation of an affine expression. #' #' @name NegExpression-class #' @aliases NegExpression #' @rdname NegExpression-class .NegExpression <- setClass("NegExpression", contains = "UnaryOperator") NegExpression <- function(expr) { .NegExpression(expr = expr) } setMethod("op_name", "NegExpression", function(object) { "-" }) setMethod("op_func", "NegExpression", function(object) { function(x) { -x } }) #' @param object A \linkS4class{NegExpression} object. #' @describeIn NegExpression The (row, col) dimensions of the expression. setMethod("dim_from_args", "NegExpression", function(object) { dim(object@args[[1]]) }) #' @describeIn NegExpression The (is positive, is negative) sign of the expression. setMethod("sign_from_args", "NegExpression", function(object) { c(is_nonpos(object@args[[1]]), is_nonneg(object@args[[1]])) }) #' @param idx An index into the atom. #' @describeIn NegExpression The expression is not weakly increasing in any argument. setMethod("is_incr", "NegExpression", function(object, idx) { FALSE }) #' @describeIn NegExpression The expression is weakly decreasing in every argument. setMethod("is_decr", "NegExpression", function(object, idx) { TRUE }) #' @describeIn NegExpression Is the expression symmetric? setMethod("is_symmetric", "NegExpression", function(object) { is_symmetric(object@args[[1]]) }) #' @describeIn NegExpression Is the expression Hermitian? setMethod("is_hermitian", "NegExpression", function(object) { is_hermitian(object@args[[1]]) }) NegExpression.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.neg_expr(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn NegExpression The graph implementation of the expression. setMethod("graph_implementation", "NegExpression", function(object, arg_objs, dim, data = NA_real_) { NegExpression.graph_implementation(arg_objs, dim, data) }) #' The BinaryOperator class. #' #' This base class represents expressions involving binary operators. #' #' @slot lh_exp The \linkS4class{Expression} on the left-hand side of the operator. #' @slot rh_exp The \linkS4class{Expression} on the right-hand side of the operator. #' @slot op_name A \code{character} string indicating the binary operation. #' @name BinaryOperator-class #' @aliases BinaryOperator #' @rdname BinaryOperator-class BinaryOperator <- setClass("BinaryOperator", representation(lh_exp = "ConstValORExpr", rh_exp = "ConstValORExpr"), contains = "AffAtom") setMethod("initialize", "BinaryOperator", function(.Object, ..., lh_exp, rh_exp) { .Object@lh_exp = lh_exp .Object@rh_exp = rh_exp callNextMethod(.Object, ..., atom_args = list(.Object@lh_exp, .Object@rh_exp)) }) setMethod("op_name", "BinaryOperator", function(object) { "BINARY_OP" }) #' @param x,object A \linkS4class{BinaryOperator} object. #' @describeIn BinaryOperator Returns the name of the BinaryOperator object. setMethod("name", "BinaryOperator", function(x) { pretty_args <- list() for(a in x@args) { if(is(a, "AddExpression") || is(a, "DivExpression")) pretty_args <- list(pretty_args, paste("(", name(a), ")", sep = "")) else pretty_args <- list(pretty_args, name(a)) } paste(pretty_args[[1]], op_name(x), pretty_args[[2]]) }) #' @param values A list of arguments to the atom. #' @describeIn BinaryOperator Apply the binary operator to the values. setMethod("to_numeric", "BinaryOperator", function(object, values) { values <- lapply(values, intf_convert_if_scalar) Reduce(op_name(object), values) }) #' @describeIn BinaryOperator Default to rule for multiplication. setMethod("sign_from_args", "BinaryOperator", function(object) { mul_sign(object@args[[1]], object@args[[2]]) }) #' @describeIn BinaryOperator Is the expression imaginary? setMethod("is_imag", "BinaryOperator", function(object) { (is_imag(object@args[[1]]) && is_real(object@args[[2]])) || (is_real(object@args[[1]]) && is_imag(object@args[[2]])) }) #' @describeIn BinaryOperator Is the expression complex valued? setMethod("is_complex", "BinaryOperator", function(object) { (is_complex(object@args[[1]]) || is_complex(object@args[[2]])) && !(is_imag(object@args[[1]]) && is_imag(object@args[[2]])) }) #' #' The MulExpression class. #' #' This class represents the matrix product of two linear expressions. #' See \linkS4class{Multiply} for the elementwise product. #' #' @seealso \linkS4class{Multiply} #' @name MulExpression-class #' @aliases MulExpression #' @rdname MulExpression-class .MulExpression <- setClass("MulExpression", contains = "BinaryOperator") MulExpression <- function(lh_exp, rh_exp) { .MulExpression(lh_exp = lh_exp, rh_exp = rh_exp) } setMethod("op_name", "MulExpression", function(object) { "*" }) #' @param object A \linkS4class{MulExpression} object. #' @param values A list of arguments to the atom. #' @describeIn MulExpression Matrix multiplication. setMethod("to_numeric", "MulExpression", function(object, values) { if(is.null(dim(object@args[[1]])) || is.null(dim(object@args[[2]]))) return(values[[1]] * values[[2]]) else return(values[[1]] %*% values[[2]]) }) #' @describeIn MulExpression The (row, col) dimensions of the expression. setMethod("dim_from_args", "MulExpression", function(object) { mul_dims(dim(object@args[[1]]), dim(object@args[[2]])) }) #' @describeIn MulExpression Multiplication is convex (affine) in its arguments only if one of the arguments is constant. setMethod("is_atom_convex", "MulExpression", function(object) { is_constant(object@args[[1]]) || is_constant(object@args[[2]]) }) #' @describeIn MulExpression If the multiplication atom is convex, then it is affine. setMethod("is_atom_concave", "MulExpression", function(object) { is_atom_convex(object) }) #' @describeIn MulExpression Is the atom log-log convex? setMethod("is_atom_log_log_convex", "MulExpression", function(object) { TRUE }) #' @describeIn MulExpression Is the atom log-log concave? setMethod("is_atom_log_log_concave", "MulExpression", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn MulExpression Is the left-hand expression positive? setMethod("is_incr", "MulExpression", function(object, idx) { is_nonneg(object@args[[3-idx]]) }) #' @describeIn MulExpression Is the left-hand expression negative? setMethod("is_decr", "MulExpression", function(object, idx) { is_nonpos(object@args[[3-idx]]) }) #' @param values A list of numeric values for the arguments #' @describeIn MulExpression Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MulExpression", function(object, values) { if(is_constant(object@args[[1]]) || is_constant(object@args[[2]])) return(callNextMethod(object, values)) # TODO: Verify that the following code is correct for non-affine arguments. X <- values[[1]] Y <- values[[2]] DX_rows <- size(object@args[[1]]) block_rows <- DX_rows/nrow(Y) # DX = [diag(Y11), diag(Y12), ...] # [diag(Y21), diag(Y22), ...] # [ ... ... ...] DX <- kronecker(Y, sparseMatrix(i = 1:block_rows, j = 1:block_rows, x = 1)) cols <- ifelse(length(dim(object@args[[2]])) == 1, 1, ncol(object@args[[2]])) DY <- Matrix(bdiag(lapply(1:cols, function(k) { t(X) })), sparse = TRUE) return(list(DX, DY)) }) MulExpression.graph_implementation <- function(arg_objs, dim, data = NA_real_) { # Promote the right-hand side to a diagonal matrix if necessary lhs <- arg_objs[[1]] rhs <- arg_objs[[2]] if(lo.is_const(lhs)) return(list(lo.mul_expr(lhs, rhs, dim), list())) else if(lo.is_const(rhs)) return(list(lo.rmul_expr(lhs, rhs, dim), list())) else stop("Product of two non-constant expressions is not DCP.") } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn MulExpression The graph implementation of the expression. setMethod("graph_implementation", "MulExpression", function(object, arg_objs, dim, data = NA_real_) { MulExpression.graph_implementation(arg_objs, dim, data) }) #' #' The Multiply class. #' #' This class represents the elementwise product of two expressions. #' #' @name Multiply-class #' @aliases Multiply #' @rdname Multiply-class .Multiply <- setClass("Multiply", contains = "MulExpression") #' @param lh_exp An \linkS4class{Expression} or R numeric data. #' @param rh_exp An \linkS4class{Expression} or R numeric data. #' @rdname Multiply-class Multiply <- function(lh_exp, rh_exp) { .Multiply(lh_exp = lh_exp, rh_exp = rh_exp) } setMethod("initialize", "Multiply", function(.Object, ..., lh_exp, rh_exp) { lh_exp <- as.Constant(lh_exp) rh_exp <- as.Constant(rh_exp) if(is_scalar(lh_exp) && !is_scalar(rh_exp)) lh_exp <- promote(lh_exp, dim(rh_exp)) else if(is_scalar(rh_exp) && !is_scalar(lh_exp)) rh_exp <- promote(rh_exp, dim(lh_exp)) callNextMethod(.Object, ..., lh_exp = lh_exp, rh_exp = rh_exp) }) #' @param object A \linkS4class{Multiply} object. #' @param values A list of arguments to the atom. #' @describeIn Multiply Multiplies the values elementwise. setMethod("to_numeric", "Multiply", function(object, values) { values[[1]] * values[[2]] }) #' @describeIn Multiply The sum of the argument dimensions - 1. setMethod("dim_from_args", "Multiply", function(object) { sum_dims(lapply(object@args, dim)) }) #' @describeIn Multiply Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Multiply", function(object) { TRUE }) #' @describeIn Multiply Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Multiply", function(object) { TRUE }) #' @describeIn Multiply Is the expression a positive semidefinite matrix? setMethod("is_psd", "Multiply", function(object) { (is_psd(object@args[[1]]) && is_psd(object@args[[2]])) || (is_nsd(object@args[[1]]) && is_nsd(object@args[[2]])) }) #' @describeIn Multiply Is the expression a negative semidefinite matrix? setMethod("is_nsd", "Multiply", function(object) { (is_psd(object@args[[1]]) && is_nsd(object@args[[2]])) || (is_nsd(object@args[[1]]) && is_psd(object@args[[2]])) }) Multiply.graph_implementation <- function(arg_objs, dim, data = NA_real_) { lhs <- arg_objs[[1]] rhs <- arg_objs[[2]] if(lo.is_const(lhs)) return(list(lo.multiply(lhs, rhs), list())) else if(lo.is_const(rhs)) return(list(lo.multiply(rhs, lhs), list())) else stop("Product of two non-constant expressions is not DCP.") } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Multiply The graph implementation of the expression. setMethod("graph_implementation", "Multiply", function(object, arg_objs, dim, data = NA_real_) { Multiply.graph_implementation(arg_objs, dim, data) }) #' #' The DivExpression class. #' #' This class represents one expression divided by another expression. #' #' @name DivExpression-class #' @aliases DivExpression #' @rdname DivExpression-class .DivExpression <- setClass("DivExpression", contains = "Multiply") DivExpression <- function(lh_exp, rh_exp) { .DivExpression(lh_exp = lh_exp, rh_exp = rh_exp) } setMethod("op_name", "DivExpression", function(object) { "/" }) #' @param object A \linkS4class{DivExpression} object. #' @param values A list of arguments to the atom. #' @describeIn DivExpression Matrix division by a scalar. setMethod("to_numeric", "DivExpression", function(object, values) { if(!is.null(dim(values[[2]])) && prod(dim(values[[2]])) == 1) values[[2]] <- as.vector(values[[2]])[1] return(values[[1]] / values[[2]]) }) #' @param object A \linkS4class{DivExpression} object. #' @describeIn DivExpression Is the left-hand expression quadratic and the right-hand expression constant? setMethod("is_quadratic", "DivExpression", function(object) { is_quadratic(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn DivExpression Is the expression quadratic of piecewise affine? setMethod("is_qpwa", "DivExpression", function(object) { is_qpwa(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn DivExpression The (row, col) dimensions of the left-hand expression. setMethod("dim_from_args", "DivExpression", function(object) { dim(object@args[[1]]) }) #' @describeIn DivExpression Division is convex (affine) in its arguments only if the denominator is constant. setMethod("is_atom_convex", "DivExpression", function(object) { is_constant(object@args[[2]]) }) #' @describeIn DivExpression Division is concave (affine) in its arguments only if the denominator is constant. setMethod("is_atom_concave", "DivExpression", function(object) { is_atom_convex(object) }) #' @describeIn DivExpression Is the atom log-log convex? setMethod("is_atom_log_log_convex", "DivExpression", function(object) { TRUE }) #' @describeIn DivExpression Is the atom log-log concave? setMethod("is_atom_log_log_concave", "DivExpression", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn DivExpression Is the right-hand expression positive? setMethod("is_incr", "DivExpression", function(object, idx) { if(idx == 1) return(is_nonneg(object@args[[2]])) else return(is_nonpos(object@args[[1]])) }) #' @describeIn DivExpression Is the right-hand expression negative? setMethod("is_decr", "DivExpression", function(object, idx) { if(idx == 1) return(is_nonpos(object@args[[2]])) else return(is_nonneg(object@args[[1]])) }) DivExpression.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.div_expr(arg_objs[[1]], arg_objs[[2]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn DivExpression The graph implementation of the expression. setMethod("graph_implementation", "DivExpression", function(object, arg_objs, dim, data = NA_real_) { DivExpression.graph_implementation(arg_objs, dim, data) }) #' #' The Conjugate class. #' #' This class represents the complex conjugate of an expression. #' #' @slot expr An \linkS4class{Expression} or R numeric data. #' @name Conjugate-class #' @aliases Conjugate #' @rdname Conjugate-class .Conjugate <- setClass("Conjugate", representation(expr = "ConstValORExpr"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} or R numeric data. #' @rdname Conjugate-class Conjugate <- function(expr) { .Conjugate(expr = expr) } setMethod("initialize", "Conjugate", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{Conjugate} object. #' @param values A list of arguments to the atom. #' @describeIn Conjugate Elementwise complex conjugate of the constant. setMethod("to_numeric", "Conjugate", function(object, values) { Conj(values[[1]]) }) #' @describeIn Conjugate The (row, col) dimensions of the expression. setMethod("dim_from_args", "Conjugate", function(object) { dim(object@args[[1]]) }) #' @param idx An index into the atom. #' @describeIn Conjugate Is the composition weakly increasing in argument idx? setMethod("is_incr", "Conjugate", function(object, idx) { FALSE }) #' @describeIn Conjugate Is the composition weakly decreasing in argument idx? setMethod("is_decr", "Conjugate", function(object, idx) { FALSE }) #' @describeIn Conjugate Is the expression symmetric? setMethod("is_symmetric", "Conjugate", function(object) { is_symmetric(object@args[[1]]) }) #' @describeIn Conjugate Is the expression hermitian? setMethod("is_hermitian", "Conjugate", function(object) { is_hermitian(object@args[[1]]) }) #' #' The Conv class. #' #' This class represents the 1-D discrete convolution of two vectors. #' #' @slot lh_exp An \linkS4class{Expression} or R numeric data representing the left-hand vector. #' @slot rh_exp An \linkS4class{Expression} or R numeric data representing the right-hand vector. #' @name Conv-class #' @aliases Conv #' @rdname Conv-class .Conv <- setClass("Conv", representation(lh_exp = "ConstValORExpr", rh_exp = "ConstValORExpr"), contains = "AffAtom") #' @param lh_exp An \linkS4class{Expression} or R numeric data representing the left-hand vector. #' @param rh_exp An \linkS4class{Expression} or R numeric data representing the right-hand vector. #' @rdname Conv-class Conv <- function(lh_exp, rh_exp) { .Conv(lh_exp = lh_exp, rh_exp = rh_exp) } setMethod("initialize", "Conv", function(.Object, ..., lh_exp, rh_exp) { .Object@lh_exp <- lh_exp .Object@rh_exp <- rh_exp callNextMethod(.Object, ..., atom_args = list(.Object@lh_exp, .Object@rh_exp)) }) #' @param object A \linkS4class{Conv} object. #' @param values A list of arguments to the atom. #' @describeIn Conv The convolution of the two values. setMethod("to_numeric", "Conv", function(object, values) { .Call('_CVXR_cpp_convolve', PACKAGE = 'CVXR', as.vector(values[[1]]), as.vector(values[[2]])) }) #' @describeIn Conv Check both arguments are vectors and the first is a constant. setMethod("validate_args", "Conv", function(object) { if(!is_vector(object@args[[1]]) || !is_vector(object@args[[2]])) stop("The arguments to Conv must resolve to vectors.") if(!is_constant(object@args[[1]])) stop("The first argument to Conv must be constant.") }) #' @describeIn Conv The dimensions of the atom. setMethod("dim_from_args", "Conv", function(object) { lh_length <- dim(object@args[[1]])[1] rh_length <- dim(object@args[[2]])[1] c(lh_length + rh_length - 1, 1) }) #' @describeIn Conv The sign of the atom. setMethod("sign_from_args", "Conv", function(object) { mul_sign(object@args[[1]], object@args[[2]]) }) #' @param idx An index into the atom. #' @describeIn Conv Is the left-hand expression positive? setMethod("is_incr", "Conv", function(object, idx) { is_nonneg(object@args[[1]]) }) #' @param idx An index into the atom. #' @describeIn Conv Is the left-hand expression negative? setMethod("is_decr", "Conv", function(object, idx) { is_nonpos(object@args[[1]]) }) Conv.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.conv(arg_objs[[1]], arg_objs[[2]], dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Conv The graph implementation of the atom. setMethod("graph_implementation", "Conv", function(object, arg_objs, dim, data = NA_real_) { Conv.graph_implementation(arg_objs, dim, data) }) # # Difference Matrix # # Returns a sparse matrix representation of the first order difference operator. # # @param dim The length of the matrix dimensions. # @param axis The axis to take the difference along. # @return A square matrix representing the first order difference. get_diff_mat <- function(dim, axis) { # Construct a sparse matrix representation val_arr <- c() row_arr <- c() col_arr <- c() for(i in 1:dim) { val_arr <- c(val_arr, 1) row_arr <- c(row_arr, i) col_arr <- c(col_arr, i) if(i > 1) { val_arr <- c(val_arr, -1) row_arr <- c(row_arr, i) col_arr <- c(col_arr, i-1) } } mat <- sparseMatrix(i = row_arr, j = col_arr, x = val_arr, dims = c(dim, dim)) if(axis == 2) mat else t(mat) } #' #' The CumSum class. #' #' This class represents the cumulative sum. #' #' @slot expr An \linkS4class{Expression} to be summed. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @name CumSum-class #' @aliases CumSum #' @rdname CumSum-class .CumSum <- setClass("CumSum", prototype = prototype(axis = 2), contains = c("AffAtom", "AxisAtom")) #' @param expr An \linkS4class{Expression} to be summed. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @rdname CumSum-class CumSum <- function(expr, axis = 2) { .CumSum(expr = expr, axis = axis) } #' @param object A \linkS4class{CumSum} object. #' @param values A list of arguments to the atom. #' @describeIn CumSum The cumulative sum of the values along the specified axis. setMethod("to_numeric", "CumSum", function(object, values) { # apply(values[[1]], object@axis, base::cumsum) if(object@axis == 1) do.call(rbind, lapply(seq_len(nrow(values[[1]])), function(i) { base::cumsum(values[[1]][i,]) })) else if(object@axis == 2) do.call(cbind, lapply(seq_len(ncol(values[[1]])), function(j) { base::cumsum(values[[1]][,j]) })) else base::cumsum(values[[1]]) }) #' @describeIn CumSum The dimensions of the atom. setMethod("dim_from_args", "CumSum", function(object) { dim(object@args[[1]]) }) #' @describeIn CumSum Returns the axis along which the cumulative sum is taken. setMethod("get_data", "CumSum", function(object) { list(object@axis) }) #' @param values A list of numeric values for the arguments #' @describeIn CumSum Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "CumSum", function(object, values) { # TODO: This is inefficient val_dim <- dim(values[[1]]) collapse <- setdiff(1:length(val_dim), object@axis) dim <- val_dim[collapse] mat <- matrix(0, nrow = dim, ncol = dim) mat[lower.tri(mat, diag = TRUE)] <- 1 # var <- Variable(dim(object@args[[1]])) var <- new("Variable", dim = dim(object@args[[1]])) if(object@axis == 2) grad <- .grad(new("MulExpression", lh_exp = mat, rh_exp = var), values)[[2]] else grad <- .grad(new("MulExpression", lh_exp = var, rh_exp = t(mat)), values)[[1]] list(grad) }) CumSum.graph_implementation <- function(arg_objs, dim, data = NA_real_) { # Implicit O(n) definition: # X = Y[:1,:] - Y[1:,:] Y <- create_var(dim) axis <- data[[1]] collapse <- setdiff(1:length(dim), axis) new_dim <- dim[collapse] diff_mat <- get_diff_mat(new_dim, axis) diff_mat <- create_const(diff_mat, c(new_dim, new_dim), sparse = TRUE) if(axis == 2) diff <- lo.mul_expr(diff_mat, Y) else diff <- lo.rmul_expr(Y, diff_mat) list(Y, list(create_eq(arg_objs[[1]], diff))) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn CumSum The graph implementation of the atom. setMethod("graph_implementation", "CumSum", function(object, arg_objs, dim, data = NA_real_) { CumSum.graph_implementation(arg_objs, dim, data) }) #' #' The DiagVec class. #' #' This class represents the conversion of a vector into a diagonal matrix. #' #' @slot expr An \linkS4class{Expression} representing the vector to convert. #' @name DiagVec-class #' @aliases DiagVec #' @rdname DiagVec-class .DiagVec <- setClass("DiagVec", representation(expr = "Expression"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing the vector to convert. #' @rdname DiagVec-class DiagVec <- function(expr) { .DiagVec(expr = expr) } setMethod("initialize", "DiagVec", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{DiagVec} object. #' @param values A list of arguments to the atom. #' @describeIn DiagVec Convert the vector constant into a diagonal matrix. setMethod("to_numeric", "DiagVec", function(object, values) { diag(as.vector(values[[1]])) }) #' @describeIn DiagVec The dimensions of the atom. setMethod("dim_from_args", "DiagVec", function(object) { rows <- dim(object@args[[1]])[1] c(rows, rows) }) #' @describeIn DiagVec Is the atom log-log convex? setMethod("is_atom_log_log_convex", "DiagVec", function(object) { TRUE }) #' @describeIn DiagVec Is the atom log-log concave? setMethod("is_atom_log_log_concave", "DiagVec", function(object) { TRUE }) #' @describeIn DiagVec Is the expression symmetric? setMethod("is_symmetric", "DiagVec", function(object) { TRUE }) #' @describeIn DiagVec Is the expression hermitian? setMethod("is_hermitian", "DiagVec", function(object) { TRUE }) DiagVec.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.diag_vec(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn DiagVec The graph implementation of the atom. setMethod("graph_implementation", "DiagVec", function(object, arg_objs, dim, data = NA_real_) { DiagVec.graph_implementation(arg_objs, dim, data) }) #' #' The DiagMat class. #' #' This class represents the extraction of the diagonal from a square matrix. #' #' @slot expr An \linkS4class{Expression} representing the matrix whose diagonal we are interested in. #' @name DiagMat-class #' @aliases DiagMat #' @rdname DiagMat-class .DiagMat <- setClass("DiagMat", representation(expr = "Expression"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing the matrix whose diagonal we are interested in. #' @rdname DiagMat-class DiagMat <- function(expr) { .DiagMat(expr = expr) } setMethod("initialize", "DiagMat", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{DiagMat} object. #' @param values A list of arguments to the atom. #' @describeIn DiagMat Extract the diagonal from a square matrix constant. setMethod("to_numeric", "DiagMat", function(object, values) { diag(values[[1]]) }) #' @describeIn DiagMat The size of the atom. setMethod("dim_from_args", "DiagMat", function(object) { rows <- dim(object@args[[1]])[1] c(rows, 1) }) #' @describeIn DiagMat Is the atom log-log convex? setMethod("is_atom_log_log_convex", "DiagMat", function(object) { TRUE }) #' @describeIn DiagMat Is the atom log-log concave? setMethod("is_atom_log_log_concave", "DiagMat", function(object) { TRUE }) DiagMat.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.diag_mat(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn DiagMat The graph implementation of the atom. setMethod("graph_implementation", "DiagMat", function(object, arg_objs, dim, data = NA_real_) { DiagMat.graph_implementation(arg_objs, dim, data) }) #' #' Turns an expression into a DiagVec object #' #' @param expr An \linkS4class{Expression} that represents a vector or square matrix. #' @return An \linkS4class{Expression} representing the diagonal vector/matrix. #' @rdname Diag-int Diag <- function(expr) { expr <- as.Constant(expr) if(is_vector(expr)) return(DiagVec(Vec(expr))) else if(ndim(expr) == 2 && nrow(expr) == ncol(expr)) return(DiagMat(expr = expr)) else stop("Argument to Diag must be a vector or square matrix.") } #' #' Takes the k-th order differences #' #' @param lag The degree of lag between differences #' @param k The integer value of the order of differences #' @param x An \linkS4class{Expression} that represents a vector #' @param axis The axis along which to apply the function. For a 2D matrix, \code{1} indicates rows and \code{2} indicates columns. #' @return Takes in a vector of length n and returns a vector of length n-k of the kth order differences #' @rdname Diff-int Diff <- function(x, lag = 1, k = 1, axis = 2) { x <- as.Constant(x) if((axis == 2 && ndim(x) < 2) || ndim(x) == 0) stop("Invalid axis given input dimensions.") else if(axis == 1) x <- t(x) if(ndim(x) == 1) m <- size(x) else m <- dim(x)[setdiff(seq_len(ndim(x)), axis)] if(k < 0 || k >= m) stop("Must have k >= 0 and x must have < k elements along collapsed axis.") if(lag <= 0 || lag >= m) stop("Must have lag > 0 and x must have < lag elements along collapsed axis.") d <- x for(i in seq_len(k)) { if(ndim(x) == 2) d <- d[(1+lag):m,] - d[1:(m-lag),] else d <- d[(1+lag):m] - d[1:(m-lag)] m <- m-1 } if(axis == 1) t(d) else d } #' #' The HStack class. #' #' Horizontal concatenation of values. #' #' @slot ... \linkS4class{Expression} objects or matrices. All arguments must have the same dimensions except for axis 2 (columns). #' @name HStack-class #' @aliases HStack #' @rdname HStack-class .HStack <- setClass("HStack", contains = "AffAtom") #' @param ... \linkS4class{Expression} objects or matrices. All arguments must have the same dimensions except for axis 2 (columns). #' @rdname HStack-class HStack <- function(...) { arg_list <- lapply(list(...), as.Constant) for(idx in seq_along(arg_list)) { arg <- arg_list[[idx]] if(ndim(arg) == 0) arg_list[[idx]] <- flatten(arg) } .HStack(atom_args = arg_list) } #' @param object A \linkS4class{HStack} object. #' @param values A list of arguments to the atom. #' @describeIn HStack Horizontally concatenate the values using \code{cbind}. setMethod("to_numeric", "HStack", function(object, values) { # do.call("cbind", values) # Doesn't work on some objects like xts. mat <- Reduce("cbind", values) colnames(mat) <- NULL # Get rid of init column name. return(mat) }) #' @describeIn HStack The dimensions of the atom. setMethod("dim_from_args", "HStack", function(object) { if(ndim(object@args[[1]]) == 1) # return(c(sum(sapply(object@args, size)), NA)) return(c(sum(sapply(object@args, size)), 1)) else { cols <- sum(sapply(object@args, function(arg) { dim(arg)[2] })) arg_dim <- dim(object@args[[1]]) dims <- c(arg_dim[1], cols) if(length(arg_dim) >= 3) dims <- c(dims, arg_dim[3:length(arg_dim)]) return(dims) } }) #' @describeIn HStack Is the atom log-log convex? setMethod("is_atom_log_log_convex", "HStack", function(object) { TRUE }) #' @describeIn HStack Is the atom log-log concave? setMethod("is_atom_log_log_concave", "HStack", function(object) { TRUE }) #' @describeIn HStack Check all arguments have the same height. setMethod("validate_args", "HStack", function(object) { model <- dim(object@args[[1]]) error <- "All the input dimensions except for axis 2 (columns) must match exactly." len <- length(object@args) if(len >= 2) { for(arg in object@args[2:len]) { if(length(dim(arg)) != length(model)) stop(error) else if(length(model) > 1) { for(i in 1:length(model)) { if(i != 2 && dim(arg)[i] != model[i]) stop(error) } } } } }) HStack.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.hstack(arg_objs, dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn HStack The graph implementation of the atom. setMethod("graph_implementation", "HStack", function(object, arg_objs, dim, data = NA_real_) { HStack.graph_implementation(arg_objs, dim, data) }) setMethod("cbind2", signature(x = "Expression", y = "ANY"), function(x, y, ...) { HStack(x, y) }) setMethod("cbind2", signature(x = "ANY", y = "Expression"), function(x, y, ...) { HStack(x, y) }) #' #' The Imag class. #' #' This class represents the imaginary part of an expression. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @name Imag-class #' @aliases Imag #' @rdname Imag-class .Imag <- setClass("Imag", representation(expr = "Expression"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing a vector or matrix. #' @rdname Imag-class Imag <- function(expr) { .Imag(expr = expr) } setMethod("initialize", "Imag", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object An \linkS4class{Imag} object. #' @param values A list of arguments to the atom. #' @describeIn Imag The imaginary part of the given value. setMethod("to_numeric", "Imag", function(object, values) { Im(values[[1]]) }) #' @describeIn Imag The dimensions of the atom. setMethod("dim_from_args", "Imag", function(object) { dim(object@args[[1]]) }) #' @describeIn Imag Is the atom imaginary? setMethod("is_imag", "Imag", function(object) { FALSE }) #' @describeIn Imag Is the atom complex valued? setMethod("is_complex", "Imag", function(object) { FALSE }) #' @describeIn Imag Is the atom symmetric? setMethod("is_symmetric", "Imag", function(object) { is_hermitian(object@args[[1]]) }) #' #' The Index class. #' #' This class represents indexing or slicing into a matrix. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @slot key A list containing the start index, end index, and step size of the slice. #' @name Index-class #' @aliases Index #' @rdname Index-class .Index <- setClass("Index", representation(expr = "Expression", key = "list"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing a vector or matrix. #' @param key A list containing the start index, end index, and step size of the slice. #' @rdname Index-class Index <- function(expr, key) { .Index(expr = expr, key = key) } setMethod("initialize", "Index", function(.Object, ..., expr, key) { .Object@key <- ku_validate_key(key, dim(expr)) # TODO: Double check key validation .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object An \linkS4class{Index} object. #' @param values A list of arguments to the atom. #' @describeIn Index The index/slice into the given value. setMethod("to_numeric", "Index", function(object, values) { ku_slice_mat(values[[1]], object@key) }) #' @describeIn Index The dimensions of the atom. setMethod("dim_from_args", "Index", function(object) { ku_dim(object@key, dim(object@args[[1]])) }) #' @describeIn Index Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Index", function(object) { TRUE }) #' @describeIn Index Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Index", function(object) { TRUE }) #' @describeIn Index A list containing \code{key}. setMethod("get_data", "Index", function(object) { list(object@key) }) Index.graph_implementation <- function(arg_objs, dim, data = NA_real_) { obj <- lo.index(arg_objs[[1]], dim, data[[1]]) list(obj, list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Index The graph implementation of the atom. setMethod("graph_implementation", "Index", function(object, arg_objs, dim, data = NA_real_) { Index.graph_implementation(arg_objs, dim, data) }) #' #' The SpecialIndex class. #' #' This class represents indexing using logical indexing or a list of indices into a matrix. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @slot key A list containing the start index, end index, and step size of the slice. #' @name SpecialIndex-class #' @aliases SpecialIndex #' @rdname SpecialIndex-class .SpecialIndex <- setClass("SpecialIndex", representation(expr = "Expression", key = "list", .select_mat = "ConstVal", .dim = "NumORNULL"), prototype(.select_mat = NA_real_, .dim = NA_real_), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing a vector or matrix. #' @param key A list containing the start index, end index, and step size of the slice. #' @rdname SpecialIndex-class SpecialIndex <- function(expr, key) { .SpecialIndex(expr = expr, key = key) } setMethod("initialize", "SpecialIndex", function(.Object, ..., expr, key) { .Object@expr <- expr .Object@key <- key row <- key[[1]] col <- key[[2]] # Order the entries of expr and select them using key. expr_dim <- dim(expr) expr_size <- size(expr) idx_mat <- seq(expr_size) idx_mat <- matrix(idx_mat, nrow = expr_dim[1], ncol = expr_dim[2]) if(is.matrix(row) && is.null(col)) select_mat <- matrix(idx_mat[row], ncol = 1) else if(is.null(row) && is.null(col)) select_mat <- idx_mat else if(is.null(row) && !is.null(col)) select_mat <- idx_mat[ , col, drop = FALSE] else if(!is.null(row) && is.null(col)) select_mat <- idx_mat[row, , drop = FALSE] else select_mat <- idx_mat[row, col, drop = FALSE] [email protected]_mat <- select_mat [email protected] <- dim([email protected]_mat) callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param x,object An \linkS4class{Index} object. #' @describeIn SpecialIndex Returns the index in string form. setMethod("name", "SpecialIndex", function(x) { paste(name(x@args[[1]]), as.character(x@key)) }) #' @param values A list of arguments to the atom. #' @describeIn Index The index/slice into the given value. setMethod("to_numeric", "SpecialIndex", function(object, values) { ku_slice_mat(values[[1]], object@key) }) #' @describeIn Index The dimensions of the atom. setMethod("dim_from_args", "SpecialIndex", function(object) { [email protected] }) #' @describeIn SpecialIndex Is the atom log-log convex? setMethod("is_atom_log_log_convex", "SpecialIndex", function(object) { TRUE }) #' @describeIn SpecialIndex Is the atom log-log concave? setMethod("is_atom_log_log_concave", "SpecialIndex", function(object) { TRUE }) #' @describeIn SpecialIndex A list containing \code{key}. setMethod("get_data", "SpecialIndex", function(object) { list(object@key) }) #' @describeIn SpecialIndex Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "SpecialIndex", function(object) { select_mat <- [email protected]_mat if(!is.null(dim(select_mat))) final_dim <- dim(select_mat) else # Always cast 1-D arrays as column vectors final_dim <- c(length(select_mat), 1) # Select the chosen entries from expr. select_vec <- as.vector(select_mat) ##select_vec <- as.matrix(select_mat, nrow=final_dim[1L], ncol=final_dim[2L]) expr_size <- size(object@args[[1]]) identity <- sparseMatrix(i = 1:expr_size, j = 1:expr_size, x = rep(1, expr_size)) idmat <- matrix(identity[select_vec, ], ncol = expr_size) v <- Vec(expr) if(is_scalar(v) || is_scalar(as.Constant(idmat))) lowered <- Reshape(idmat * v, c(final_dim[1], final_dim[2])) else lowered <- Reshape(idmat %*% v, c(final_dim[1], final_dim[2])) return(grad(lowered)) }) #' #' The Kron class. #' #' This class represents the kronecker product. #' #' @slot lh_exp An \linkS4class{Expression} or numeric constant representing the left-hand matrix. #' @slot rh_exp An \linkS4class{Expression} or numeric constant representing the right-hand matrix. #' @name Kron-class #' @aliases Kron #' @rdname Kron-class .Kron <- setClass("Kron", representation(lh_exp = "ConstValORExpr", rh_exp = "ConstValORExpr"), contains = "AffAtom") #' @param lh_exp An \linkS4class{Expression} or numeric constant representing the left-hand matrix. #' @param rh_exp An \linkS4class{Expression} or numeric constant representing the right-hand matrix. #' @rdname Kron-class Kron <- function(lh_exp, rh_exp) { .Kron(lh_exp = lh_exp, rh_exp = rh_exp) } setMethod("initialize", "Kron", function(.Object, ..., lh_exp, rh_exp) { .Object@lh_exp <- lh_exp .Object@rh_exp <- rh_exp callNextMethod(.Object, ..., atom_args = list(.Object@lh_exp, .Object@rh_exp)) }) #' @param object A \linkS4class{Kron} object. #' @param values A list of arguments to the atom. #' @describeIn Kron The kronecker product of the two values. setMethod("to_numeric", "Kron", function(object, values) { base::kronecker(values[[1]], values[[2]]) }) #' @describeIn Kron Check both arguments are vectors and the first is a constant. setMethod("validate_args", "Kron", function(object) { if(!is_constant(object@args[[1]])) stop("The first argument to Kron must be constant.") else if(ndim(object@args[[1]]) != 2 || ndim(object@args[[2]]) != 2) stop("Kron requires matrix arguments.") }) #' @describeIn Kron The dimensions of the atom. setMethod("dim_from_args", "Kron", function(object) { rows <- dim(object@args[[1]])[1] * dim(object@args[[2]])[1] cols <- dim(object@args[[1]])[2] * dim(object@args[[2]])[2] c(rows, cols) }) #' @describeIn Kron The sign of the atom. setMethod("sign_from_args", "Kron", function(object) { mul_sign(object@args[[1]], object@args[[2]]) }) #' @param idx An index into the atom. #' @describeIn Kron Is the left-hand expression positive? setMethod("is_incr", "Kron", function(object, idx) { is_nonneg(object@args[[1]]) }) #' @describeIn Kron Is the right-hand expression negative? setMethod("is_decr", "Kron", function(object, idx) { is_nonpos(object@args[[1]]) }) Kron.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.kron(arg_objs[[1]], arg_objs[[2]], dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector with two elements representing the size of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Kron The graph implementation of the atom. setMethod("graph_implementation", "Kron", function(object, arg_objs, dim, data = NA_real_) { Kron.graph_implementation(arg_objs, dim, data) }) #' #' The Promote class. #' #' This class represents the promotion of a scalar expression into a vector/matrix. #' #' @slot expr An \linkS4class{Expression} or numeric constant. #' @slot promoted_dim The desired dimensions. #' @name Promote-class #' @aliases Promote #' @rdname Promote-class .Promote <- setClass("Promote", representation(expr = "Expression", promoted_dim = "numeric"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} or numeric constant. #' @param promoted_dim The desired dimensions. #' @rdname Promote-class Promote <- function(expr, promoted_dim) { .Promote(expr = expr, promoted_dim = promoted_dim) } promote <- function(expr, promoted_dim) { expr <- as.Constant(expr) if(!all(dim(expr) == promoted_dim)) { if(!is_scalar(expr)) stop("Only scalars may be promoted.") return(Promote(expr = expr, promoted_dim = promoted_dim)) } else return(expr) } setMethod("initialize", "Promote", function(.Object, ..., expr, promoted_dim) { .Object@expr <- expr .Object@promoted_dim <- promoted_dim callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{Promote} object. #' @param values A list containing the value to promote. #' @describeIn Promote Promotes the value to the new dimensions. setMethod("to_numeric", "Promote", function(object, values) { array(1, dim = object@promoted_dim) * as.vector(values[[1]])[1] }) #' @describeIn Promote Is the expression symmetric? setMethod("is_symmetric", "Promote", function(object) { ndim(object) == 2 && dim(object)[1] == dim(object)[2] }) #' @describeIn Promote Returns the (row, col) dimensions of the expression. setMethod("dim_from_args", "Promote", function(object) { object@promoted_dim }) #' @describeIn Promote Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Promote", function(object) { TRUE }) #' @describeIn Promote Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Promote", function(object) { TRUE }) #' @describeIn Promote Returns information needed to reconstruct the expression besides the args. setMethod("get_data", "Promote", function(object) { list(object@promoted_dim) }) Promote.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.promote(arg_objs[[1]], dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Promote The graph implementation of the atom. setMethod("graph_implementation", "Promote", function(object, arg_objs, dim, data = NA_real_) { Promote.graph_implementation(arg_objs, dim, data) }) #' #' The Real class. #' #' This class represents the real part of an expression. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @name Real-class #' @aliases Real #' @rdname Real-class .Real <- setClass("Real", representation(expr = "Expression"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing a vector or matrix. #' @rdname Real-class Real <- function(expr) { .Real(expr = expr) } setMethod("initialize", "Real", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object An \linkS4class{Real} object. #' @param values A list of arguments to the atom. #' @describeIn Real The imaginary part of the given value. setMethod("to_numeric", "Real", function(object, values) { Re(values[[1]]) }) #' @describeIn Real The dimensions of the atom. setMethod("dim_from_args", "Real", function(object) { dim(object@args[[1]]) }) #' @describeIn Real Is the atom imaginary? setMethod("is_imag", "Real", function(object) { FALSE }) #' @describeIn Real Is the atom complex valued? setMethod("is_complex", "Real", function(object) { FALSE }) #' @describeIn Real Is the atom symmetric? setMethod("is_symmetric", "Real", function(object) { is_hermitian(object@args[[1]]) }) #' #' The Reshape class. #' #' This class represents the reshaping of an expression. The operator vectorizes the expression, #' then unvectorizes it into the new dimensions. Entries are stored in column-major order. #' #' @slot expr An \linkS4class{Expression} or numeric matrix. #' @slot new_dim The new dimensions. #' @name Reshape-class #' @aliases Reshape #' @rdname Reshape-class .Reshape <- setClass("Reshape", representation(expr = "ConstValORExpr", new_dim = "numeric"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} or numeric matrix. #' @param new_dim The new dimensions. #' @rdname Reshape-class Reshape <- function(expr, new_dim) { .Reshape(expr = expr, new_dim = new_dim) } setMethod("initialize", "Reshape", function(.Object, ..., expr, new_dim) { .Object@new_dim <- new_dim .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{Reshape} object. #' @param values A list of arguments to the atom. #' @describeIn Reshape Reshape the value into the specified dimensions. setMethod("to_numeric", "Reshape", function(object, values) { dim(values[[1]]) <- object@new_dim values[[1]] }) #' @describeIn Reshape Check the new shape has the same number of entries as the old. setMethod("validate_args", "Reshape", function(object) { old_len <- size(object@args[[1]]) new_len <- prod(object@new_dim) if(old_len != new_len) stop("Invalid reshape dimensions (", paste(object@new_dim, sep = ","), ")") }) #' @describeIn Reshape The \code{c(rows, cols)} dimensions of the new expression. setMethod("dim_from_args", "Reshape", function(object) { object@new_dim }) #' @describeIn Reshape Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Reshape", function(object) { TRUE }) #' @describeIn Reshape Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Reshape", function(object) { TRUE }) #' @describeIn Reshape Returns a list containing the new shape. setMethod("get_data", "Reshape", function(object) { list(object@new_dim) }) Reshape.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.reshape(arg_objs[[1]], dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Reshape The graph implementation of the atom. setMethod("graph_implementation", "Reshape", function(object, arg_objs, dim, data = NA_real_) { Reshape.graph_implementation(arg_objs, dim, data) }) #' #' The SumEntries class. #' #' This class represents the sum of all entries in a vector or matrix. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @name SumEntries-class #' @aliases SumEntries #' @rdname SumEntries-class .SumEntries <- setClass("SumEntries", contains = c("AxisAtom", "AffAtom")) #' @param expr An \linkS4class{Expression} representing a vector or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname SumEntries-class SumEntries <- function(expr, axis = NA_real_, keepdims = FALSE) { .SumEntries(expr = expr, axis = axis, keepdims = keepdims) } #' @param object A \linkS4class{SumEntries} object. #' @param values A list of arguments to the atom. #' @describeIn SumEntries Sum the entries along the specified axis. setMethod("to_numeric", "SumEntries", function(object, values) { apply_with_keepdims(values[[1]], sum, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn SumEntries Is the atom log-log convex? setMethod("is_atom_log_log_convex", "SumEntries", function(object) { TRUE }) #' @describeIn SumEntries Is the atom log-log concave? setMethod("is_atom_log_log_concave", "SumEntries", function(object) { FALSE }) SumEntries.graph_implementation <- function(arg_objs, dim, data = NA_real_) { # TODO: Handle keepdims properly by setting a 1-D vector's dimension to c(len, NA_integer_). axis <- data[[1]] keepdims <- data[[2]] if(is.na(axis)) obj <- lo.sum_entries(arg_objs[[1]], dim) else if(axis == 1) { # if(keepdims) # const_dim <- c(arg_objs[[1]]$dim[2], 1) # else # const_dim <- c(arg_objs[[1]]$dim[2], NA_integer_) # Always treat result as a column vector. const_dim <- c(arg_objs[[1]]$dim[2], 1) ones <- create_const(array(1, dim = const_dim), const_dim) obj <- lo.rmul_expr(arg_objs[[1]], ones, dim) } else { # axis == 2 # if(keepdims) # const_dim <- c(1, arg_objs[[1]]$dim[1]) # else # const_dim <- c(arg_objs[[1]]$dim[1], NA_integer_) # ones <- create_const(array(1, dim = const_dim), const_dim) # obj <- lo.mul_expr(ones, arg_objs[[1]], dim) if(keepdims) { # Keep result as a row vector. const_dim <- c(1, arg_objs[[1]]$dim[1]) ones <- create_const(array(1, dim = const_dim), const_dim) obj <- lo.mul_expr(ones, arg_objs[[1]], dim) } else { # Treat collapsed 1-D vector as a column vector. const_dim <- c(arg_objs[[1]]$dim[1], 1) ones <- create_const(array(1, dim = const_dim), const_dim) obj <- lo.rmul_expr(lo.transpose(arg_objs[[1]]), ones, dim) } } list(obj, list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn SumEntries The graph implementation of the atom. setMethod("graph_implementation", "SumEntries", function(object, arg_objs, dim, data = NA_real_) { SumEntries.graph_implementation(arg_objs, dim, data) }) #' #' The Trace class. #' #' This class represents the sum of the diagonal entries in a matrix. #' #' @slot expr An \linkS4class{Expression} representing a matrix. #' @name Trace-class #' @aliases Trace #' @rdname Trace-class .Trace <- setClass("Trace", representation(expr = "Expression"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} representing a matrix. #' @rdname Trace-class Trace <- function(expr) { .Trace(expr = expr) } setMethod("initialize", "Trace", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{Trace} object. #' @param values A list of arguments to the atom. #' @describeIn Trace Sum the diagonal entries. setMethod("to_numeric", "Trace", function(object, values) { sum(diag(values[[1]])) }) #' @describeIn Trace Check the argument is a square matrix. setMethod("validate_args", "Trace", function(object) { arg_dim <- dim(object@args[[1]]) if(arg_dim[1] != arg_dim[2]) stop("Argument to Trace must be a square matrix") }) #' @describeIn Trace The atom is a scalar. setMethod("dim_from_args", "Trace", function(object){ c(1,1) }) #' @describeIn Trace Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Trace", function(object) { TRUE }) #' @describeIn Trace Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Trace", function(object) { FALSE }) Trace.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.trace(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Trace The graph implementation of the atom. setMethod("graph_implementation", "Trace", function(object, arg_objs, dim, data = NA_real_) { Trace.graph_implementation(arg_objs, dim, data) }) #' #' The Transpose class. #' #' This class represents the matrix transpose. #' #' @name Transpose-class #' @aliases Transpose #' @rdname Transpose-class .Transpose <- setClass("Transpose", representation(expr = "Expression", axes = "ConstValORNULL"), prototype(axes = NULL), contains = "AffAtom") Transpose <- function(expr, axes = NULL) { .Transpose(expr = expr, axes = axes) } setMethod("initialize", "Transpose", function(.Object, ..., expr, axes = NULL) { .Object@expr <- expr .Object@axes <- axes callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object A \linkS4class{Transpose} object. #' @param values A list of arguments to the atom. #' @describeIn Transpose The transpose of the given value. setMethod("to_numeric", "Transpose", function(object, values) { if(is.vector(values[[1]])) return(t(values[[1]])) else if(is(values[[1]], "Matrix")) { if(!is.null(object@axes)) stop("Cannot permute Matrix object axes to (", paste(object@axes, collapse = ","), ")") return(t(values[[1]])) } else return(aperm(values[[1]], perm = object@axes)) }) #' @describeIn Transpose Is the expression symmetric? setMethod("is_symmetric", "Transpose", function(object) { is_symmetric(object@args[[1]]) }) #' @describeIn Transpose Is the expression hermitian? setMethod("is_hermitian", "Transpose", function(object) { is_hermitian(object@args[[1]]) }) #' @describeIn Transpose The dimensions of the atom. setMethod("dim_from_args", "Transpose", function(object) { if(is.null(object@axes)) rev(dim(object@args[[1]])) else dim(object@args[[1]])[object@axes] }) #' @describeIn Transpose Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Transpose", function(object) { TRUE }) #' @describeIn Transpose Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Transpose", function(object) { TRUE }) #' @describeIn Transpose Returns the axes for transposition. setMethod("get_data", "Transpose", function(object) { list(object@axes) }) Transpose.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.transpose(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Transpose The graph implementation of the atom. setMethod("graph_implementation", "Transpose", function(object, arg_objs, dim, data = NA_real_) { Transpose.graph_implementation(arg_objs, dim, data) }) #' #' The UpperTri class. #' #' The vectorized strictly upper triagonal entries of a matrix. #' #' @slot expr An \linkS4class{Expression} or numeric matrix. #' @name UpperTri-class #' @aliases UpperTri #' @rdname UpperTri-class .UpperTri <- setClass("UpperTri", representation(expr = "ConstValORExpr"), contains = "AffAtom") #' @param expr An \linkS4class{Expression} or numeric matrix. #' @rdname UpperTri-class UpperTri <- function(expr) { .UpperTri(expr = expr) } setMethod("initialize", "UpperTri", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object An \linkS4class{UpperTri} object. #' @param values A list of arguments to the atom. #' @describeIn UpperTri Vectorize the upper triagonal entries. setMethod("to_numeric", "UpperTri", function(object, values) { # Vectorize the upper triagonal entries tridx <- upper.tri(values[[1]], diag = FALSE) values[[1]][tridx] }) #' @describeIn UpperTri Check the argument is a square matrix. setMethod("validate_args", "UpperTri", function(object) { arg_dim <- dim(object@args[[1]]) if(ndim(object@args[[1]]) != 2 || arg_dim[1] != arg_dim[2]) stop("Argument to UpperTri must be a square matrix.") }) #' @describeIn UpperTri The dimensions of the atom. setMethod("dim_from_args", "UpperTri", function(object) { arg_dim <- dim(object@args[[1]]) rows <- arg_dim[1] cols <- arg_dim[2] c(floor(rows*(cols-1)/2), 1) }) #' @describeIn UpperTri Is the atom log-log convex? setMethod("is_atom_log_log_convex", "UpperTri", function(object) { TRUE }) #' @describeIn UpperTri Is the atom log-log concave? setMethod("is_atom_log_log_concave", "UpperTri", function(object) { TRUE }) UpperTri.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.upper_tri(arg_objs[[1]]), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn UpperTri The graph implementation of the atom. setMethod("graph_implementation", "UpperTri", function(object, arg_objs, dim, data = NA_real_) { UpperTri.graph_implementation(arg_objs, dim, data) }) # Reshape into single column vector. Vec <- function(X) { X <- as.Constant(X) # Reshape(expr = X, new_dim = size(X)) Reshape(expr = X, new_dim = c(size(X), 1)) } #' #' The VStack class. #' #' Vertical concatenation of values. #' #' @slot ... \linkS4class{Expression} objects or matrices. All arguments must have the same number of columns. #' @name VStack-class #' @aliases VStack #' @rdname VStack-class .VStack <- setClass("VStack", contains = "AffAtom") #' @param ... \linkS4class{Expression} objects or matrices. All arguments must have the same number of columns. #' @rdname VStack-class VStack <- function(...) { .VStack(atom_args = list(...)) } #' @param object A \linkS4class{VStack} object. #' @param values A list of arguments to the atom. #' @describeIn VStack Vertically concatenate the values using \code{rbind}. setMethod("to_numeric", "VStack", function(object, values) { # do.call("rbind", values) # Doesn't work on some objects like xts. mat <- Reduce("rbind", values) rownames(mat) <- NULL # Get rid of init row name return(mat) }) #' @describeIn VStack Check all arguments have the same width. setMethod("validate_args", "VStack", function(object) { model <- dim(object@args[[1]]) if(length(object@args) >= 2) { for(arg in object@args[2:length(object@args)]) { arg_dim <- dim(arg) if(length(arg_dim) != length(model) || length(model) != length(arg_dim) || (length(model) > 1 && any(model[2:length(model)] != arg_dim[2:length(arg_dim)])) || (length(model) <= 1 && any(model != arg_dim))) stop("All the input dimensions except for axis 1 must match exactly.") } } }) #' @describeIn VStack The dimensions of the atom. setMethod("dim_from_args", "VStack", function(object) { if(ndim(object@args[[1]]) == 0) c(length(object@args), 1) else if(ndim(object@args[[1]]) == 1) c(length(object@args), dim(object@args[[1]])[1]) else { rows <- sum(sapply(object@args, function(arg) { dim(arg)[1] })) arg_dim <- dim(object@args[[1]]) if(length(arg_dim) < 2) # c(rows, NA) c(rows, 1) else c(rows, arg_dim[2:length(arg_dim)]) } }) #' @describeIn VStack Is the atom log-log convex? setMethod("is_atom_log_log_convex", "VStack", function(object) { TRUE }) #' @describeIn VStack Is the atom log-log concave? setMethod("is_atom_log_log_concave", "VStack", function(object) { TRUE }) VStack.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(lo.vstack(arg_objs, dim), list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn VStack The graph implementation of the atom. setMethod("graph_implementation", "VStack", function(object, arg_objs, dim, data = NA_real_) { VStack.graph_implementation(arg_objs, dim, data) }) #' #' The Wrap class. #' #' This virtual class represents a no-op wrapper to assert properties. #' #' @name Wrap-class #' @aliases Wrap #' @rdname Wrap-class Wrap <- setClass("Wrap", contains = c("VIRTUAL", "AffAtom")) #' @param object A \linkS4class{Wrap} object. #' @param values A list of arguments to the atom. #' @describeIn Wrap Returns the input value. setMethod("to_numeric", "Wrap", function(object, values) { values[[1]] }) #' @describeIn Wrap The dimensions of the atom. setMethod("dim_from_args", "Wrap", function(object) { dim(object@args[[1]]) }) #' @describeIn Wrap Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Wrap", function(object) { TRUE }) #' @describeIn Wrap Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Wrap", function(object) { TRUE }) Wrap.graph_implementation <- function(arg_objs, dim, data = NA_real_) { list(arg_objs[[1]], list()) } #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Wrap The graph implementation of the atom. setMethod("graph_implementation", "Wrap", function(object, arg_objs, dim, data = NA_real_) { Wrap.graph_implementation(arg_objs, dim, data) }) #' #' The PSDWrap class. #' #' A no-op wrapper to assert the input argument is positive semidefinite. #' #' @name PSDWrap-class #' @aliases PSDWrap #' @rdname PSDWrap-class .PSDWrap <- setClass("PSDWrap", contains = "Wrap") #' @param arg A \linkS4class{Expression} object or matrix. #' @rdname PSDWrap-class PSDWrap <- function(arg) { .PSDWrap(atom_args = list(arg)) } #' @param object A \linkS4class{PSDWrap} object. #' @describeIn PSDWrap Is the atom positive semidefinite? setMethod("is_psd", "PSDWrap", function(object) { TRUE }) setMethod("rbind2", signature(x = "Expression", y = "ANY"), function(x, y, ...) { VStack(x, y) }) setMethod("rbind2", signature(x = "ANY", y = "Expression"), function(x, y, ...) { VStack(x, y) }) Bmat <- function(block_lists) { row_blocks <- lapply(block_lists, function(blocks) { do.call("HStack", blocks) }) do.call("VStack", row_blocks) }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/affine.R
#' #' The Atom class. #' #' This virtual class represents atomic expressions in CVXR. #' #' @name Atom-class #' @aliases Atom #' @rdname Atom-class Atom <- setClass("Atom", representation(atom_args = "list", .dim = "NumORNULL"), prototype(atom_args = list(), .dim = NULL), contains = c("VIRTUAL", "Expression")) setMethod("initialize", "Atom", function(.Object, ..., atom_args = list(), .dim = NULL, validate = TRUE) { # .Object@id <- ifelse(is.na(id), get_id(), id) .Object <- callNextMethod(.Object, ..., validate = FALSE) if(length(atom_args) == 0) stop("No arguments given to ", class(.Object), ".") .Object@args <- lapply(atom_args, as.Constant) validate_args(.Object) [email protected] <- dim_from_args(.Object) if(length([email protected]) > 2) stop("Atoms must be at most 2D.") if(validate) validObject(.Object) .Object }) setMethod("show", "Atom", function(object) { if(is.null(get_data(object))) data <- list() else data <- sapply(get_data(object), as.character) arg_names <- sapply(object@args, name) cat(class(object), "(", paste(c(arg_names, data), collapse = ", "), ")", sep = "") }) #' @param x,object An \linkS4class{Atom} object. #' @describeIn Atom Returns the string representtation of the function call setMethod("name", "Atom", function(x) { if(is.null(get_data(x))) data <- list() else data <- sapply(get_data(x), as.character) arg_names <- sapply(x@args, name) paste(class(x), "(", paste(c(arg_names, data), collapse = ", "), ")", sep = "") }) #' @describeIn Atom Raises an error if the arguments are invalid. setMethod("validate_args", "Atom", function(object) { if(!allow_complex(object) && any(sapply(object@args, is_complex))) stop("Arguments to ", class(object), " cannot be complex.") }) #' @rdname dim_from_args setMethod("dim_from_args", "Atom", function(object) { stop("Unimplemented") }) #' @describeIn Atom The \code{c(row, col)} dimensions of the atom. setMethod("dim", "Atom", function(x) { [email protected] }) #' @describeIn Atom The number of rows in the atom. setMethod("nrow", "Atom", function(x) { dim(x)[1] }) #' @describeIn Atom The number of columns in the atom. setMethod("ncol", "Atom", function(x) { dim(x)[2] }) #' @describeIn Atom Does the atom handle complex numbers? setMethod("allow_complex", "Atom", function(object) { FALSE }) #' @rdname sign_from_args setMethod("sign_from_args", "Atom", function(object) { stop("Unimplemented") }) #' @describeIn Atom A logical value indicating whether the atom is nonnegative. setMethod("is_nonneg", "Atom", function(object) { sign_from_args(object)[1] }) #' @describeIn Atom A logical value indicating whether the atom is nonpositive. setMethod("is_nonpos", "Atom", function(object) { sign_from_args(object)[2] }) #' @describeIn Atom A logical value indicating whether the atom is imaginary. setMethod("is_imag", "Atom", function(object) { FALSE }) #' @describeIn Atom A logical value indicating whether the atom is complex valued. setMethod("is_complex", "Atom", function(object) { FALSE }) #' @rdname curvature-atom setMethod("is_atom_convex", "Atom", function(object) { stop("Unimplemented") }) #' @rdname curvature-atom setMethod("is_atom_concave", "Atom", function(object) { stop("Unimplemented") }) #' @rdname curvature-atom setMethod("is_atom_affine", "Atom", function(object) { is_atom_concave(object) && is_atom_convex(object) }) #' @rdname curvature-atom setMethod("is_atom_log_log_convex", "Atom", function(object) { FALSE }) #' @rdname curvature-atom setMethod("is_atom_log_log_concave", "Atom", function(object) { FALSE }) #' @rdname curvature-atom setMethod("is_atom_log_log_affine", "Atom", function(object) { is_atom_log_log_concave(object) && is_atom_log_log_convex(object) }) #' @rdname curvature-comp setMethod("is_incr", "Atom", function(object, idx) { stop("Unimplemented") }) #' @rdname curvature-comp setMethod("is_decr", "Atom", function(object, idx) { stop("Unimplemented") }) #' @describeIn Atom A logical value indicating whether the atom is convex. setMethod("is_convex", "Atom", function(object) { # Applies DCP composition rule if(is_constant(object)) return(TRUE) else if(is_atom_convex(object)) { idx <- 1 for(arg in object@args) { if(!(is_affine(arg) || (is_convex(arg) && is_incr(object, idx)) || (is_concave(arg) && is_decr(object, idx)))) return(FALSE) idx <- idx + 1 } return(TRUE) } else return(FALSE) }) #' @describeIn Atom A logical value indicating whether the atom is concave. setMethod("is_concave", "Atom", function(object) { # Applies DCP composition rule if(is_constant(object)) return(TRUE) else if(is_atom_concave(object)) { idx <- 1 for(arg in object@args) { if(!(is_affine(arg) || (is_concave(arg) && is_incr(object, idx)) || (is_convex(arg) && is_decr(object, idx)))) return(FALSE) idx <- idx + 1 } return(TRUE) } else return(FALSE) }) #' @describeIn Atom A logical value indicating whether the atom is log-log convex. setMethod("is_log_log_convex", "Atom", function(object) { # Verifies DGP composition rule. if(is_log_log_constant(object)) return(TRUE) else if(is_atom_log_log_convex(object)) { idx <- 1 for(arg in object@args) { if(!(is_log_log_affine(arg) || (is_log_log_convex(arg) && is_incr(object, idx)) || (is_log_log_concave(arg) && is_decr(object, idx)))) return(FALSE) idx <- idx + 1 } return(TRUE) } else return(FALSE) }) #' @describeIn Atom A logical value indicating whether the atom is log-log concave. setMethod("is_log_log_concave", "Atom", function(object) { # Verifies DGP composition rule. if(is_log_log_constant(object)) return(TRUE) else if(is_atom_log_log_concave(object)) { idx <- 1 for(arg in object@args) { if(!(is_log_log_affine(arg) || (is_log_log_concave(arg) && is_incr(object, idx)) || (is_log_log_convex(arg) && is_decr(object, idx)))) return(FALSE) idx <- idx + 1 } return(TRUE) } else return(FALSE) }) #' @describeIn Atom Represent the atom as an affine objective and conic constraints. setMethod("canonicalize", "Atom", function(object) { # Constant atoms are treated as a leaf. if(is_constant(object)) { # Parameterized expressions are evaluated later. if(!is.na(parameters(object)) && length(parameters(object)) > 0) { param <- CallbackParam(value(object), dim(object)) return(canonical_form(param)) # Non-parameterized expressions are evaluated immediately. } else return(canonical_form(Constant(value(object)))) } else { arg_objs <- list() constraints <- list() for(arg in object@args) { canon <- canonical_form(arg) arg_objs[[length(arg_objs) + 1]] <- canon[[1]] constraints <- c(constraints, canon[[2]]) } # Special info required by the graph implementation. data <- get_data(object) graph <- graph_implementation(object, arg_objs, dim(object), data) return(list(graph[[1]], c(constraints, graph[[2]]))) } }) #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector with two elements representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @describeIn Atom The graph implementation of the atom. setMethod("graph_implementation", "Atom", function(object, arg_objs, dim, data = NA_real_) { stop("Unimplemented") }) # .value_impl.Atom <- function(object) { #' @describeIn Atom Returns the value of each of the componets in an Atom. Returns an empty matrix if it's an empty atom setMethod("value_impl", "Atom", function(object) { obj_dim <- dim(object) # dims with 0's dropped in presolve. if(0 %in% obj_dim) result <- matrix(nrow = 0, ncol = 0) # Catch the case when the expression is known to be zero through DCP analysis else if(is_zero(object)) result <- matrix(0, nrow = obj_dim[1], ncol = obj_dim[2]) else { arg_values <- list() for(arg in object@args) { # An argument without a value makes all higher level values NA. # But if the atom is constant with non-constant arguments, it doesn't depend on its arguments, so it isn't NA. arg_val <- value_impl(arg) if(any(is.na(arg_val)) && !is_constant(object)) return(NA_real_) else arg_values <- c(arg_values, list(arg_val)) } result <- to_numeric(object, arg_values) } return(result) }) #' @describeIn Atom Returns the value of the atom. setMethod("value", "Atom", function(object) { if(any(sapply(parameters(object), function(p) { is.na(value(p)) }))) return(NA_real_) return(value_impl(object)) }) #' @describeIn Atom The (sub/super)-gradient of the atom with respect to each variable. setMethod("grad", "Atom", function(object) { # Short-circuit to all zeros if known to be constant if(is_constant(object)) return(constant_grad(object)) # Returns NA if variable values are not supplied arg_values <- list() for(arg in object@args) { arg_val <- value(arg) if(any(is.na(arg_val))) return(error_grad(object)) else arg_values <- c(arg_values, list(arg_val)) } # A list of gradients wrt arguments grad_self <- .grad(object, arg_values) # The chain rule result <- list() idx <- 1 for(arg in object@args) { # A dictionary of gradients wrt variables. # Partial argument / partial x. grad_arg <- grad(arg) for(key in names(grad_arg)) { # None indicates gradient is not defined. if(any(is.na( as.vector(grad_arg[[key]]) )) || any(is.na( as.vector(grad_self[[idx]]) ))) result[[key]] <- NA_real_ else { D <- grad_arg[[key]] %*% grad_self[[idx]] # Convert 1x1 matrices to scalars. if((is.matrix(D) || is(D, "Matrix")) && all(dim(D) == c(1,1))) D <- D[1,1] if(key %in% names(result)) result[[key]] <- result[[key]] + D else result[[key]] <- D } } idx <- idx + 1 } return(result) }) setMethod(".grad", "Atom", function(object, values) { stop("Unimplemented") }) #' @describeIn Atom A list of constraints describing the closure of the region where the expression is finite. setMethod("domain", "Atom", function(object) { cons <- list() for(arg in object@args) { for(con in domain(arg)) cons <- c(cons, con) } c(.domain(object), cons) }) setMethod(".domain", "Atom", function(object) { list() }) #' @describeIn Atom Returns a list of the atom types present amongst this atom's arguments setMethod("atoms", "Atom", function(object) { atom_list <- list() for(arg in object@args) atom_list <- c(atom_list, atoms(arg)) atom_list <- c(atom_list, list(class(object))) return(unique(atom_list)) }) #' #' The AxisAtom class. #' #' This virtual class represents atomic expressions that can be applied along an axis in CVXR. #' #' @slot expr A numeric element, data.frame, matrix, vector, or Expression. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @name AxisAtom-class #' @aliases AxisAtom #' @rdname AxisAtom-class AxisAtom <- setClass("AxisAtom", representation(expr = "ConstValORExpr", axis = "ANY", keepdims = "logical"), prototype(axis = NA_real_, keepdims = FALSE), contains = c("VIRTUAL", "Atom")) setMethod("initialize", "AxisAtom", function(.Object, ..., expr, axis = NA_real_, keepdims = FALSE) { .Object@expr <- expr .Object@axis <- axis .Object@keepdims <- keepdims .Object <- callNextMethod(.Object, ..., atom_args = list(.Object@expr)) }) #' @param object An \linkS4class{Atom} object. #' @describeIn AxisAtom The dimensions of the atom determined from its arguments. setMethod("dim_from_args", "AxisAtom", function(object) { # TODO: Revisit this when we properly handle dimensions of scalars (NULL) and 1-D vectors (length only). arg_dim <- dim(object@args[[1]]) if(object@keepdims && is.na(object@axis)) # Copy scalar to maintain original dimensions. arg_dim <- rep(1, length(arg_dim)) else if(object@keepdims && !is.na(object@axis)) { # Collapse dimensions NOT in axis to 1. collapse <- setdiff(1:length(arg_dim), object@axis) arg_dim[collapse] <- 1 } else if(!object@keepdims && is.na(object@axis)) # Return a scalar. # arg_dim <- NULL # TODO: Should this be NA instead? arg_dim <- rep(1, length(arg_dim)) else { # Drop dimensions NOT in axis and collapse atom. # arg_dim <- arg_dim[object@axis] collapse <- setdiff(1:length(arg_dim), object@axis) arg_dim <- c(arg_dim[object@axis], rep(1, length(collapse))) } return(arg_dim) }) #' @describeIn AxisAtom A list containing \code{axis} and \code{keepdims}. setMethod("get_data", "AxisAtom", function(object) { list(object@axis, object@keepdims) }) #' @describeIn AxisAtom Check that the new dimensions have the same number of entries as the old. setMethod("validate_args", "AxisAtom", function(object) { if(!is.na(object@axis) && any(object@axis > ndim(object@args[[1]]) || object@axis <= 0)) stop("Invalid argument for axis. Must be an integer between 1 and ", ndim(object@args[[1]])) callNextMethod() }) #' @param values A list of numeric values for the arguments #' @describeIn AxisAtom Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".axis_grad", "AxisAtom", function(object, values) { if(is.na(object@axis) || ndim(object@args[[1]]) < 2) { value <- matrix(values[[1]], nrow = size(object@args[[1]]), ncol = 1) D <- .column_grad(object, value) if(is(D, "Matrix") || !any(is.na(D))) D <- Matrix(D, sparse = TRUE) } else { m <- nrow(object@args[[1]]) n <- ncol(object@args[[1]]) if(object@axis == 2) { # Function apply to each column D <- sparseMatrix(i = c(), j = c(), dims = c(m*n, n)) for(i in 1:n) { value <- values[[1]][,i] d <- t(.column_grad(object, value)) if(any(is.na(as.vector(d)))) return(list(NA_real_)) row <- seq((i-1)*n+1, (i-1)*n+m, length.out = m) col <- rep(1,m) * i D <- D + sparseMatrix(i = row, j = col, x = as.vector(d), dims = c(m*n, n)) } } else { # Function apply to each row values <- t(values[[1]]) D <- sparseMatrix(i = c(), j = c(), dims = c(m*n, m)) for(i in 1:m) { value <- values[,i] d <- t(.column_grad(object, value)) if(any(is.na(as.vector(d)))) return(list(NA_real_)) row <- seq(i, i+(n-1)*m, length.out = n) col <- rep(1,n)*i D <- D + sparseMatrix(i = row, j = col, x = as.vector(d), dims = c(m*n, m)) } } } list(D) }) #' @param value A numeric value #' @describeIn AxisAtom Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "AxisAtom", function(object, value) { stop("Unimplemented") }) #' #' The CumMax class. #' #' This class represents the cumulative maximum of an expression. #' #' @slot expr An \linkS4class{Expression}. #' @slot axis A numeric vector indicating the axes along which to apply the function. For a 2D matrix, \code{1} indicates rows, \code{2} indicates columns, and \code{c(1,2)} indicates rows and columns. #' @name CumMax-class #' @aliases CumMax #' @rdname CumMax-class .CumMax <- setClass("CumMax", prototype = prototype(axis = 2), contains = "AxisAtom") #' @param expr An \linkS4class{Expression}. #' @param axis A numeric vector indicating the axes along which to apply the function. For a 2D matrix, \code{1} indicates rows, \code{2} indicates columns, and \code{c(1,2)} indicates rows and columns. #' @rdname CumMax-class CumMax <- function(expr, axis = 2) { .CumMax(expr = expr, axis = axis) } #' @param object A \linkS4class{CumMax} object. #' @param values A list of arguments to the atom. #' @describeIn CumMax The cumulative maximum along the axis. setMethod("to_numeric", "CumMax", function(object, values) { # apply(values[[1]], object@axis, base::cummax) if(object@axis == 1) do.call(rbind, lapply(seq_len(nrow(values[[1]])), function(i) { base::cummax(values[[1]][i,]) })) else if(object@axis == 2) do.call(cbind, lapply(seq_len(ncol(values[[1]])), function(j) { base::cummax(values[[1]][,j]) })) else base::cummax(values[[1]]) }) #' @param values A list of numeric values for the arguments #' @describeIn CumMax Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "CumMax", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value. #' @describeIn CumMax Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "CumMax", function(object, value) { # Grad: 1 for a largest index. value <- as.vector(value) maxes <- base::cummax(value) D <- matrix(0, nrow = length(value), ncol = 1) D[1,1] <- 1 if(length(value) > 1) D[2:nrow(D),] <- maxes[2:length(maxes)] > maxes[1:(length(maxes)-1)] return(D) }) #' @describeIn CumMax The dimensions of the atom determined from its arguments. setMethod("dim_from_args", "CumMax", function(object) { dim(object@args[[1]]) }) #' @describeIn CumMax The (is positive, is negative) sign of the atom. setMethod("sign_from_args", "CumMax", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) }) #' @describeIn CumMax Returns the axis along which the cumulative max is taken. setMethod("get_data", "CumMax", function(object) { list(object@axis) }) #' @describeIn CumMax Is the atom convex? setMethod("is_atom_convex", "CumMax", function(object) { TRUE }) #' @describeIn CumMax Is the atom concave? setMethod("is_atom_concave", "CumMax", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn CumMax Is the atom weakly increasing in the index? setMethod("is_incr", "CumMax", function(object, idx) { TRUE }) #' @describeIn CumMax Is the atom weakly decreasing in the index? setMethod("is_decr", "CumMax", function(object, idx) { FALSE }) #' #' The EyeMinusInv class. #' #' This class represents the unity resolvent of an elementwise positive matrix \eqn{X}, i.e., \eqn{(I - X)^{-1}}, #' and it enforces the constraint that the spectral radius of \eqn{X} is at most 1. #' This atom is log-log convex. #' #' @slot X An \linkS4class{Expression} or numeric matrix. #' @name EyeMinusInv-class #' @aliases EyeMinusInv #' @rdname EyeMinusInv-class .EyeMinusInv <- setClass("EyeMinusInv", representation(X = "ConstValORExpr"), validity = function(object) { if(length(dim(object@X)) != 2 || nrow(object@X) != ncol(object@X)) stop("[EyeMinusInv: X] The argument X must be a square matrix.") return(TRUE) }, contains = "Atom") #' @param X An \linkS4class{Expression} or numeric matrix. #' @rdname EyeMinusInv-class EyeMinusInv <- function(X) { .EyeMinusInv(X = X) } setMethod("initialize", "EyeMinusInv", function(.Object, ..., X) { .Object@X <- X .Object <- callNextMethod(.Object, ..., atom_args = list(.Object@X)) .Object@args[[1]] <- X .Object }) #' @param object,x An \linkS4class{EyeMinusInv} object. #' @param values A list of arguments to the atom. #' @describeIn EyeMinusInv The unity resolvent of the matrix. setMethod("to_numeric", "EyeMinusInv", function(object, values) { base::solve(diag(nrow(object@args[[1]])) - values[[1]]) }) #' @describeIn EyeMinusInv The name and arguments of the atom. setMethod("name", "EyeMinusInv", function(x) { paste(class(x), x@args[[1]]) }) #' @describeIn EyeMinusInv The dimensions of the atom determined from its arguments. setMethod("dim_from_args", "EyeMinusInv", function(object) { dim(object@args[[1]]) }) #' @describeIn EyeMinusInv The (is positive, is negative) sign of the atom. setMethod("sign_from_args", "EyeMinusInv", function(object) { c(TRUE, FALSE) }) #' @describeIn EyeMinusInv Is the atom convex? setMethod("is_atom_convex", "EyeMinusInv", function(object) { FALSE }) #' @describeIn EyeMinusInv Is the atom concave? setMethod("is_atom_concave", "EyeMinusInv", function(object) { FALSE }) #' @describeIn EyeMinusInv Is the atom log-log convex? setMethod("is_atom_log_log_convex", "EyeMinusInv", function(object) { TRUE }) #' @describeIn EyeMinusInv Is the atom log-log concave? setMethod("is_atom_log_log_concave", "EyeMinusInv", function(object) { FALSE }) # TODO: Figure out monotonicity. #' @param idx An index into the atom. #' @describeIn EyeMinusInv Is the atom weakly increasing in the index? setMethod("is_incr", "EyeMinusInv", function(object, idx) { FALSE }) #' @describeIn EyeMinusInv Is the atom weakly decreasing in the index? setMethod("is_decr", "EyeMinusInv", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn EyeMinusInv Gives EyeMinusInv the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "EyeMinusInv", function(object, values) { NA_real_ }) # The resolvent of a positive matrix, (sI - X)^(-1). # For an elementwise positive matrix X and a positive scalar s, this atom computes # (sI - X)^(-1), and it enforces the constraint that the spectral radius of X/s is # at most 1. # This atom is log-log convex. Resolvent <- function(X, s) { 1.0 / (s * EyeMinusInv(X / s)) } #' #' The GeoMean class. #' #' This class represents the (weighted) geometric mean of vector \eqn{x} with optional powers given by \eqn{p}. #' #' \deqn{\left(x_1^{p_1} \cdots x_n^{p_n} \right)^{\frac{1}{\mathbf{1}^Tp}}} #' #' The geometric mean includes an implicit constraint that \eqn{x_i \geq 0} whenever \eqn{p_i > 0}. If \eqn{p_i = 0, x_i} will be unconstrained. #' The only exception to this rule occurs when \eqn{p} has exactly one nonzero element, say \eqn{p_i}, in which case \code{GeoMean(x,p)} is equivalent to \eqn{x_i} (without the nonnegativity constraint). #' A specific case of this is when \eqn{x \in \mathbf{R}^1}. #' #' @slot x An \linkS4class{Expression} or numeric vector. #' @slot p (Optional) A vector of weights for the weighted geometric mean. The default is a vector of ones, giving the \strong{unweighted} geometric mean \eqn{x_1^{1/n} \cdots x_n^{1/n}}. #' @slot max_denom (Optional) The maximum denominator to use in approximating \code{p/sum(p)} with \code{w}. If \code{w} is not an exact representation, increasing \code{max_denom} may offer a more accurate representation, at the cost of requiring more convex inequalities to represent the geometric mean. Defaults to 1024. #' @slot w (Internal) A list of \code{bigq} objects that represent a rational approximation of \code{p/sum(p)}. #' @slot approx_error (Internal) The error in approximating \code{p/sum(p)} with \code{w}, given by \eqn{\|p/\mathbf{1}^Tp - w\|_{\infty}}. #' @name GeoMean-class #' @aliases GeoMean #' @importClassesFrom gmp bigq bigz #' @rdname GeoMean-class .GeoMean <- setClass("GeoMean", representation(x = "ConstValORExpr", p = "numeric", max_denom = "numeric", w = "bigq", w_dyad = "bigq", approx_error = "numeric", tree = "Rdict", cone_lb = "numeric", cone_num = "numeric", cone_num_over = "numeric"), prototype(p = NA_real_, max_denom = 1024), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric vector. #' @param p (Optional) A vector of weights for the weighted geometric mean. The default is a vector of ones, giving the \strong{unweighted} geometric mean \eqn{x_1^{1/n} \cdots x_n^{1/n}}. #' @param max_denom (Optional) The maximum denominator to use in approximating \code{p/sum(p)} with \code{w}. If \code{w} is not an exact representation, increasing \code{max_denom} may offer a more accurate representation, at the cost of requiring more convex inequalities to represent the geometric mean. Defaults to 1024. #' @rdname GeoMean-class GeoMean <- function(x, p = NA_real_, max_denom = 1024) { .GeoMean(x = x, p = p, max_denom = max_denom) } setMethod("initialize", "GeoMean", function(.Object, ..., x, p = NA_real_, max_denom = 1024) { .Object@x <- x .Object@max_denom <- max_denom .Object <- callNextMethod(.Object, ..., atom_args = list(.Object@x), validate = FALSE) x <- .Object@args[[1]] if(is_vector(x)) n <- ifelse(ndim(x) == 0, 1, max(dim(x))) else stop("x must be a row or column vector.") if(any(is.na(p))) p <- rep(1, n) .Object@p <- p if(length(.Object@p) != n) stop("x and p must have the same number of elements.") if(any(.Object@p < 0) || sum(.Object@p) <= 0) stop("powers must be nonnegative and not all zero.") frac <- fracify(.Object@p, .Object@max_denom) .Object@w <- frac[[1]] .Object@w_dyad <- frac[[2]] .Object@approx_error <- approx_error(.Object@p, .Object@w) .Object@tree <- decompose(.Object@w_dyad) # known lower bound on number of cones needed to represent w_dyad .Object@cone_lb <- lower_bound(.Object@w_dyad) # number of cones used past known lower bound .Object@cone_num_over <- over_bound(.Object@w_dyad, .Object@tree) # number of cones used .Object@cone_num <- .Object@cone_lb + .Object@cone_num_over validObject(.Object) .Object }) #' @param object A \linkS4class{GeoMean} object. #' @param values A list of arguments to the atom. #' @describeIn GeoMean The (weighted) geometric mean of the elements of \code{x}. setMethod("to_numeric", "GeoMean", function(object, values) { values <- as.vector(values[[1]]) val <- 1.0 for(idx in 1:length(values)) { x <- values[[idx]] p <- object@w[idx] val <- val * Rmpfr::mpfr(x, Rmpfr::getPrec(x))^p } return(gmp::asNumeric(val)) # TODO: Handle mpfr objects in the backend later }) #' @describeIn GeoMean Returns constraints describing the domain of the node setMethod(".domain", "GeoMean", function(object) { list(object@args[[1]][object@w > 0] >= 0) }) #' @param values A list of numeric values for the arguments #' @describeIn GeoMean Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "GeoMean", function(object, values) { x <- as.matrix(values[[1]]) # No special case when only one non-zero weight w_arr <- as.double(object@w) # TODO: I'm casting bigq/bigz to double to construct Matrix properly. # Outside domain if(any(x[w_arr > 0] <= 0)) return(list(NA_real_)) else { D <- w_arr/as.vector(x) * to_numeric(object, values) return(list(Matrix(D, sparse = TRUE))) } }) #' @describeIn GeoMean The name and arguments of the atom. setMethod("name", "GeoMean", function(x) { vals <- paste(sapply(x@w, as.character), collapse = ", ") paste("GeoMean(", name(x@args[[1]]), ", (", vals, "))", sep = "") }) #' @describeIn GeoMean The atom is a scalar. setMethod("dim_from_args", "GeoMean", function(object) { c(1,1) }) #' @describeIn GeoMean The atom is non-negative. setMethod("sign_from_args", "GeoMean", function(object) { c(TRUE, FALSE) }) #' @describeIn GeoMean The atom is not convex. setMethod("is_atom_convex", "GeoMean", function(object) { FALSE }) #' @describeIn GeoMean The atom is concave. setMethod("is_atom_concave", "GeoMean", function(object) { TRUE }) #' @describeIn GeoMean Is the atom log-log convex? setMethod("is_atom_log_log_convex", "GeoMean", function(object) { TRUE }) #' @describeIn GeoMean Is the atom log-log concave? setMethod("is_atom_log_log_concave", "GeoMean", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn GeoMean The atom is weakly increasing in every argument. setMethod("is_incr", "GeoMean", function(object, idx) { TRUE }) #' @describeIn GeoMean The atom is not weakly decreasing in any argument. setMethod("is_decr", "GeoMean", function(object, idx) { FALSE }) #' @describeIn GeoMean Returns \code{list(w, dyadic completion, tree of dyads)}. setMethod("get_data", "GeoMean", function(object) { list(object@w, object@w_dyad, object@tree) }) #' @param args An optional list that contains the arguments to reconstruct the atom. Default is to use current arguments of the atom. #' @param id_objects Currently unused. #' @describeIn GeoMean Returns a shallow copy of the GeoMean atom setMethod("copy", "GeoMean", function(object, args = NULL, id_objects = list()) { if(is.null(args)) args <- object@args copy <- do.call(class(object), args) data <- get_data(object) copy@w <- data[[1]] copy@w_dyad <- data[[2]] copy@tree <- data[[3]] copy@approx_error <- object@approx_error copy@cone_lb <- object@cone_lb copy@cone_num_over <- object@cone_num_over copy@cone_num <- object@cone_num copy }) #' #' The HarmonicMean atom. #' #' The harmonic mean of x, \eqn{\frac{1}{n} \sum_{i=1}^n x_i^{-1}}, where n is the length of x. #' #' @param x An expression or number whose harmonic mean is to be computed. Must have positive entries. #' @return The harmonic mean of \code{x}. HarmonicMean <- function(x) { x <- as.Constant(x) size(x) * Pnorm(x = x, p = -1) } #' #' The LambdaMax class. #' #' The maximum eigenvalue of a matrix, \eqn{\lambda_{\max}(A)}. #' #' @slot A An \linkS4class{Expression} or numeric matrix. #' @name LambdaMax-class #' @aliases LambdaMax #' @rdname LambdaMax-class .LambdaMax <- setClass("LambdaMax", representation(A = "ConstValORExpr"), contains = "Atom") #' @param A An \linkS4class{Expression} or numeric matrix. #' @rdname LambdaMax-class LambdaMax <- function(A) { .LambdaMax(A = A) } setMethod("initialize", "LambdaMax", function(.Object, ..., A) { .Object@A <- A callNextMethod(.Object, ..., atom_args = list(.Object@A)) }) #' @param object A \linkS4class{LambdaMax} object. #' @param values A list of arguments to the atom. #' @describeIn LambdaMax The largest eigenvalue of \code{A}. Requires that \code{A} be symmetric. setMethod("to_numeric", "LambdaMax", function(object, values) { # if(any(t(values[[1]]) != values[[1]])) # stop("LambdaMax called on a non-symmetric matrix") max(eigen(values[[1]], only.values = TRUE)$values) }) #' @describeIn LambdaMax Returns the constraints describing the domain of the atom. setMethod(".domain", "LambdaMax", function(object) { list(Conj(t(object@args[[1]])) == object@args[[1]]) }) #' @describeIn LambdaMax Gives the (sub/super)gradient of the atom with respect to each argument. Matrix expressions are vectorized, so the gradient is a matrix. setMethod(".grad", "LambdaMax", function(object, values) { r <- base::eigen(values[[1]], only.values = FALSE) # Eigenvalues returned in decreasing order. v <- r$vectors # eigenvectors w <- r$values # eigenvalues d <- rep(0, length(w)) d[1] <- 1 d <- diag(d) D <- v %*% d %*% t(v) list(Matrix(as.vector(D), sparse = TRUE)) }) #' @describeIn LambdaMax Check that \code{A} is square. setMethod("validate_args", "LambdaMax", function(object) { if(ndim(object@args[[1]]) != 2 || nrow(object@args[[1]]) != ncol(object@args[[1]])) stop("The argument to LambdaMax must resolve to a square matrix") }) #' @describeIn LambdaMax The atom is a scalar. setMethod("dim_from_args", "LambdaMax", function(object) { c(1,1) }) #' @describeIn LambdaMax The sign of the atom is unknown. setMethod("sign_from_args", "LambdaMax", function(object) { c(FALSE, FALSE) }) #' @describeIn LambdaMax The atom is convex. setMethod("is_atom_convex", "LambdaMax", function(object) { TRUE }) #' @describeIn LambdaMax The atom is not concave. setMethod("is_atom_concave", "LambdaMax", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn LambdaMax The atom is not monotonic in any argument. setMethod("is_incr", "LambdaMax", function(object, idx) { FALSE }) #' @describeIn LambdaMax The atom is not monotonic in any argument. setMethod("is_decr", "LambdaMax", function(object, idx) { FALSE }) #' #' The LambdaMin atom. #' #' The minimum eigenvalue of a matrix, \eqn{\lambda_{\min}(A)}. #' #' @param A An \linkS4class{Expression} or numeric matrix. #' @return Returns the minimum eigenvalue of a matrix. LambdaMin <- function(A) { A <- as.Constant(A) -LambdaMax(-A) } #' #' The LambdaSumLargest class. #' #' This class represents the sum of the \code{k} largest eigenvalues of a matrix. #' #' @slot k A positive integer. #' @name LambdaSumLargest-class #' @aliases LambdaSumLargest #' @rdname LambdaSumLargest-class .LambdaSumLargest <- setClass("LambdaSumLargest", representation(k = "numeric"), contains = "LambdaMax") #' @param A An \linkS4class{Expression} or numeric matrix. #' @param k A positive integer. #' @rdname LambdaSumLargest-class LambdaSumLargest <- function(A, k) { .LambdaSumLargest(A = A, k = k) } setMethod("initialize", "LambdaSumLargest", function(.Object, ..., k) { .Object@k <- k callNextMethod(.Object, ...) }) #' @describeIn LambdaSumLargest Does the atom handle complex numbers? setMethod("allow_complex", "LambdaSumLargest", function(object) { TRUE }) #' @param object A \linkS4class{LambdaSumLargest} object. #' @param values A list of arguments to the atom. #' @describeIn LambdaSumLargest Returns the largest eigenvalue of \code{A}, which must be symmetric. setMethod("to_numeric", "LambdaSumLargest", function(object, values) { # if(any(t(values[[1]]) != values[[1]])) # stop("LambdaSumLargest called on a non-symmetric matrix") eigs <- eigen(values[[1]], only.values = TRUE)$values value(SumLargest(eigs, object@k)) }) #' @describeIn LambdaSumLargest Verify that the argument \code{A} is square. setMethod("validate_args", "LambdaSumLargest", function(object) { A <- object@args[[1]] if(ndim(A) != 2 || nrow(A) != ncol(A)) stop("First argument must be a square matrix.") else if(as.integer(object@k) != object@k || object@k <= 0) stop("Second argument must be a positive integer.") }) #' @describeIn LambdaSumLargest Returns the parameter \code{k}. setMethod("get_data", "LambdaSumLargest", function(object) { list(object@k) }) #' @param values A list of numeric values for the arguments #' @describeIn LambdaSumLargest Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "LambdaSumLargest", function(object, values) { stop("Unimplemented") }) #' #' The LambdaSumSmallest atom. #' #' This class represents the sum of the \code{k} smallest eigenvalues of a matrix. #' #' @param A An \linkS4class{Expression} or numeric matrix. #' @param k A positive integer. #' @return Returns the sum of the k smallest eigenvalues of a matrix. LambdaSumSmallest <- function(A, k) { A <- as.Constant(A) -LambdaSumLargest(-A, k) } #' #' The LogDet class. #' #' The natural logarithm of the determinant of a matrix, \eqn{\log\det(A)}. #' #' @slot A An \linkS4class{Expression} or numeric matrix. #' @name LogDet-class #' @aliases LogDet #' @rdname LogDet-class .LogDet <- setClass("LogDet", representation(A = "ConstValORExpr"), contains = "Atom") #' @param A An \linkS4class{Expression} or numeric matrix. #' @rdname LogDet-class LogDet <- function(A) { .LogDet(A = A) } setMethod("initialize", "LogDet", function(.Object, ..., A) { .Object@A <- A callNextMethod(.Object, ..., atom_args = list(.Object@A)) }) #' @param object A \linkS4class{LogDet} object. #' @param values A list of arguments to the atom. #' @describeIn LogDet The log-determinant of SDP matrix \code{A}. This is the sum of logs of the eigenvalues and is equivalent to the nuclear norm of the matrix logarithm of \code{A}. setMethod("to_numeric", "LogDet", function(object, values) { if(is.complex(values[[1]])) { eigvals <- eigen(values[[1]], only.values = TRUE)$values return(log(prod(eigvals))) } else { logdet <- determinant(values[[1]], logarithm = TRUE) if(logdet$sign == 1) return(as.numeric(logdet$modulus)) else return(-Inf) } }) #' @describeIn LogDet Check that \code{A} is square. setMethod("validate_args", "LogDet", function(object) { arg_dim <- dim(object@args[[1]]) if(length(arg_dim) == 1 || arg_dim[1] != arg_dim[2]) stop("The argument to LogDet must be a square matrix") }) #' @describeIn LogDet The atom is a scalar. setMethod("dim_from_args", "LogDet", function(object) { c(1,1) }) #' @describeIn LogDet The atom is non-negative. setMethod("sign_from_args", "LogDet", function(object) { c(TRUE, FALSE) }) #' @describeIn LogDet The atom is not convex. setMethod("is_atom_convex", "LogDet", function(object) { FALSE }) #' @describeIn LogDet The atom is concave. setMethod("is_atom_concave", "LogDet", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn LogDet The atom is not monotonic in any argument. setMethod("is_incr", "LogDet", function(object, idx) { FALSE }) #' @describeIn LogDet The atom is not monotonic in any argument. setMethod("is_decr", "LogDet", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn LogDet Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "LogDet", function(object, values) { X <- as.matrix(values[[1]]) eigen_val <- eigen(X, only.values = TRUE)$values if(min(eigen_val) > 0) { # Grad: t(X^(-1)) D <- t(base::solve(X)) return(list(Matrix(as.vector(D), sparse = TRUE))) } else # Outside domain return(list(NA_real_)) }) #' @describeIn LogDet Returns constraints describing the domain of the node setMethod(".domain", "LogDet", function(object) { list(object@args[[1]] %>>% 0) }) #' #' The LogSumExp class. #' #' The natural logarithm of the sum of the elementwise exponential, \eqn{\log\sum_{i=1}^n e^{x_i}}. #' #' @slot x An \linkS4class{Expression} representing a vector or matrix. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @name LogSumExp-class #' @aliases LogSumExp #' @rdname LogSumExp-class .LogSumExp <- setClass("LogSumExp", contains = "AxisAtom") #' @param x An \linkS4class{Expression} representing a vector or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname LogSumExp-class LogSumExp <- function(x, axis = NA_real_, keepdims = FALSE) { .LogSumExp(expr = x, axis = axis, keepdims = keepdims) } #' @param object A \linkS4class{LogSumExp} object. #' @param values A list of arguments to the atom. #' @describeIn LogSumExp Evaluates \eqn{e^x} elementwise, sums, and takes the natural log. setMethod("to_numeric", "LogSumExp", function(object, values) { if(is.na(object@axis)) log(sum(exp(values[[1]]))) else # log(apply(exp(values[[1]]), object@axis, sum)) log(apply_with_keepdims(exp(values[[1]]), sum, axis = object@axis, keepdims = object@keepdims)) }) #' @param values A list of numeric values. #' @describeIn LogSumExp Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "LogSumExp", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value. #' @describeIn LogSumExp Gives the (sub/super)gradient of the atom w.r.t. each column variable. setMethod(".column_grad", "LogSumExp", function(object, value) { denom <- sum(exp(value)) nom <- exp(value) D <- nom/denom D }) #' @describeIn LogSumExp Returns sign (is positive, is negative) of the atom. setMethod("sign_from_args", "LogSumExp", function(object) { c(FALSE, FALSE) }) #' @describeIn LogSumExp The atom is convex. setMethod("is_atom_convex", "LogSumExp", function(object) { TRUE }) #' @describeIn LogSumExp The atom is not concave. setMethod("is_atom_concave", "LogSumExp", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn LogSumExp The atom is weakly increasing in the index. setMethod("is_incr", "LogSumExp", function(object, idx) { TRUE }) #' @param idx An index into the atom. #' @describeIn LogSumExp The atom is not weakly decreasing in the index. setMethod("is_decr", "LogSumExp", function(object, idx) { FALSE }) #' #' The MatrixFrac class. #' #' The matrix fraction function \eqn{tr(X^T P^{-1} X)}. #' #' @slot X An \linkS4class{Expression} or numeric matrix. #' @slot P An \linkS4class{Expression} or numeric matrix. #' @name MatrixFrac-class #' @aliases MatrixFrac #' @rdname MatrixFrac-class .MatrixFrac <- setClass("MatrixFrac", representation(X = "ConstValORExpr", P = "ConstValORExpr"), contains = "Atom") #' @param X An \linkS4class{Expression} or numeric matrix. #' @param P An \linkS4class{Expression} or numeric matrix. #' @rdname MatrixFrac-class MatrixFrac <- function(X, P) { .MatrixFrac(X = X, P = P) } setMethod("initialize", "MatrixFrac", function(.Object, ..., X, P) { .Object@X <- X .Object@P <- P callNextMethod(.Object, ..., atom_args = list(.Object@X, .Object@P)) }) #' @describeIn MatrixFrac Does the atom handle complex numbers? setMethod("allow_complex", "MatrixFrac", function(object) { TRUE }) #' @param object A \linkS4class{MatrixFrac} object. #' @param values A list of arguments to the atom. #' @describeIn MatrixFrac The trace of \eqn{X^TP^{-1}X}. setMethod("to_numeric", "MatrixFrac", function(object, values) { # TODO: Raise error if not invertible? X <- values[[1]] P <- values[[2]] if(is_complex(object@args[[1]])) product <- t(Conj(X)) %*% base::solve(P) %*% X else product <- t(X) %*% base::solve(P) %*% X if(length(dim(product)) == 2) return(sum(diag(product))) else return(product) }) #' @describeIn MatrixFrac Check that the dimensions of \code{x} and \code{P} match. setMethod("validate_args", "MatrixFrac", function(object) { X <- object@args[[1]] P <- object@args[[2]] if(ndim(P) != 2 || nrow(P) != ncol(P)) stop("The second argument to MatrixFrac must be a square matrix.") else if(nrow(X) != nrow(P)) stop("The arguments to MatrixFrac have incompatible dimensions.") }) #' @describeIn MatrixFrac The atom is a scalar. setMethod("dim_from_args", "MatrixFrac", function(object) { c(1,1) }) #' @describeIn MatrixFrac The atom is positive. setMethod("sign_from_args", "MatrixFrac", function(object) { c(TRUE, FALSE) }) #' @describeIn MatrixFrac The atom is convex. setMethod("is_atom_convex", "MatrixFrac", function(object) { TRUE }) #' @describeIn MatrixFrac The atom is not concave. setMethod("is_atom_concave", "MatrixFrac", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn MatrixFrac The atom is not monotonic in any argument. setMethod("is_incr", "MatrixFrac", function(object, idx) { FALSE }) #' @describeIn MatrixFrac The atom is not monotonic in any argument. setMethod("is_decr", "MatrixFrac", function(object, idx) { FALSE }) #' @describeIn MatrixFrac True if x is affine and P is constant. setMethod("is_quadratic", "MatrixFrac", function(object) { is_affine(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn MatrixFrac True if x is piecewise linear and P is constant. setMethod("is_qpwa", "MatrixFrac", function(object) { is_pwl(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn MatrixFrac Returns constraints describing the domain of the node setMethod(".domain", "MatrixFrac", function(object) { list(object@args[[2]] %>>% 0) }) #' @param values A list of numeric values for the arguments #' @describeIn MatrixFrac Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MatrixFrac", function(object, values) { X <- as.matrix(values[[1]]) P <- as.matrix(values[[2]]) P_inv <- tryCatch({ base::solve(P) }, error = function(e) { list(NA_real_, NA_real_) }) ## if(is.null(dim(P_inv)) && is.na(P_inv)) ## return(list(NA_real_, NA_real_)) if(is.null(dim(P_inv))) return(list(NA_real_, NA_real_)) # partial_X = (P^-1+P^-T)X # partial_P = (P^-1 * X * X^T * P^-1)^T DX <- (P_inv + t(P_inv)) %*% X DX <- as.vector(t(DX)) DX <- Matrix(DX, sparse = TRUE) DP <- P_inv %*% X DP <- DP %*% t(X) DP <- DP %*% P_inv DP <- -t(DP) DP <- Matrix(as.vector(t(DP)), sparse = TRUE) list(DX, DP) }) #' #' The MaxEntries class. #' #' The maximum of an expression. #' #' @slot x An \linkS4class{Expression} representing a vector or matrix. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @name MaxEntries-class #' @aliases MaxEntries #' @rdname MaxEntries-class .MaxEntries <- setClass("MaxEntries", contains = "AxisAtom") #' @param x An \linkS4class{Expression} representing a vector or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname MaxEntries-class MaxEntries <- function(x, axis = NA_real_, keepdims = FALSE) { .MaxEntries(expr = x, axis = axis, keepdims = keepdims) } #' @param object A \linkS4class{MaxEntries} object. #' @param values A list of arguments to the atom. #' @describeIn MaxEntries The largest entry in \code{x}. setMethod("to_numeric", "MaxEntries", function(object, values) { apply_with_keepdims(values[[1]], max, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn MaxEntries The sign of the atom. setMethod("sign_from_args", "MaxEntries", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) }) #' @describeIn MaxEntries The atom is convex. setMethod("is_atom_convex", "MaxEntries", function(object) { TRUE }) #' @describeIn MaxEntries The atom is not concave. setMethod("is_atom_concave", "MaxEntries", function(object) { FALSE }) #' @describeIn MaxEntries Is the atom log-log convex. setMethod("is_atom_log_log_convex", "MaxEntries", function(object) { TRUE }) #' @describeIn MaxEntries Is the atom log-log concave. setMethod("is_atom_log_log_concave", "MaxEntries", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn MaxEntries The atom is weakly increasing in every argument. setMethod("is_incr", "MaxEntries", function(object, idx) { TRUE }) #' @param idx An index into the atom. #' @describeIn MaxEntries The atom is not weakly decreasing in any argument. setMethod("is_decr", "MaxEntries", function(object, idx) { FALSE }) #' @describeIn MaxEntries Is \code{x} piecewise linear? setMethod("is_pwl", "MaxEntries", function(object) { is_pwl(object@args[[1]]) }) #' @param values A list of numeric values for the arguments #' @describeIn MaxEntries Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MaxEntries", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value #' @describeIn MaxEntries Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "MaxEntries", function(object, value) { # Grad: 1 for a largest index value <- as.vector(value) idx <- (value == max(value)) D <- matrix(0, nrow = length(value), ncol = 1) D[idx,1] <- 1 D }) #' #' The MinEntries class. #' #' The minimum of an expression. #' #' @slot x An \linkS4class{Expression} representing a vector or matrix. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @name MinEntries-class #' @aliases MinEntries #' @rdname MinEntries-class .MinEntries <- setClass("MinEntries", contains = "AxisAtom") #' @param x An \linkS4class{Expression} representing a vector or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname MinEntries-class MinEntries <- function(x, axis = NA_real_, keepdims = FALSE) { .MinEntries(expr = x, axis = axis, keepdims = keepdims) } #' @param object A \linkS4class{MinEntries} object. #' @param values A list of arguments to the atom. #' @describeIn MinEntries The largest entry in \code{x}. setMethod("to_numeric", "MinEntries", function(object, values) { apply_with_keepdims(values[[1]], min, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn MinEntries The sign of the atom. setMethod("sign_from_args", "MinEntries", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) }) #' @describeIn MinEntries The atom is not convex. setMethod("is_atom_convex", "MinEntries", function(object) { FALSE }) #' @describeIn MinEntries The atom is concave. setMethod("is_atom_concave", "MinEntries", function(object) { TRUE }) #' @describeIn MinEntries Is the atom log-log convex? setMethod("is_atom_log_log_convex", "MinEntries", function(object) { FALSE }) #' @describeIn MinEntries Is the atom log-log concave? setMethod("is_atom_log_log_concave", "MinEntries", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn MinEntries The atom is weakly increasing in every argument. setMethod("is_incr", "MinEntries", function(object, idx) { TRUE }) #' @param idx An index into the atom. #' @describeIn MinEntries The atom is not weakly decreasing in any argument. setMethod("is_decr", "MinEntries", function(object, idx) { FALSE }) #' @describeIn MinEntries Is \code{x} piecewise linear? setMethod("is_pwl", "MinEntries", function(object) { is_pwl(object@args[[1]]) }) #' @param values A list of numeric values for the arguments #' @describeIn MinEntries Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MinEntries", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value #' @describeIn MinEntries Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "MinEntries", function(object, value) { # Grad: 1 for a largest index value <- as.vector(value) idx <- (value == min(value)) D <- matrix(0, nrow = length(value), ncol = 1) D[idx,1] <- 1 D }) #' #' The Pnorm class. #' #' This class represents the vector p-norm. #' #' If given a matrix variable, \code{Pnorm} will treat it as a vector and compute the p-norm of the concatenated columns. #' #' For \eqn{p \geq 1}, the p-norm is given by \deqn{\|x\|_p = \left(\sum_{i=1}^n |x_i|^p\right)^{1/p}} with domain \eqn{x \in \mathbf{R}^n}. #' For \eqn{p < 1, p\neq 0}, the p-norm is given by \deqn{\|x\|_p = \left(\sum_{i=1}^n x_i^p\right)^{1/p}} with domain \eqn{x \in \mathbf{R}^n_+}. #' #' \itemize{ #' \item Note that the "p-norm" is actually a \strong{norm} only when \eqn{p \geq 1} or \eqn{p = +\infty}. For these cases, it is convex. #' \item The expression is undefined when \eqn{p = 0}. #' \item Otherwise, when \eqn{p < 1}, the expression is concave, but not a true norm. #' } #' #' @slot x An \linkS4class{Expression} representing a vector or matrix. #' @slot p A number greater than or equal to 1, or equal to positive infinity. #' @slot max_denom The maximum denominator considered in forming a rational approximation for \eqn{p}. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @slot keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @slot .approx_error (Internal) The absolute difference between \eqn{p} and its rational approximation. #' @slot .original_p (Internal) The original input \eqn{p}. #' @name Pnorm-class #' @aliases Pnorm #' @rdname Pnorm-class .Pnorm <- setClass("Pnorm", representation(p = "numeric", max_denom = "numeric", .approx_error = "numeric", .original_p = "numeric"), prototype(p = 2, max_denom = 1024, .approx_error = NA_real_, .original_p = NA_real_), contains = "AxisAtom") #' @param x An \linkS4class{Expression} representing a vector or matrix. #' @param p A number greater than or equal to 1, or equal to positive infinity. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @param max_denom (Optional) The maximum denominator considered in forming a rational approximation for \eqn{p}. The default is 1024. #' @rdname Pnorm-class Pnorm <- function(x, p = 2, axis = NA_real_, keepdims = FALSE, max_denom = 1024) { if(p == 1) Norm1(x, axis = axis, keepdims = keepdims) else if(p %in% c(Inf, "inf", "Inf")) NormInf(x, axis = axis, keepdims = keepdims) else .Pnorm(expr = x, axis = axis, keepdims = keepdims, p = p, max_denom = max_denom) } setMethod("initialize", "Pnorm", function(.Object, ..., p = 2, max_denom = 1024, .approx_error = NA_real_, .original_p = NA_real_) { if(p == 1) stop("Use the Norm1 class to instantiate a 1-norm.") else if(p %in% c(Inf, "inf", "Inf")) stop("Use the NormInf class to instantiate an infinity-norm.") # else if(p < 0) # .Object@p <- pow_neg(p, max_denom) # else if(p > 0 && p < 1) # .Object@p <- pow_mid(p, max_denom) # else if(p > 1) # .Object@p <- pow_high(p, max_denom) # else # stop("Invalid value of p.") .Object@p <- p .Object@max_denom <- max_denom [email protected]_error <- abs(.Object@p - p) [email protected]_p <- p callNextMethod(.Object, ...) }) #' #' Internal method for calculating the p-norm #' #' @param x A matrix #' @param p A number grater than or equal to 1, or equal to positive infinity #' @return Returns the specified norm of matrix x .p_norm <- function(x, p) { if(p == Inf) max(abs(x)) else if(p == 0) sum(x != 0) else if(p %% 2 == 0 || p < 1) sum(x^p)^(1/p) else if(p >= 1) sum(abs(x)^p)^(1/p) else stop("Invalid p = ", p) } #' @describeIn Pnorm Does the atom handle complex numbers? setMethod("allow_complex", "Pnorm", function(object) { TRUE }) #' @param object A \linkS4class{Pnorm} object. #' @param values A list of arguments to the atom. #' @describeIn Pnorm The p-norm of \code{x}. setMethod("to_numeric", "Pnorm", function(object, values) { if(is.na(object@axis)) values <- as.vector(values[[1]]) else values <- as.matrix(values[[1]]) if(object@p < 1 && any(values < 0)) return(-Inf) if(object@p < 0 && any(values == 0)) return(0) apply_with_keepdims(values, function(x) { .p_norm(x, object@p) }, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn Pnorm Check that the arguments are valid. setMethod("validate_args", "Pnorm", function(object) { callNextMethod() if(!is.na(object@axis) && object@p != 2) stop("The axis parameter is only supported for p = 2.") if(object@p < 1 && is_complex(object@args[[1]])) stop("Pnorm(x, p) cannot have x complex for p < 1.") }) #' @describeIn Pnorm The atom is positive. setMethod("sign_from_args", "Pnorm", function(object) { c(TRUE, FALSE) }) #' @describeIn Pnorm The atom is convex if \eqn{p \geq 1}. setMethod("is_atom_convex", "Pnorm", function(object) { object@p > 1 }) #' @describeIn Pnorm The atom is concave if \eqn{p < 1}. setMethod("is_atom_concave", "Pnorm", function(object) { object@p < 1 }) #' @describeIn Pnorm Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Pnorm", function(object) { TRUE }) #' @describeIn Pnorm Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Pnorm", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Pnorm The atom is weakly increasing if \eqn{p < 1} or \eqn{p > 1} and \code{x} is positive. setMethod("is_incr", "Pnorm", function(object, idx) { object@p < 1 || (object@p > 1 && is_nonneg(object@args[[1]])) }) #' @param idx An index into the atom. #' @describeIn Pnorm The atom is weakly decreasing if \eqn{p > 1} and \code{x} is negative. setMethod("is_decr", "Pnorm", function(object, idx) { object@p > 1 && is_nonpos(object@args[[1]]) }) #' @describeIn Pnorm The atom is not piecewise linear unless \eqn{p = 1} or \eqn{p = \infty}. setMethod("is_pwl", "Pnorm", function(object) { FALSE }) #' @describeIn Pnorm Returns \code{list(p, axis)}. setMethod("get_data", "Pnorm", function(object) { list(object@p, object@axis) }) #' @describeIn Pnorm The name and arguments of the atom. setMethod("name", "Pnorm", function(x) { sprintf("%s(%s, %s)", class(x), name(x@args[[1]]), x@p) }) #' @describeIn Pnorm Returns constraints describing the domain of the node setMethod(".domain", "Pnorm", function(object) { if(object@p < 1 && object@p != 0) list(object@args[[1]] >= 0) else list() }) #' @param values A list of numeric values for the arguments #' @describeIn Pnorm Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Pnorm", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value #' @describeIn Pnorm Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "Pnorm", function(object, value) { rows <- size(object@args[[1]]) value <- as.matrix(value) # Outside domain if(object@p < 1 && any(value <= 0)) return(NA_real_) D_null <- sparseMatrix(i = c(), j = c(), dims = c(rows, 1)) denominator <- .p_norm(value, object@p) denominator <- denominator^(object@p - 1) # Subgrad is 0 when denom is 0 (or undefined) if(denominator == 0) { if(object@p > 1) return(D_null) else return(NA_real_) } else { numerator <- value^(object@p - 1) frac <- numerator / denominator return(matrix(as.vector(frac))) } }) #' #' The MixedNorm atom. #' #' The \eqn{l_{p,q}} norm of X, \eqn{(\sum_k (\sum_l ||X_{k,l}||^p)^{q/p})^{1/q}}. #' #' @param X The matrix to take the \eqn{l_{p,q}} norm of #' @param p The type of inner norm #' @param q The type of outer norm #' @return Returns the mixed norm of X with specified parameters p and q MixedNorm <- function(X, p = 2, q = 1) { X <- as.Constant(X) # Inner norms vecnorms <- Norm(X, p, axis = 1) # Outer norms Norm(vecnorms, q) } #' #' The Norm atom. #' #' Wrapper around the different norm atoms. #' #' @param x The matrix to take the norm of #' @param p The type of norm. Valid options include any positive integer, 'fro' (for frobenius), #' 'nuc' (sum of singular values), np.inf or 'inf' (infinity norm). #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return Returns the specified norm of x. #' @rdname Norm-atom Norm <- function(x, p = 2, axis = NA_real_, keepdims = FALSE) { x <- as.Constant(x) # Matrix norms take precedence. num_nontrivial_idxs <- sum(dim(x) > 1) if(is.na(axis) && ndim(x) == 2) { if(p == 1) # Matrix 1-norm. MaxEntries(Norm1(x, axis = 2)) else if(p == "fro" || (p == 2 && num_nontrivial_idxs == 1)) # Frobenius norm. Pnorm(Vec(x), 2) else if(p == 2) # Matrix 2-norm is largest singular value. SigmaMax(x) else if(p == "nuc") # The nuclear norm (sum of singular values) NormNuc(x) else if(p %in% c(Inf, "inf", "Inf")) # The matrix infinity-norm. MaxEntries(Norm1(x, axis = 1)) else stop("Unsupported matrix norm.") } else { if(p == 1 || is_scalar(x)) Norm1(x, axis = axis, keepdims = keepdims) else if(p %in% c(Inf, "inf", "Inf")) NormInf(x, axis = axis, keepdims = keepdims) else Pnorm(x, p, axis = axis, keepdims = keepdims) } } #' #' The Norm2 atom. #' #' The 2-norm of an expression. #' #' @param x An \linkS4class{Expression} object. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return Returns the 2-norm of x. #' @rdname Norm2-atom Norm2 <- function(x, axis = NA_real_, keepdims = FALSE) { Pnorm(x, p = 2, axis = axis, keepdims = keepdims) } #' #' The Norm1 class. #' #' This class represents the 1-norm of an expression. #' #' @slot x An \linkS4class{Expression} object. #' @name Norm1-class #' @aliases Norm1 #' @rdname Norm1-class .Norm1 <- setClass("Norm1", contains = "AxisAtom") #' @param x An \linkS4class{Expression} object. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname Norm1-class Norm1 <- function(x, axis = NA_real_, keepdims = FALSE) { .Norm1(expr = x, axis = axis, keepdims = keepdims) } #' @param object A \linkS4class{Norm1} object. #' @describeIn Norm1 The name and arguments of the atom. setMethod("name", "Norm1", function(x) { paste(class(x), "(", name(x@args[[1]]), ")", sep = "") }) #' @param values A list of arguments to the atom. #' @describeIn Norm1 Returns the 1-norm of x along the given axis. setMethod("to_numeric", "Norm1", function(object, values) { if(is.na(object@axis)) # base::norm(values[[1]], type = "O") sum(abs(values[[1]])) else # apply_with_keepdims(values[[1]], function(x) { norm(as.matrix(x), type = "O") }, axis = object@axis, keepdims = object@keepdims) apply_with_keepdims(values[[1]], function(x) { sum(abs(x)) }, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn Norm1 Does the atom handle complex numbers? setMethod("allow_complex", "Norm1", function(object) { TRUE }) #' @describeIn Norm1 The atom is always positive. setMethod("sign_from_args", "Norm1", function(object) { c(TRUE, FALSE) }) #' @describeIn Norm1 The atom is convex. setMethod("is_atom_convex", "Norm1", function(object) { TRUE }) #' @describeIn Norm1 The atom is not concave. setMethod("is_atom_concave", "Norm1", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Norm1 Is the composition weakly increasing in argument \code{idx}? setMethod("is_incr", "Norm1", function(object, idx) { is_nonneg(object@args[[1]]) }) #' @param idx An index into the atom. #' @describeIn Norm1 Is the composition weakly decreasing in argument \code{idx}? setMethod("is_decr", "Norm1", function(object, idx) { is_nonpos(object@args[[1]]) }) #' @describeIn Norm1 Is the atom piecewise linear? setMethod("is_pwl", "Norm1", function(object) { is_pwl(object@args[[1]]) && (is_real(object@args[[1]]) || is_imag(object@args[[1]])) }) #' @describeIn Norm1 Returns the axis. setMethod("get_data", "Norm1", function(object) { list(object@axis) }) #' @describeIn Norm1 Returns constraints describing the domain of the node setMethod(".domain", "Norm1", function(object) { list() }) #' @param values A list of numeric values for the arguments #' @describeIn Norm1 Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Norm1", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value #' @describeIn Norm1 Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "Norm1", function(object, value) { rows <- size(object@args[[1]]) D_null <- Matrix(0, nrow = rows, ncol = 1, sparse = TRUE) D_null <- D_null + (value > 0) D_null <- D_null - (value < 0) D_null # TODO: Check this is same as ravel and transpose command in CVXPY. }) #' #' The NormInf class. #' #' This class represents the infinity-norm. #' #' @name NormInf-class #' @aliases NormInf #' @rdname NormInf-class .NormInf <- setClass("NormInf", contains = "AxisAtom") NormInf <- function(x, axis = NA_real_, keepdims = FALSE) { .NormInf(expr = x, axis = axis, keepdims = keepdims) } #' @param x,object A \linkS4class{NormInf} object. #' @describeIn NormInf The name and arguments of the atom. setMethod("name", "NormInf", function(x) { paste(class(x), "(", name(x@args[[1]]), ")", sep = "") }) #' @describeIn NormInf Returns the infinity norm of \code{x}. setMethod("to_numeric", "NormInf", function(object, values) { if(is.na(object@axis)) # base::norm(values[[1]], type = "I") max(abs(values[[1]])) else # apply_with_keepdims(values[[1]], function(x) { norm(as.matrix(x), type = "I") }, axis = object@axis, keepdims = object@keepdims) apply_with_keepdims(values[[1]], function(x) { max(abs(x)) }, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn NormInf Does the atom handle complex numbers? setMethod("allow_complex", "NormInf", function(object) { TRUE }) #' @describeIn NormInf The atom is always positive. setMethod("sign_from_args", "NormInf", function(object) { c(TRUE, FALSE) }) #' @describeIn NormInf The atom is convex. setMethod("is_atom_convex", "NormInf", function(object) { TRUE }) #' @describeIn NormInf The atom is not concave. setMethod("is_atom_concave", "NormInf", function(object) { FALSE }) #' @describeIn NormInf Is the atom log-log convex? setMethod("is_atom_log_log_convex", "NormInf", function(object) { TRUE }) #' @describeIn NormInf Is the atom log-log concave? setMethod("is_atom_log_log_concave", "NormInf", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn NormInf Is the composition weakly increasing in argument \code{idx}? setMethod("is_incr", "NormInf", function(object, idx) { is_nonneg(object@args[[1]]) }) #' @param idx An index into the atom. #' @describeIn NormInf Is the composition weakly decreasing in argument \code{idx}? setMethod("is_decr", "NormInf", function(object, idx) { is_nonpos(object@args[[1]]) }) #' @describeIn NormInf Is the atom piecewise linear? setMethod("is_pwl", "NormInf", function(object) { is_pwl(object@args[[1]]) }) #' @describeIn NormInf Returns the axis. setMethod("get_data", "NormInf", function(object) { list(object@axis) }) #' @describeIn NormInf Returns constraints describing the domain of the node setMethod(".domain", "NormInf", function(object) { list() }) #' @param values A list of numeric values for the arguments #' @describeIn NormInf Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "NormInf", function(object, values) { .axis_grad(object, values) }) #' @param value A numeric value #' @describeIn NormInf Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "NormInf", function(object, value) { stop("Unimplemented") }) # TODO: Implement this! }) #' #' The NormNuc class. #' #' The nuclear norm, i.e. sum of the singular values of a matrix. #' #' @slot A An \linkS4class{Expression} or numeric matrix. #' @name NormNuc-class #' @aliases NormNuc #' @rdname NormNuc-class .NormNuc <- setClass("NormNuc", representation(A = "ConstValORExpr"), contains = "Atom") #' @param A An \linkS4class{Expression} or numeric matrix. #' @rdname NormNuc-class NormNuc <- function(A) { .NormNuc(A = A) } setMethod("initialize", "NormNuc", function(.Object, ..., A) { .Object@A <- A callNextMethod(.Object, ..., atom_args = list(.Object@A)) }) #' @param object A \linkS4class{NormNuc} object. #' @param values A list of arguments to the atom. #' @describeIn NormNuc The nuclear norm (i.e., the sum of the singular values) of \code{A}. setMethod("to_numeric", "NormNuc", function(object, values) { # Returns the nuclear norm (i.e. the sum of the singular values) of A sum(svd(values[[1]])$d) }) #' @describeIn NormNuc Does the atom handle complex numbers? setMethod("allow_complex", "NormNuc", function(object) { TRUE }) #' @describeIn NormNuc The atom is a scalar. setMethod("dim_from_args", "NormNuc", function(object) { c(1,1) }) #' @describeIn NormNuc The atom is positive. setMethod("sign_from_args", "NormNuc", function(object) { c(TRUE, FALSE) }) #' @describeIn NormNuc The atom is convex. setMethod("is_atom_convex", "NormNuc", function(object) { TRUE }) #' @describeIn NormNuc The atom is not concave. setMethod("is_atom_concave", "NormNuc", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn NormNuc The atom is not monotonic in any argument. setMethod("is_incr", "NormNuc", function(object, idx) { FALSE }) #' @param idx An index into the atom. #' @describeIn NormNuc The atom is not monotonic in any argument. setMethod("is_decr", "NormNuc", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn NormNuc Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "NormNuc", function(object, values) { # Grad: UV^T s <- svd(values[[1]]) D <- s$u %*% t(s$v) list(Matrix(as.vector(D), sparse = TRUE)) }) #' #' The OneMinusPos class. #' #' This class represents the difference \eqn{1 - x} with domain \eqn{\{x : 0 < x < 1}\} #' #' @slot x An \linkS4class{Expression} or numeric matrix. #' @name OneMinusPos-class #' @aliases OneMinusPos #' @rdname OneMinusPos-class .OneMinusPos <- setClass("OneMinusPos", representation(x = "ConstValORExpr", .ones = "ConstVal"), prototype(.ones = NA_real_), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric matrix. #' @rdname OneMinusPos-class OneMinusPos <- function(x) { .OneMinusPos(x = x) } setMethod("initialize", "OneMinusPos", function(.Object, ..., x) { .Object@x <- x [email protected] <- matrix(1, nrow = nrow(x), ncol = ncol(x)) .Object <- callNextMethod(.Object, ..., atom_args = list(.Object@x)) .Object@args[[1]] <- x .Object }) #' @describeIn OneMinusPos The name and arguments of the atom. setMethod("name", "OneMinusPos", function(x) { paste(class(x), x@args[[1]]) }) #' @param object A \linkS4class{OneMinusPos} object. #' @param values A list of arguments to the atom. #' @describeIn OneMinusPos Returns one minus the value. setMethod("to_numeric", "OneMinusPos", function(object, values) { [email protected] - values[[1]] }) #' @describeIn OneMinusPos The dimensions of the atom. setMethod("dim_from_args", "OneMinusPos", function(object) { dim(object@args[[1]]) }) #' @describeIn OneMinusPos Returns the sign (is positive, is negative) of the atom. setMethod("sign_from_args", "OneMinusPos", function(object) { c(TRUE, FALSE) }) #' @describeIn OneMinusPos Is the atom convex? setMethod("is_atom_convex", "OneMinusPos", function(object) { FALSE }) #' @describeIn OneMinusPos Is the atom concave? setMethod("is_atom_concave", "OneMinusPos", function(object) { FALSE }) #' @describeIn OneMinusPos Is the atom log-log convex? setMethod("is_atom_log_log_convex", "OneMinusPos", function(object) { FALSE }) #' @describeIn OneMinusPos Is the atom log-log concave? setMethod("is_atom_log_log_concave", "OneMinusPos", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn OneMinusPos Is the atom weakly increasing in the argument \code{idx}? setMethod("is_incr", "OneMinusPos", function(object, idx) { FALSE }) #' @param idx An index into the atom. #' @describeIn OneMinusPos Is the atom weakly decreasing in the argument \code{idx}? setMethod("is_decr", "OneMinusPos", function(object, idx) { TRUE }) #' @param values A list of numeric values for the arguments #' @describeIn OneMinusPos Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "OneMinusPos", function(object, values) { Matrix([email protected], sparse = TRUE) }) #' #' The DiffPos atom. #' #' The difference between expressions, \eqn{x - y}, where \eqn{x > y > 0}. #' #' @param x An \linkS4class{Expression} #' @param y An \linkS4class{Expression} #' @return The difference \eqn{x - y} with domain \eqn{x,y: x > y > 0}. DiffPos <- function(x, y) { x * OneMinusPos(y/x) } #' #' The PfEigenvalue class. #' #' This class represents the Perron-Frobenius eigenvalue of a positive matrix. #' #' @slot X An \linkS4class{Expression} or numeric matrix. #' @name PfEigenvalue-class #' @aliases PfEigenvalue #' @rdname PfEigenvalue-class .PfEigenvalue <- setClass("PfEigenvalue", representation(X = "ConstValORExpr"), validity = function(object) { if(length(dim(object@X)) != 2 || nrow(object@X) != ncol(object@X)) stop("[PfEigenvalue: X] The argument X must be a square matrix") return(TRUE) }, contains = "Atom") #' @param X An \linkS4class{Expression} or numeric matrix. #' @rdname PfEigenvalue-class PfEigenvalue <- function(X) { .PfEigenvalue(X = X) } setMethod("initialize", "PfEigenvalue", function(.Object, ..., X = X) { .Object@X <- X .Object <- callNextMethod(.Object, ..., atom_args = list(.Object@X)) .Object@args[[1]] <- X .Object }) #' @param x,object A \linkS4class{PfEigenvalue} object. #' @describeIn PfEigenvalue The name and arguments of the atom. setMethod("name", "PfEigenvalue", function(x) { paste(class(x), x@args[[1]]) }) #' @param values A list of arguments to the atom. #' @describeIn PfEigenvalue Returns the Perron-Frobenius eigenvalue of \code{X}. setMethod("to_numeric", "PfEigenvalue", function(object, values) { eig <- eigen(values[[1]], only.values = TRUE) max(abs(eig$values)) }) #' @describeIn PfEigenvalue The dimensions of the atom. setMethod("dim_from_args", "PfEigenvalue", function(object) { c(1,1) }) #' @describeIn PfEigenvalue Returns the sign (is positive, is negative) of the atom. setMethod("sign_from_args", "PfEigenvalue", function(object) { c(TRUE, FALSE) }) #' @describeIn PfEigenvalue Is the atom convex? setMethod("is_atom_convex", "PfEigenvalue", function(object) { FALSE }) #' @describeIn PfEigenvalue Is the atom concave? setMethod("is_atom_concave", "PfEigenvalue", function(object) { FALSE }) #' @describeIn PfEigenvalue Is the atom log-log convex? setMethod("is_atom_log_log_convex", "PfEigenvalue", function(object) { TRUE }) #' @describeIn PfEigenvalue Is the atom log-log concave? setMethod("is_atom_log_log_concave", "PfEigenvalue", function(object) { FALSE }) # TODO: Figure out monotonicity. #' @param idx An index into the atom. #' @describeIn PfEigenvalue Is the atom weakly increasing in the argument \code{idx}? setMethod("is_incr", "PfEigenvalue", function(object, idx) { FALSE }) #' @param idx An index into the atom. #' @describeIn PfEigenvalue Is the atom weakly decreasing in the argument \code{idx}? setMethod("is_decr", "PfEigenvalue", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn PfEigenvalue Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "PfEigenvalue", function(object, values) { NA_real_ }) #' #' The ProdEntries class. #' #' The product of the entries in an expression. #' #' @slot expr An \linkS4class{Expression} representing a vector or matrix. #' @slot axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @name ProdEntries-class #' @aliases ProdEntries #' @rdname ProdEntries-class .ProdEntries <- setClass("ProdEntries", contains = "AxisAtom") #' @param ... \linkS4class{Expression} objects, vectors, or matrices. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @rdname ProdEntries-class ProdEntries <- function(..., axis = NA_real_, keepdims = FALSE) { exprs <- list(...) if(length(exprs) == 0) stop("Must provide at least one expression") else if(length(exprs) == 1) .ProdEntries(expr = exprs[[1]], axis = axis, keepdims = keepdims) else .ProdEntries(expr = do.call("HStack", exprs)) } #' @param object A \linkS4class{ProdEntries} object. #' @param values A list of values to take the product of. #' @describeIn ProdEntries The product of all the entries. setMethod("to_numeric", "ProdEntries", function(object, values) { apply_with_keepdims(values[[1]], prod, axis = object@axis, keepdims = object@keepdims) }) #' @describeIn ProdEntries Returns the sign (is positive, is negative) of the atom. setMethod("sign_from_args", "ProdEntries", function(object) { if(is_nonneg(object@args[[1]])) c(TRUE, FALSE) else c(FALSE, FALSE) }) #' @describeIn ProdEntries Is the atom convex? setMethod("is_atom_convex", "ProdEntries", function(object) { FALSE }) #' @describeIn ProdEntries Is the atom concave? setMethod("is_atom_concave", "ProdEntries", function(object) { FALSE }) #' @describeIn ProdEntries Is the atom log-log convex? setMethod("is_atom_log_log_convex", "ProdEntries", function(object) { TRUE }) #' @describeIn ProdEntries is the atom log-log concave? setMethod("is_atom_log_log_concave", "ProdEntries", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn ProdEntries Is the atom weakly increasing in the argument \code{idx}? setMethod("is_incr", "ProdEntries", function(object, idx) { is_nonneg(object@args[[1]]) }) #' @param idx An index into the atom. #' @describeIn ProdEntries Is the atom weakly decreasing in the argument \code{idx}? setMethod("is_decr", "ProdEntries", function(object, idx) { FALSE }) #' @param value A numeric value. #' @describeIn ProdEntries Gives the (sub/super)gradient of the atom w.r.t. each column variable setMethod(".column_grad", "ProdEntries", function(object, value) { prod(value)/value }) #' @param values A list of numeric values for the arguments #' @describeIn ProdEntries Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "ProdEntries", function(object, values) { .axis_grad(object, values) }) #' #' The QuadForm class. #' #' This class represents the quadratic form \eqn{x^T P x} #' #' @slot x An \linkS4class{Expression} or numeric vector. #' @slot P An \linkS4class{Expression}, numeric matrix, or vector. #' @name QuadForm-class #' @aliases QuadForm #' @rdname QuadForm-class .QuadForm <- setClass("QuadForm", representation(x = "ConstValORExpr", P = "ConstValORExpr"), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric vector. #' @param P An \linkS4class{Expression}, numeric matrix, or vector. #' @rdname QuadForm-class QuadForm <- function(x, P) { .QuadForm(x = x, P = P) } setMethod("initialize", "QuadForm", function(.Object, ..., x, P) { .Object@x <- x .Object@P <- P callNextMethod(.Object, ..., atom_args = list(.Object@x, .Object@P)) }) #' @describeIn QuadForm The name and arguments of the atom. setMethod("name", "QuadForm", function(x) { paste(class(x), "(", x@args[[1]], ", ", x@args[[2]], ")", sep = "") }) #' @param object A \linkS4class{QuadForm} object. #' @describeIn QuadForm Does the atom handle complex numbers? setMethod("allow_complex", "QuadForm", function(object) { TRUE }) #' @param values A list of numeric values for the arguments #' @describeIn QuadForm Returns the quadratic form. setMethod("to_numeric", "QuadForm", function(object, values) { prod <- values[[2]] %*% values[[1]] if(is_complex(object@args[[1]])) return(t(Conj(values[[1]])) %*% prod) else return(t(values[[1]]) %*% prod) }) #' @describeIn QuadForm Checks the dimensions of the arguments. setMethod("validate_args", "QuadForm", function(object) { callNextMethod() n <- nrow(object@args[[2]]) x_dim <- dim(object@args[[1]]) # if(ncol(object@args[[2]]) != n || !(dim(object@args[[1]]) %in% list(c(n, 1), c(n, NA_real_)))) if(ncol(object@args[[2]]) != n || !(length(x_dim) == 2 && all(x_dim == c(n,1)))) stop("Invalid dimensions for arguments.") }) #' @describeIn QuadForm Returns the sign (is positive, is negative) of the atom. setMethod("sign_from_args", "QuadForm", function(object) { c(is_atom_convex(object), is_atom_concave(object)) }) #' @describeIn QuadForm The dimensions of the atom. setMethod("dim_from_args", "QuadForm", function(object) { # if(ndim(object@args[[1]]) == 0) # c() # else # c(1,1) c(1,1) }) #' @describeIn QuadForm Is the atom convex? setMethod("is_atom_convex", "QuadForm", function(object) { is_psd(object@args[[2]]) }) #' @describeIn QuadForm Is the atom concave? setMethod("is_atom_concave", "QuadForm", function(object) { is_nsd(object@args[[2]]) }) #' @describeIn QuadForm Is the atom log-log convex? setMethod("is_atom_log_log_convex", "QuadForm", function(object) { TRUE }) #' @describeIn QuadForm Is the atom log-log concave? setMethod("is_atom_log_log_concave", "QuadForm", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn QuadForm Is the atom weakly increasing in the argument \code{idx}? setMethod("is_incr", "QuadForm", function(object, idx) { (is_nonneg(object@args[[1]]) && is_nonneg(object@args[[2]])) || (is_nonpos(object@args[[1]]) && is_nonneg(object@args[[2]])) }) #' @param idx An index into the atom. #' @describeIn QuadForm Is the atom weakly decreasing in the argument \code{idx}? setMethod("is_decr", "QuadForm", function(object, idx) { (is_nonneg(object@args[[1]]) && is_nonpos(object@args[[2]])) || (is_nonpos(object@args[[1]]) && is_nonpos(object@args[[2]])) }) #' @describeIn QuadForm Is the atom quadratic? setMethod("is_quadratic", "QuadForm", function(object) { TRUE }) #' @describeIn QuadForm Is the atom piecewise linear? setMethod("is_pwl", "QuadForm", function(object) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn QuadForm Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "QuadForm", function(object, values) { x <- values[[1]] P <- values[[2]] D <- 2*P %*% t(x) Matrix(as.vector(t(D)), sparse = TRUE) }) #' #' The SymbolicQuadForm class. #' #' @slot x An \linkS4class{Expression} or numeric vector. #' @slot P An \linkS4class{Expression}, numeric matrix, or vector. #' @slot original_expression The original \linkS4class{Expression}. #' @name SymbolicQuadForm-class #' @aliases SymbolicQuadForm #' @rdname SymbolicQuadForm-class .SymbolicQuadForm <- setClass("SymbolicQuadForm", representation(x = "ConstValORExpr", P = "ConstValORExpr", original_expression = "Expression"), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric vector. #' @param P An \linkS4class{Expression}, numeric matrix, or vector. #' @param expr The original \linkS4class{Expression}. #' @rdname SymbolicQuadForm-class SymbolicQuadForm <- function(x, P, expr) { .SymbolicQuadForm(x = x, P = P, original_expression = expr) } setMethod("initialize", "SymbolicQuadForm", function(.Object, ..., x, P, original_expression) { .Object@x <- x .Object@original_expression <- original_expression .Object <- callNextMethod(.Object, ..., atom_args = list(x, P), validate = FALSE) .Object@P <- .Object@args[[2]] validObject(.Object) .Object }) #' @param object A \linkS4class{SymbolicQuadForm} object. #' @describeIn SymbolicQuadForm The dimensions of the atom. setMethod("dim_from_args", "SymbolicQuadForm", function(object) { dim_from_args(object@original_expression) }) #' @describeIn SymbolicQuadForm The sign (is positive, is negative) of the atom. setMethod("sign_from_args", "SymbolicQuadForm", function(object) { sign_from_args(object@original_expression) }) #' @describeIn SymbolicQuadForm The original expression. setMethod("get_data", "SymbolicQuadForm", function(object) { list(object@original_expression) }) #' @describeIn SymbolicQuadForm Is the original expression convex? setMethod("is_atom_convex", "SymbolicQuadForm", function(object) { is_atom_convex(object@original_expression) }) #' @describeIn SymbolicQuadForm Is the original expression concave? setMethod("is_atom_concave", "SymbolicQuadForm", function(object) { is_atom_concave(object@original_expression) }) #' @param idx An index into the atom. #' @describeIn SymbolicQuadForm Is the original expression weakly increasing in argument \code{idx}? setMethod("is_incr", "SymbolicQuadForm", function(object, idx) { is_incr(object@original_expression, idx) }) #' @describeIn SymbolicQuadForm Is the original expression weakly decreasing in argument \code{idx}? setMethod("is_decr", "SymbolicQuadForm", function(object, idx) { is_decr(object@original_expression, idx) }) #' @describeIn SymbolicQuadForm The atom is quadratic. setMethod("is_quadratic", "SymbolicQuadForm", function(object) { TRUE }) #' @param values A list of numeric values for the arguments #' @describeIn SymbolicQuadForm Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "SymbolicQuadForm", function(object, values) { stop("Unimplemented") }) #' #' Compute a Matrix Decomposition. #' #' Compute sgn, scale, M such that \eqn{P = sgn * scale * dot(M, t(M))}. #' #' @param P A real symmetric positive or negative (semi)definite input matrix #' @param cond Cutoff for small eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered negligible. #' @param rcond Cutoff for small eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered negligible. #' @return A list consisting of induced matrix 2-norm of P and a rectangular matrix such that P = scale * (dot(M1, t(M1)) - dot(M2, t(M2))) .decomp_quad <- function(P, cond = NA, rcond = NA) { eig <- eigen(P, only.values = FALSE) w <- eig$values V <- eig$vectors if(!is.na(rcond)) cond <- rcond if(cond == -1 || is.na(cond)) cond <- 1e6 * .Machine$double.eps # All real numbers are stored as double precision in R scale <- max(abs(w)) if(scale < cond) return(list(scale = 0, M1 = V[,FALSE], M2 = V[,FALSE])) w_scaled <- w / scale maskp <- w_scaled > cond maskn <- w_scaled < -cond # TODO: Allow indefinite QuadForm if(any(maskp) && any(maskn)) warning("Forming a non-convex expression QuadForm(x, indefinite)") if(sum(maskp) <= 1) M1 <- as.matrix(V[,maskp] * sqrt(w_scaled[maskp])) else M1 <- V[,maskp] %*% diag(sqrt(w_scaled[maskp])) if(sum(maskn) <= 1) M2 <- as.matrix(V[,maskn]) * sqrt(-w_scaled[maskn]) else M2 <- V[,maskn] %*% diag(sqrt(-w_scaled[maskn])) list(scale = scale, M1 = M1, M2 = M2) } #' #' The QuadOverLin class. #' #' This class represents the sum of squared entries in X divided by a scalar y, \eqn{\sum_{i,j} X_{i,j}^2/y}. #' #' @slot x An \linkS4class{Expression} or numeric matrix. #' @slot y A scalar \linkS4class{Expression} or numeric constant. #' @name QuadOverLin-class #' @aliases QuadOverLin #' @rdname QuadOverLin-class .QuadOverLin <- setClass("QuadOverLin", representation(x = "ConstValORExpr", y = "ConstValORExpr"), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric matrix. #' @param y A scalar \linkS4class{Expression} or numeric constant. #' @rdname QuadOverLin-class QuadOverLin <- function(x, y) { .QuadOverLin(x = x, y = y) } setMethod("initialize", "QuadOverLin", function(.Object, ..., x, y) { .Object@x <- x .Object@y <- y callNextMethod(.Object, ..., atom_args = list(.Object@x, .Object@y)) }) #' @describeIn QuadOverLin Does the atom handle complex numbers? setMethod("allow_complex", "QuadOverLin", function(object) { TRUE }) #' @param object A \linkS4class{QuadOverLin} object. #' @param values A list of arguments to the atom. #' @describeIn QuadOverLin The sum of the entries of \code{x} squared over \code{y}. setMethod("to_numeric", "QuadOverLin", function(object, values) { sum(Mod(values[[1]])^2) / values[[2]] }) #' @describeIn QuadOverLin Check the dimensions of the arguments. setMethod("validate_args", "QuadOverLin", function(object) { if(!is_scalar(object@args[[2]])) stop("The second argument to QuadOverLin must be a scalar.") if(is_complex(object@args[[2]])) stop("The second argument to QuadOverLin cannot be complex.") callNextMethod() }) #' @describeIn QuadOverLin The atom is a scalar. setMethod("dim_from_args", "QuadOverLin", function(object) { c(1,1) }) #' @describeIn QuadOverLin The atom is positive. setMethod("sign_from_args", "QuadOverLin", function(object) { c(TRUE, FALSE) }) #' @describeIn QuadOverLin The atom is convex. setMethod("is_atom_convex", "QuadOverLin", function(object) { TRUE }) #' @describeIn QuadOverLin The atom is not concave. setMethod("is_atom_concave", "QuadOverLin", function(object) { FALSE }) #' @describeIn QuadOverLin Is the atom log-log convex? setMethod("is_atom_log_log_convex", "QuadOverLin", function(object) { TRUE }) #' @describeIn QuadOverLin Is the atom log-log concave? setMethod("is_atom_log_log_concave", "QuadOverLin", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn QuadOverLin A logical value indicating whether the atom is weakly increasing in argument \code{idx}. setMethod("is_incr", "QuadOverLin", function(object, idx) { (idx == 1) && is_nonneg(object@args[[idx]]) }) #' @describeIn QuadOverLin A logical value indicating whether the atom is weakly decreasing in argument \code{idx}. setMethod("is_decr", "QuadOverLin", function(object, idx) { ((idx == 1) && is_nonpos(object@args[[idx]])) || (idx == 2) }) #' @describeIn QuadOverLin Quadratic if \code{x} is affine and \code{y} is constant. setMethod("is_quadratic", "QuadOverLin", function(object) { is_affine(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn QuadOverLin Quadratic of piecewise affine if \code{x} is piecewise linear and \code{y} is constant. setMethod("is_qpwa", "QuadOverLin", function(object) { is_pwl(object@args[[1]]) && is_constant(object@args[[2]]) }) #' @describeIn QuadOverLin Returns constraints describing the domain of the node setMethod(".domain", "QuadOverLin", function(object) { list(object@args[[2]] >= 0) }) #' @param values A list of numeric values for the arguments #' @describeIn QuadOverLin Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "QuadOverLin", function(object, values) { X <- values[[1]] y <- as.vector(values[[2]]) if(y <= 0) return(list(NA_real_, NA_real_)) else { # DX = 2X/y, Dy = -||X||^2_2/y^2 Dy <- -sum(Mod(X)^2)/y^2 Dy <- Matrix(Dy, sparse = TRUE) DX <- 2.0*X/y DX <- Matrix(as.vector(t(DX)), sparse = TRUE) return(list(DX, Dy)) } }) #' #' The SigmaMax class. #' #' The maximum singular value of a matrix. #' #' @slot A An \linkS4class{Expression} or numeric matrix. #' @name SigmaMax-class #' @aliases SigmaMax #' @rdname SigmaMax-class .SigmaMax <- setClass("SigmaMax", representation(A = "ConstValORExpr"), contains = "Atom") #' @param A An \linkS4class{Expression} or matrix. #' @rdname SigmaMax-class SigmaMax <- function(A = A) { .SigmaMax(A = A) } setMethod("initialize", "SigmaMax", function(.Object, ..., A) { .Object@A <- A callNextMethod(.Object, ..., atom_args = list(.Object@A)) }) #' @param object A \linkS4class{SigmaMax} object. #' @param values A list of arguments to the atom. #' @describeIn SigmaMax The largest singular value of \code{A}. setMethod("to_numeric", "SigmaMax", function(object, values) { base::norm(values[[1]], type = "2") }) #' @describeIn SigmaMax Does the atom handle complex numbers? setMethod("allow_complex", "SigmaMax", function(object) { TRUE }) #' @describeIn SigmaMax The atom is a scalar. setMethod("dim_from_args", "SigmaMax", function(object) { c(1,1) }) #' @describeIn SigmaMax The atom is positive. setMethod("sign_from_args", "SigmaMax", function(object) { c(TRUE, FALSE) }) #' @describeIn SigmaMax The atom is convex. setMethod("is_atom_convex", "SigmaMax", function(object) { TRUE }) #' @describeIn SigmaMax The atom is concave. setMethod("is_atom_concave", "SigmaMax", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn SigmaMax The atom is not monotonic in any argument. setMethod("is_incr", "SigmaMax", function(object, idx) { FALSE }) #' @describeIn SigmaMax The atom is not monotonic in any argument. setMethod("is_decr", "SigmaMax", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn SigmaMax Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "SigmaMax", function(object, values) { # Grad: U diag(e_1) t(V) s <- svd(values[[1]]) ds <- rep(0, length(s$d)) ds[1] <- 1 D <- s$u %*% diag(ds) %*% t(s$v) list(Matrix(as.vector(D), sparse = TRUE)) }) #' #' The SumLargest class. #' #' The sum of the largest k values of a matrix. #' #' @slot x An \linkS4class{Expression} or numeric matrix. #' @slot k The number of largest values to sum over. #' @name SumLargest-class #' @aliases SumLargest #' @rdname SumLargest-class .SumLargest <- setClass("SumLargest", representation(x = "ConstValORExpr", k = "numeric"), contains = "Atom") #' @param x An \linkS4class{Expression} or numeric matrix. #' @param k The number of largest values to sum over. #' @rdname SumLargest-class SumLargest <- function(x, k) { .SumLargest(x = x, k = k) } setMethod("initialize", "SumLargest", function(.Object, ..., x, k) { .Object@x <- x .Object@k <- k callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object A \linkS4class{SumLargest} object. #' @param values A list of arguments to the atom. #' @describeIn SumLargest The sum of the \code{k} largest entries of the vector or matrix. setMethod("to_numeric", "SumLargest", function(object, values) { # Return the sum of the k largest entries of the matrix value <- as.vector(values[[1]]) k <- min(object@k, length(value)) val_sort <- sort(value, decreasing = TRUE) sum(val_sort[1:k]) }) #' @describeIn SumLargest Check that \code{k} is a positive integer. setMethod("validate_args", "SumLargest", function(object) { if(as.integer(object@k) != object@k || object@k <= 0) stop("[SumLargest: validation] k must be a positive integer") callNextMethod() }) #' @describeIn SumLargest The atom is a scalar. setMethod("dim_from_args", "SumLargest", function(object) { c(1,1) }) #' @describeIn SumLargest The sign of the atom. setMethod("sign_from_args", "SumLargest", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) }) #' @describeIn SumLargest The atom is convex. setMethod("is_atom_convex", "SumLargest", function(object) { TRUE }) #' @describeIn SumLargest The atom is not concave. setMethod("is_atom_concave", "SumLargest", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn SumLargest The atom is weakly increasing in every argument. setMethod("is_incr", "SumLargest", function(object, idx) { TRUE }) #' @describeIn SumLargest The atom is not weakly decreasing in any argument. setMethod("is_decr", "SumLargest", function(object, idx) { FALSE }) #' @describeIn SumLargest A list containing \code{k}. setMethod("get_data", "SumLargest", function(object) { list(object@k) }) #' @param values A list of numeric values for the arguments #' @describeIn SumLargest Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "SumLargest", function(object, values) { # Grad: 1 for each of the k largest indices value <- as.vector(t(values[[1]])) k <- min(object@k, length(value)) indices <- order(value, decreasing = TRUE) arg_dim <- dim(object@args[[1]]) D <- matrix(0, nrow = arg_dim[1]*arg_dim[2], ncol = 1) D[indices[1:k]] <- 1 list(Matrix(D, sparse = TRUE)) }) #' #' The SumSmallest atom. #' #' The sum of the smallest k values of a matrix. #' #' @param x An \linkS4class{Expression} or numeric matrix. #' @param k The number of smallest values to sum over. #' @return Sum of the smlalest k values SumSmallest <- function(x, k) { x <- as.Constant(x) -SumLargest(x = -x, k = k) } #' #' The SumSquares atom. #' #' The sum of the squares of the entries. #' #' @param expr An \linkS4class{Expression} or numeric matrix. #' @return Sum of the squares of the entries in the expression. SumSquares <- function(expr) { QuadOverLin(x = expr, y = 1) } #' #' The TotalVariation atom. #' #' The total variation of a vector, matrix, or list of matrices. #' Uses L1 norm of discrete gradients for vectors and L2 norm of discrete gradients for matrices. #' #' @param value An \linkS4class{Expression} representing the value to take the total variation of. #' @param ... Additional matrices extending the third dimension of value. #' @return An expression representing the total variation. TotalVariation <- function(value, ...) { value <- as.Constant(value) if(ndim(value) == 0 || (nrow(value) == 1 && ncol(value) == 1)) stop("TotalVariation cannot take a scalar argument") else if(ndim(value) == 1 || nrow(value) == 1 || ncol(value) == 1) { # L1 norm for vectors if(nrow(value) == 1) value <- t(value) Norm(value[2:nrow(value),1] - value[1:(nrow(value)-1),1], 1) } else { # L2 norm for matrices val_dim <- dim(value) rows <- val_dim[1] cols <- val_dim[2] args <- lapply(list(...), as.Constant) values <- c(list(value), args) diffs <- list() for(mat in values) { if(rows > 1 && cols > 1) { diffs <- c(diffs, list(mat[1:(rows-1), 2:cols] - mat[1:(rows-1), 1:(cols-1)], mat[2:rows, 1:(cols-1)] - mat[1:(rows-1), 1:(cols-1)])) } else { diffs <- c(diffs, list(matrix(0, nrow = rows-1, ncol = cols-1), matrix(0, nrow = rows-1, ncol = cols-1))) } } len <- nrow(diffs[[1]]) * ncol(diffs[[2]]) stacked <- .VStack(atom_args = lapply(diffs, function(diff) { Reshape(diff, c(1, len)) })) SumEntries(Norm(stacked, p = 2, axis = 2)) } }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/atoms.R
## Added format_matrix and set_matrix_data. get_problem_matrix <- function(linOps, id_to_col = integer(0), constr_offsets = integer(0)) { cvxCanon <- CVXcanon$new() lin_vec <- CVXcanon.LinOpVector$new() ## KLUDGE: Anqi, fix id_to_col to have proper names! # if (is.null(names(id_to_col))) names(id_to_col) <- unlist(id_to_col) ## END OF KLUDGE id_to_col_C <- id_to_col ## The following ensures that id_to_col_C is an integer vector ## with names retained. This is the C equivalent of map<int, int> in R storage.mode(id_to_col_C) <- "integer" ##if (any(is.na(id_to_col))) ## id_to_col <- c() ## Loading the variable offsets from our R list into a C++ map ## for (id in names(id_to_col)) { ## col <- id_to_col[[id]] ## id_to_col_C$map(key = as.integer(id), value = as.integer(col)) ## } ## This array keeps variables data in scope after build_lin_op_tree returns tmp <- R6List$new() for (lin in linOps) { tree <- build_lin_op_tree(lin, tmp) tmp$append(tree) lin_vec$push_back(tree) } ## REMOVE this later when we are sure if (typeof(constr_offsets) != "integer") { stop("get_problem_matrix: expecting integer vector for constr_offsets") } if (length(constr_offsets) == 0) problemData <- cvxCanon$build_matrix(lin_vec, id_to_col_C) else { ## Load constraint offsets into a C++ vector ##constr_offsets_C <- CVXCanon.IntVector$new() ##for (offset in constr_offsets) ## constr_offsets_C$push_back(as.integer(offset)) constr_offsets_C <- constr_offsets storage.mode(constr_offsets_C) <- "integer" problemData <- cvxCanon$build_matrix(lin_vec, id_to_col_C, constr_offsets_C) } ## Unpacking ## V <- problemData$getV() ## I <- problemData$getI() ## J <- problemData$getJ() ## const_vec <- problemData$getConstVec() list(V = problemData$getV(), I = problemData$getI(), J = problemData$getJ(), const_vec = matrix(problemData$getConstVec(), ncol = 1)) } format_matrix <- function(matrix, format='dense') { ## Returns the matrix in the appropriate form, ## so that it can be efficiently loaded with our swig wrapper ## TODO: Should we convert bigq/bigz values? What if it's a sparse matrix? if(is.bigq(matrix) || is.bigz(matrix)) { matdbl <- matrix(sapply(matrix, as.double)) dim(matdbl) <- dim(matrix) matrix <- matdbl } if (format == 'dense') { ## Ensure is 2D. as.matrix(matrix) } else if (format == 'sparse') { Matrix::Matrix(matrix, sparse = TRUE) } else if (format == 'scalar') { ## Should this be a 1x1 matrix? YESSSSS as I later found out. as.matrix(matrix) } else { stop(sprintf("format_matrix: format %s unknown", format)) } } set_matrix_data <- function(linC, linR) { ## Calls the appropriate CVXcanon function to set the matrix ## data field of our C++ linOp. if (is.list(linR$data) && linR$data$class == "LinOp") { if (linR$data$type == 'sparse_const') { linC$sparse_data <- format_matrix(linR$data$data, 'sparse') } else if (linR$data$type == 'dense_const') { linC$dense_data <- format_matrix(linR$data$data) } else { stop(sprintf("set_matrix_data: data.type %s unknown", linR$data$type)) } } else { if (linR$type == 'sparse_const') { linC$sparse_data <- format_matrix(linR$data, 'sparse') } else { linC$dense_data <- format_matrix(linR$data) } } } set_slice_data <- function(linC, linR) { ## What does this do? for (i in seq.int(length(linR$data) - 1L)) { ## the last element is "class" sl <- linR$data[[i]] ## In R this is just a vector of ints ## ## Using zero based indexing throughout ## start_idx <- 0L ## if (!is.na(sl$start_idx)) ## start_idx <- sl$start_idx - 1L ## Using zero-based indexing ## stop_idx <- linR$args[[1]]$dim[i] - 1L ## if (!is.na(sl$stop_idx)) ## stop_idx <- sl$stop_idx - 1L ## step <- 1L ## if(!is.na(sl$step)) ## step <- sl$step ## ## handle [::-1] case ## if(step < 0 && is.na(sl$start_idx) && is.na(sl$stop_idx)) { ## tmp <- start ## start_idx <- stop_idx - 1 ## stop_idx <- tmp ## } ##for(var in c(start_idx, stop_idx, step)) ## vec$push_back(var) ## vec <- c(start_idx, stop_idx, step) ## if (length(sl) == 1L) { ## vec <- c(sl - 1L, sl, 1L) ## } else if (length(sl) == 2L) { ## vec <- c(sl[1L] - 1L, sl[2L], 1L) # Using zero-based indexing, and step assumed to be 1. ## } else { ## r <- range(sl) ## vec <- c(r[1L] - 1L, r[2L], 1L) ## } ##vec <- c(sl, 1L) # Using 1-based indexing, and step assumed to be 1. linC$slice_push_back(sl - 1) ## Make indices zero-based for C++ } } build_lin_op_tree <- function(root_linR, tmp, verbose = FALSE) { Q <- Deque$new() root_linC <- CVXcanon.LinOp$new() Q$append(list(linR = root_linR, linC = root_linC)) while(Q$length() > 0) { node <- Q$popleft() linR <- node$linR linC <- node$linC ## Updating the arguments our LinOp ## tmp is a list for(argR in linR$args) { tree <- CVXcanon.LinOp$new() tmp$append(tree) Q$append(list(linR = argR, linC = tree)) linC$args_push_back(tree) } ## Setting the type of our LinOp; at the C level, it is an ENUM! ## Can we avoid this case conversion and use UPPER CASE to match C? linC$type <- toupper(linR$type) ## Check with Anqi ## Setting size linC$size_push_back(as.integer(linR$dim[1])) linC$size_push_back(as.integer(linR$dim[2])) ## Loading the problem data into the approriate array format if(!is.null(linR$data)) { ## if(length(linR$data) == 2 && is(linR$data[1], 'slice')) if (length(linR$data) == 3L && linR$data[[3L]] == 'key') { ## ASK Anqi about this set_slice_data(linC, linR) ## TODO } else if(is.numeric(linR$data) || is.integer(linR$data)) linC$dense_data <- format_matrix(linR$data, 'scalar') else if(linR$data$class == 'LinOp' && linR$data$type == 'scalar_const') linC$dense_data <- format_matrix(linR$data$data, 'scalar') else set_matrix_data(linC, linR) } } root_linC }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/canonInterface.R
#' #' The Canonical class. #' #' This virtual class represents a canonical expression. #' #' @rdname Canonical-class setClass("Canonical", representation(id = "integer", args = "list", validate = "logical"), prototype(id = NA_integer_, args = list(), validate = TRUE), contains = "VIRTUAL") setMethod("initialize", "Canonical", function(.Object, id = NA_integer_, args = list(), validate = TRUE) { .Object@id <- ifelse(is.na(id), get_id(), id) .Object@args <- args .Object@validate <- validate if(.Object@validate) validObject(.Object) .Object }) #' @param object A \linkS4class{Canonical} object. #' @describeIn Canonical The expression associated with the input. setMethod("expr", "Canonical", function(object) { if(length(object@args) != 1) stop("'expr' is ambiguous, there should only be one argument.") return(object@args[[1]]) }) #' @describeIn Canonical The unique ID of the canonical expression. setMethod("id", "Canonical", function(object) { object@id }) #' @describeIn Canonical The graph implementation of the input. setMethod("canonical_form", "Canonical", function(object) { canonicalize(object) }) #' @describeIn Canonical List of \linkS4class{Variable} objects in the expression. setMethod("variables", "Canonical", function(object) { unique(flatten_list(lapply(object@args, function(arg) { variables(arg) }))) }) #' @describeIn Canonical List of \linkS4class{Parameter} objects in the expression. setMethod("parameters", "Canonical", function(object) { unique(flatten_list(lapply(object@args, function(arg) { parameters(arg) }))) }) #' @describeIn Canonical List of \linkS4class{Constant} objects in the expression. setMethod("constants", "Canonical", function(object) { const_list <- flatten_list(lapply(object@args, function(arg) { constants(arg) })) # const_id <- sapply(const_list, function(constant) { id(constant) }) # const_list[!duplicated(const_id)] const_list[!duplicated(const_list)] }) #' @describeIn Canonical List of \linkS4class{Atom} objects in the expression. setMethod("atoms", "Canonical", function(object) { unique(flatten_list(lapply(object@args, function(arg) { atoms(arg) }))) }) setMethod("tree_copy", "Canonical", function(object, id_objects = list()) { new_args <- list() for(arg in object@args) { if(is.list(arg)) { arg_list <- lapply(arg, function(elem) { tree_copy(elem, id_objects) }) new_args <- c(new_args, arg_list) } else new_args <- c(new_args, tree_copy(arg, id_objects)) } return(copy(object, args = new_args, id_objects = id_objects)) }) setMethod("copy", "Canonical", function(object, args = NULL, id_objects = list()) { # if("id" %in% names(attributes(object)) && as.character(object@id) %in% names(id_objects)) if(!is.na(object@id) && as.character(object@id) %in% names(id_objects)) return(id_objects[[as.character(object@id)]]) if(is.null(args)) args <- object@args data <- get_data(object) if(!is.null(data) && length(data) != 0) return(do.call(class(object), c(args, data))) else return(do.call(class(object), args)) }) #' @describeIn Canonical Information needed to reconstruct the expression aside from its arguments. setMethod("get_data", "Canonical", function(object) { list() })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/canonical.R
#' #' The InverseData class. #' #' This class represents the data encoding an optimization problem. #' #' @rdname InverseData-class .InverseData <- setClass("InverseData", representation(problem = "Problem", id_map = "list", var_offsets = "list", x_length = "numeric", var_dims = "list", id2var = "list", real2imag = "list", id2cons = "list", cons_id_map = "list", r = "numeric", minimize = "logical", sorted_constraints = "list", is_mip = "logical"), prototype(id_map = list(), var_offsets = list(), x_length = NA_real_, var_dims = list(), id2var = list(), real2imag = list(), id2cons = list(), cons_id_map = list(), r = NA_real_, minimize = NA, sorted_constraints = list(), is_mip = NA)) InverseData <- function(problem) { .InverseData(problem = problem) } setMethod("initialize", "InverseData", function(.Object, ..., problem, id_map = list(), var_offsets = list(), x_length = NA_real_, var_dims = list(), id2var = list(), real2imag = list(), id2cons = list(), cons_id_map = list(), r = NA_real_, minimize = NA, sorted_constraints = list(), is_mip = NA) { # Basic variable offset information varis <- variables(problem) varoffs <- get_var_offsets(.Object, varis) .Object@id_map <- varoffs$id_map .Object@var_offsets <- varoffs$var_offsets .Object@x_length <- varoffs$x_length .Object@var_dims <- varoffs$var_dims # Map of variable id to variable .Object@id2var <- stats::setNames(varis, sapply(varis, function(var) { as.character(id(var)) })) # Map of real to imaginary parts of complex variables var_comp <- Filter(is_complex, varis) .Object@real2imag <- lapply(seq_along(var_comp), function(i) { get_id() }) names(.Object@real2imag) <- sapply(var_comp, function(var) { as.character(id(var)) }) constrs <- constraints(problem) constr_comp <- Filter(is_complex, constrs) constr_dict <- lapply(seq_along(constr_comp), function(i) { get_id() }) names(constr_dict) <- sapply(constr_comp, function(cons) { as.character(id(cons)) }) .Object@real2imag <- utils::modifyList(.Object@real2imag, constr_dict) # Map of constraint id to constraint .Object@id2cons <- stats::setNames(constrs, sapply(constrs, function(cons) { as.character(id(cons)) })) .Object@cons_id_map <- list() .Object@r <- r .Object@minimize <- minimize .Object@sorted_constraints <- sorted_constraints .Object@is_mip <- is_mip return(.Object) }) setMethod("get_var_offsets", signature(object = "InverseData", variables = "list"), function(object, variables) { var_dims <- list() var_offsets <- list() id_map <- list() vert_offset <- 0 for(x in variables) { var_dims[[as.character(id(x))]] <- dim(x) var_offsets[[as.character(id(x))]] <- vert_offset id_map[[as.character(id(x))]] <- list(vert_offset, size(x)) vert_offset <- vert_offset + size(x) } return(list(id_map = id_map, var_offsets = var_offsets, x_length = vert_offset, var_dims = var_dims)) }) # TODO: Find best format for sparse matrices. .CoeffExtractor <- setClass("CoeffExtractor", representation(inverse_data = "InverseData", id_map = "list", N = "numeric", var_dims = "list"), prototype(id_map = list(), N = NA_real_, var_dims = list())) CoeffExtractor <- function(inverse_data) { .CoeffExtractor(inverse_data = inverse_data) } setMethod("initialize", "CoeffExtractor", function(.Object, inverse_data, id_map, N, var_dims) { .Object@id_map <- inverse_data@var_offsets .Object@N <- inverse_data@x_length .Object@var_dims <- inverse_data@var_dims return(.Object) }) setMethod("get_coeffs", signature(object = "CoeffExtractor", expr = "Expression"), function(object, expr) { if(is_constant(expr)) return(constant(object, expr)) else if(is_affine(expr)) return(affine(object, expr)) else if(is_quadratic(expr)) return(quad_form(object, expr)) else stop("Unknown expression type ", class(expr)) }) setMethod("constant", signature(object = "CoeffExtractor", expr = "Expression"), function(object, expr) { size <- size(expr) list(Matrix(nrow = size, ncol = object@N), as.vector(value(expr))) }) setMethod("affine", signature(object = "CoeffExtractor", expr = "list"), function(object, expr) { if(length(expr) == 0) size <- 0 else size <- sum(sapply(expr, size)) op_list <- lapply(expr, function(e) { canonical_form(e)[[1]] }) VIJb <- get_problem_matrix(op_list, object@id_map) V <- VIJb[[1]] I <- VIJb[[2]] + 1 # TODO: Convert 0-indexing to 1-indexing in get_problem_matrix. J <- VIJb[[3]] + 1 b <- VIJb[[4]] A <- sparseMatrix(i = I, j = J, x = V, dims = c(size, object@N)) list(A, as.vector(b)) }) setMethod("affine", signature(object = "CoeffExtractor", expr = "Expression"), function(object, expr) { affine(object, list(expr)) }) setMethod("extract_quadratic_coeffs", "CoeffExtractor", function(object, affine_expr, quad_forms) { # Assumes quadratic forms all have variable arguments. Affine expressions can be anything. # Extract affine data. affine_problem <- Problem(Minimize(affine_expr), list()) affine_inverse_data <- InverseData(affine_problem) affine_id_map <- affine_inverse_data@id_map affine_var_dims <- affine_inverse_data@var_dims extractor <- CoeffExtractor(affine_inverse_data) cb <- affine(extractor, expr(affine_problem@objective)) c <- cb[[1]] b <- cb[[2]] # Combine affine data with quadratic forms. coeffs <- list() for(var in variables(affine_problem)) { var_id <- as.character(id(var)) if(var_id %in% names(quad_forms)) { orig_id <- as.character(id(quad_forms[[var_id]][[3]]@args[[1]])) var_offset <- affine_id_map[[var_id]][[1]] var_size <- affine_id_map[[var_id]][[2]] if(!any(is.na(value(quad_forms[[var_id]][[3]]@P)))) { P <- value(quad_forms[[var_id]][[3]]@P) if(is(P, "sparseMatrix")) P <- as.matrix(P) c_part <- c[1, (var_offset + 1):(var_offset + var_size)] P <- sweep(P, MARGIN = 2, FUN = "*", c_part) } else P <- sparseMatrix(i = 1:var_size, j = 1:var_size, x = c[1, (var_offset + 1):(var_offset + var_size)]) if(orig_id %in% names(coeffs)) { coeffs[[orig_id]]$P <- coeffs[[orig_id]]$P + P coeffs[[orig_id]]$q <- coeffs[[orig_id]]$q + rep(0, nrow(P)) } else { coeffs[[orig_id]] <- list() coeffs[[orig_id]]$P <- P coeffs[[orig_id]]$q <- rep(0, nrow(P)) } } else { var_offset <- affine_id_map[[var_id]][[1]] var_size <- as.integer(prod(affine_var_dims[[var_id]])) if(var_id %in% names(coeffs)) { coeffs[[var_id]]$P <- coeffs[[var_id]]$P + sparseMatrix(i = c(), j = c(), dims = c(var_size, var_size)) coeffs[[var_id]]$q <- coeffs[[var_id]]$q + c[1, (var_offset + 1):(var_offset + var_size)] } else { coeffs[[var_id]] <- list() coeffs[[var_id]]$P <- sparseMatrix(i = c(), j = c(), dims = c(var_size, var_size)) coeffs[[var_id]]$q <- c[1, (var_offset + 1):(var_offset + var_size)] } } } return(list(coeffs, b)) }) setMethod("coeff_quad_form", signature(object = "CoeffExtractor", expr = "Expression"), function(object, expr) { # Extract quadratic, linear constant parts of a quadratic objective. # Insert no-op such that root is never a quadratic form, for easier processing. root <- LinOp(NO_OP, dim(expr), list(expr), list()) # Replace quadratic forms with dummy variables. tmp <- replace_quad_forms(root, list()) root <- tmp[[1]] quad_forms <- tmp[[2]] # Calculate affine parts and combine them with quadratic forms to get the coefficients. tmp <- extract_quadratic_coeffs(object, root$args[[1]], quad_forms) coeffs <- tmp[[1]] constant <- tmp[[2]] # Restore expression. root$args[[1]] <- restore_quad_forms(root$args[[1]], quad_forms) # Sort variables corresponding to their starting indices in ascending order. shuffle <- order(unlist(object@id_map), decreasing = FALSE) offsets <- object@id_map[shuffle] # Concatenate quadratic matrices and vectors. P <- Matrix(nrow = 0, ncol = 0) q <- c() for(var_id in names(offsets)) { offset <- offsets[[var_id]] if(var_id %in% names(coeffs)) { P <- bdiag(P, coeffs[[var_id]]$P) q <- c(q, coeffs[[var_id]]$q) } else { var_dim <- object@var_dims[[var_id]] size <- as.integer(prod(var_dim)) P <- bdiag(P, Matrix(0, nrow = size, ncol = size)) q <- c(q, rep(0, size)) } } if(!(nrow(P) == ncol(P) && ncol(P) == object@N) || length(q) != object@N) stop("Resulting quadratic form does not have appropriate dimensions.") if(length(constant) != 1) stop("Constant must be a scalar.") return(list(P, q, constant[1])) }) # Helper function for getting args of an Expression or LinOp. get_args <- function(x) { if(is(x, "Expression")) return(x@args) else return(x$args) } # Helper function for setting args of an Expression or LinOp. set_args <- function(x, idx, val) { if(is(x, "Expression")) x@args[[idx]] <- val else x$args[[idx]] <- val return(x) } replace_quad_forms <- function(expr, quad_forms) { nargs <- length(get_args(expr)) if(nargs == 0) return(list(expr, quad_forms)) for(idx in 1:nargs) { arg <- get_args(expr)[[idx]] if(is(arg, "SymbolicQuadForm") || is(arg, "QuadForm")) { tmp <- replace_quad_form(expr, idx, quad_forms) expr <- tmp[[1]] quad_forms <- tmp[[2]] } else { tmp <- replace_quad_forms(arg, quad_forms) expr <- set_args(expr, idx, tmp[[1]]) quad_forms <- tmp[[2]] } } return(list(expr, quad_forms)) } replace_quad_form <- function(expr, idx, quad_forms) { quad_form <- get_args(expr)[[idx]] # placeholder <- Variable(dim(quad_form)) placeholder <- new("Variable", dim = dim(quad_form)) expr <- set_args(expr, idx, placeholder) quad_forms[[as.character(id(placeholder))]] <- list(expr, idx, quad_form) return(list(expr, quad_forms)) } restore_quad_forms <- function(expr, quad_forms) { nargs <- length(get_args(expr)) if(nargs == 0) return(expr) for(idx in 1:nargs) { arg <- get_args(expr)[[idx]] if(is(arg, "Variable") && as.character(id(arg)) %in% names(quad_forms)) expr <- set_args(expr, idx, quad_forms[[as.character(id(arg))]][[3]]) else { arg <- restore_quad_forms(arg, quad_forms) expr <- set_args(expr, idx, arg) } } return(expr) } # # # # The QuadCoeffExtractor class # # # # Given a quadratic expression of size m*n, this class extracts the coefficients # # (Ps, Q, R) such that the (i,j) entry of the expression is given by # # t(X) %*% Ps[[k]] %*% x + Q[k,] %*% x + R[k] # # where k = i + j*m. x is the vectorized variables indexed by id_map # # # setClass("QuadCoeffExtractor", representation(id_map = "list", N = "numeric")) # # get_coeffs.QuadCoeffExtractor <- function(object, expr) { # if(is_constant(expr)) # return(.coeffs_constant(object, expr)) # else if(is_affine(expr)) # return(.coeffs_affine(object, expr)) # else if(is(expr, "AffineProd")) # return(.coeffs_affine_prod(object, expr)) # else if(is(expr, "QuadOverLin")) # return(.coeffs_quad_over_lin(object, expr)) # else if(is(expr, "Power")) # return(.coeffs_power(object, expr)) # else if(is(expr, "MatrixFrac")) # return(.coeffs_matrix_frac(object, expr)) # else if(is(expr, "AffAtom")) # return(.coeffs_affine_atom(object, expr)) # else # stop("Unknown expression type: ", class(expr)) # } # # .coeffs_constant.QuadCoeffExtractor <- function(object, expr) { # if(is_scalar(expr)) { # sz <- 1 # R <- matrix(value(expr)) # } else { # sz <- prod(size(expr)) # R <- matrix(value(expr), nrow = sz) # TODO: Check if this should be transposed # } # Ps <- lapply(1:sz, function(i) { sparseMatrix(i = c(), j = c(), dims = c(object@N, object@N)) }) # Q <- sparseMatrix(i = c(), j = c(), dims = c(sz, object@N)) # list(Ps, Q, R) # } # # .coeffs_affine.QuadCoeffExtractor <- function(object, expr) { # sz <- prod(size(expr)) # canon <- canonical_form(expr) # prob_mat <- get_problem_matrix(list(create_eq(canon[[1]])), object@id_map) # # V <- prob_mat[[1]] # I <- prob_mat[[2]] # J <- prob_mat[[3]] # R <- prob_mat[[4]] # # Q <- sparseMatrix(i = I, j = J, x = V, dims = c(sz, object@N)) # Ps <- lapply(1:sz, function(i) { sparseMatrix(i = c(), j = c(), dims = c(object@N, object@N)) }) # list(Ps, Q, as.vector(R)) # TODO: Check if R is flattened correctly # } # # .coeffs_affine_prod.QuadCoeffExtractor <- function(object, expr) { # XPQR <- .coeffs_affine(expr@args[[1]]) # YPQR <- .coeffs_affine(expr@args[[2]]) # Xsize <- size(expr@args[[1]]) # Ysize <- size(expr@args[[2]]) # # XQ <- XPQR[[2]] # XR <- XPQR[[3]] # YQ <- YPQR[[2]] # YR <- YPQR[[3]] # m <- Xsize[1] # p <- Xsize[2] # n <- Ysize[2] # # Ps <- list() # Q <- sparseMatrix(i = c(), j = c(), dims = c(m*n, object@N)) # R <- rep(0, m*n) # # ind <- 0 # for(j in 1:n) { # for(i in 1:m) { # M <- sparseMatrix(i = c(), j = c(), dims = c(object@N, object@N)) # for(k in 1:p) { # Xind <- k*m + i # Yind <- j*p + k # # a <- XQ[Xind,] # b <- XR[Xind] # c <- YQ[Yind,] # d <- YR[Yind] # # M <- M + t(a) %*% c # Q[ind,] <- Q[ind,] + b*c + d*a # R[ind] <- R[ind] + b*d # } # Ps <- c(Ps, Matrix(M, sparse = TRUE)) # ind <- ind + 1 # } # } # list(Ps, Matrix(Q, sparse = TRUE), R) # } # # .coeffs_quad_over_lin.QuadCoeffExtractor <- function(object, expr) { # coeffs <- .coeffs_affine(object, expr@args[[1]]) # A <- coeffs[[2]] # b <- coeffs[[3]] # # P <- t(A) %*% A # q <- Matrix(2*t(b) %*% A) # r <- sum(b*b) # y <- value(expr@args[[2]]) # list(list(P/y), q/y, r/y) # } # # .coeffs_power.QuadCoeffExtractor <- function(object, expr) { # if(expr@p == 1) # return(get_coeffs(object, expr@args[[1]])) # else if(expr@p == 2) { # coeffs <- .coeffs_affine(object, expr@args[[1]]) # A <- coeffs[[2]] # b <- coeffs[[3]] # # Ps <- lapply(1:nrow(A), function(i) { Matrix(t(A[i,]) %*% A[i,], sparse = TRUE) }) # Q <- 2*Matrix(diag(b) %*% A, sparse = TRUE) # R <- b^2 # return(list(Ps, Q, R)) # } else # stop("Error while processing Power") # } # # .coeffs_matrix_frac <- function(object, expr) { # coeffs <- .coeffs_affine(expr@args[[1]]) # A <- coeffs[[2]] # b <- coeffs[[3]] # arg_size <- size(expr@args[[1]]) # m <- arg_size[1] # n <- arg_size[2] # Pinv <- base::solve(value(expr@args[[2]])) # # M <- sparseMatrix(i = c(), j = c(), dims = c(object@N, object@N)) # Q <- sparseMatrix(i = c(), j = c(), dims = c(1, object@N)) # R <- 0 # # for(i in seq(1, m*n, m)) { # A2 <- A[i:(i+m),] # b2 <- b[i:(i+m)] # # M <- M + t(A2) %*% Pinv %*% A2 # Q <- Q + 2*t(A2) %*% (Pinv %*% b2) # R <- R + sum(b2 * (Pinv %*% b2)) # } # list(list(Matrix(M, sparse = TRUE)), Matrix(Q, sparse = TRUE), R) # } # # .coeffs_affine_atom <- function(object, expr) { # sz <- prod(size(expr)) # Ps <- lapply(1:sz, function(i) { sparseMatrix(i = c(), j = c(), dims = c(object@N, object@N)) }) # Q <- sparseMatrix(i = c(), j = c(), dims = c(sz, object@N)) # Parg <- NA # Qarg <- NA # Rarg <- NA # # fake_args <- list() # offsets <- list() # offset <- 0 # for(idx in 1:length(expr@args)) { # arg <- expr@args[[idx]] # if(is_constant(arg)) # fake_args <- c(fake_args, list(create_const(value(arg), size(arg)))) # else { # coeffs <- get_coeffs(object, arg) # if(is.na(Parg)) { # Parg <- coeffs[[1]] # Qarg <- coeffs[[2]] # Rarg <- coeffs[[3]] # } else { # Parg <- Parg + coeffs[[1]] # Qarg <- rbind(Qarg, q) # Rarg <- c(Rarg, r) # } # fake_args <- c(fake_args, list(create_var(size(arg), idx))) # offsets[idx] <- offset # offset <- offset + prod(size(arg)) # } # } # graph <- graph_implementation(expr, fake_args, size(expr), get_data(expr)) # # # Get the matrix representation of the function # prob_mat <- get_problem_matrix(list(create_eq(graph[[1]])), offsets) # V <- prob_mat[[1]] # I <- prob_mat[[2]] # J <- prob_mat[[3]] # R <- as.vector(prob_mat[[4]]) # TODO: Check matrix is flattened correctly # # # Return AX + b # for(idx in 1:length(V)) { # v <- V[idx] # i <- I[idx] # j <- J[idx] # # Ps[[i]] <- Ps[[i]] + v*Parg[j] # Q[i,] <- Q[i,] + v*Qarg[j,] # R[i] <- R[i] + v*Rarg[j] # } # Ps <- lapply(Ps, function(P) { Matrix(P, sparse = TRUE) }) # list(Ps, Matrix(Q, sparse = TRUE), R) # }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/coeff_extractor.R
#' #' Lifts complex numbers to a real representation. #' #' This reduction takes in a complex problem and returns #' an equivalent real problem. #' @rdname Complex2Real-class Complex2Real <- setClass("Complex2Real", contains = "Reduction") Complex2Real.accepts <- function(problem) { leaves <- c(variables(problem), parameters(problem), constants(problem)) any(sapply(leaves, function(l) { is_complex(l) })) } #' @param object A \linkS4class{Complex2Real} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn Complex2Real Checks whether or not the problem involves any complex numbers. setMethod("accepts", signature(object = "Complex2Real", problem = "Problem"), function(object, problem) { Complex2Real.accepts(problem) }) #' @describeIn Complex2Real Converts a Complex problem into a Real one. setMethod("perform", signature(object = "Complex2Real", problem = "Problem"), function(object, problem) { inverse_data <- InverseData(problem) leaf_map <- list() obj <- Complex2Real.canonicalize_tree(problem@objective, inverse_data@real2imag, leaf_map) real_obj <- obj[[1]] imag_obj <- obj[[2]] if(length(imag_obj) > 0) stop("Cannot have imaginary component in canonicalized objective") constrs <- list() for(constraint in problem@constraints) { if(inherits(constraint, "EqConstraint")) constraint <- lower_equality(constraint) constr <- Complex2Real.canonicalize_tree(constraint, inverse_data@real2imag, leaf_map) real_constr <- constr[[1]] imag_constr <- constr[[2]] if(!is.null(real_constr)) constrs <- c(constrs, real_constr) if(!is.null(imag_constr)) constrs <- c(constrs, imag_constr) } new_problem <- Problem(real_obj, constrs) return(list(object, new_problem, inverse_data)) }) #' @param solution A \linkS4class{Solution} object to invert. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn Complex2Real Returns a solution to the original problem given the inverse data. setMethod("invert", signature(object = "Complex2Real", solution = "Solution", inverse_data = "InverseData"), function(object, solution, inverse_data) { pvars <- list() dvars <- list() if(solution@status %in% SOLUTION_PRESENT) { for(vid in names(inverse_data@id2var)) { var <- inverse_data@id2var[[vid]] if(is_real(var)) pvars[[vid]] <- solution@primal_vars[[vid]] else if(is_imag(var)) { imag_id <- inverse_data@real2imag[[vid]] pvars[[vid]] <- 1i*solution@primal_vars[[as.character(imag_id)]] } else if(is_complex(var) && is_hermitian(var)) { imag_id <- inverse_data@real2imag[[vid]] # Imaginary part may have been lost. if(as.character(imag_id) %in% names(solution@primal_vars)) { imag_val <- solution@primal_vars[[as.character(imag_id)]] pvars[[vid]] <- solution@primal_vars[[vid]] + 1i*(imag_val - t(imag_val))/2 } else pvars[[vid]] <- solution@primal_vars[[vid]] } else if(is_complex(var)) { imag_id <- inverse_data@real2imag[[vid]] pvars[[vid]] <- solution@primal_vars[[vid]] + 1i*solution@primal_vars[[as.character(imag_id)]] } } for(cid in names(inverse_data@id2cons)) { cons <- inverse_data@id2cons[[cid]] if(is_real(cons)) dvars[[vid]] <- solution@dual_vars[[cid]] else if(is_imag(cons)) { imag_id <- inverse_data@real2imag[[cid]] dvars[[cid]] <- 1i*solution@dual_vars[[as.character(imag_id)]] # For equality and inequality constraints. } else if((is(cons, "ZeroConstraint") || is(cons, "EqConstraint") || is(cons, "NonPosConstraint")) && is_complex(cons)) { imag_id <- inverse_data@real2imag[[cid]] dvars[[cid]] <- solution@dual_vars[[cid]] + 1i*solution@dual_vars[[as.character(imag_id)]] # For PSD constraints. } else if(is(cons, "PSDConstraint") && is_complex(cons)) { n <- nrow(cons@args[[1]]) dual <- solution@dual_vars[[cid]] dvars[[cid]] <- dual[1:n,1:n] + 1i*dual[(n+1):nrow(dual), (n+1):ncol(dual)] } else stop("Unknown constraint type") } } return(Solution(solution@status, solution@opt_val, pvars, dvars, solution@attr)) }) #' #' Recursively Canonicalizes a Complex Expression. #' #' @param expr An \linkS4class{Expression} object. #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @param leaf_map A map that consists of a tree representation of the expression. #' @return A list of the parsed out real and imaginary components of the #' expression that was constructed by performing the canonicalization of each leaf #' in the tree. Complex2Real.canonicalize_tree <- function(expr, real2imag, leaf_map) { # TODO: Don't copy affine expressions? if(inherits(expr, "PartialProblem")) stop("Unimplemented") else { real_args <- list() imag_args <- list() for(arg in expr@args) { canon <- Complex2Real.canonicalize_tree(arg, real2imag, leaf_map) real_args <- c(real_args, list(canon[[1]])) imag_args <- c(imag_args, list(canon[[2]])) } outs <- Complex2Real.canonicalize_expr(expr, real_args, imag_args, real2imag, leaf_map) return(list(real_out = outs[[1]], imag_out = outs[[2]])) } } #' #' Canonicalizes a Complex Expression #' #' @param expr An \linkS4class{Expression} object. #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression. #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression. #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @param leaf_map A map that consists of a tree representation of the overall expression #' @return A list of the parsed out real and imaginary components of the expression at hand. Complex2Real.canonicalize_expr <- function(expr, real_args, imag_args, real2imag, leaf_map) { if(inherits(expr, names(Complex2Real.CANON_METHODS))) { expr_id <- as.character(id(expr)) # Only canonicalize a variable/constant/parameter once. if(length(expr@args) == 0 && expr_id %in% names(leaf_map)) return(leaf_map[[expr_id]]) result <- Complex2Real.CANON_METHODS[[class(expr)]](expr, real_args, imag_args, real2imag) if(length(expr@args) == 0) leaf_map[[expr_id]] <- result return(result) } else { if(!all(sapply(imag_args, is.null))) stop("Not all imaginary arguments are NULL") return(list(copy(expr, real_args), NULL)) } } # Atom canonicalizers. #' #' Complex canonicalizer for the absolute value atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of the absolute value atom of a complex expression, where the returned #' variables are its real and imaginary components parsed out. Complex2Real.abs_canon <- function(expr, real_args, imag_args, real2imag) { if(is.null(real_args[[1]])) # Imaginary output <- abs(imag_args[[1]]) else if(is.null(imag_args[[1]])) # Real output <- abs(real_args[[1]]) else { # Complex real <- flatten(real_args[[1]]) imag <- flatten(imag_args[[1]]) norms <- p_norm(hstack(real, imag), p = 2, axis = 1) output <- reshape_expr(norms, dim(real_args[[1]])) } return(list(output, NULL)) } # Affine canonicalization. #' #' Complex canonicalizer for the separable atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a separable atom, where the returned #' variables are its real and imaginary components parsed out. Complex2Real.separable_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize linear functions that are separable in real and imaginary parts. if(all(sapply(imag_args, is.null))) outputs <- list(copy(expr, real_args), NULL) else if(all(sapply(real_args, is.null))) outputs <- list(NULL, copy(expr, imag_args)) else { # Mixed real and imaginary arguments. for(idx in seq_along(real_args)) { real_val <- real_args[[idx]] if(is.null(real_val)) real_args[[idx]] <- Constant(matrix(0, nrow = nrow(imag_args[[idx]]), ncol = ncol(imag_args[[idx]]))) else if(is.null(imag_args[[idx]])) imag_args[[idx]] <- Constant(matrix(0, nrow = nrow(real_args[[idx]]), ncol = ncol(real_args[[idx]]))) } outputs <- list(copy(expr, real_args), copy(expr, imag_args)) } return(outputs) } #' #' Complex canonicalizer for the real atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a real atom, where the returned #' variables are the real component and NULL for the imaginary component. Complex2Real.real_canon <- function(expr, real_args, imag_args, real2imag) { # If no real arguments, return zero. if(is.null(real_args[[1]])) return(list(0, NULL)) else return(list(real_args[[1]], NULL)) } #' #' Complex canonicalizer for the imaginary atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of an imaginary atom, where the returned #' variables are the imaginary component and NULL for the real component. Complex2Real.imag_canon <- function(expr, real_args, imag_args, real2imag) { # If no imaginary arguments, return zero. if(is.null(imag_args[[1]])) return(list(0, NULL)) else return(list(imag_args[[1]], NULL)) } #' #' Complex canonicalizer for the conjugate atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a conjugate atom, where the returned #' variables are the real components and negative of the imaginary component. Complex2Real.conj_canon <- function(expr, real_args, imag_args, real2imag) { if(is.null(imag_args[[1]])) imag_arg <- NULL else imag_arg <- -imag_args[[1]] return(list(real_args[[1]], imag_arg)) } #' #' Helper function to combine arguments. #' #' @param expr An \linkS4class{Expression} object #' @param lh_arg The arguments for the left-hand side #' @param rh_arg The arguments for the right-hand side #' @return A joined expression of both left and right expressions Complex2Real.join <- function(expr, lh_arg, rh_arg) { # if(is.null(lh_arg) || is.null(rh_arg)) return(NULL) else return(copy(expr, list(lh_arg, rh_arg))) } #' #' Helper function to sum arguments. #' #' @param lh_arg The arguments for the left-hand side #' @param rh_arg The arguments for the right-hand side #' @param neg Whether to negate the right hand side Complex2Real.add <- function(lh_arg, rh_arg, neg = FALSE) { # Negates rh_arg if neg is TRUE. if(!is.null(rh_arg) && neg) rh_arg <- -rh_arg if(is.null(lh_arg) && is.null(rh_arg)) return(NULL) else if(is.null(lh_arg)) return(rh_arg) else if(is.null(rh_arg)) return(lh_arg) else return(lh_arg + rh_arg) } #' #' Complex canonicalizer for the binary atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a binary atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.binary_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize functions like multiplication. real_by_real <- Complex2Real.join(expr, real_args[[1]], real_args[[2]]) imag_by_imag <- Complex2Real.join(expr, imag_args[[1]], imag_args[[2]]) real_by_imag <- Complex2Real.join(expr, real_args[[1]], imag_args[[2]]) imag_by_real <- Complex2Real.join(expr, imag_args[[1]], real_args[[2]]) real_output <- Complex2Real.add(real_by_real, imag_by_imag, neg = TRUE) imag_output <- Complex2Real.add(real_by_imag, imag_by_real, neg = FALSE) return(list(real_output, imag_output)) } #' #' Complex canonicalizer for the constant atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a constant atom, where the returned #' variables are the real component and the imaginary component in the \linkS4class{Constant} #' atom. Complex2Real.constant_canon <- function(expr, real_args, imag_args, real2imag) { if(is_real(expr)) return(list(Constant(Re(value(expr))), NULL)) else if(is_imag(expr)) return(list(NULL, Constant(Im(value(expr))))) else return(list(Constant(Re(value(expr))), Constant(Im(value(expr))))) } # Matrix canonicalization. # We expand the matrix A to B = [[Re(A), -Im(A)], [Im(A), Re(A)]] # B has the same eigenvalues as A (if A is Hermitian). # If x is an eigenvector of A, then [Re(x), Im(x)] and [Im(x), -Re(x)] # are eigenvectors with same eigenvalue. # Thus each eigenvalue is repeated twice. #' #' Complex canonicalizer for the hermitian atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a hermitian matrix atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.hermitian_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize functions that take a Hermitian matrix. if(is.null(imag_args[[1]])) mat <- real_args[[1]] else { if(is.null(real_args[[1]])) real_args[[1]] <- matrix(0, nrow = nrow(imag_args[[1]]), ncol = ncol(imag_args[[1]])) mat <- bmat(list(list(real_args[[1]], -imag_args[[1]]), list(imag_args[[1]], real_args[[1]]))) } return(list(copy(expr, list(mat)), NULL)) } #' #' Complex canonicalizer for the nuclear norm atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a nuclear norm matrix atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.norm_nuc_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize nuclear norm with Hermitian matrix input. # Divide by two because each eigenvalue is repeated twice. canon <- Complex2Real.hermitian_canon(expr, real_args, imag_args, real2imag) real <- canon[[1]] imag <- canon[[2]] if(!is.null(imag_args[[1]])) real <- real/2 return(list(real, imag)) } #' #' Complex canonicalizer for the largest sum atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of the largest sum atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.lambda_sum_largest_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize nuclear norm with Hermitian matrix input. # Divide by two because each eigenvalue is repeated twice. canon <- Complex2Real.hermitian_canon(expr, real_args, imag_args, real2imag) real <- canon[[1]] imag <- canon[[2]] real@k <- 2*real@k if(!is.null(imag_args[[1]])) real <- real/2 return(list(real, imag)) } #' #' Upcast 0D and 1D to 2D. #' #' @param expr An \linkS4class{Expression} object #' @return An expression of dimension at least 2. Complex2Real.at_least_2D <- function(expr) { # if(length(dim(expr)) < 2) return(reshape_expr(expr, c(size(expr), 1))) else return(expr) } #' #' Complex canonicalizer for the quadratic atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a quadratic atom, where the returned #' variables are the real component and the imaginary component as NULL. Complex2Real.quad_canon <- function(expr, real_args, imag_args, real2imag) { # Convert quad_form to real. if(is.null(imag_args[[1]])) { vec <- real_args[[1]] mat <- real_args[[2]] } else if(is.null(real_args[[1]])) { vec <- imag_args[[1]] mat <- real_args[[2]] } else { vec <- vstack(Complex2Real.at_least_2D(real_args[[1]]), Complex2Real.at_least_2D(imag_args[[1]])) if(is.null(real_args[[2]])) real_args[[2]] <- matrix(0, nrow = nrow(imag_args[[2]]), ncol = ncol(imag_args[[2]])) else if(is.null(imag_args[[2]])) imag_args[[2]] <- matrix(0, nrow = nrow(real_args[[2]]), ncol = ncol(real_args[[2]])) mat <- bmat(list(list(real_args[[2]], -imag_args[[2]]), list(imag_args[[2]], real_args[[2]]) )) # mat <- Constant(value(mat)) mat <- PSDWrap(mat) } return(list(copy(expr, list(vec, mat)), NULL)) } #' #' Complex canonicalizer for the quadratic over linear term atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a quadratic over a linear term atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.quad_over_lin_canon <- function(expr, real_args, imag_args, real2imag) { # Convert quad_over_lin to real. mat <- bmat(list(real_args[[1]], imag_args[[1]])) return(list(copy(expr, list(mat, real_args[[2]])), NULL)) } #' #' Complex canonicalizer for the matrix fraction atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a matrix atom, where the returned #' variables are converted to real variables. Complex2Real.matrix_frac_canon <- function(expr, real_args, imag_args, real2imag) { # Convert matrix_frac to real. if(is.null(real_args[[1]])) real_args[[1]] <- matrix(0, nrow = nrow(imag_args[[1]]), ncol = ncol(imag_args[[1]])) if(is.null(imag_args[[1]])) imag_args[[1]] <- matrix(0, nrow = nrow(real_args[[1]]), ncol = ncol(real_args[[1]])) vec <- vstack(Complex2Real.at_least_2D(real_args[[1]]), Complex2Real.at_least_2D(imag_args[[1]])) if(is.null(real_args[[2]])) real_args[[2]] <- matrix(0, nrow = nrow(imag_args[[2]]), ncol = ncol(imag_args[[2]])) else if(is.null(imag_args[[2]])) imag_args[[2]] <- matrix(0, nrow = nrow(real_args[[2]]), ncol = ncol(real_args[[2]])) mat <- bmat(list(list(real_args[[2]], -imag_args[[2]]), list(imag_args[[2]], real_args[[2]]) )) return(list(copy(expr, list(vec, mat)), NULL)) } #' #' Complex canonicalizer for the non-positive atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a non positive atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.nonpos_canon <- function(expr, real_args, imag_args, real2imag) { if(is.null(imag_args[[1]])) return(list(list(copy(expr, real_args)), NULL)) imag_cons <- list(NonPosConstraint(imag_args[[1]], id = real2imag[[as.character(id(expr))]])) if(is.null(real_args[[1]])) return(list(NULL, imag_cons)) else return(list(list(copy(expr, real_args)), imag_cons)) } #' #' Complex canonicalizer for the parameter matrix atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a parameter matrix atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.param_canon <- function(expr, real_args, imag_args, real2imag) { if(is_real(expr)) return(list(expr, NULL)) else if(is_imag(expr)) { imag <- CallbackParam(function() { list(Im(value(expr)), dim(expr)) }) return(list(NULL, imag)) } else { real <- CallbackParam(function() { list(Re(value(expr)), dim(expr)) }) imag <- CallbackParam(function() { list(Im(value(expr)), dim(expr)) }) return(list(real, imag)) } } #' #' Complex canonicalizer for the p norm atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a pnorm atom, where the returned #' variables are the real component and the NULL imaginary component. Complex2Real.pnorm_canon <- function(expr, real_args, imag_args, real2imag) { abs_args <- Complex2Real.abs_canon(expr, real_args, imag_args, real2imag) abs_real_args <- abs_args[[1]] return(list(copy(expr, list(abs_real_args)), NULL)) } #' #' Complex canonicalizer for the positive semidefinite atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a positive semidefinite atom, where the returned #' variables are the real component and the NULL imaginary component. Complex2Real.psd_canon <- function(expr, real_args, imag_args, real2imag) { # Canonicalize functions that take a Hermitian matrix. if(is.null(imag_args[[1]])) mat <- real_args[[1]] else { if(is.null(real_args[[1]])) real_args[[1]] <- matrix(0, nrow = nrow(imag_args[[1]]), ncol = ncol(imag_args[[1]])) mat <- bmat(list(list(real_args[[1]], -imag_args[[1]]), list(imag_args[[1]], real_args[[1]]))) } return(list(list(copy(expr, list(mat))), NULL)) } #' #' Complex canonicalizer for the SOC atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a SOC atom, where the returned #' variables are the real component and the NULL imaginary component. Complex2Real.soc_canon <- function(expr, real_args, imag_args, real2imag) { if(is.null(real_args[[2]])) # Imaginary. output <- list(SOC(real_args[[1]], imag_args[[2]], axis = expr@axis, id = real2imag[[as.character(expr@id)]])) else if(is.null(imag_args[[2]])) # Real. output <- list(SOC(real_args[[1]], real_args[[2]], axis = expr@axis, id = expr@id)) else { # Complex. orig_dim <- dim(real_args[[2]]) real <- flatten(real_args[[2]]) imag <- flatten(imag_args[[2]]) flat_X <- new("Variable", dim = dim(real)) inner_SOC <- SOC(flat_X, vstack(real, imag), axis = 1) # TODO: Check the axis here is correct. real_X <- reshape_expr(flat_X, orig_dim) outer_SOC <- SOC(real_args[[1]], real_X, axis = expr@axis, id = expr@id) output <- list(inner_SOC, outer_SOC) } return(list(output, NULL)) } #' #' Complex canonicalizer for the variable atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a variable atom, where the returned #' variables are the real component and the NULL imaginary component. Complex2Real.variable_canon <- function(expr, real_args, imag_args, real2imag) { if(is_real(expr)) return(list(expr, NULL)) # imag <- Variable(dim(expr), id = real2imag[[as.character(id(expr))]]) imag <- new("Variable", dim = dim(expr), id = real2imag[[as.character(expr@id)]]) if(is_imag(expr)) return(list(NULL, imag)) else if(is_complex(expr) && is_hermitian(expr)) # return(list(Variable(dim(expr), id = id(expr), symmetric = TRUE), (imag - t(imag))/2)) return(list(new("Variable", dim = dim(expr), id = expr@id, symmetric = TRUE), (imag - t(imag))/2)) else # Complex. # return(list(Variable(dim(expr), id = id(expr)), imag)) return(list(new("Variable", dim = dim(expr), id = expr@id), imag)) } #' #' Complex canonicalizer for the zero atom #' #' @param expr An \linkS4class{Expression} object #' @param real_args A list of \linkS4class{Constraint} objects for the real part of the expression #' @param imag_args A list of \linkS4class{Constraint} objects for the imaginary part of the expression #' @param real2imag A list mapping the ID of the real part of a complex expression to the ID of its imaginary part. #' @return A canonicalization of a zero atom, where the returned #' variables are the real component and the imaginary component. Complex2Real.zero_canon <- function(expr, real_args, imag_args, real2imag) { if(is.null(imag_args[[1]])) return(list(list(copy(expr, real_args)), NULL)) imag_cons <- list(ZeroConstraint(imag_args[[1]], id = real2imag[[as.character(id(expr))]])) if(is.null(real_args[[1]])) return(list(NULL, imag_cons)) else return(list(list(copy(expr, real_args)), imag_cons)) } Complex2Real.CANON_METHODS <- list(AddExpression = Complex2Real.separable_canon, Bmat = Complex2Real.separable_canon, CumSum = Complex2Real.separable_canon, Diag = Complex2Real.separable_canon, HStack = Complex2Real.separable_canon, Index = Complex2Real.separable_canon, SpecialIndex = Complex2Real.separable_canon, Promote = Complex2Real.separable_canon, Reshape = Complex2Real.separable_canon, SumEntries = Complex2Real.separable_canon, Trace = Complex2Real.separable_canon, Transpose = Complex2Real.separable_canon, NegExpression = Complex2Real.separable_canon, UpperTri = Complex2Real.separable_canon, VStack = Complex2Real.separable_canon, Conv = Complex2Real.binary_canon, DivExpression = Complex2Real.binary_canon, Kron = Complex2Real.binary_canon, MulExpression = Complex2Real.binary_canon, Multiply = Complex2Real.binary_canon, Conjugate = Complex2Real.conj_canon, Imag = Complex2Real.imag_canon, Real = Complex2Real.real_canon, Variable = Complex2Real.variable_canon, Constant = Complex2Real.constant_canon, Parameter = Complex2Real.param_canon, NonPosConstraint = Complex2Real.nonpos_canon, PSDConstraint = Complex2Real.psd_canon, SOC = Complex2Real.soc_canon, ZeroConstraint = Complex2Real.zero_canon, Abs = Complex2Real.abs_canon, Norm1 = Complex2Real.pnorm_canon, NormInf = Complex2Real.pnorm_canon, Pnorm = Complex2Real.pnorm_canon, LambdaMax = Complex2Real.hermitian_canon, LogDet = Complex2Real.norm_nuc_canon, NormNuc = Complex2Real.norm_nuc_canon, SigmaMax = Complex2Real.hermitian_canon, QuadForm = Complex2Real.quad_canon, QuadOverLin = Complex2Real.quad_over_lin_canon, MatrixFrac = Complex2Real.matrix_frac_canon, LambdaSumLargest = Complex2Real.lambda_sum_largest_canon)
/scratch/gouwar.j/cran-all/cranData/CVXR/R/complex2real.R
#' #' Is the constraint a stuffed cone constraint? #' #' @param constraint A \linkS4class{Constraint} object. #' @return Is the constraint a stuffed-cone constraint? is_stuffed_cone_constraint <- function(constraint) { # Conic solvers require constraints to be stuffed in the following way. if(length(variables(constraint)) != 1) return(FALSE) for(arg in constraint@args) { if(inherits(arg, "Reshape")) arg <- arg@args[[1]] if(inherits(arg, "AddExpression")) { if(!inherits(arg@args[[1]], c("MulExpression", "Multiply"))) return(FALSE) if(!inherits(arg@args[[1]]@args[[1]], "Constant")) return(FALSE) if(!inherits(arg@args[[2]], "Constant")) return(FALSE) } else if(inherits(arg, c("MulExpression", "Multiply"))) { if(!inherits(arg@args[[1]], "Constant")) return(FALSE) } else return(FALSE) } return(TRUE) } #' #' Is the objective a stuffed cone objective? #' #' @param objective An \linkS4class{Objective} object. #' @return Is the objective a stuffed-cone objective? is_stuffed_cone_objective <- function(objective) { # Conic solvers require objectives to be stuffed in the following way. expr <- expr(objective) return(is_affine(expr) && length(variables(expr)) == 1 && inherits(expr, "AddExpression") && length(expr@args) == 2 && inherits(expr@args[[1]], c("MulExpression", "Multiply")) && inherits(expr@args[[2]], "Constant")) } #' Summary of cone dimensions present in constraints. #' #' Constraints must be formatted as dictionary that maps from #' constraint type to a list of constraints of that type. #' #' Attributes #' ---------- #' zero : int #' The dimension of the zero cone. #' nonpos : int #' The dimension of the non-positive cone. #' exp : int #' The dimension of the exponential cone. #' soc : list of int #' A list of the second-order cone dimensions. #' psd : list of int #' A list of the positive semidefinite cone dimensions, where the #' dimension of the PSD cone of k by k matrices is k. .ConeDims <- setClass("ConeDims", representation(constr_map = "list", zero = "numeric", nonpos = "numeric", exp = "numeric", soc = "list", psd = "list"), prototype(zero = NA_real_, nonpos = NA_real_, exp = NA_real_, soc = list(), psd = list())) ConeDims <- function(constr_map) { .ConeDims(constr_map = constr_map) } setMethod("initialize", "ConeDims", function(.Object, constr_map, zero = NA_real_, nonpos = NA_real_, exp = NA_real_, soc = list(), psd = list()) { .Object@zero <- ifelse(is.null(constr_map$ZeroConstraint), 0, sum(sapply(constr_map$ZeroConstraint, function(c) { size(c) }))) .Object@nonpos <- ifelse(is.null(constr_map$NonPosConstraint), 0, sum(sapply(constr_map$NonPosConstraint, function(c) { size(c) }))) .Object@exp <- ifelse(is.null(constr_map$ExpCone), 0, sum(sapply(constr_map$ExpCone, function(c) { num_cones(c) }))) .Object@soc <- as.list(Reduce(c, lapply(constr_map$SOC, function(c) { cone_sizes(c) }))) .Object@psd <- lapply(constr_map$PSDConstraint, function(c) { dim(c)[1] }) return(.Object) }) #' The ConicSolver class. #' #' Conic solver class with reduction semantics. #' #' @rdname ConicSolver-class ConicSolver <- setClass("ConicSolver", representation(dims = "character"), # The key that maps to ConeDims in the data returned by perform(). prototype(dims = "dims"), contains = "ReductionSolver") # Every conic solver must support Zero and NonPos constraints. setMethod("supported_constraints", "ConicSolver", function(solver) { c("ZeroConstraint", "NonPosConstraint") }) # Some solvers cannot solve problems that do not have constraints. # For such solvers, requires_constr should return TRUE. setMethod("requires_constr", "ConicSolver", function(solver) { FALSE }) #' @param object A \linkS4class{ConicSolver} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn ConicSolver Can the problem be solved with a conic solver? setMethod("accepts", signature(object = "ConicSolver", problem = "Problem"), function(object, problem) { return(inherits(problem@objective, "Minimize") && (mip_capable(object) || !is_mixed_integer(problem)) && is_stuffed_cone_objective(problem@objective) && length(convex_attributes(variables(problem))) == 0 && (length(problem@constraints) > 0 || !requires_constr(object)) && all(sapply(problem@constraints, inherits, what = supported_constraints(object) )) && all(sapply(problem@constraints, is_stuffed_cone_constraint))) }) #' #' Return the coefficient and offset in \eqn{Ax + b}. #' #' @param expr An \linkS4class{Expression} object. #' @return The coefficient and offset in \eqn{Ax + b}. ConicSolver.get_coeff_offset <- function(expr) { if(inherits(expr, "Reshape")) # May be a Reshape as root. expr <- expr@args[[1]] if(length(expr@args[[1]]@args) == 0) { # Convert data to float64. # expr is t(c) %*% x offset <- 0 coeff <- value(expr@args[[1]]) } else { # expr is t(c) %*% x + d offset <- matrix(t(value(expr@args[[2]])), ncol = 1) coeff <- value(expr@args[[1]]@args[[1]]) } # Convert scalars to sparse matrices. if(is.atomic(coeff) && length(coeff) == 1) coeff <- Matrix(coeff, sparse = TRUE) return(list(coeff, offset)) } #' #' Returns a sparse matrix that spaces out an expression. #' #' @param dim A vector outlining the dimensions of the matrix. #' @param spacing An int of the number of rows between the start of each non-zero block. #' @param offset An int of the number of zeros at the beginning of the matrix. #' @return A sparse matrix that spaces out an expression ConicSolver.get_spacing_matrix <- function(dim, spacing, offset) { ncol <- dim[2L] i <- seq.int(from = 1 + offset, by = spacing, length.out = ncol) if (i[ncol] > dim[1L]) stop("Dimension mismatch") j <- seq_len(ncol) Matrix::sparseMatrix(i = i[j], j = j, x = rep(1, ncol), dims = dim) } ## ConicSolver.get_spacing_matrix <- function(dim, spacing, offset) { ## val_arr <- c() ## row_arr <- c() ## col_arr <- c() ## # Selects from each column. ## for(var_row in 1:dim[2]) { ## val_arr <- c(val_arr, 1.0) ## row_arr <- c(row_arr, spacing*(var_row - 1) + offset + 1) ## col_arr <- c(col_arr, var_row) ## } ## # Pad out number of rows with zeroes. ## mat <- sparseMatrix(i = row_arr, j = col_arr, x = val_arr) ## if(dim[1] > nrow(mat)) { ## pad <- sparseMatrix(i = c(), j = c(), dims = c(dim[1] - nrow(mat), ncol(mat))) ## mat <- rbind(mat, pad) ## } ## if(!all(dim(mat) == dim)) ## stop("Dimension mismatch") ## return(mat) ## } #' @param constr A \linkS4class{Constraint} to format. #' @param exp_cone_order A list indicating how the exponential cone arguments are ordered. #' @describeIn ConicSolver Return a list representing a cone program whose problem data tensors #' will yield the coefficient "A" and offset "b" for the respective constraints: #' Linear Equations: \eqn{A x = b}, #' Linear inequalities: \eqn{A x \leq b}, #' Second order cone: \eqn{A x \leq_{SOC} b}, #' Exponential cone: \eqn{A x \leq_{EXP} b}, #' Semidefinite cone: \eqn{A x \leq_{SOP} b}. setMethod("reduction_format_constr", "ConicSolver", function(object, problem, constr, exp_cone_order) { coeffs <- list() offsets <- list() for(arg in constr@args) { res <- ConicSolver.get_coeff_offset(arg) coeffs <- c(coeffs, list(res[[1]])) offsets <- c(offsets, list(res[[2]])) } height <- ifelse(length(coeffs) == 0, 0, sum(sapply(coeffs, function(c) { dim(c)[1] }))) if(inherits(constr, c("NonPosConstraint", "ZeroConstraint"))) # Both of these constraints have but a single argument. # t(c) %*% x + b (<)= 0 if and only if t(c) %*% x (<)= b. return(list(Matrix(coeffs[[1]], sparse = TRUE), -offsets[[1]])) else if(inherits(constr, "SOC")) { # Group each t row with appropriate X rows. if(constr@axis != 2) stop("SOC must be applied with axis == 2") # Interleave the rows of coeffs[[1]] and coeffs[[2]]: # coeffs[[1]][1,] # coeffs[[2]][1:(gap-1),] # coeffs[[1]][2,] # coeffs[[2]][gap:(2*(gap-1)),] # TODO: Keep X_coeff sparse while reshaping! X_coeff <- coeffs[[2]] reshaped <- matrix(t(X_coeff), nrow = nrow(coeffs[[1]]), byrow = TRUE) stacked <- -cbind(coeffs[[1]], reshaped) stacked <- matrix(t(stacked), nrow = nrow(coeffs[[1]]) + nrow(X_coeff), ncol = ncol(coeffs[[1]]), byrow = TRUE) offset <- cbind(offsets[[1]], matrix(t(offsets[[2]]), nrow = nrow(offsets[[1]]), byrow = TRUE)) offset <- matrix(t(offset), ncol = 1) return(list(Matrix(stacked, sparse = TRUE), as.vector(offset))) } else if(inherits(constr, "ExpCone")) { for(i in 1:length(coeffs)) { mat <- ConicSolver.get_spacing_matrix(c(height, nrow(coeffs[[i]])), length(exp_cone_order), exp_cone_order[i]) offsets[[i]] <- mat %*% offsets[[i]] coeffs[[i]] <- -mat %*% coeffs[[i]] } # return(list(sum(coeffs), sum(offsets))) coeff_sum <- Reduce("+", coeffs) offset_sum <- Reduce("+", offsets) return(list(coeff_sum, as.vector(offset_sum))) } else if(inherits(constr, "PSDConstraint")) { ## Sign flipped relative fo NonPos, Zero. return(list(-coeffs[[1L]], offsets[[1L]])) } else # subclasses must handle PSD constraints. stop("Unsupported constraint type.") }) #' @param constraints A list of \linkS4class{Constraint} objects. #' @describeIn ConicSolver Combine the constraints into a single matrix, offset. setMethod("group_coeff_offset", "ConicSolver", function(object, problem, constraints, exp_cone_order) { # Combine the constraints into a single matrix, offset. if(is.null(constraints) || length(constraints) == 0 || any(is.na(constraints))) return(list(Matrix(0, nrow = 0, ncol = 0), numeric(0))) matrices <- list() offset <- c() for(cons in constraints) { res <- reduction_format_constr(object, problem, cons, exp_cone_order) matrices <- c(matrices, list(res[[1]])) offset <- c(offset, res[[2]]) } coeff <- Matrix(do.call(rbind, matrices), sparse = TRUE) return(list(coeff, offset)) }) #' @param solution A \linkS4class{Solution} object to invert. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn ConicSolver Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "ConicSolver", solution = "Solution", inverse_data = "InverseData"), function(object, solution, inverse_data) { # Returns the solution to the original problem given the inverse_data. status <- solution$status if(status %in% SOLUTION_PRESENT) { opt_val <- solution$value primal_vars <- list() primal_vars[[inverse_data[[object@var_id]]]] <- solution$primal eq_dual <- get_dual_values(solution$eq_dual, extract_dual_value, inverse_data[object@eq_constr]) leq_dual <- get_dual_values(solution$ineq_dual, extract_dual_value, inverse_data[object@neq_constr]) eq_dual <- utils::modifyList(eq_dual, leq_dual) dual_vars <- eq_dual } else { primal_vars <- list() primal_vars[[inverse_data[[object@var_id]]]] <- NA_real_ dual_vars <- NA if(status == INFEASIBLE) opt_val <- Inf else if(status == UNBOUNDED) opt_val <- -Inf else opt_val <- NA_real_ } return(Solution(status, opt_val, primal_vars, dual_vars, list())) }) #' #' An interface for the ECOS solver #' #' @name ECOS-class #' @aliases ECOS #' @rdname ECOS-class #' @export setClass("ECOS", representation(exp_cone_order = "numeric"), # Order of exponential cone arguments for solver. Internal only! prototype(exp_cone_order = c(0, 2, 1)), contains = "ConicSolver") #' @rdname ECOS-class #' @export ECOS <- function() { new("ECOS") } # Solver capabilities. #' @describeIn ECOS Can the solver handle mixed-integer programs? setMethod("mip_capable", "ECOS", function(solver) { FALSE }) setMethod("supported_constraints", "ECOS", function(solver) { c(supported_constraints(ConicSolver()), "SOC", "ExpCone") }) # EXITCODES from ECOS # ECOS_OPTIMAL (0) Problem solved to optimality # ECOS_PINF (1) Found certificate of primal infeasibility # ECOS_DINF (2) Found certificate of dual infeasibility # ECOS_INACC_OFFSET (10) Offset exitflag at inaccurate results # ECOS_MAXIT (-1) Maximum number of iterations reached # ECOS_NUMERICS (-2) Search direction unreliable # ECOS_OUTCONE (-3) s or z got outside the cone, numerics? # ECOS_SIGINT (-4) solver interrupted by a signal/ctrl-c # ECOS_FATAL (-7) Unknown problem in solver # Map of ECOS status to CVXR status. #' @param solver,object,x A \linkS4class{ECOS} object. #' @param status A status code returned by the solver. #' @describeIn ECOS Converts status returned by the ECOS solver to its respective CVXPY status. setMethod("status_map", "ECOS", function(solver, status) { if(status == 0) return(OPTIMAL) else if(status == 1) return(INFEASIBLE) else if(status == 2) return(UNBOUNDED) else if(status == 10) return(OPTIMAL_INACCURATE) else if(status == 11) return(INFEASIBLE_INACCURATE) else if(status == 12) return(UNBOUNDED_INACCURATE) else if(status %in% c(-1, -2, -3, -4, -7)) return(SOLVER_ERROR) else stop("ECOS status unrecognized: ", status) }) #' @describeIn ECOS Imports the solver ##setMethod("import_solver", "ECOS", function(solver) { requireNamespace("ECOSolveR", quietly = TRUE) }) ## Since ECOS is required, this is always TRUE setMethod("import_solver", "ECOS", function(solver) { TRUE }) #' @describeIn ECOS Returns the name of the solver setMethod("name", "ECOS", function(x) { ECOS_NAME }) #' @param problem A \linkS4class{Problem} object. #' @describeIn ECOS Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "ECOS", problem = "Problem"), function(object, problem) { data <- list() inv_data <- list() inv_data[[object@var_id]] <- id(variables(problem)[[1]]) offsets <- ConicSolver.get_coeff_offset(problem@objective@args[[1]]) data[[C_KEY]] <- as.vector(offsets[[1]]) data[[OFFSET]] <- offsets[[2]] inv_data[[OFFSET]] <- data[[OFFSET]][1] constr_map <- group_constraints(problem@constraints) data[[ConicSolver()@dims]] <- ConeDims(constr_map) inv_data[[object@eq_constr]] <- constr_map$ZeroConstraint offsets <- group_coeff_offset(object, problem, constr_map$ZeroConstraint, ECOS()@exp_cone_order) data[[A_KEY]] <- offsets[[1]] data[[B_KEY]] <- offsets[[2]] # Order and group nonlinear constraints. neq_constr <- c(constr_map$NonPosConstraint, constr_map$SOC, constr_map$ExpCone) inv_data[[object@neq_constr]] <- neq_constr offsets <- group_coeff_offset(object, problem, neq_constr, ECOS()@exp_cone_order) data[[G_KEY]] <- offsets[[1]] data[[H_KEY]] <- offsets[[2]] return(list(object, data, inv_data)) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn ECOS Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "ECOS", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { status <- status_map(object, solution$retcodes[["exitFlag"]]) # Timing data. attr <- list() attr[[SOLVE_TIME]] <- solution$timing[["tsolve"]] attr[[SETUP_TIME]] <- solution$timing[["tsetup"]] attr[[NUM_ITERS]] <- solution$retcodes[["iter"]] if(status %in% SOLUTION_PRESENT) { primal_val <- solution$summary[["pcost"]] opt_val <- primal_val + inverse_data[[OFFSET]] primal_vars <- list() var_id <- inverse_data[[object@var_id]] primal_vars[[as.character(var_id)]] <- as.matrix(solution$x) eq_dual <- get_dual_values(solution$y, extract_dual_value, inverse_data[[object@eq_constr]]) leq_dual <- get_dual_values(solution$z, extract_dual_value, inverse_data[[object@neq_constr]]) eq_dual <- utils::modifyList(eq_dual, leq_dual) dual_vars <- eq_dual return(Solution(status, opt_val, primal_vars, dual_vars, attr)) } else return(failure_solution(status)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose An integer number indicating level of solver verbosity. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn ReductionSolver Solve a problem represented by data returned from apply. setMethod("solve_via_data", "ECOS", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) cones <- ECOS.dims_to_solver_dict(data[[ConicSolver()@dims]]) if(is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$ECOS$feastol } if(is.null(reltol)) { reltol <- SOLVER_DEFAULT_PARAM$ECOS$reltol } if(is.null(abstol)) { abstol <- SOLVER_DEFAULT_PARAM$ECOS$abstol } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$ECOS$maxit } ecos_opts <- ECOSolveR::ecos.control(maxit = as.integer(num_iter), feastol = feastol, reltol = reltol, abstol = abstol, verbose = as.integer(verbose)) ecos_opts[names(solver_opts)] <- solver_opts solution <- ECOSolveR::ECOS_csolve(c = data[[C_KEY]], G = data[[G_KEY]], h = data[[H_KEY]], dims = cones, A = data[[A_KEY]], b = data[[B_KEY]], control = ecos_opts) return(solution) }) #' An interface for the SCS solver #' #' @name SCS-class #' @aliases SCS #' @rdname SCS-class #' @export setClass("SCS", representation(exp_cone_order = "numeric"), # Order of exponential cone arguments for solver. Internal only! prototype(exp_cone_order = c(0, 1, 2)), contains = "ConicSolver") #' @rdname SCS-class #' @export SCS <- function() { new("SCS") } # Solver capabilities. #' @describeIn SCS Can the solver handle mixed-integer programs? setMethod("mip_capable", "SCS", function(solver) { FALSE }) setMethod("requires_constr", "SCS", function(solver) { TRUE }) setMethod("supported_constraints", "SCS", function(solver) { c(supported_constraints(ConicSolver()), "SOC", "ExpCone", "PSDConstraint") }) # Map of SCS status to CVXR status. #' @param solver,object,x A \linkS4class{SCS} object. #' @param status A status code returned by the solver. #' @describeIn SCS Converts status returned by SCS solver to its respective CVXPY status. setMethod("status_map", "SCS", function(solver, status) { if(status == "solved") return(OPTIMAL) else if(grepl("solved.*inaccurate", status)) return(OPTIMAL_INACCURATE) else if(status == "unbounded") return(UNBOUNDED) else if(grepl("unbounded.*inaccurate", status)) return(UNBOUNDED_INACCURATE) else if(status == "infeasible") return(INFEASIBLE) else if(grepl("infeasible.*inaccurate", status)) return(INFEASIBLE_INACCURATE) else if(status %in% c("failure", "indeterminate", "interrupted")) return(SOLVER_ERROR) else stop("SCS status unrecognized: ", status) }) #' @describeIn SCS Returns the name of the solver setMethod("name", "SCS", function(x) { SCS_NAME }) #' @describeIn SCS Imports the solver ##setMethod("import_solver", "SCS", function(solver) { requireNamespace("scs", quietly = TRUE) }) ## Since scs is required, this is always TRUE setMethod("import_solver", "SCS", function(solver) { TRUE }) #' @param problem A \linkS4class{Problem} object. #' @param constr A \linkS4class{Constraint} to format. #' @param exp_cone_order A list indicating how the exponential cone arguments are ordered. #' @describeIn SCS Return a linear operator to multiply by PSD constraint coefficients. setMethod("reduction_format_constr", "SCS", function(object, problem, constr, exp_cone_order) { # Extract coefficient and offset vector from constraint. # Special cases PSD constraints, as SCS expects constraints to be # imposed on solely the lower triangular part of the variable matrix. # Moreover, it requires the off-diagonal coefficients to be scaled by # sqrt(2). if(is(constr, "PSDConstraint")) { expr <- expr(constr) triangularized_expr <- scaled_lower_tri(expr + t(expr))/2 extractor <- CoeffExtractor(InverseData(problem)) Ab <- affine(extractor, triangularized_expr) A_prime <- Ab[[1]] b_prime <- Ab[[2]] # SCS requests constraints to be formatted as Ax + s = b, # where s is constrained to reside in some cone. Here, however, # we are formatting the constraint as A"x + b" = -Ax + b; h ence, # A = -A", b = b". return(list(-1*A_prime, b_prime)) } else callNextMethod(object, problem, constr, exp_cone_order) }) #' @describeIn SCS Returns a new problem and data for inverting the new solution setMethod("perform", signature(object = "SCS", problem = "Problem"), function(object, problem) { # Returns a new problem and data for inverting the new solution. data <- list() inv_data <- list() inv_data[[object@var_id]] <- id(variables(problem)[[1]]) # Parse the coefficient vector from the objective. offsets <- ConicSolver.get_coeff_offset(problem@objective@args[[1]]) data[[C_KEY]] <- offsets[[1]] data[[OFFSET]] <- offsets[[2]] data[[C_KEY]] <- as.vector(data[[C_KEY]]) inv_data[[OFFSET]] <- data[[OFFSET]][1] # Order and group nonlinear constraints. constr_map <- group_constraints(problem@constraints) data[[ConicSolver()@dims]] <- ConeDims(constr_map) inv_data[[ConicSolver()@dims]] <- data[[ConicSolver()@dims]] # SCS requires constraints to be specified in the following order: # 1) Zero cone. # 2) Non-negative orthant. # 3) SOC. # 4) PSD. # 5) Exponential. zero_constr <- constr_map$ZeroConstraint neq_constr <- c(constr_map$NonPosConstraint, constr_map$SOC, constr_map$PSDConstraint, constr_map$ExpCone) inv_data[[object@eq_constr]] <- zero_constr inv_data[[object@neq_constr]] <- neq_constr # Obtain A, b such that Ax + s = b, s \in cones. # Note that SCS mandates that the cones MUST be ordered with # zero cones first, then non-negative orthant, then SOC, then # PSD, then exponential. offsets <- group_coeff_offset(object, problem, c(zero_constr, neq_constr), object@exp_cone_order) data[[A_KEY]] <- offsets[[1]] data[[B_KEY]] <- offsets[[2]] return(list(object, data, inv_data)) }) #' #' Extracts the dual value for constraint starting at offset. #' #' Special cases PSD constraints, as per the SCS specification. #' #' @param result_vec The vector to extract dual values from. #' @param offset The starting point of the vector to extract from. #' @param constraint A \linkS4class{Constraint} object. #' @return The dual values for the corresponding PSD constraints SCS.extract_dual_value <- function(result_vec, offset, constraint) { if(is(constraint, "PSDConstraint")) { dim <- nrow(constraint) lower_tri_dim <- floor(dim*(dim+1)/2) new_offset <- offset + lower_tri_dim lower_tri <- result_vec[(offset + 1):new_offset] full <- tri_to_full(lower_tri, dim) return(list(full, new_offset)) } else return(extract_dual_value(result_vec, offset, constraint)) } #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn SCS Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "SCS", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { # Returns the solution to the original problem given the inverse_data. status <- status_map(object, solution$info$status) attr <- list() attr[[SOLVE_TIME]] <- solution$info$solveTime attr[[SETUP_TIME]] <- solution$info$setupTime attr[[NUM_ITERS]] <- solution$info$iter if(status %in% SOLUTION_PRESENT) { primal_val <- solution$info$pobj opt_val <- primal_val + inverse_data[[OFFSET]] primal_vars <- list() var_id <- inverse_data[[object@var_id]] primal_vars[[as.character(var_id)]] <- as.matrix(solution$x) num_zero <- inverse_data[[ConicSolver()@dims]]@zero eq_idx <- seq_len(num_zero) ineq_idx <- seq(num_zero + 1, length.out = length(solution$y) - num_zero) eq_dual_vars <- get_dual_values(solution$y[eq_idx], SCS.extract_dual_value, inverse_data[[object@eq_constr]]) ineq_dual_vars <- get_dual_values(solution$y[ineq_idx], SCS.extract_dual_value, inverse_data[[object@neq_constr]]) dual_vars <- list() dual_vars <- utils::modifyList(dual_vars, eq_dual_vars) dual_vars <- utils::modifyList(dual_vars, ineq_dual_vars) return(Solution(status, opt_val, primal_vars, dual_vars, attr)) } else return(failure_solution(status)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn SCS Solve a problem represented by data returned from apply. setMethod("solve_via_data", "SCS", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) # TODO: Cast A to dense because scs R package rejects sparse matrices? ## Fix until scs::scs can handle sparse symmetric matrices A <- data[[A_KEY]] ## Fix for Matrix version 1.3 ## if (inherits(A, "dsCMatrix")) A <- as(A, "dgCMatrix") ## if (!inherits(A, "dgCMatrix")) A <- as(as(A, "CsparseMatrix"), "dgCMatrix") ## Matrix 1.5 change! if (!inherits(A, "dgCMatrix")) A <- as(as(A, "CsparseMatrix"), "generalMatrix") args <- list(A = A, b = data[[B_KEY]], c = data[[C_KEY]]) if(warm_start && !is.null(solver_cache) && length(solver_cache) > 0 && name(object) %in% names(solver_cache)) { args$x <- solver_cache[[name(object)]]$x args$y <- solver_cache[[name(object)]]$y args$s <- solver_cache[[name(object)]]$s } cones <- SCS.dims_to_solver_dict(data[[ConicSolver()@dims]]) ## if(!all(c(is.null(feastol), is.null(reltol), is.null(abstol)))) { ## warning("Ignoring inapplicable parameter feastol/reltol/abstol for SCS.") ## } solver_defaults <- SOLVER_DEFAULT_PARAM$SCS if(is.null(num_iter)) { num_iter <- solver_defaults$max_iters } if (is.null(reltol)) { reltol <- solver_defaults$eps_rel } if (is.null(abstol)) { abstol <- solver_defaults$eps_abs } if (is.null(feastol)) { feastol <- solver_defaults$eps_infeas } control = scs::scs_control(max_iters = num_iter, verbose = verbose, eps_rel = reltol, eps_abs = abstol, eps_infeas = feastol) #Fill in parameter values control[names(solver_opts)] <- solver_opts # Returns the result of the call to the solver. results <- scs::scs(A = args$A, b = args$b, obj = args$c, cone = cones, control = control) if(!is.null(solver_cache) && length(solver_cache) > 0) solver_cache[[name(object)]] <- results return(results) }) #' An interface to the CBC solver #' #' @name CBC_CONIC-class #' @aliases CBC_CONIC #' @rdname CBC_CONIC-class #' @export setClass("CBC_CONIC", contains = "SCS") #' @rdname CBC_CONIC-class #' @export CBC_CONIC <- function() { new("CBC_CONIC") } # Solver capabilities. #' @describeIn CBC_CONIC Can the solver handle mixed-integer programs? setMethod("mip_capable", "CBC_CONIC", function(solver) { TRUE }) #' @param solver,object,x A \linkS4class{CBC_CONIC} object. #' @param status A status code returned by the solver. #' @describeIn CBC_CONIC Converts status returned by the CBC solver to its respective CVXPY status. setMethod("status_map", "CBC_CONIC", function(solver, status) { if(status$is_proven_optimal) OPTIMAL else if(status$is_proven_dual_infeasible || status$is_proven_infeasible) INFEASIBLE else SOLVER_ERROR # probably need to check this the most }) # Map of CBC_CONIC MIP/LP status to CVXR status. #' @describeIn CBC_CONIC Converts status returned by the CBC solver to its respective CVXPY status for mixed integer problems. setMethod("status_map_mip", "CBC_CONIC", function(solver, status) { if(status == "solution") OPTIMAL else if(status == "relaxation_infeasible") INFEASIBLE else if(status == "stopped_on_user_event") SOLVER_ERROR else stop("CBC_CONIC MIP status unrecognized: ", status) }) #' @describeIn CBC_CONIC Converts status returned by the CBC solver to its respective CVXPY status for linear problems. setMethod("status_map_lp", "CBC_CONIC", function(solver, status) { if(status == "optimal") OPTIMAL else if(status == "primal_infeasible") INFEASIBLE else if(status == "stopped_due_to_errors" || status == "stopped_by_event_handler") SOLVER_ERROR else stop("CBC_CONIC LP status unrecognized: ", status) }) #' @describeIn CBC_CONIC Returns the name of the solver setMethod("name", "CBC_CONIC", function(x) { CBC_NAME }) #' @describeIn CBC_CONIC Imports the solver setMethod("import_solver", "CBC_CONIC", function(solver) { requireNamespace("rcbc", quietly = TRUE) }) #' @param problem A \linkS4class{Problem} object. #' @describeIn CBC_CONIC Can CBC_CONIC solve the problem? setMethod("accepts", signature(object = "CBC_CONIC", problem = "Problem"), function(object, problem) { # Can CBC_CONIC solve the problem? # TODO: Check if the matrix is stuffed. if(!is_affine(problem@objective@args[[1]])) return(FALSE) for(constr in problem@constraints) { if(!inherits(constr, supported_constraints(object))) return(FALSE) for(arg in constr@args) { if(!is_affine(arg)) return(FALSE) } } return(TRUE) }) #' @describeIn CBC_CONIC Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "CBC_CONIC", problem = "Problem"), function(object, problem) { tmp <- callNextMethod(object, problem) object <- tmp[[1]] data <- tmp[[2]] inv_data <- tmp[[3]] variables <- variables(problem)[[1]] data[[BOOL_IDX]] <- lapply(variables@boolean_idx, function(t) { t[1] }) data[[INT_IDX]] <- lapply(variables@integer_idx, function(t) { t[1] }) inv_data$is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 return(list(object, data, inv_data)) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn CBC_CONIC Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "CBC_CONIC", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { solution <- solution[[1]] status <- status_map(object, solution) primal_vars <- list() dual_vars <- list() if(status %in% SOLUTION_PRESENT) { opt_val <- solution$objective_value primal_vars[[object@var_id]] <- solution$column_solution } else { if(status == INFEASIBLE) opt_val <- Inf else if(status == UNBOUNDED) opt_val <- -Inf else opt_val <- NA_real_ } return(Solution(status, opt_val, primal_vars, dual_vars, list())) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn CBC_CONIC Solve a problem represented by data returned from apply. setMethod("solve_via_data", "CBC_CONIC", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) cvar <- data$c b <- data$b ## Conversion below forced by changes in Matrix package version 1.3.x A <- as(as(data$A, "CsparseMatrix"), "dgTMatrix") dims <- SCS.dims_to_solver_dict(data$dims) if(is.null(dim(data$c))){ n <- length(cvar) # Should dim be used here? } else { n <- dim(cvar)[1] } # Initialize variable constraints var_lb <- rep(-Inf, n) var_ub <- rep(Inf, n) is_integer <- rep.int(FALSE, n) row_ub <- rep(Inf, nrow(A)) row_lb <- rep(-Inf, nrow(A)) #Setting equality constraints if(dims[[EQ_DIM]] > 0){ row_ub[1:dims[[EQ_DIM]]] <- b[1:dims[[EQ_DIM]]] row_lb[1:dims[[EQ_DIM]]] <- b[1:dims[[EQ_DIM]]] } #Setting inequality constraints leq_start <- dims[[EQ_DIM]] leq_end <- dims[[EQ_DIM]] + dims[[LEQ_DIM]] if(leq_start != leq_end){ row_ub[(leq_start+1):(leq_end)] <- b[(leq_start+1):(leq_end)] } # Make boolean constraints if(length(data$bool_vars_idx) > 0){ var_lb[unlist(data$bool_vars_idx)] <- 0 var_ub[unlist(data$bool_vars_idx)] <- 1 is_integer[unlist(data$bool_vars_idx)] <- TRUE } if(length(data$int_vars_idx) > 0) { is_integer[unlist(data$int_vars_idx)] <- TRUE } #Warnigs for including parameters if(!all(c(is.null(feastol), is.null(reltol), is.null(abstol), is.null(num_iter)))) { warning("Ignoring inapplicable parameter feastol/reltol/abstol for CBC.") } result <- rcbc::cbc_solve( obj = cvar, mat = A, row_ub = row_ub, row_lb = row_lb, col_lb = var_lb, col_ub = var_ub, is_integer = is_integer, max = FALSE, cbc_args = solver_opts ) return(list(result)) }) #' An interface for the CPLEX solver #' #' @name CPLEX_CONIC-class #' @aliases CPLEX_CONIC #' @rdname CPLEX_CONIC-class #' @export CPLEX_CONIC <- setClass("CPLEX_CONIC", contains = "SCS") #' @rdname CPLEX_CONIC-class #' @export CPLEX_CONIC <- function() { new("CPLEX_CONIC") } #' @describeIn CPLEX_CONIC Can the solver handle mixed-integer programs? setMethod("mip_capable", "CPLEX_CONIC", function(solver) { TRUE }) setMethod("supported_constraints", "CPLEX_CONIC", function(solver) { c(supported_constraints(ConicSolver()), "SOC") }) #' @param solver,object,x A \linkS4class{CPLEX_CONIC} object. #' @describeIn CPLEX_CONIC Returns the name of the solver. setMethod("name", "CPLEX_CONIC", function(x) { CPLEX_NAME }) #' @describeIn CPLEX_CONIC Imports the solver. setMethod("import_solver", "CPLEX_CONIC", function(solver) { requireNamespace("Rcplex", quietly = TRUE) }) #' @param problem A \linkS4class{Problem} object. #' @describeIn CPLEX_CONIC Can CPLEX solve the problem? setMethod("accepts", signature(object = "CPLEX_CONIC", problem = "Problem"), function(object, problem) { # Can CPLEX solve the problem? # TODO: Check if the matrix is stuffed. if(!is_affine(problem@objective@args[[1]])) return(FALSE) for(constr in problem@constraints) { if(!inherits(constr, supported_constraints(object))) return(FALSE) for(arg in constr@args) { if(!is_affine(arg)) return(FALSE) } } return(TRUE) }) # Map of CPLEX status to CVXR status. # TODO: Add more! #' @param status A status code returned by the solver. #' @describeIn CPLEX_CONIC Converts status returned by the CPLEX solver to its respective CVXPY status. setMethod("status_map", "CPLEX_CONIC", function(solver, status) { if(status %in% c(1, 101, 102)){ OPTIMAL } else if(status %in% c(3, 22, 4, 103)){ INFEASIBLE } else if(status %in% c(2, 21, 118)){ UNBOUNDED } else if(status %in% c(10, 107)){ USER_LIMIT } else stop("CPLEX status unrecognized: ", status) }) #' @describeIn CPLEX_CONIC Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "CPLEX_CONIC", problem = "Problem"), function(object, problem) { #COPIED OVER FROM SCS CONIC, which is what CVXPY does (except they superclass it to a class w the same method) # Returns a new problem and data for inverting the new solution. data <- list() inv_data <- list() inv_data[[object@var_id]] <- id(variables(problem)[[1]]) # Parse the coefficient vector from the objective. offsets <- ConicSolver.get_coeff_offset(problem@objective@args[[1]]) data[[C_KEY]] <- offsets[[1]] data[[OFFSET]] <- offsets[[2]] data[[C_KEY]] <- as.vector(data[[C_KEY]]) inv_data[[OFFSET]] <- data[[OFFSET]][1] # Order and group nonlinear constraints. constr_map <- group_constraints(problem@constraints) data[[ConicSolver()@dims]] <- ConeDims(constr_map) inv_data[[ConicSolver()@dims]] <- data[[ConicSolver()@dims]] # SCS requires constraints to be specified in the following order: # 1) Zero cone. # 2) Non-negative orthant. # 3) SOC. # 4) PSD. # 5) Exponential. zero_constr <- constr_map$ZeroConstraint neq_constr <- c(constr_map$NonPosConstraint, constr_map$SOC, constr_map$PSDConstraint, constr_map$ExpCone) inv_data[[object@eq_constr]] <- zero_constr inv_data[[object@neq_constr]] <- neq_constr inv_data$is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 # Obtain A, b such that Ax + s = b, s \in cones. # Note that SCS mandates that the cones MUST be ordered with # zero cones first, then non-negative orthant, then SOC, then # PSD, then exponential. offsets <- group_coeff_offset(object, problem, c(zero_constr, neq_constr), object@exp_cone_order) data[[A_KEY]] <- offsets[[1]] data[[B_KEY]] <- offsets[[2]] # Include Boolean and Integer indices variables <- variables(problem)[[1]] data[[BOOL_IDX]] <- lapply(variables@boolean_idx, function(t) { t[1] }) data[[INT_IDX]] <- lapply(variables@integer_idx, function(t) { t[1] }) inv_data$is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 return(list(object, data, inv_data)) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn CPLEX_CONIC Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "CPLEX_CONIC", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { # Returns the solution to the original problem given the inverse_data. model <- solution$model status <- status_map(object, model$status) primal_vars <- list() dual_vars <- list() if(status %in% SOLUTION_PRESENT) { #Get objective value opt_val <- model$obj + inverse_data[[OFFSET]] #Get solution primal_vars[[as.character(inverse_data[[object@var_id]])]] <- model$xopt #Only add duals if not a MIP if(!inverse_data[["is_mip"]]) { #eq and leq constraints all returned at once by CPLEX eq_dual <- get_dual_values(solution$eq_dual, extract_dual_value, inverse_data[[object@eq_constr]]) leq_dual <- get_dual_values(solution$ineq_dual, extract_dual_value, inverse_data[[object@neq_constr]]) eq_dual <- utils::modifyList(eq_dual, leq_dual) #dual_vars <- get_dual_values(solution$y, extract_dual_value, inverse_data[[object@neq_constr]]) dual_vars <- eq_dual } } else { primal_vars[[as.character(inverse_data[[object@var_id]])]] <- NA_real_ if(!inverse_data[["is_mip"]]) { dual_var_ids <- sapply(c(inverse_data[[object@eq_constr]], inverse_data[[object@neq_constr]]), function(constr) { constr@id }) dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) names(dual_vars) <- dual_var_ids } if(status == INFEASIBLE) opt_val <- Inf else if(status == UNBOUNDED) opt_val <- -Inf else opt_val <- NA_real_ } return(Solution(status, opt_val, primal_vars, dual_vars, list())) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn CPLEX_CONIC Solve a problem represented by data returned from apply. setMethod("solve_via_data", "CPLEX_CONIC", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) cvar <- data[[C_KEY]] bvec <- data[[B_KEY]] Amat <- data[[A_KEY]] dims <- data[[DIMS]] total_soc <- sum(unlist(dims@soc)) n_var <- length(cvar) cvar <- c(cvar, rep(0, total_soc)) #Initializing variable types vtype <- rep("C", n_var + total_soc) #Setting Boolean variable types for(i in seq_along(data[BOOL_IDX]$bool_vars_idx)){ vtype[data[BOOL_IDX]$bool_vars_idx[[i]]] <- "B" } #Setting Integer variable types for(i in seq_along(data[INT_IDX]$int_vars_idx)){ vtype[data[BOOL_IDX]$int_vars_idx[[i]]] <- "I" } #Setting sense of the A matrix sense_vec <- rep("E", nrow(Amat)) #Add inequalities leq_start <- dims@zero leq_end <- dims@zero + dims@nonpos for(j in leq_start:leq_end){ sense_vec[j + 1] <- "L" } #Setting Lower bounds of variables lb <- rep(-Inf, n_var + total_soc) qc <- list() soc_start <- leq_start + dims@nonpos current_var <- n_var for(i in seq_along(dims@soc)){ for(j in 1:dims@soc[[i]]){ sense_vec[soc_start + dims@soc[[i]][j]] <- "E" if(j == 1){ lb[current_var + j] <- 0 #The first variable of every SOC has a 0 lower bound } } #Add SOC vars to linear constraints n_soc <- dims@soc[[i]] Asub <- matrix(0, nrow = nrow(Amat), ncol = n_soc) Asub[(soc_start+1):(soc_start + n_soc),] <- diag(rep(1, n_soc)) Amat <- cbind(Amat, Asub) #Add quadratic constraints qc_mat <- matrix(0, nrow = n_var + total_soc, ncol = n_var + total_soc) qc_mat[current_var + 1, current_var + 1] <- -1 for(k in 1:(n_soc-1)){ qc_mat[current_var + 1 + k, current_var + 1 + k] <- 1 } qc[[i]] <- qc_mat soc_start <- soc_start + n_soc current_var <- current_var + n_soc } QC <- list(QC = list(Q = qc), dir = rep("L", length(dims@soc)) , b = rep(0.0, length(dims@soc))) ## Throw parameter warnings if(!all(c(is.null(feastol), is.null(reltol), is.null(abstol)))) { warning("Ignoring inapplicable parameter feastol/reltol/abstol for CPLEX.") } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$CPLEX$itlim } #Setting verbosity off control <- list(trace = verbose, itlim = num_iter) #Setting rest of the parameters control[names(solver_opts)] <- solver_opts # Solve problem. results_dict <- list() tryCatch({ # Define CPLEX problem and solve model <- Rcplex::Rcplex_solve_QCP(cvec=cvar, Amat=Amat, bvec=bvec, QC=QC, lb=lb, ub=Inf, sense=sense_vec, objsense="min", vtype=vtype, control=control) }, error = function(e) { results_dict$status <- SOLVER_ERROR }) #Changing dualvar to include SOC y <- model$extra$lambda soc_start <- leq_start + dims@nonpos for(i in seq_along(dims@soc)){ y <- append(y, 0, soc_start) soc_start <- soc_start + dims@soc[[i]] + 1 } results_dict$y <- -y results_dict$model <- model results_dict$eq_dual <- results_dict$y[1:dims@zero] results_dict$ineq_dual <- results_dict$y[-(1:dims@zero)] return(results_dict) }) #' An interface for the CVXOPT solver. #' setClass("CVXOPT", contains = "ECOS") CVXOPT <- function() { new("CVXOPT") } # Solver capabilities. #' @describeIn CVXOPT Can the solver handle mixed-integer programs? setMethod("mip_capable", "CVXOPT", function(solver) { FALSE }) setMethod("supported_constraints", "CVXOPT", function(solver) { c(supported_constraints(ConicSolver()), "SOC", "PSDConstraint") }) # Map of CVXOPT status to CVXR status. #' @param solver,object,x A \linkS4class{CVXOPT} object. #' @param status A status code returned by the solver. #' @describeIn CVXOPT Converts status returned by the CVXOPT solver to its respective CVXPY status. setMethod("status_map", "CVXOPT", function(solver, status) { if(status == "optimal") OPTIMAL else if(status %in% c("infeasible", "primal infeasible", "LP relaxation is primal infeasible")) INFEASIBLE else if(status %in% c("unbounded", "LP relaxation is dual infeasible", "dual infeasible")) UNBOUNDED else if(status %in% c("solver_error", "unknown", "undefined")) SOLVER_ERROR else stop("CVXOPT status unrecognized: ", status) }) #' @describeIn CVXOPT Returns the name of the solver. setMethod("name", "CVXOPT", function(x) { CVXOPT_NAME }) #' @describeIn CVXOPT Imports the solver. ## CVXOPT is not implemented as there is no R package equivalent to cccopt. We should check out cccp, though setMethod("import_solver", "CVXOPT", function(solver) { requireNamespace("cccp", quietly = TRUE) }) #' @param problem A \linkS4class{Problem} object. #' @describeIn CVXOPT Can CVXOPT solve the problem? setMethod("accepts", signature(object = "CVXOPT", problem = "Problem"), function(object, problem) { # Can CVXOPT solver the problem? # TODO: Check if the matrix is stuffed. import_solver(object) if(!is_affine(problem@objective@args[[1]])) return(FALSE) for(constr in problem@constraints) { if(!inherits(constr, supported_constraints(object))) return(FALSE) for(arg in constr@args) { if(!is_affine(arg)) return(FALSE) } } return(TRUE) }) #' @describeIn CVXOPT Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "CVXOPT", problem = "Problem"), function(object, problem) { data <- list() inv_data <- list() inv_data[[object@var_id]] <- id(variables(problem)[[1]]) tmp <- ConicSolver.get_coeff_offset(problem@objective@args[[1]]) data[[C_KEY]] <- as.vector(tmp[[1]]) data[[OFFSET]] <- tmp[[2]] inv_data[[OFFSET]] <- data[[OFFSET]][1] constr_map <- group_constraints(problem@constraints) data[[ConicSolver()@dims]] <- ConeDims(constr_map) inv_data[[object@eq_constr]] <- constr_map$ZeroConstraint tmp <- group_coeff_offset(object, problem, constr_map$ZeroConstraint, ECOS()@exp_cone_order) data[[A_KEY]] <- tmp[[1]] data[[B_KEY]] <- tmp[[2]] # Order and group nonlinear constraints. neq_constr <- c(constr_map$NonPosConstraint, constr_map$SOC, constr_map$PSDConstraint) inv_data[[object@neq_constr]] <- neq_constr tmp <- group_coeff_offset(object, problem, neq_constr, ECOS()@exp_cone_order) data[[G_KEY]] <- tmp[[1]] data[[H_KEY]] <- tmp[[2]] var <- variables(problem)[[1]] data[[BOOL_IDX]] <- as.integer(var@boolean_idx[,1]) data[[INT_IDX]] <- as.integer(var@integer_idx[,1]) #Add information about return(list(object, data, inv_data)) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn CVXOPT Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "CVXOPT", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { status <- solution$status primal_vars <- list() dual_vars <- list() if(status %in% SOLUTION_PRESENT){ opt_val <- solution$value + inverse_data[[OFFSET]] primal_vars[[as.character(inverse_data[[object@var_id]])]] <- solution$primal eq_dual <- get_dual_values(solution$eq_dual, extract_dual_value, inverse_data[[object@eq_constr]]) leq_dual <- get_dual_values(solution$ineq_dual, extract_dual_value, inverse_data[[object@neq_constr]]) eq_dual <- utils::modifyList(eq_dual, leq_dual) dual_vars <- eq_dual return(Solution(status, opt_val, primal_vars, dual_vars, list())) } else { return(failure_solution(status)) } }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn CVXOPT Solve a problem represented by data returned from apply. setMethod("solve_via_data", "CVXOPT", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { #Tweak parameters if(is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$CVXOPT$feastol } if(is.null(reltol)) { reltol <- SOLVER_DEFAULT_PARAM$CVXOPT$reltol } if(is.null(abstol)) { abstol <- SOLVER_DEFAULT_PARAM$CVXOPT$abstol } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$CVXOPT$max_iters } param <- cccp::ctrl(maxiters=as.integer(num_iter), abstol=abstol, reltol=reltol, feastol=feastol, trace=as.logical(verbose)) param$params[names(solver_opts)] <- solver_opts G <- as.matrix(data[[G_KEY]]) h <- as.matrix(data[[H_KEY]]) nvar <- dim(G)[2] dims <- data[[DIMS]] zero_dims <- dims@zero nonpos_dims <- dims@nonpos soc_dims <- dims@soc psd_dims <- dims@psd clistLength <- (nonpos_dims > 0) + length(soc_dims) + length(psd_dims) # For all the constraints except the zero constraint clist <- vector(mode="list", length = clistLength) clistCounter <- 0 ghCounter <- 0 # Deal with non positive constraints if(nonpos_dims > 0){ clistCounter <- clistCounter + 1 indices <- seq.int(from = ghCounter + 1, length.out = nonpos_dims) clist[[clistCounter]] <- cccp::nnoc(G = G[indices, , drop = FALSE], h = h[indices, , drop = FALSE]) ghCounter <- ghCounter + nonpos_dims } # Deal with SOC constraints for(i in soc_dims){ clistCounter <- clistCounter + 1 indices <- seq.int(from = ghCounter + 2, length.out = i - 1) clist[[clistCounter]] <- cccp::socc(F = -G[indices, , drop = FALSE], g = h[indices, , drop = FALSE], d = -G[ghCounter + 1, , drop = FALSE], f = h[ghCounter + 1, , drop = FALSE]) ghCounter <- ghCounter + i } # Deal with PSD constraints for(i in psd_dims){ Flist <- vector(mode="list", length = nvar+1) indices <- seq.int(from = ghCounter + 1, length.out = i^2) currG <- G[indices, , drop = FALSE] currh <- h[indices, , drop = FALSE] Flist[[1]] <- matrix(currh, nrow = i) for(j in seq_len(nvar)){ Flist[[j+1]] <- matrix(currG[, j, drop = FALSE], nrow = i) } clistCounter <- clistCounter + 1 clist[[clistCounter]] <- cccp::psdc(Flist = Flist[-1], F0 = Flist[[1]]) ghCounter <- ghCounter + i } if(zero_dims > 0){ results <- cccp::cccp(q=data[[C_KEY]], A=as.matrix(data[[A_KEY]]), b=as.matrix(data[[B_KEY]]), cList=clist, optctrl=param) } else { results <- cccp::cccp(q=data[[C_KEY]], cList=clist, optctrl=param) } solution <- list() solution$status <- status_map(object, results$status) solution$value <- (results$state[1] + data[[OFFSET]])[[1]] solution$primal <- cccp::getx(results) solution$eq_dual <- cccp::gety(results) solution$ineq_dual <- unlist(cccp::getz(results)) #solution$ineq_dual <- as.matrix(c(temp[[1]], temp[[2]], temp[[3]], temp[[4]][abs(temp[[4]]) > 1e-8])[1:nrow(G)]) return(solution) }) #' An interface for the ECOS BB solver. #' #' @name ECOS_BB-class #' @aliases ECOS_BB #' @rdname ECOS_BB-class #' @export setClass("ECOS_BB", contains = "ECOS") #' @rdname ECOS_BB-class #' @export ECOS_BB <- function() { new("ECOS_BB") } #' @param solver,object,x A \linkS4class{ECOS_BB} object. #' @describeIn ECOS_BB Can the solver handle mixed-integer programs? setMethod("mip_capable", "ECOS_BB", function(solver) { TRUE }) #' @describeIn ECOS_BB Returns the name of the solver. setMethod("name", "ECOS_BB", function(x) { ECOS_BB_NAME }) #' @param problem A \linkS4class{Problem} object. #' @describeIn ECOS_BB Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "ECOS_BB", problem = "Problem"), function(object, problem) { res <- callNextMethod(object, problem) object <- res[[1]] data <- res[[2]] inv_data <- res[[3]] # Because the problem variable is single dimensional, every # boolean/integer index has length one. var <- variables(problem)[[1]] data[[BOOL_IDX]] <- as.integer(var@boolean_idx[,1]) data[[INT_IDX]] <- as.integer(var@integer_idx[,1]) return(list(object, data, inv_data)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn ECOS_BB Solve a problem represented by data returned from apply. setMethod("solve_via_data", "ECOS_BB", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) cones <- ECOS.dims_to_solver_dict(data[[ConicSolver()@dims]]) if(is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$ECOS_BB$feastol } if(is.null(reltol)) { reltol <- SOLVER_DEFAULT_PARAM$ECOS_BB$reltol } if(is.null(abstol)) { abstol <- SOLVER_DEFAULT_PARAM$ECOS_BB$abstol } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$ECOS_BB$maxit } num_iter <- as.integer(num_iter) ecos_opts <- ECOSolveR::ecos.control(maxit = num_iter, feastol = feastol, reltol = reltol, abstol = abstol, verbose = as.integer(verbose), mi_max_iters = num_iter) ecos_opts[names(solver_opts)] <- solver_opts solution <- ECOSolveR::ECOS_csolve(c = data[[C_KEY]], G = data[[G_KEY]], h = data[[H_KEY]], dims = cones, A = data[[A_KEY]], b = data[[B_KEY]], bool_vars = data[[BOOL_IDX]], int_vars = data[[INT_IDX]], control = ecos_opts) return(solution) }) #' #' Utility method for formatting a ConeDims instance into a dictionary #' that can be supplied to ECOS. #' #' @param cone_dims A \linkS4class{ConeDims} instance. #' @return A dictionary of cone dimensions #' @export ECOS.dims_to_solver_dict <- function(cone_dims) { cones <- list(l = as.integer(cone_dims@nonpos), q = lapply(cone_dims@soc, function(v) { as.integer(v) }), e = as.integer(cone_dims@exp)) return(cones) } #' An interface for the GLPK solver. #' #' @name GLPK-class #' @aliases GLPK #' @rdname GLPK-class #' @export setClass("GLPK", contains = "CVXOPT") #' @rdname GLPK-class #' @export GLPK <- function() { new("GLPK") } #' @describeIn GLPK Can the solver handle mixed-integer programs? setMethod("mip_capable", "GLPK", function(solver) { TRUE }) setMethod("supported_constraints", "GLPK", function(solver) { supported_constraints(ConicSolver()) }) #' @param solver,object,x A \linkS4class{GLPK} object. #' @param status A status code returned by the solver. #' @describeIn GLPK Converts status returned by the GLPK solver to its respective CVXPY status. setMethod("status_map", "GLPK", function(solver, status) { if(status == 5) OPTIMAL else if(status == 2) SOLUTION_PRESENT else if(status == 3 | status == 4) INFEASIBLE else if(status == 1 | status == 6) UNBOUNDED else stop("GLPK status unrecognized: ", status) }) #' @describeIn GLPK Returns the name of the solver. setMethod("name", "GLPK", function(x) { GLPK_NAME }) #' @describeIn GLPK Imports the solver. setMethod("import_solver", "GLPK", function(solver) { requireNamespace("Rglpk", quietly = TRUE) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn GLPK Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "GLPK", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { status <- solution$status primal_vars <- list() dual_vars <- list() if(status %in% SOLUTION_PRESENT) { opt_val <- solution$value primal_vars <- list() primal_vars[[as.character(inverse_data[[as.character(object@var_id)]])]] <- solution$primal return(Solution(status, opt_val, primal_vars, dual_vars, list())) } else return(failure_solution(status)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn GLPK Solve a problem represented by data returned from apply. setMethod("solve_via_data", "GLPK", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) if(verbose) solver_opts$verbose <- verbose solver_opts$canonicalize_status <- FALSE #Throw warnings if non-default values have been put in if(!is.null(feastol)){ warning("A value has been set for feastol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(reltol)){ warning("A value has been set for reltol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(abstol)){ warning("A value has been set for abstol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(num_iter)){ warning("A value has been set for num_iter, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } # Construct problem data. c <- data[[C_KEY]] dims <- data[[ConicSolver()@dims]] nvar <- length(c) A <- data[[A_KEY]] b <- data[[B_KEY]] if(nrow(A) == 0) A <- Matrix(0, nrow = 0, ncol = length(c)) G <- data[[G_KEY]] h <- data[[H_KEY]] if(nrow(G) == 0) G <- Matrix(0, nrow = 0, ncol = length(c)) mat <- rbind(A, G) rhs <- c(b, h) bounds <- list(lower = list(ind = seq_along(c), val = rep(-Inf, nvar))) types <- rep("C", nvar) bools <- data[[BOOL_IDX]] ints <- data[[INT_IDX]] if (length(bools) > 0) { types[bools] <- "B" } if (length(ints) > 0) { types[ints] <- "I" } results_dict <- Rglpk::Rglpk_solve_LP(obj = c, mat = slam::as.simple_triplet_matrix(mat), dir = c(rep("==", dims@zero), rep("<=", dims@nonpos)), rhs = rhs, bounds = bounds, types = types, control = solver_opts, max = FALSE) # Convert results to solution format. solution <- list() solution[[STATUS]] <- status_map(object, results_dict$status) if(solution[[STATUS]] %in% SOLUTION_PRESENT) { ## Get primal variable values solution[[PRIMAL]] <- results_dict$solution ## Get objective value solution[[VALUE]] <- results_dict$optimum # solution[[EQ_DUAL]] <- results_dict$auxiliary[[1]] # TODO: How do we get the dual variables? # solution[[INEQ_DUAL]] <- results_dict$auxiliar[[2]] } return(solution) }) #' An interface for the GLPK MI solver. #' #' @name GLPK_MI-class #' @aliases GLPK_MI #' @rdname GLPK_MI-class #' @export setClass("GLPK_MI", contains = "GLPK") #' @rdname GLPK_MI-class #' @export GLPK_MI <- function() { new("GLPK_MI") } #' @describeIn GLPK_MI Can the solver handle mixed-integer programs? setMethod("mip_capable", "GLPK_MI", function(solver) { TRUE }) setMethod("supported_constraints", "GLPK_MI", function(solver) { supported_constraints(ConicSolver()) }) # Map of GLPK_MI status to CVXR status. #' @param solver,object,x A \linkS4class{GLPK_MI} object. #' @param status A status code returned by the solver. #' @describeIn GLPK_MI Converts status returned by the GLPK_MI solver to its respective CVXPY status. setMethod("status_map", "GLPK_MI", function(solver, status) { if(status == 5) OPTIMAL else if(status == 2) SOLUTION_PRESENT #Not sure if feasible is the same thing as this else if(status == 3 | status == 4) INFEASIBLE else if(status == 1 | status == 6) UNBOUNDED else stop("GLPK_MI status unrecognized: ", status) }) #' @describeIn GLPK_MI Returns the name of the solver. setMethod("name", "GLPK_MI", function(x) { GLPK_MI_NAME }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn GLPK_MI Solve a problem represented by data returned from apply. setMethod("solve_via_data", "GLPK_MI", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) if(verbose) solver_opts$verbose <- verbose solver_opts$canonicalize_status <- FALSE if(!is.null(feastol)){ warning("A value has been set for feastol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(reltol)){ warning("A value has been set for reltol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(abstol)){ warning("A value has been set for abstol, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } if(!is.null(num_iter)){ warning("A value has been set for num_iter, but the GLPK solver does not accept this parameter. Solver will run without taking this parameter into consideration.") } # Construct problem data. c <- data[[C_KEY]] dims <- data[[ConicSolver()@dims]] nvar <- length(c) A <- data[[A_KEY]] b <- data[[B_KEY]] if(nrow(A) == 0) A <- Matrix(0, nrow = 0, ncol = length(c)) G <- data[[G_KEY]] h <- data[[H_KEY]] if(nrow(G) == 0) G <- Matrix(0, nrow = 0, ncol = length(c)) mat <- rbind(A, G) rhs <- c(b, h) bounds <- list(lower = list(ind = seq_along(c), val = rep(-Inf, nvar))) types <- rep("C", nvar) bools <- data[[BOOL_IDX]] ints <- data[[INT_IDX]] if (length(bools) > 0) { types[bools] <- "B" } if (length(ints) > 0) { types[ints] <- "I" } results_dict <- Rglpk::Rglpk_solve_LP(obj = c, mat = slam::as.simple_triplet_matrix(mat), dir = c(rep("==", dims@zero), rep("<=", dims@nonpos)), rhs = rhs, bounds = bounds, types = types, control = solver_opts, max = FALSE) # Convert results to solution format. solution <- list() solution[[STATUS]] <- status_map(object, results_dict$status) if(solution[[STATUS]] %in% SOLUTION_PRESENT) { ## Get primal variable values solution[[PRIMAL]] <- results_dict$solution ## Get objective value solution[[VALUE]] <- results_dict$optimum # solution[[EQ_DUAL]] <- results_dict$auxiliary[[1]] # TODO: How do we get the dual variables? # solution[[INEQ_DUAL]] <- results_dict$auxiliar[[2]] solution[[EQ_DUAL]] <- list() solution[[INEQ_DUAL]] <- list() } solution }) #' An interface for the GUROBI conic solver. #' #' @name GUROBI_CONIC-class #' @aliases GUROBI_CONIC #' @rdname GUROBI_CONIC-class #' @export setClass("GUROBI_CONIC", contains = "SCS") #' @rdname GUROBI_CONIC-class #' @export GUROBI_CONIC <- function() { new("GUROBI_CONIC") } # Solver capabilities. #' @param solver,object,x A \linkS4class{GUROBI_CONIC} object. #' @describeIn GUROBI_CONIC Can the solver handle mixed-integer programs? setMethod("mip_capable", "GUROBI_CONIC", function(solver) { TRUE }) setMethod("supported_constraints", "GUROBI_CONIC", function(solver) { c(supported_constraints(ConicSolver()), "SOC") }) # Is this one that's used? Should we delete? # Map of Gurobi status to CVXR status. # # @describeIn GUROBI_CONIC Converts status returned by the GUROBI solver to its respective CVXPY status. # setMethod("status_map", "GUROBI_CONIC", function(solver, status) { # if(status == 2) # return(OPTIMAL) # else if(status == 3) # return(INFEASIBLE) # else if(status == 5) # return(UNBOUNDED) # else if(status %in% c(4, 6, 7, 8, 10, 11, 12, 13)) # return(SOLVER_ERROR) # else if(status == 9) # TODO: Could be anything. Means time expired. # return(OPTIMAL_INACCURATE) # else # stop("GUROBI status unrecognized: ", status) # }) #' @describeIn GUROBI_CONIC Returns the name of the solver. setMethod("name", "GUROBI_CONIC", function(x) { GUROBI_NAME }) #' @describeIn GUROBI_CONIC Imports the solver. setMethod("import_solver", "GUROBI_CONIC", function(solver) { requireNamespace("gurobi", quietly = TRUE) }) # Map of GUROBI status to CVXR status. #' @param status A status code returned by the solver. #' @describeIn GUROBI_CONIC Converts status returned by the GUROBI solver to its respective CVXPY status. setMethod("status_map", "GUROBI_CONIC", function(solver, status) { if(status == 2 || status == "OPTIMAL") OPTIMAL else if(status == 3 || status == 6 || status == "INFEASIBLE") #DK: I added the words because the GUROBI solver seems to return the words INFEASIBLE else if(status == 5 || status == "UNBOUNDED") UNBOUNDED else if(status == 4 | status == "INF_OR_UNBD") INFEASIBLE_INACCURATE else if(status %in% c(7,8,9,10,11,12)) SOLVER_ERROR # TODO: Could be anything else if(status == 13) OPTIMAL_INACCURATE # Means time expired. else stop("GUROBI status unrecognized: ", status) }) #' @param problem A \linkS4class{Problem} object. #' @describeIn GUROBI_CONIC Can GUROBI_CONIC solve the problem? setMethod("accepts", signature(object = "GUROBI_CONIC", problem = "Problem"), function(object, problem) { # TODO: Check if the matrix is stuffed. if(!is_affine(problem@objective@args[[1]])) return(FALSE) for(constr in problem@constraints) { if(!inherits(constr, supported_constraints(object))) return(FALSE) for(arg in constr@args) { if(!is_affine(arg)) return(FALSE) } } return(TRUE) }) #' @describeIn GUROBI_CONIC Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "GUROBI_CONIC", problem = "Problem"), function(object, problem) { tmp <- callNextMethod(object, problem) object <- tmp[[1]] data <- tmp[[2]] inv_data <- tmp[[3]] variables <- variables(problem)[[1]] data[[BOOL_IDX]] <- lapply(variables@boolean_idx, function(t) { t[1] }) data[[INT_IDX]] <- lapply(variables@integer_idx, function(t) { t[1] }) inv_data$is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 return(list(object, data, inv_data)) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn GUROBI_CONIC Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "GUROBI_CONIC", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { status <- solution$status dual_vars <- list() #CVXPY doesn't include for some reason? #attr <- list() #attr[[SOLVE_TIME]] <- solution$runtime #attr[[NUM_ITERS]] <- solution$baritercount if(status %in% SOLUTION_PRESENT) { opt_val <- solution$value + inverse_data[[OFFSET]] primal_vars <- list() primal_vars[[as.character(inverse_data[[as.character(object@var_id)]])]] <- solution$primal if(!inverse_data[["is_mip"]]) { eq_dual <- get_dual_values(solution$eq_dual, extract_dual_value, inverse_data[[object@eq_constr]]) leq_dual <- get_dual_values(solution$ineq_dual, extract_dual_value, inverse_data[[object@neq_constr]]) eq_dual <- utils::modifyList(eq_dual, leq_dual) dual_vars <- eq_dual } } else { primal_vars <- list() primal_vars[[as.character(inverse_data[[as.character(object@var_id)]])]] <- NA_real_ if(!inverse_data[["is_mip"]]) { dual_var_ids <- sapply(c(inverse_data[[object@eq_constr]], inverse_data[[object@neq_constr]]), function(constr) { constr@id }) dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) names(dual_vars) <- dual_var_ids } if(status == INFEASIBLE) opt_val <- Inf else if(status == UNBOUNDED) opt_val <- -Inf else opt_val <- NA_real_ } return(Solution(status, opt_val, primal_vars, dual_vars, list())) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn GUROBI_CONIC Solve a problem represented by data returned from apply. setMethod("solve_via_data", "GUROBI_CONIC", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) cvar <- data[[C_KEY]] b <- data[[B_KEY]] A <- data[[A_KEY]] dims <- data[[DIMS]] n <- length(cvar) #Create a new model and add objective term model <- list() model$obj <- c(cvar, rep(0, sum(unlist(dims@soc)))) #Add variable types vtype <- character(n) for(i in seq_along(data[[BOOL_IDX]])){ vtype[data[[BOOL_IDX]][[i]]] <- 'B' #B for binary } for(i in seq_along(data[[INT_IDX]])){ vtype[data[[INT_IDX]][[i]]] <- 'I' #I for integer } for(i in 1:n) { if(vtype[i] == ""){ vtype[i] <- 'C' #C for continuous } } model$vtype <- vtype #put in variable types model$lb <- rep(-Inf, n) model$ub <- rep(Inf, n) # Add equality constraints: iterate over the rows of A, # adding each row into the model. model$A <- A model$rhs <- b model$sense <- c(rep('=', dims@zero), rep('<', dims@nonpos), rep('=', sum(unlist(dims@soc)))) total_soc <- sum(unlist(dims@soc)) current_vars <- n current_rows <- dims@zero + dims@nonpos + 1 # Add SOC variables # Sort of strange. A good example of how it works can be seen in # https://www.gurobi.com/documentation/8.1/examples/qcp_r.html#subsubsection:qcp.R for(i in seq_along(dims@soc)){ n_soc <- dims@soc[[i]] model$vtype <- c(model$vtype, rep('C', n_soc)) model$lb <- c(model$lb, 0, rep(-Inf, n_soc - 1)) model$ub <- c(model$ub, rep(Inf, n_soc)) Asub <- matrix(0, nrow = nrow(A), ncol = n_soc) Asub[current_rows:(current_rows + n_soc - 1),] <- diag(rep(1, n_soc)) model$A <- cbind(model$A, Asub) # To create quadratic constraints, first create a 0 square matrix with dimension of # the total number of variables (normal + SOC). Then fill the diagonals of the # SOC part with the first being negative and the rest being positive qc <- list() qc$Qc <- matrix(0, nrow = n + total_soc, ncol = n + total_soc) qc$Qc[current_vars + 1, current_vars + 1] <- -1 for(j in 1:(n_soc-1)){ qc$Qc[current_vars + 1 + j, current_vars + 1 + j] <- 1 } qc$rhs <- 0.0 model$quadcon[[i]] <- qc current_vars <- current_vars + n_soc current_rows = current_rows + n_soc } if(!all(c(is.null(reltol), is.null(abstol)))) { warning("Ignoring inapplicable parameter reltol/abstol for GUROBI.") } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$GUROBI$num_iter } if (is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$GUROBI$FeasibilityTol } params <- list(OutputFlag = as.numeric(verbose), QCPDual = 1, #equivalent to TRUE IterationLimit = num_iter, FeasibilityTol = feastol, OptimalityTol = feastol) params[names(solver_opts)] <- solver_opts solution <- list() tryCatch({ result <- gurobi::gurobi(model, params) # Solve. solution[["value"]] <- result$objval solution[["primal"]] <- result$x #Only add duals if it's not a MIP if(sum(unlist(data[[BOOL_IDX]])) + sum(unlist(data[[INT_IDX]])) == 0){ solution[["y"]] <- -append(result$pi, result$qcpi, dims@zero + dims@nonpos) if(dims@zero == 0){ solution[["eq_dual"]] <- c() solution[["ineq_dual"]] <- solution[["y"]] } else { solution[["eq_dual"]] <- solution[["y"]][1:dims@zero] solution[["ineq_dual"]] <- solution[["y"]][-(1:dims@zero)] } } }, error = function(e) { # Error in the solution. }) solution[[SOLVE_TIME]] <- result$runtime solution[["status"]] <- status_map(object, result$status) solution[["num_iters"]] <- result$baritercount # Is there a better way to check if there is a solution? # if(solution[["status"]] == SOLVER_ERROR && !is.na(result$x)){ # solution[["status"]] <- OPTIMAL_INACCURATE # } return(solution) }) #' An interface for the MOSEK solver. #' #' @name MOSEK-class #' @aliases MOSEK #' @rdname MOSEK-class #' @export setClass("MOSEK", representation(exp_cone_order = "numeric"), # Order of exponential cone constraints. Internal only! prototype(exp_cone_order = c(2, 1, 0)), contains = "ConicSolver") #' @rdname MOSEK-class #' @export MOSEK <- function() { new("MOSEK") } #' #' Turns symmetric 2D array into a lower triangular matrix #' #' @param v A list of length (dim * (dim + 1) / 2). #' @param dim The number of rows (equivalently, columns) in the output array. #' @return Return the symmetric 2D array defined by taking "v" to specify its #' lower triangular matrix. vectorized_lower_tri_to_mat <- function(v, dim) { v <- unlist(v) rows <- c() cols <- c() vals <- c() running_idx <- 1 for(j in seq_len(dim)) { rows <- c(rows, j + seq_len(dim-j+1) - 1) cols <- c(cols, rep(j, dim-j+1)) vals <- c(vals, v[running_idx:(running_idx + dim - j)]) running_idx <- running_idx + dim - j + 1 } A <- sparseMatrix(i = rows, j = cols, x = vals, dims = c(dim, dim)) d <- diag(diag(A)) A <- A + t(A) - d return(A) } #' #' Given a problem returns a PSD constraint #' #' @param problem A \linkS4class{Problem} object. #' @param c A vector of coefficients. #' @return Returns an array G and vector h such that the given constraint is #' equivalent to \eqn{G*z \leq_{PSD} h}. psd_coeff_offset <- function(problem, c) { extractor <- CoeffExtractor(InverseData(problem)) tmp <- affine(extractor, expr(c)) A_vec <- tmp[[1]] b_vec <- tmp[[2]] G <- -A_vec h <- b_vec dim <- nrow(expr(c)) return(list(G, h, dim)) } #' @param solver,object,x A \linkS4class{MOSEK} object. #' @describeIn MOSEK Can the solver handle mixed-integer programs? setMethod("mip_capable", "MOSEK", function(solver) { TRUE }) setMethod("supported_constraints", "MOSEK", function(solver) { c(supported_constraints(ConicSolver()), "SOC", "PSDConstraint", "ExpCone") }) #' @describeIn MOSEK Imports the solver. #' @importFrom utils packageDescription setMethod("import_solver", "MOSEK", function(solver) { requireNamespace("Rmosek", quietly = TRUE) && (!is.null(utils::packageDescription("Rmosek")$Configured.MSK_VERSION)) ## TODO: Add exponential cone support. }) #' @describeIn MOSEK Returns the name of the solver. setMethod("name", "MOSEK", function(x) { MOSEK_NAME }) #' @param problem A \linkS4class{Problem} object. #' @describeIn MOSEK Can MOSEK solve the problem? setMethod("accepts", signature(object = "MOSEK", problem = "Problem"), function(object, problem) { # TODO: Check if the matrix is stuffed. import_solver(object) if(!is_affine(problem@objective@args[[1]])) return(FALSE) for(constr in problem@constraints) { if(!inherits(constr, supported_constraints(object))) return(FALSE) for(arg in constr@args) { if(!is_affine(arg)) return(FALSE) } } return(TRUE) }) #' @param constraints A list of \linkS4class{Constraint} objects for which coefficient #' andd offset data ("G", "h" respectively) is needed #' @param exp_cone_order A parameter that is only used when a \linkS4class{Constraint} object #' describes membership in the exponential cone. #' @describeIn MOSEK Returns a large matrix "coeff" and a vector of constants "offset" such #' that every \linkS4class{Constraint} in "constraints" holds at z in R^n iff #' "coeff" * z <=_K offset", where K is a product of cones supported by MOSEK #' and CVXR (zero cone, nonnegative orthant, second order cone, exponential cone). The #' nature of K is inferred later by accessing the data in "lengths" and "ids". setMethod("block_format", "MOSEK", function(object, problem, constraints, exp_cone_order = NA) { if(length(constraints) == 0 || is.null(constraints) || any(is.na(constraints))) return(list(NULL, NULL)) matrices <- list() offsets <- c() lengths <- c() ids <- c() for(con in constraints) { coeff_offs <- reduction_format_constr(object, problem, con, exp_cone_order) coeff <- coeff_offs[[1]] offset <- coeff_offs[[2]] matrices <- c(matrices, list(coeff)) offsets <- c(offsets, offset) lengths <- c(lengths, prod(dim(as.matrix(offset)))) ids <- c(ids, id(con)) } coeff <- Matrix(do.call(rbind, matrices), sparse = TRUE) return(list(coeff, offsets, lengths, ids)) }) #' @describeIn MOSEK Returns a new problem and data for inverting the new solution. setMethod("perform", signature(object = "MOSEK", problem = "Problem"), function(object, problem) { data <- list() inv_data <- list(suc_slacks = list(), y_slacks = list(), snx_slacks = list(), psd_dims = list()) inv_data[[object@var_id]] <- id(variables(problem)[[1]]) # Get integrality constraint information. var <- variables(problem)[[1]] data[[BOOL_IDX]] <- sapply(var@boolean_idx, function(t) { as.integer(t[1]) }) data[[INT_IDX]] <- sapply(var@integer_idx, function(t) { as.integer(t[1]) }) inv_data$integer_variables <- length(data[[BOOL_IDX]]) + length(data[[INT_IDX]]) > 0 # Parse the coefficient vector from the objective. coeff_offs <- ConicSolver.get_coeff_offset(problem@objective@args[[1]]) c <- coeff_offs[[1]] constant <- coeff_offs[[2]] data[[C_KEY]] <- as.vector(c) inv_data$n0 <- length(data[[C_KEY]]) data[[OBJ_OFFSET]] <- constant[1] data[[DIMS]] <- list() data[[DIMS]][[SOC_DIM]] <- list() data[[DIMS]][[EXP_DIM]] <- list() data[[DIMS]][[PSD_DIM]] <- list() data[[DIMS]][[LEQ_DIM]] <- 0 data[[DIMS]][[EQ_DIM]] <- 0 inv_data[[OBJ_OFFSET]] <- constant[1] Gs <- list() hs <- list() if(length(problem@constraints) == 0) { ##data[[G_KEY]] <- Matrix(nrow = 0, ncol = 0, sparse = TRUE) ## Ensure G's dimensions match that of c. data[[G_KEY]] <- Matrix(nrow = 0, ncol = length(c), sparse = TRUE) data[[H_KEY]] <- matrix(nrow = 0, ncol = 0) inv_data$is_LP <- TRUE return(list(object, data, inv_data)) } # Linear inequalities. leq_constr <- problem@constraints[sapply(problem@constraints, inherits, what = "NonPosConstraint" )] if(length(leq_constr) > 0) { blform <- block_format(object, problem, leq_constr) # G, h : G*z <= h. G <- blform[[1]] h <- blform[[2]] lengths <- blform[[3]] ids <- blform[[4]] inv_data$suc_slacks <- c(inv_data$suc_slacks, lapply(1:length(lengths), function(k) { c(ids[k], lengths[k]) })) data[[DIMS]][[LEQ_DIM]] <- sum(lengths) Gs <- c(Gs, G) hs <- c(hs, h) } # Linear equations. eq_constr <- problem@constraints[sapply(problem@constraints, inherits, what = "ZeroConstraint")] if(length(eq_constr) > 0) { blform <- block_format(object, problem, eq_constr) # G, h : G*z == h. G <- blform[[1]] h <- blform[[2]] lengths <- blform[[3]] ids <- blform[[4]] inv_data$y_slacks <- c(inv_data$y_slacks, lapply(1:length(lengths), function(k) { c(ids[k], lengths[k]) })) data[[DIMS]][[EQ_DIM]] <- sum(lengths) Gs <- c(Gs, G) hs <- c(hs, h) } # Second order cone. soc_constr <- problem@constraints[sapply(problem@constraints, inherits, what = "SOC" )] data[[DIMS]][[SOC_DIM]] <- list() for(ci in soc_constr) data[[DIMS]][[SOC_DIM]] <- c(data[[DIMS]][[SOC_DIM]], cone_sizes(ci)) if(length(soc_constr) > 0) { blform <- block_format(object, problem, soc_constr) # G*z <=_{soc} h. G <- blform[[1]] h <- blform[[2]] lengths <- blform[[3]] ids <- blform[[4]] inv_data$snx_slacks <- c(inv_data$snx_slacks, lapply(1:length(lengths), function(k) { c(ids[k], lengths[k]) })) Gs <- c(Gs, G) hs <- c(hs, h) } # Exponential cone. exp_constr <- problem@constraints[sapply(problem@constraints, inherits, what = "ExpCone" )] if(length(exp_constr) > 0) { # G*z <=_{EXP} h. blform <- block_format(object, problem, exp_constr, object@exp_cone_order) G <- blform[[1]] h <- blform[[2]] lengths <- blform[[3]] ids <- blform[[4]] data[[DIMS]][[EXP_DIM]] <- lengths Gs <- c(Gs, G) hs <- c(hs, h) } # PSD constraints. psd_constr <- problem@constraints[sapply(problem@constraints, inherits, what = "PSDConstraint" )] if(length(psd_constr) > 0) { data[[DIMS]][[PSD_DIM]] <- list() for(c in psd_constr) { coeff_offs <- psd_coeff_offset(problem, c) G_vec <- coeff_offs[[1]] h_vec <- coeff_offs[[2]] dim <- coeff_offs[[3]] inv_data$psd_dims <- c(inv_data$psd_dims, list(list(id(c), dim))) data[[DIMS]][[PSD_DIM]] <- c(data[[DIMS]][[PSD_DIM]], list(dim)) Gs <- c(Gs, G_vec) hs <- c(hs, h_vec) } } if(length(Gs) == 0) ## data[[G_KEY]] <- Matrix(nrow = 0, ncol = 0, sparse = TRUE) ## G is already sparse data[[G_KEY]] <- G else data[[G_KEY]] <- Matrix(do.call(rbind, Gs), sparse = TRUE) if(length(hs) == 0) data[[H_KEY]] <- matrix(nrow = 0, ncol = 0) else data[[H_KEY]] <- Matrix(do.call(cbind, hs), sparse = TRUE) inv_data$is_LP <- (length(psd_constr) + length(exp_constr) + length(soc_constr)) == 0 return(list(object, data, inv_data)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn MOSEK Solve a problem represented by data returned from apply. setMethod("solve_via_data", "MOSEK", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) ## Check if the CVXR standard form has zero variables. If so, ## return a trivial solution. This is necessary because MOSEK ## will crash if handed a problem with zero variables. c <- data[[C_KEY]] if (length(c) == 0) { res <- list() res[[STATUS]] <- OPTIMAL res[[PRIMAL]] <- list() res[[VALUE]] <- data[[OFFSET]] res[[EQ_DUAL]] <- list() res[[INEQ_DUAL]] <- list() return(res) } # The following lines recover problem parameters, and define helper constants. # # The problem's objective is "min c.T * z". # The problem's constraint set is "G * z <=_K h." # The rows in (G, h) are formatted in order of # (1) linear inequalities, # (2) linear equations, # (3) soc constraints, # (4) exponential cone constraints, # (5) vectorized linear matrix inequalities. # The parameter "dims" indicates the exact # dimensions of each of these cones. # # MOSEK's standard form requires that we replace generalized # inequalities with slack variables and linear equations. # The parameter "n" is the size of the column-vector variable # after adding slacks for SOC and EXP constraints. To be # consistent with MOSEK documentation, subsequent comments # refer to this variable as "x". G <- data[[G_KEY]] h <- data[[H_KEY]] dims <- data[[DIMS]] dims_SOC_DIM <- dims[[SOC_DIM]] dims_EXP_DIM <- dims[[EXP_DIM]] dims_PSD_DIM <- dims[[PSD_DIM]] data_BOOL_IDX <- data[[BOOL_IDX]] data_INT_IDX <- data[[INT_IDX]] num_bool <- length(data_BOOL_IDX) num_int <- length(data_INT_IDX) length_dims_SOC_DIM <- length(dims_SOC_DIM) unlist_dims_EXP_DIM <- unlist(dims_EXP_DIM) unlist_dims_SOC_DIM <- unlist(dims_SOC_DIM) dims_LEQ_DIM <- dims[[LEQ_DIM]] n0 <- length(c) n <- n0 + sum(unlist_dims_SOC_DIM, na.rm = TRUE) + sum(unlist_dims_EXP_DIM, na.rm = TRUE) # unlisted dims to make sure sum function works and na.rm to handle empty lists psd_total_dims <- sum(unlist(dims_PSD_DIM)^2, na.rm = TRUE) m <- length(h) # Define variables, cone constraints, and integrality constraints. # # The variable "x" is a length-n block vector, with # Block 1: "z" from "G * z <=_K h", # Block 2: slacks for SOC constraints, and # Block 3: slacks for EXP cone constraints. # # Once we declare x in the MOSEK model, we add the necessary # conic constraints for slack variables (Blocks 2 and 3). # The last step is to add integrality constraints. # # Note that the API call for PSD variables contains the word "bar". # MOSEK documentation consistently uses "bar" as a sort of flag, # indicating that a function deals with PSD variables. ##env <- Rmosek::Env() remove these as Rmosek doesn't need environments ##task <- env.Task(0,0) ##instead defines prob prob <- list(sense="min") ## TODO: Handle logging for verbose. ## Parse all user-specified parameters (override default logging ## parameters if applicable). ## Rmosek expects a list of lists ## prob$dparam <- list(...); prob$iparam <- list(...); prob$sparam <- list(...) if (!is.null(solver_opts)) { prob$dparam <- solver_opts$dparam prob$iparam <- solver_opts$iparam prob$sparam <- solver_opts$sparam } if(!all(c(is.null(feastol), is.null(reltol), is.null(abstol), is.null(num_iter)))) { warning("Ignoring inapplicable parameter feastol/reltol/abstol/num_iter for MOSEK.") } #task.appendvars(n), no task for Rmosek, but declares the number of variables in the model. Need to expand prob$c as well to match this dimension #task.putvarboundlist(1:n, rep(mosek.boundkey.fr, n), matrix(0, nrow = n, ncol = 1), matrix(0, nrow = n, ncol = 1)) #kind of confused why x's are all 0's, but that's what's in python code #prob$bx <- rbind( blx = rep(0,n), # bux = rep(0,n)) prob$bx <- rbind(blx = rep(-Inf, n), bux = rep(Inf, n)) #Initialize the cone. Not 100% sure about this bit NUMCONES <- length_dims_SOC_DIM + floor(sum(unlist_dims_EXP_DIM, na.rm = TRUE)/3) prob$cones <- matrix(list(), nrow = 2, ncol = NUMCONES) if(psd_total_dims > 0) prob$bardim <- unlist(dims_PSD_DIM) running_idx <- n0 for(i in seq_along(unlist_dims_SOC_DIM)) { prob$cones[,i] <- list("QUAD", as.numeric((running_idx + 1):(running_idx + unlist_dims_SOC_DIM[[i]]))) # latter term is size_cone running_idx <- running_idx + unlist_dims_SOC_DIM[[i]] } if(floor(sum(unlist_dims_EXP_DIM, na.rm = TRUE)/3) != 0){ # check this, feels sketchy for(k in 1:floor(sum(unlist_dims_EXP_DIM, na.rm = TRUE)/3) ) { prob$cones[,(length_dims_SOC_DIM+k)] <- list("PEXP", as.numeric((running_idx+1):(running_idx + 3)) ) running_idx <- running_idx + 3 } } if(num_bool + num_int > 0) { if(num_bool > 0) { unlist_data_BOOL_IDX <- unlist(data_BOOL_IDX) prob$intsub <- unlist_data_BOOL_IDX #since the variable constraints are already declared, we are resetting them so they can only be 0 or 1 prob$bx[, unlist_data_BOOL_IDX] <- rbind( rep(0, length(unlist_data_BOOL_IDX)), rep(1, length(unlist_data_BOOL_IDX)) ) } if(num_int > 0) prob$intsub <- unlist(data_INT_IDX) } # Define linear inequality and equality constraints. # # Mosek will see a total of m linear expressions, which must # define linear inequalities and equalities. The variable x # contributes to these linear expressions by standard # matrix-vector multiplication; the matrix in question is # referred to as "A" in the mosek documentation. The PSD # variables have a different means of contributing to the # linear expressions. Specifically, a PSD variable Xj contributes # "+tr( \bar{A}_{ij} * Xj )" to the i-th linear expression, # where \bar{A}_{ij} is specified by a call to putbaraij. # # The following code has three phases. # (1) Build the matrix A. # (2) Specify the \bar{A}_{ij} for PSD variables. # (3) Specify the RHS of the m linear (in)equalities. # # Remark : The parameter G gives every row in the first # n0 columns of A. The remaining columns of A are for SOC # and EXP slack variables. We can actually account for all # of these slack variables at once by specifying a giant # identity matrix in the appropriate position in A. # task.appendcons(m) is equivalent to prob$bc ##G should already be sparse but Matrix 1.3.x causes problems. ## if (!inherits(G, "dgCMatrix")) G <- as(as(G, "CsparseMatrix"), "dgCMatrix") ## Matrix 1.5 change if (!inherits(G, "dgCMatrix")) G <- as(as(G, "CsparseMatrix"), "generalMatrix") G_sum <- summary(G) nrow_G_sparse <- nrow(G) ncol_G_sparse <- ncol(G) row <- G_sum$i col <- G_sum$j vals <- G_sum$x total_soc_exp_slacks <- sum(unlist_dims_SOC_DIM, na.rm = TRUE) + sum(unlist_dims_EXP_DIM, na.rm = TRUE) # initializing A matrix if(ncol_G_sparse == 0 || (ncol_G_sparse + total_soc_exp_slacks) == 0) ## prob$A <- sparseMatrix(i = c(), j = c(), dims = c(0, 0)) ## G is already sparse prob$A <- G else { # this is a bit hacky, probably should fix later. Filling out part of the A matrix from G # Equivalent to task.putaijlist(as.list(row), as.list(col), as.list(vals)) if(total_soc_exp_slacks > 0) { i <- unlist(dims[[LEQ_DIM]]) + unlist(dims[[EQ_DIM]]) # Constraint index in (1, ..., m) j <- length(c) # Index of the first slack variable in the block vector "x". rows <- (i:(i + total_soc_exp_slacks-1))+1 cols <- (j:(j + total_soc_exp_slacks-1))+1 row <- c(row, rows) col <- c(col, cols) vals <- c(vals, rep(1, length(rows))) } prob$A <- sparseMatrix(i = row, j = col, x = vals, dims = c(nrow_G_sparse, ncol_G_sparse + total_soc_exp_slacks)) } # Constraint index: start of LMIs. i <- dims_LEQ_DIM + dims[[EQ_DIM]] + total_soc_exp_slacks + 1 dim_exist_PSD <- length(dims_PSD_DIM) #indicates whether or not we have any LMIs if(dim_exist_PSD > 0){ #A bit hacky here too, specifying the lower triangular part of symmetric coefficient matrix barA barAi <- c() #Specifies row index of block matrix barAj <- c() #Specifies column index of block matrix barAk <- c() #Specifies row index within the block matrix specified above barAl <- c() #Specifies column index within the block matrix specified above barAv <- c() #Values for all the matrices for(j in 1:length(dims_PSD_DIM)) { #For each PSD matrix for(row_idx in 1:dims_PSD_DIM[[j]]) { for(col_idx in 1:dims_PSD_DIM[[j]]) { val <- ifelse(row_idx == col_idx, 1, 0.5) row <- max(row_idx, col_idx) col <- min(row_idx, col_idx) #mat <- task.appendsparsesymmat(dim, list(row), list(col), list(val)) #task.putbaraij(i, j, list(mat), list(1.0)) barAi <- c(barAi, i) barAj <- c(barAj, j) #NEED TO CHECK. Multiple PSD_DIM example? barAk <- c(barAk, row) barAl <- c(barAl, col) barAv <- c(barAv, val) i <- i + 1 #for each symmetric matrix } } } #Attaching. Does mosek automatically check the symmetric matrix dimensions? prob$barA$i <- barAi prob$barA$j <- barAj prob$barA$k <- barAk prob$barA$l <- barAl prob$barA$v <- barAv } num_eq <- length(h) - dims_LEQ_DIM #CVXPY has the first dims[[LEQ_DIM]] variables as upper bounded #type_constraint <- rep(mosek.boundkey.up, dims[[LEQ_DIM]]) + rep(mosek.boundkey.fx, num_eq) #task.putconboundlist(1:m, type_constraint, h, h), equivalent to prob$bc hl_holder <- as.numeric(h) hu_holder <- as.numeric(h) #upper constraints for the LEQ_DIM number of variables, so set lower bound to -Inf hl_holder[seq_len(dims_LEQ_DIM)] <- rep(-Inf, dims_LEQ_DIM) prob$bc <- rbind(blc = hl_holder, buc = hu_holder) # Define the objective and optimize the MOSEK task. #initialize coefficients of objective with the same number of variables declared (dim of x) c_holder <- rep(0, n) c_holder[1:length(c)] <- c prob$c <- c_holder if(is.logical(verbose) && verbose ){ verbose <- 10 } else if(!verbose){ verbose <- 0 } else if(!is.null(solver_opts$verbose)){ verbose <- solver_opts$verbose } if(is.null(solver_opts$soldetail)){ solver_opts$soldetail <- 3 } else { warning("Solver might not output correct answer depending on the input of the soldetail variable. Default is 3") } if(is.null(solver_opts$getinfo)){ solver_opts$getinfo <- TRUE } else { warning("Solver might not output correct answer depending on the input of the getinfo variable. Default is TRUE") } r <- Rmosek::mosek(prob, list(verbose = verbose, usesol = solver_opts$usesol, useparam = solver_opts$useparam, soldetail = solver_opts$soldetail, getinfo = solver_opts$getinfo, writebefore = solver_opts$writebefore, writeafter = solver_opts$writeafter)) return(r) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A list containing data necessary for the inversion. #' @describeIn MOSEK Returns the solution to the original problem given the inverse_data. setMethod("invert", "MOSEK", function(object, solution, inverse_data) { ## REMOVE LATER ## results <- solution ## has_attr <- !is.null(mosek.solsta$near_optimal) ## We ignore MOSEK 8.1 and below. status_map <- function(status) { status <- tolower(status) if(status %in% c("optimal", "integer_optimal")) return(OPTIMAL) ## else if(status %in% c("prim_feas", "near_optimal", "near_integer_optimal")) ## return(OPTIMAL_INACCURATE) else if(status == "prim_infeas_cer" || status == "primal_infeasible_cer") { #Documentation says it's this, but docs also say it spits out dual_infeas_cer, which is wrong #check later if(!is.null(attributes(status))) #check if status has any attributes, hasattr in python return(INFEASIBLE) else return(INFEASIBLE) } else if(status == "dual_infeasible_cer") { if(!is.null(attributes(status))) return(UNBOUNDED_INACCURATE) else return(UNBOUNDED) } else return(SOLVER_ERROR) } ##env <- results$env ##task <- results$task ## Naras: FIX solver_opts solver_opts <- solution$solver_options if(inverse_data$integer_variables) sol <- solution$sol$int else if(!is.null(solver_opts$bfs) && solver_opts$bfs && inverse_data$is_LP) sol <- solution$sol$bas # The basic feasible solution. else sol <- solution$sol$itr # The solution found via interior point method. problem_status <- sol$prosta solution_status <- sol$solsta if(is.na(solution$response$code)) status <- SOLVER_ERROR else status <- status_map(solution_status) ## For integer problems, problem status determines infeasibility (no solution). ## if(sol == mosek.soltype.itg && problem_status == mosek.prosta.prim_infeas) ## Using reference https://docs.mosek.com/9.0/rmosek/accessing-solution.html if(inverse_data$integer_variables && (problem_status == "MSK_PRO_STA_PRIM_INFEAS" || problem_status == "PRIMAL_INFEASIBLE")) status <- INFEASIBLE if(status %in% SOLUTION_PRESENT) { # Get objective value. opt_val <- sol$pobjval + inverse_data[[OBJ_OFFSET]] # Recover the CVXR standard form primal variable. ## z <- rep(0, inverse_data$n0) ## task.getxxslice(sol, 0, length(z), z) primal_vars <- list() primal_vars[[as.character(inverse_data[[object@var_id]])]] <- sol$xx ## Recover the CVXR standard form dual variables. ## if(sol == mosek.soltype.itn) if (inverse_data$integer_variables) { dual_var_ids <- sapply(c(inverse_data$suc_slacks, inverse_data$y_slacks, inverse_data$snx_slacks, inverse_data$psd_dims), function(slack) { slack[[1L]] }) dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) names(dual_vars) <- dual_var_ids } else dual_vars <- MOSEK.recover_dual_variables(sol, inverse_data) } else { if(status == INFEASIBLE) opt_val <- Inf else if(status == UNBOUNDED) opt_val <- -Inf else opt_val <- NA_real_ vid <- primal_vars <- list() primal_vars[[as.character(inverse_data[[object@var_id]])]] <- NA_real_ dual_var_ids <- sapply(c(inverse_data$suc_slacks, inverse_data$y_slacks, inverse_data$snx_slacks, inverse_data$psd_dims), function(slack) { slack[[1L]] }) dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) names(dual_vars) <- dual_var_ids } ## Store computation time. attr <- list() attr[[SOLVE_TIME]] <- solution$dinfo$OPTIMIZER_TIME ## Delete the MOSEK Task and Environment ##task.__exit__(NA, NA, NA) ##env.__exit__(NA, NA, NA) return(Solution(status, opt_val, primal_vars, dual_vars, attr)) }) #' #' Recovers MOSEK solutions dual variables #' #' @param sol List of the solutions returned by the MOSEK solver. #' @param inverse_data A list of the data returned by the perform function. #' @return A list containing the mapping of CVXR's \linkS4class{Constraint} #' object's id to its corresponding dual variables in the current solution. MOSEK.recover_dual_variables <- function(sol, inverse_data) { dual_vars <- list() ## Dual variables for the inequality constraints. suc_len <- ifelse(length(inverse_data$suc_slacks) == 0, 0, sum(sapply(inverse_data$suc_slacks, function(val) { val[[2]] }))) if(suc_len > 0) { ## suc <- rep(0, suc_len) ## task.getsucslice(sol, 0, suc_len, suc) dual_vars <- utils::modifyList(dual_vars, MOSEK.parse_dual_vars(sol$suc[seq_len(suc_len)], inverse_data$suc_slacks)) } ## Dual variables for the original equality constraints. y_len <- ifelse(length(inverse_data$y_slacks) == 0, 0, sum(sapply(inverse_data$y_slacks, function(val) { val[[2]] }))) if(y_len > 0) { ##y <- rep(0, y_len) ## task.getyslice(sol, suc_len, suc_len + y_len, y) dual_vars <- utils::modifyList(dual_vars, MOSEK.parse_dual_vars(sol$suc[seq.int(suc_len, length.out = y_len)], inverse_data$y_slacks)) } ## Dual variables for SOC and EXP constraints. snx_len <- ifelse(length(inverse_data$snx_slacks) == 0, 0, sum(sapply(inverse_data$snx_slacks, function(val) { val[[2]] }))) if(snx_len > 0) { ##snx <- matrix(0, nrow = snx_len, ncol = 1) ##task.getsnxslice(sol, inverse_data$n0, inverse_data$n0 + snx_len, snx) dual_vars <- utils::modifyList(dual_vars, MOSEK.parse_dual_vars(sol$snx, inverse_data$snx_slacks)) } ## Dual variables for PSD constraints. for(psd_info in inverse_data$psd_dims) { id <- as.character(psd_info[[1L]]) dim <- psd_info[[2L]] ##sj <- rep(0, dim*floor((dim + 1)/2)) ##task.getbars(sol, j, sj) dual_vars[[id]] <- vectorized_lower_tri_to_mat(sol$bars[[1L]], dim) } return(dual_vars) } #' #' Parses MOSEK dual variables into corresponding CVXR constraints and dual values #' #' @param dual_var List of the dual variables returned by the MOSEK solution. #' @param constr_id_to_constr_dim A list that contains the mapping of entry "id" #' that is the index of the CVXR \linkS4class{Constraint} object to which the #' next "dim" entries of the dual variable belong. #' @return A list with the mapping of the CVXR \linkS4class{Constraint} object #' indices with the corresponding dual values. MOSEK.parse_dual_vars <- function(dual_var, constr_id_to_constr_dim) { dual_vars <- list() running_idx <- 1 for(val in constr_id_to_constr_dim) { id <- as.character(val[[1]]) dim <- val[[2]] ## if(dim == 1) ## dual_vars[id] <- dual_vars[running_idx] # a scalar. ## else ## dual_vars[id] <- as.matrix(dual_vars[running_idx:(running_idx + dim)]) dual_vars[[id]] <- dual_var[seq.int(running_idx, length.out = dim)] running_idx <- running_idx + dim } return(dual_vars) } ## MOSEK._handle_mosek_params <- function(task, params) { ## if(is.na(params)) ## return() ## ##requireNamespace("Rmosek", quietly = TRUE) ## handle_str_param <- function(param, value) { ## if(startsWith(param, "MSK_DPAR_")) ## task.putnadourparam(param, value) ## else if(startsWith(param, "MSK_IPAR_")) ## task.putnaintparam(param, value) ## else if(startsWith(param, "MSK_SPAR_")) ## task.putnastrparam(param, value) ## else ## stop("Invalid MOSEK parameter ", param) ## } ## handle_enum_param <- function(param, value) { ## if(is(param, "dparam")) ## task.putdouparam(param, value) ## else if(is(param, "iparam")) ## task.putintparam(param, value) ## else if(is(param, "sparam")) ## task.putstrparam(param, value) ## else ## stop("Invalid MOSEK parameter ", param) ## } ## for(p in params) { ## param <- p[[1]] ## value <- p[[2]] ## if(is(param, "character")) ## handle_str_param(param, value) ## else ## handle_enum_param(param, value) ## } ## } #' Utility method for formatting a ConeDims instance into a dictionary #' that can be supplied to SCS. #' @param cone_dims A \linkS4class{ConeDims} instance. #' @return The dimensions of the cones. SCS.dims_to_solver_dict <- function(cone_dims) { cones <- list(z = as.integer(cone_dims@zero), l = as.integer(cone_dims@nonpos), q = sapply(cone_dims@soc, as.integer), ep = as.integer(cone_dims@exp), s = sapply(cone_dims@psd, as.integer)) return(cones) } #' #' Utility methods for special handling of semidefinite constraints. #' #' @param matrix The matrix to get the lower triangular matrix for #' @return The lower triangular part of the matrix, stacked in column-major order scaled_lower_tri <- function(matrix) { # Returns an expression representing the lower triangular entries. # Scales the strictly lower triangular entries by sqrt(2), as # required by SCS. rows <- cols <- nrow(matrix) entries <- floor(rows * (cols + 1)/2) row_arr <- seq_len(entries) col_arr <- matrix(1:(rows*cols), nrow = rows, ncol = cols) col_arr <- col_arr[lower.tri(col_arr, diag = TRUE)] val_arr <- matrix(0, nrow = rows, ncol = cols) val_arr[lower.tri(val_arr, diag = TRUE)] <- sqrt(2) diag(val_arr) <- 1 val_arr <- as.vector(val_arr) val_arr <- val_arr[val_arr != 0] coeff <- Constant(sparseMatrix(i = row_arr, j = col_arr, x = val_arr, dims = c(entries, rows*cols))) vectorized_matrix <- reshape_expr(matrix, c(rows*cols, 1)) return(coeff %*% vectorized_matrix) } #' #' Expands lower triangular to full matrix. #' #' @param lower_tri A matrix representing the lower triangular part of the matrix, #' stacked in column-major order #' @param n The number of rows (columns) in the full square matrix. #' @return A matrix that is the scaled expansion of the lower triangular matrix. tri_to_full <- function(lower_tri, n) { # Expands n*floor((n+1)/2) lower triangular to full matrix. # Scales off-diagonal by 1/sqrt(2), as per the SCS specification. full <- matrix(0, nrow = n, ncol = n) full[upper.tri(full, diag = TRUE)] <- lower_tri full[lower.tri(full, diag = TRUE)] <- lower_tri unscaled_diag <- diag(full) full <- full/sqrt(2) diag(full) <- unscaled_diag matrix(full, nrow = n*n, byrow = FALSE) } # SuperSCS <- setClass("SuperSCS", contains = "SCS") # SuperSCS.default_settings <- function(object) { # list(use_indirect = FALSE, eps = 1e-8, max_iters = 10000) # } # # #' @param solver,object,x A \linkS4class{SuperSCS} object. # #' @describeIn SuperSCS Returns the name of the SuperSCS solver # setMethod("name", "SuperSCS", function(x) { SUPER_SCS_NAME }) # # #' @describeIn SuperSCS imports the SuperSCS solver. # setMethod("import_solver", "SuperSCS", function(solver) { # stop("Unimplemented: SuperSCS is currently unavailable in R.") # }) # # #' @param data Data generated via an apply call. # #' @param warm_start An option for warm start. # #' @param verbose A boolean of whether to enable solver verbosity. # #' @param solver_opts A list of Solver specific options # #' @param solver_cache Cache for the solver. # #' @describeIn SuperSCS Solve a problem represented by data returned from apply. # setMethod("solve_via_data", "SuperSCS", function(object, data, warm_start, verbose, solver_opts, solver_cache) { # if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) # args <- list(A = data[[A_KEY]], b = data[[B_KEY]], c = data[[C_KEY]]) # if(warm_start && !is.null(solver_cache) && length(solver_cache) > 0 && name(object) %in% names(solver_cache)) { # args$x <- solver_cache[[name(object)]]$x # args$y <- solver_cache[[name(object)]]$y # args$s <- solver_cache[[name(object)]]$s # } # cones <- SCS.dims_to_solver_dict(data[[ConicSolver()@dims]]) # # # Settings. # user_opts <- names(solver_opts) # for(k in names(SuperSCS.default_settings)) { # if(!k %in% user_opts) # solver_opts[[k]] <- SuperSCS.default_settings[[k]] # } # results <- SuperSCS::solve(args, cones, verbose = verbose, solver_opts) # if(!is.null(solver_cache) && length(solver_cache) > 0) # solver_cache[[name(object)]] <- results # return(results) # }) # XPRESS <- setClass("XPRESS", contains = "SCS") # # # Solver capabilities. # setMethod("mip_capable", "XPRESS", function(solver) { TRUE }) # setMethod("supported_constraints", "XPRESS", function(solver) { c(supported_constraints(ConicSolver()), "SOC") }) # # # Map of XPRESS status to CVXR status. # setMethod("status_map", "XPRESS", function(solver, status) { # if(status == 2) # return(OPTIMAL) # else if(status == 3) # return(INFEASIBLE) # else if(status == 5) # return(UNBOUNDED) # else if(status %in% c(4, 6, 7, 8, 10, 11, 12, 13)) # return(SOLVER_ERROR) # else if(status == 9) # TODO: Could be anything. Means time expired. # return(OPTIMAL_INACCURATE) # else # stop("XPRESS status unrecognized: ", status) # }) # # setMethod("name", "XPRESS", function(x) { XPRESS_NAME }) # setMethod("import_solver", "XPRESS", function(solver) { # stop("Unimplemented: XPRESS solver unavailable in R.") # }) # # setMethod("accepts", signature(object = "XPRESS", problem = "Problem"), function(object, problem) { # # TODO: Check if the matrix is stuffed. # if(!is_affine(problem@objective@args[[1]])) # return(FALSE) # for(constr in problem@constraints) { # if(!inherits(constr, supported_constraints(object))) # return(FALSE) # for(arg in constr@args) { # if(!is_affine(arg)) # return(FALSE) # } # } # return(TRUE) # }) # # setMethod("perform", signature(object = "XPRESS", problem = "Problem"), function(object, problem) { # tmp <- callNextMethod(object, problem) # data <- tmp[[1]] # inv_data <- tmp[[2]] # variables <- variables(problem)[[1]] # data[[BOOL_IDX]] <- lapply(variables@boolean_idx, function(t) { t[1] }) # data[[INT_IDX]] <- lapply(variables@integer_idx, function(t) { t[1] }) # inv_data$is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 # return(list(object, data, inv_data)) # }) # # setMethod("invert", signature(object = "XPRESS", solution = "list", inverse_data = "list"), function(object, solution, inverse_data) { # status <- solution[[STATUS]] # # if(status %in% SOLUTION_PRESENT) { # opt_val <- solution[[VALUE]] # primal_vars <- list() # primal_vars[[inverse_data[[object@var_id]]]] <- solution$primal # if(!inverse_data@is_mip) # dual_vars <- get_dual_values(solution[[EQ_DUAL]], extract_dual_value, inverse_data[[EQ_CONSTR]]) # } else { # primal_vars <- list() # primal_vars[[inverse_data[[object@var_id]]]] <- NA_real_ # if(!inverse_data@is_mip) { # dual_var_ids <- sapply(inverse_data[[EQ_CONSTR]], function(constr) { constr@id }) # dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) # names(dual_vars) <- dual_var_ids # } # # if(status == INFEASIBLE) # opt_val <- Inf # else if(status == UNBOUNDED) # opt_val <- -Inf # else # opt_val <- NA # } # # other <- list() # other[[XPRESS_IIS]] <- solution[[XPRESS_IIS]] # other[[XPRESS_TROW]] <- solution[[XPRESS_TROW]] # return(Solution(status, opt_val, primal_vars, dual_vars, other)) # }) # # setMethod("solve_via_data", "XPRESS", function(object, data, warm_start, verbose, solver_opts, solver_cache) { # if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) # solver <- XPRESS_OLD() # solver_opts[[BOOL_IDX]] <- data[[BOOL_IDX]] # solver_opts[[INT_IDX]] <- data[[INT_IDX]] # prob_data <- list() # prob_data[[name(object)]] <- ProblemData() # solve(solver, data$objective, data$constraints, prob_data, warm_start, verbose, solver_opts) # })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/conic_solvers.R
#' #' The Constant class. #' #' This class represents a constant. #' #' @slot value A numeric element, vector, matrix, or data.frame. Vectors are automatically cast into a matrix column. #' @slot sparse (Internal) A logical value indicating whether the value is a sparse matrix. #' @slot is_pos (Internal) A logical value indicating whether all elements are non-negative. #' @slot is_neg (Internal) A logical value indicating whether all elements are non-positive. #' @name Constant-class #' @aliases Constant #' @rdname Constant-class .Constant <- setClass("Constant", representation(value = "ConstVal", sparse = "logical", imag = "logical", nonneg = "logical", nonpos = "logical", symm = "logical", herm = "logical", eigvals = "numeric", .is_vector = "logical", .cached_is_pos = "logical"), prototype(value = NA_real_, sparse = NA, imag = NA, nonneg = NA, nonpos = NA, symm = NA, herm = NA, eigvals = NA_real_, .is_vector = NA, .cached_is_pos = NA), contains = "Leaf") #' @param value A numeric element, vector, matrix, or data.frame. Vectors are automatically cast into a matrix column. #' @rdname Constant-class #' @examples #' x <- Constant(5) #' y <- Constant(diag(3)) #' get_data(y) #' value(y) #' is_nonneg(y) #' size(y) #' as.Constant(y) #' @export Constant <- function(value) { .Constant(value = value) } setMethod("initialize", "Constant", function(.Object, ..., value = NA_real_, sparse = NA, imag = NA, nonneg = NA, nonpos = NA, symm = NA, herm = NA, eigvals = NA_real_, .is_vector = NA, .cached_is_pos = NA) { # Keep sparse matrices sparse. if(is(value, "ConstSparseVal")) { .Object@value <- Matrix(value, sparse = TRUE) .Object@sparse <- TRUE } else { .Object@value <- as.matrix(value) .Object@sparse <- FALSE } .Object@imag <- imag .Object@nonneg <- nonneg .Object@nonpos <- nonpos .Object@symm <- symm .Object@herm <- herm .Object@eigvals <- eigvals [email protected]_vector <- is.vector(value) [email protected]_is_pos <- .cached_is_pos callNextMethod(.Object, ..., dim = intf_dim(.Object@value)) }) #' @param x,object A \linkS4class{Constant} object. #' @rdname Constant-class setMethod("show", "Constant", function(object) { cat("Constant(", curvature(object), ", ", sign(object), ", (", paste(dim(object), collapse = ","), "))", sep = "") }) #' @describeIn Constant The name of the constant. setMethod("name", "Constant", function(x) { as.character(head(x@value)) }) #' @describeIn Constant Returns itself as a constant. setMethod("constants", "Constant", function(object) { list(object) }) #' @describeIn Constant The value of the constant. setMethod("value", "Constant", function(object) { # if([email protected]_vector) # return(as.vector(object@value)) return(object@value) }) #' @describeIn Constant A logical value indicating whether all elements of the constant are positive. setMethod("is_pos", "Constant", function(object) { if(is.na([email protected]_is_pos)) [email protected]_is_pos <- all(object@value > 0) [email protected]_is_pos }) #' @describeIn Constant An empty list since the gradient of a constant is zero. setMethod("grad", "Constant", function(object) { list() }) #' @describeIn Constant The \code{c(row, col)} dimensions of the constant. setMethod("dim", "Constant", function(x) { x@dim }) #' @describeIn Constant The canonical form of the constant. setMethod("canonicalize", "Constant", function(object) { obj <- create_const(value(object), dim(object), object@sparse) list(obj, list()) }) #' @describeIn Constant A logical value indicating whether all elements of the constant are non-negative. setMethod("is_nonneg", "Constant", function(object) { if(is.na(object@nonneg)) object <- .compute_attr(object) object@nonneg }) #' @describeIn Constant A logical value indicating whether all elements of the constant are non-positive. setMethod("is_nonpos", "Constant", function(object) { if(is.na(object@nonpos)) object <- .compute_attr(object) object@nonpos }) #' @describeIn Constant A logical value indicating whether the constant is imaginary. setMethod("is_imag", "Constant", function(object) { if(is.na(object@imag)) object <- .compute_attr(object) object@imag }) #' @describeIn Constant A logical value indicating whether the constant is complex-valued. setMethod("is_complex", "Constant", function(object) { is.complex(value(object)) }) #' @describeIn Constant A logical value indicating whether the constant is symmetric. setMethod("is_symmetric", "Constant", function(object) { if(is_scalar(object)) return(TRUE) else if(ndim(object) == 2 && nrow(object) == ncol(object)) { if(is.na(object@symm)) object <- .compute_symm_attr(object) return(object@symm) } else return(FALSE) }) #' @describeIn Constant A logical value indicating whether the constant is a Hermitian matrix. setMethod("is_hermitian", "Constant", function(object) { if(is_scalar(object) && is_real(object)) return(TRUE) else if(ndim(object) == 2 && nrow(object) == ncol(object)) { if(is.na(object@herm)) object <- .compute_symm_attr(object) return(object@herm) } else return(FALSE) }) # Compute the attributes of the constant related to complex/real, sign. .compute_attr <- function(object) { # Set DCP attributes. res <- intf_is_complex(value(object)) is_real <- res[[1]] is_imag <- res[[2]] if(is_complex(object)) { is_nonneg <- FALSE is_nonpos <- FALSE } else { sign <- intf_sign(value(object)) is_nonneg <- sign[[1]] is_nonpos <- sign[[2]] } object@imag <- is_imag && !is_real object@nonpos <- is_nonpos object@nonneg <- is_nonneg object } # Determine whether the constant is symmetric/Hermitian. .compute_symm_attr <- function(object) { # Set DCP attributes. res <- intf_is_hermitian(value(object)) object@symm <- res[[1]] object@herm <- res[[2]] object } # Compute the eigenvalues of the Hermitian or symmetric matrix represented by this constant. .compute_eigvals <- function(object) { object@eigvals <- eigen(value(object), only.values = TRUE)$values object } #' @describeIn Constant A logical value indicating whether the constant is a positive semidefinite matrix. setMethod("is_psd", "Constant", function(object) { # Symbolic only cases. if(is_scalar(object) && is_nonneg(object)) return(TRUE) else if(is_scalar(object)) return(FALSE) else if(ndim(object) == 1) return(FALSE) else if(ndim(object) == 2 && nrow(object) != ncol(object)) return(FALSE) else if(!is_hermitian(object)) return(FALSE) # Compute eigenvalues if absent. if(is.na(object@eigvals)) object <- .compute_eigvals(object) return(all(Re(object@eigvals) >= -EIGVAL_TOL)) }) #' @describeIn Constant A logical value indicating whether the constant is a negative semidefinite matrix. setMethod("is_nsd", "Constant", function(object) { # Symbolic only cases. if(is_scalar(object) && is_nonpos(object)) return(TRUE) else if(is_scalar(object)) return(FALSE) else if(ndim(object) == 1) return(FALSE) else if(ndim(object) == 2 && nrow(object) != ncol(object)) return(FALSE) else if(!is_hermitian(object)) return(FALSE) # Compute eigenvalues if absent. if(is.na(object@eigvals)) object <- .compute_eigvals(object) return(all(Re(object@eigvals) <= EIGVAL_TOL)) }) #' #' Cast to a Constant #' #' Coerce an R object or expression into the \linkS4class{Constant} class. #' #' @param expr An \linkS4class{Expression}, numeric element, vector, matrix, or data.frame. #' @return A \linkS4class{Constant} representing the input as a constant. #' @docType methods #' @rdname Constant-class #' @export as.Constant <- function(expr) { if(is(expr, "Expression")) expr else Constant(value = expr) } #' #' The Parameter class. #' #' This class represents a parameter, either scalar or a matrix. #' #' @slot rows The number of rows in the parameter. #' @slot cols The number of columns in the parameter. #' @slot name (Optional) A character string representing the name of the parameter. #' @slot value (Optional) A numeric element, vector, matrix, or data.frame. Defaults to \code{NA} and may be changed with \code{value<-} later. #' @name Parameter-class #' @aliases Parameter #' @rdname Parameter-class .Parameter <- setClass("Parameter", representation(dim = "numeric", name = "character", venv = "environment", .is_vector = "logical"), ##prototype(dim = NULL, name = NA_character_, .is_vector = NA), contains = "Leaf") #' @param rows The number of rows in the parameter. #' @param cols The number of columns in the parameter. #' @param name (Optional) A character string representing the name of the parameter. #' @param value (Optional) A numeric element, vector, matrix, or data.frame. Defaults to \code{NA} and may be changed with \code{value<-} later. #' @param ... Additional attribute arguments. See \linkS4class{Leaf} for details. #' @rdname Parameter-class #' @examples #' x <- Parameter(3, name = "x0", nonpos = TRUE) ## 3-vec negative #' is_nonneg(x) #' is_nonpos(x) #' size(x) #' @export # Parameter <- function(dim = NULL, name = NA_character_, value = NA_real_, ...) { .Parameter(dim = dim, name = name, value = value, ...) } # Parameter <- function(rows = 1, cols = 1, name = NA_character_, value = NA_real_, ...) { .Parameter(dim = c(rows, cols), name = name, value = value, ...) } Parameter <- function(rows = NULL, cols = NULL, name = NA_character_, value = NA_real_, ...) { .Parameter(dim = c(rows, cols), name = name, value = value, ...) } setMethod("initialize", "Parameter", function(.Object, ..., dim = NULL, name = NA_character_, value = NA_real_, .is_vector = NA) { .Object@name <- name [email protected]_vector <- .is_vector ## .Object@id <- get_id() if(is.na(name)) .Object@name <- sprintf("%s%s", PARAM_PREFIX, .Object@id) else .Object@name <- name if(length(dim) == 0 || is.null(dim)) { # Force constants to default to c(1,1). dim <- c(1,1) [email protected]_vector <- TRUE } else if(length(dim) == 1) { # Treat as a column vector. dim <- c(dim,1) [email protected]_vector <- TRUE } else if(length(dim) == 2) [email protected]_vector <- FALSE else if(length(dim) > 2) # TODO: Tensors are currently unimplemented. stop("Unimplemented") .Object@dim <- dim # Initialize with value if provided # .Object@value <- value # callNextMethod(.Object, ..., id = .Object@id, dim = dim, value = value) .Object@venv <- e <- new.env(parent=emptyenv()) e$value <- value callNextMethod(.Object, ..., dim = dim, value = value) }) #' @param object,x A \linkS4class{Parameter} object. #' @describeIn Parameter Returns \code{list(dim, name, value, attributes)}. setMethod("get_data", "Parameter", function(object) { list(dim = dim(object), name = object@name, value = value(object), attributes = attributes(object)) }) #' @describeIn Parameter The name of the parameter. #' @export setMethod("name", "Parameter", function(x) { x@name }) ## # We also need a value_impl setMethod("value_impl", "Parameter", function(object) { object@venv$value }) #' @describeIn Parameter The value of the parameter. setMethod("value", "Parameter", function(object) { # if([email protected]_vector) # return(as.vector(object@value)) ## return(object@value) return(object@venv$value) }) #' @describeIn Parameter Set the value of the parameter. setReplaceMethod("value", "Parameter", function(object, value) { ## object@value <- validate_val(object, value) object@venv$value <- validate_val(object, value) object }) #' @describeIn Parameter An empty list since the gradient of a parameter is zero. setMethod("grad", "Parameter", function(object) { list() }) #' @describeIn Parameter Returns itself as a parameter. setMethod("parameters", "Parameter", function(object) { list(object) }) #' @describeIn Parameter The canonical form of the parameter. setMethod("canonicalize", "Parameter", function(object) { obj <- create_param(object, dim(object)) list(obj, list()) }) setMethod("show", "Parameter", function(object) { attr_str <- get_attr_str(object) if(length(attr_str) > 0) cat("Parameter(", paste(dim(object), collapse = ", "), ", ", attr_str, ")", sep = "") else cat("Parameter(", paste(dim(object), collapse = ", "), ")", sep = "") }) #' #' The CallbackParam class. #' #' This class represents a parameter whose value is obtained by evaluating a function. #' #' @slot callback A callback function that generates the parameter value. #' @slot dim The dimensions of the parameter. #' @name CallbackParam-class #' @aliases CallbackParam #' @rdname CallbackParam-class .CallbackParam <- setClass("CallbackParam", representation(callback = "function", dim = "numeric"), prototype(dim = NULL), contains = "Parameter") #' @param callback A callback function that generates the parameter value. #' @param dim The dimensions of the parameter. #' @param ... Additional attribute arguments. See \linkS4class{Leaf} for details. #' @rdname CallbackParam-class #' @examples #' x <- Variable(2) #' fun <- function() { value(x) } #' y <- CallbackParam(fun, dim(x), nonneg = TRUE) #' get_data(y) #' @export CallbackParam <- function(callback, dim = NULL, ...) { .CallbackParam(callback = callback, dim = dim, ...) } setMethod("initialize", "CallbackParam", function(.Object, ..., callback, dim = NULL) { .Object@callback <- callback callNextMethod(.Object, ..., dim = dim) }) #' @param object A \linkS4class{CallbackParam} object. #' @rdname CallbackParam-class setMethod("value", "CallbackParam", function(object) { validate_val(object, object@callback()) }) # TODO: Cast to vector if [email protected]_vector == TRUE.
/scratch/gouwar.j/cran-all/cranData/CVXR/R/constant.R
#' #' The Constraint class. #' #' This virtual class represents a mathematical constraint. #' #' @name Constraint-class #' @aliases Constraint #' @rdname Constraint-class setClass("Constraint", representation(dual_variables = "list"), prototype(dual_variables = list()), contains = "Canonical") setMethod("initialize", "Constraint", function(.Object, ..., dual_variables = list()) { .Object <- callNextMethod(.Object, ...) # .Object@dual_variables <- lapply(.Object@args, function(arg) { Variable(dim(arg)) }) .Object@dual_variables <- lapply(.Object@args, function(arg) { new("Variable", dim = dim(arg)) }) return(.Object) }) #' @param x,object A \linkS4class{Constraint} object. #' @rdname Constraint-class setMethod("as.character", "Constraint", function(x) { name(x) }) setMethod("show", "Constraint", function(object) { print(paste(class(object), "(", as.character(object@args[[1]]), ")", sep = "")) }) #' @describeIn Constraint The dimensions of the constrained expression. setMethod("dim", "Constraint", function(x) { dim(x@args[[1]]) }) #' @describeIn Constraint The size of the constrained expression. setMethod("size", "Constraint", function(object) { size(object@args[[1]]) }) #' @describeIn Constraint Is the constraint real? setMethod("is_real", "Constraint", function(object) { !is_complex(object) }) #' @describeIn Constraint Is the constraint imaginary? setMethod("is_imag", "Constraint", function(object) { all(sapply(object@args, is_imag)) }) #' @describeIn Constraint Is the constraint complex? setMethod("is_complex", "Constraint", function(object) { any(sapply(object@args, is_complex)) }) #' @describeIn Constraint Is the constraint DCP? setMethod("is_dcp", "Constraint", function(object) { stop("Unimplemented") }) #' @describeIn Constraint Is the constraint DGP? setMethod("is_dgp", "Constraint", function(object) { stop("Unimplemented") }) #' @describeIn Constraint The residual of a constraint setMethod("residual", "Constraint", function(object) { stop("Unimplemented") }) #' @describeIn Constraint The violation of a constraint. setMethod("violation", "Constraint", function(object) { resid <- residual(object) if(any(is.na(resid))) stop("Cannot compute the violation of a constraint whose expression is NA-valued.") return(resid) }) #' @param tolerance The tolerance for checking if the constraint is violated. #' @describeIn Constraint The value of a constraint. setMethod("constr_value", "Constraint", function(object, tolerance = 1e-8) { resid <- residual(object) if(any(is.na(resid))) stop("Cannot compute the value of a constraint whose expression is NA-valued.") return(all(resid <= tolerance)) }) #' #' A Class Union of List and Constraint #' #' @name ListORConstr-class #' @rdname ListORConstr-class setClassUnion("ListORConstr", c("list", "Constraint")) # Helper function since syntax is different for LinOp (list) vs. Constraint object #' @param object A list or \linkS4class{Constraint} object. #' @describeIn ListORConstr Returns the ID associated with the list or constraint. setMethod("id", "ListORConstr", function(object) { if(is.list(object)) object$constr_id else object@id }) #' @describeIn Constraint Information needed to reconstruct the object aside from the args. setMethod("get_data", "Constraint", function(object) { list(id(object)) }) #' @describeIn Constraint The dual values of a constraint. setMethod("dual_value", "Constraint", function(object) { value(object@dual_variables[[1]]) }) #' @param value A numeric scalar, vector, or matrix. #' @describeIn Constraint Replaces the dual values of a constraint.. setReplaceMethod("dual_value", "Constraint", function(object, value) { object@dual_variables[[1]] <- value object }) #' #' The ZeroConstraint class #' #' @rdname ZeroConstraint-class .ZeroConstraint <- setClass("ZeroConstraint", representation(expr = "Expression"), contains = "Constraint") ZeroConstraint <- function(expr, id = NA_integer_) { .ZeroConstraint(expr = expr, id = id) } setMethod("initialize", "ZeroConstraint", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., args = list(expr)) }) #' @param x,object A \linkS4class{ZeroConstraint} object. #' @describeIn ZeroConstraint The string representation of the constraint. setMethod("name", "ZeroConstraint", function(x) { # paste(as.character(x@args[[1]]), "== 0") paste(name(x@args[[1]]), "== 0") }) #' @describeIn ZeroConstraint The dimensions of the constrained expression. setMethod("dim", "ZeroConstraint", function(x) { dim(x@args[[1]]) }) #' @describeIn Constraint The size of the constrained expression. setMethod("size", "ZeroConstraint", function(object) { size(object@args[[1]]) }) #' @describeIn ZeroConstraint Is the constraint DCP? setMethod("is_dcp", "ZeroConstraint", function(object) { is_affine(object@args[[1]]) }) #' @describeIn ZeroConstraint Is the constraint DGP? setMethod("is_dgp", "ZeroConstraint", function(object) { FALSE }) #' @describeIn ZeroConstraint The residual of a constraint setMethod("residual", "ZeroConstraint", function(object) { val <- value(expr(object)) if(any(is.na(val))) return(NA_real_) return(abs(val)) }) #' @describeIn ZeroConstraint The graph implementation of the object. setMethod("canonicalize", "ZeroConstraint", function(object) { canon <- canonical_form(object@args[[1]]) obj <- canon[[1]] constraints <- canon[[2]] dual_holder <- create_eq(obj, constr_id = id(object)) return(list(NA, c(constraints, list(dual_holder)))) }) #' #' The EqConstraint class #' #' @rdname EqConstraint-class .EqConstraint <- setClass("EqConstraint", representation(lhs = "ConstValORExpr", rhs = "ConstValORExpr", expr = "ConstValORExpr"), prototype(expr = NA_real_), contains = "Constraint") EqConstraint <- function(lhs, rhs, id = NA_integer_) { .EqConstraint(lhs = lhs, rhs = rhs, id = id) } setMethod("initialize", "EqConstraint", function(.Object, ..., lhs, rhs, expr = NA_real_) { .Object@lhs <- lhs .Object@rhs <- rhs .Object@expr <- lhs - rhs callNextMethod(.Object, ..., args = list(lhs, rhs)) }) setMethod(".construct_dual_variables", "EqConstraint", function(object, args) { callNextMethod(object, list(object@expr)) }) #' @param x,object A \linkS4class{EqConstraint} object. #' @describeIn EqConstraint The string representation of the constraint. setMethod("name", "EqConstraint", function(x) { # paste(as.character(x@args[[1]]), "==", as.character(x@args[[2]])) paste(name(x@args[[1]]), "==", name(x@args[[2]])) }) #' @describeIn EqConstraint The dimensions of the constrained expression. setMethod("dim", "EqConstraint", function(x) { dim(x@expr) }) #' @describeIn EqConstraint The size of the constrained expression. setMethod("size", "EqConstraint", function(object) { size(object@expr) }) #' @describeIn EqConstraint The expression to constrain. setMethod("expr", "EqConstraint", function(object) { object@expr }) #' @describeIn EqConstraint Is the constraint DCP? setMethod("is_dcp", "EqConstraint", function(object) { is_affine(object@expr) }) #' @describeIn EqConstraint Is the constraint DGP? setMethod("is_dgp", "EqConstraint", function(object) { is_log_log_affine(object@args[[1]]) && is_log_log_affine(object@args[[2]]) }) #' @describeIn EqConstraint The residual of the constraint.. setMethod("residual", "EqConstraint", function(object) { val <- value(object@expr) if(any(is.na(val))) return(NA_real_) return(abs(val)) }) #' #' The NonPosConstraint class #' #' @rdname NonPosConstraint-class .NonPosConstraint <- setClass("NonPosConstraint", representation(expr = "Expression"), contains = "Constraint") NonPosConstraint <- function(expr, id = NA_integer_) { .NonPosConstraint(expr = expr, id = id) } setMethod("initialize", "NonPosConstraint", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., args = list(expr)) }) #' @param x,object A \linkS4class{NonPosConstraint} object. #' @describeIn NonPosConstraint The string representation of the constraint. setMethod("name", "NonPosConstraint", function(x) { # paste(as.character(x@args[[1]]), "<= 0") paste(name(x@args[[1]]), "<= 0") }) #' @describeIn NonPosConstraint Is the constraint DCP? setMethod("is_dcp", "NonPosConstraint", function(object) { is_convex(object@args[[1]]) }) #' @describeIn NonPosConstraint Is the constraint DGP? setMethod("is_dgp", "NonPosConstraint", function(object) { FALSE }) #' @describeIn NonPosConstraint The graph implementation of the object. setMethod("canonicalize", "NonPosConstraint", function(object) { canon <- canonical_form(object@args[[1]]) obj <- canon[[1]] constraints <- canon[[2]] dual_holder <- create_leq(obj, constr_id = id(object)) return(list(NA, c(constraints, list(dual_holder)))) }) #' @describeIn NonPosConstraint The residual of the constraint. setMethod("residual", "NonPosConstraint", function(object) { val <- value(expr(object)) if(any(is.na(val))) return(NA_real_) return(pmax(val, 0)) }) #' #' The IneqConstraint class #' #' @rdname IneqConstraint-class .IneqConstraint <- setClass("IneqConstraint", representation(lhs = "ConstValORExpr", rhs = "ConstValORExpr", expr = "ConstValORExpr"), prototype(expr = NA_real_), contains = "Constraint") IneqConstraint <- function(lhs, rhs, id = NA_integer_) { .IneqConstraint(lhs = lhs, rhs = rhs, id = id) } setMethod("initialize", "IneqConstraint", function(.Object, ..., lhs, rhs, expr = NA_real_) { .Object@lhs <- lhs .Object@rhs <- rhs .Object@expr <- lhs - rhs if(is_complex(.Object@expr)) stop("Inequality constraints cannot be complex.") callNextMethod(.Object, ..., args = list(lhs, rhs)) }) #' @param x,object A \linkS4class{IneqConstraint} object. #' @describeIn IneqConstraint The string representation of the constraint. setMethod("name", "IneqConstraint", function(x) { # paste(as.character(x@args[[1]]), "<=", as.character(x@args[[2]])) paste(name(x@args[[1]]), "<=", name(x@args[[2]])) }) #' @describeIn IneqConstraint The dimensions of the constrained expression. setMethod("dim", "IneqConstraint", function(x) { dim(x@expr) }) #' @describeIn IneqConstraint The size of the constrained expression. setMethod("size", "IneqConstraint", function(object) { size(object@expr) }) #' @describeIn IneqConstraint The expression to constrain. setMethod("expr", "IneqConstraint", function(object) { object@expr }) #' @describeIn IneqConstraint A non-positive constraint is DCP if its argument is convex. setMethod("is_dcp", "IneqConstraint", function(object) { is_convex(object@expr) }) #' @describeIn IneqConstraint Is the constraint DGP? setMethod("is_dgp", "IneqConstraint", function(object) { is_log_log_convex(object@args[[1]]) && is_log_log_concave(object@args[[2]]) }) #' @describeIn IneqConstraint The residual of the constraint. setMethod("residual", "IneqConstraint", function(object) { val <- value(object@expr) if(any(is.na(val))) return(NA_real_) return(pmax(val, 0)) }) # TODO: Do I need the NonlinearConstraint class? #' #' The NonlinearConstraint class. #' #' This class represents a nonlinear inequality constraint, \eqn{f(x) \leq 0} where \eqn{f} is twice-differentiable. #' #' @slot f A nonlinear function. #' @slot vars_ A list of variables involved in the function. #' @slot .x_dim (Internal) The dimensions of a column vector with number of elements equal to the total elements in all the variables. #' @name NonlinearConstraint-class #' @aliases NonlinearConstraint #' @rdname NonlinearConstraint-class .NonlinearConstraint <- setClass("NonlinearConstraint", representation(f = "function", vars_ = "list", .x_dim = "numeric"), prototype(.x_dim = NULL), contains = "Constraint") #' @param f A nonlinear function. #' @param vars_ A list of variables involved in the function. #' @param id (Optional) An integer representing the unique ID of the contraint. #' @rdname NonlinearConstraint-class NonlinearConstraint <- function(f, vars_, id = NA_integer_) { .NonlinearConstraint(f = f, vars_ = vars_, id = id) } setMethod("initialize", "NonlinearConstraint", function(.Object, ..., f, vars_) { .Object@f <- f .Object@vars_ <- vars_ # The dimensions of vars_ in f(vars_) sizes <- sapply(.Object@vars_, function(v) { as.integer(prod(dim(v))) }) [email protected]_dim <- c(sum(sizes), 1) callNextMethod(.Object, ..., args = .Object@vars_) }) # Add the block to a slice of the matrix. setMethod("block_add", "NonlinearConstraint", function(object, mat, block, vert_offset, horiz_offset, rows, cols, vert_step = 1, horiz_step = 1) { if(is(mat, "sparseMatrix") && is.matrix(block)) block <- Matrix(block, sparse = TRUE) row_seq <- seq(vert_offset, rows + vert_offset, vert_step) col_seq <- seq(horiz_offset, cols + horiz_offset, horiz_step) mat[row_seq, col_seq] <- mat[row_seq, col_seq] + block mat }) # Place \code{x_0 = f()} in the vector of all variables. setMethod("place_x0", "NonlinearConstraint", function(object, big_x, var_offsets) { tmp <- object@f() m <- tmp[[1]] x0 <- tmp[[2]] offset <- 0 for(var in object@args) { var_dim <- as.integer(prod(dim(var))) var_x0 <- x0[offset:(offset + var_dim)] big_x <- block_add(object, big_x, var_x0, var_offsets[get_data(var)], 0, var_dim, 1) offset <- offset + var_dim } big_x }) # Place \code{Df} in the gradient of all functions. setMethod("place_Df", "NonlinearConstraint", function(object, big_Df, Df, var_offsets, vert_offset) { horiz_offset <- 0 for(var in object@args) { var_dim <- as.integer(prod(dim(var))) var_Df <- Df[, horiz_offset:(horiz_offset + var_dim)] big_Df <- block_add(object, big_Df, var_Df, vert_offset, var_offsets[get_data(var)], num_cones(object), var_dim) horiz_offset <- horiz_offset + var_dim } big_Df }) # Place \code{H} in the Hessian of all functions. setMethod("place_H", "NonlinearConstraint", function(object, big_H, H, var_offsets) { offset <- 0 for(var in object@args) { var_dim <- as.integer(prod(dim(var))) var_H <- H[offset:(offset + var_dim), offset:(offset + var_dim)] big_H <- block_add(object, big_H, var_H, var_offsets[get_data(var)], var_offsets[get_data(var)], var_dim, var_dim) offset <- offset + var_dim } big_H }) # Extract the function variables from the vector \code{x} of all variables. setMethod("extract_variables", "NonlinearConstraint", function(object, x, var_offsets) { local_x <- matrix(0, nrow = [email protected]_dim[1], ncol = [email protected]_dim[2]) offset <- 0 for(var in object@args) { var_dim <- as.integer(prod(dim(var))) value <- x[var_offsets[get_data(var)]:(var_offsets[get_data(var)] + var_dim)] local_x <- block_add(object, local_x, value, offset, 0, var_dim, 1) offset <- offset + var_dim } local_x }) #' #' The ExpCone class. #' #' This class represents a reformulated exponential cone constraint operating elementwise on \eqn{a, b, c}. #' #' Original cone: #' \deqn{ #' K = \{(x,y,z) | y > 0, ye^{x/y} \leq z\} \cup \{(x,y,z) | x \leq 0, y = 0, z \geq 0\} #' } #' Reformulated cone: #' \deqn{ #' K = \{(x,y,z) | y, z > 0, y\log(y) + x \leq y\log(z)\} \cup \{(x,y,z) | x \leq 0, y = 0, z \geq 0\} #' } #' #' @slot x The variable \eqn{x} in the exponential cone. #' @slot y The variable \eqn{y} in the exponential cone. #' @slot z The variable \eqn{z} in the exponential cone. #' @name ExpCone-class #' @aliases ExpCone #' @rdname ExpCone-class .ExpCone <- setClass("ExpCone", representation(x = "ConstValORExpr", y = "ConstValORExpr", z = "ConstValORExpr"), contains = "Constraint") #' @param x The variable \eqn{x} in the exponential cone. #' @param y The variable \eqn{y} in the exponential cone. #' @param z The variable \eqn{z} in the exponential cone. #' @param id (Optional) A numeric value representing the constraint ID. #' @rdname ExpCone-class ## #' @export ExpCone <- function(x, y, z, id = NA_integer_) { .ExpCone(x = x, y = y, z = z, id = id) } setMethod("initialize", "ExpCone", function(.Object, ..., x, y, z) { .Object@x <- x .Object@y <- y .Object@z <- z callNextMethod(.Object, ..., args = list(.Object@x, .Object@y, .Object@z)) }) setMethod("show", "ExpCone", function(object) { print(paste("ExpCone(", as.character(object@x), ", ", as.character(object@y), ", ", as.character(object@z), ")", sep = "")) }) #' @rdname ExpCone-class setMethod("as.character", "ExpCone", function(x) { paste("ExpCone(", as.character(x@x), ", ", as.character(x@y), ", ", as.character(x@z), ")", sep = "") }) #' @param object A \linkS4class{ExpCone} object. #' @describeIn ExpCone The size of the \code{x} argument. setMethod("residual", "ExpCone", function(object) { # TODO: The projection should be implemented directly. if(any(is.na(value(object@x))) || any(is.na(value(object@y))) || any(is.na(value(object@z)))) return(NA_real_) # x <- Variable(dim(object@x)) # y <- Variable(dim(object@y)) # z <- Variable(dim(object@z)) x <- new("Variable", dim = dim(object@x)) y <- new("Variable", dim = dim(object@y)) z <- new("Variable", dim = dim(object@z)) constr <- list(ExpCone(x, y, z)) obj <- Minimize(Norm2(HStack(x, y, z) - HStack(value(object@x), value(object@y), value(object@z)))) prob <- Problem(obj, constr) result <- solve(prob) return(result$value) }) #' @describeIn ExpCone The number of entries in the combined cones. setMethod("size", "ExpCone", function(object) { # TODO: Use size of dual variable(s) instead. sum(cone_sizes(object)) }) #' @describeIn ExpCone The number of elementwise cones. setMethod("num_cones", "ExpCone", function(object) { as.integer(prod(dim(object@args[[1]]))) }) #' @describeIn ExpCone The dimensions of the exponential cones. setMethod("cone_sizes", "ExpCone", function(object) { rep(num_cones(object), 3) }) #' @describeIn ExpCone An exponential constraint is DCP if each argument is affine. setMethod("is_dcp", "ExpCone", function(object) { all(sapply(object@args, is_affine)) }) #' @describeIn ExpCone Is the constraint DGP? setMethod("is_dgp", "ExpCone", function(object) { FALSE }) #' @describeIn ExpCone Canonicalizes by converting expressions to LinOps. setMethod("canonicalize", "ExpCone", function(object) { arg_objs <- list() arg_constr <- list() for(arg in object@args) { canon <- canonical_form(arg) arg_objs <- c(arg_objs, canon[[1]]) arg_constr <- c(arg_constr, canon[[2]]) } exp_constr <- do.call(ExpCone, arg_objs) list(0, c(list(exp_constr), arg_constr)) }) #' #' The PSDConstraint class. #' #' This class represents the positive semidefinite constraint, \eqn{\frac{1}{2}(X + X^T) \succeq 0}, i.e. \eqn{z^T(X + X^T)z \geq 0} for all \eqn{z}. #' #' @slot expr An \linkS4class{Expression}, numeric element, vector, or matrix representing \eqn{X}. #' @name PSDConstraint-class #' @aliases PSDConstraint #' @rdname PSDConstraint-class .PSDConstraint <- setClass("PSDConstraint", representation(expr = "ConstValORExpr"), validity = function(object) { expr_dim <- dim(object@expr) if(length(expr_dim) != 2 || expr_dim[1] != expr_dim[2]) stop("Non-square matrix in positive definite constraint.") return(TRUE) }, contains = "Constraint") #' @param expr An \linkS4class{Expression}, numeric element, vector, or matrix representing \eqn{X}. #' @param id (Optional) A numeric value representing the constraint ID. #' @rdname PSDConstraint-class PSDConstraint <- function(expr, id = NA_integer_) { .PSDConstraint(expr = expr, id = id) } setMethod("initialize", "PSDConstraint", function(.Object, ..., expr) { .Object@expr <- expr callNextMethod(.Object, ..., args = list(expr)) }) #' @param x,object A \linkS4class{PSDConstraint} object. #' @describeIn PSDConstraint The string representation of the constraint. setMethod("name", "PSDConstraint", function(x) { # paste(as.character(x@args[[1]]), ">> 0") paste(name(x@args[[1]]), ">> 0") }) #' @describeIn PSDConstraint The constraint is DCP if the left-hand and right-hand expressions are affine. setMethod("is_dcp", "PSDConstraint", function(object) { is_affine(object@args[[1]]) }) #' @describeIn PSDConstraint Is the constraint DGP? setMethod("is_dgp", "PSDConstraint", function(object) { FALSE }) #' @describeIn PSDConstraint A \linkS4class{Expression} representing the residual of the constraint. setMethod("residual", "PSDConstraint", function(object) { val <- value(expr(object)) if(any(is.na(val))) return(NA_real_) min_eig <- LambdaMin(object@args[[1]] + t(object@args[[1]]))/2 value(Neg(min_eig)) }) #' @describeIn PSDConstraint The graph implementation of the object. Marks the top level constraint as the \code{dual_holder} so the dual value will be saved to the \linkS4class{PSDConstraint}. setMethod("canonicalize", "PSDConstraint", function(object) { canon <- canonical_form(object@args[[1]]) obj <- canon[[1]] constraints <- canon[[2]] dual_holder <- PSDConstraint(obj, id = id(object)) return(list(NA, c(constraints, list(dual_holder)))) }) setMethod("format_constr", "PSDConstraint", function(object, eq_constr, leq_constr, dims, solver) { .format <- function(object) { leq_constr <- create_geq(expr(object), constr_id = object@id) return(list(leq_constr)) } new_leq_constr <- .format(object) # 0 <= A. leq_constr <- c(leq_constr, new_leq_constr) # Update dims. dims[[PSD_DIM]] <- c(dims[[PSD_DIM]], nrow(object)) list(eq_constr = eq_constr, leq_constr = leq_constr, dims = dims) }) #' #' The SOC class. #' #' This class represents a second-order cone constraint, i.e. \eqn{\|x\|_2 \leq t}. #' #' @slot t The scalar part of the second-order constraint. #' @slot X A matrix whose rows/columns are each a cone. #' @slot axis The dimension along which to slice: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @name SOC-class #' @aliases SOC #' @rdname SOC-class .SOC <- setClass("SOC", representation(t = "ConstValORExpr", X = "ConstValORExpr", axis = "numeric"), prototype(t = NA_real_, X = NA_real_, axis = 2), contains = "Constraint") #' @param t The scalar part of the second-order constraint. #' @param X A matrix whose rows/columns are each a cone. #' @param axis The dimension along which to slice: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @param id (Optional) A numeric value representing the constraint ID. #' @rdname SOC-class ## #' @export SOC <- function(t, X, axis = 2, id = NA_integer_) { .SOC(t = t, X = X, axis = axis, id = id) } setMethod("initialize", "SOC", function(.Object, ..., t, X, axis = 2) { # TODO: Allow imaginary X. # if(!(is.null(dim(t)) || length(dim(t)) == 1)) t_dim <- dim(t) if(!(is.null(t_dim) || length(t_dim) == 1 || (length(t_dim) == 2 && t_dim[2] == 1))) stop("t must be a scalar or 1-dimensional vector.") .Object@t <- t .Object@X <- X .Object@axis <- axis callNextMethod(.Object, ..., args = list(t, X)) }) #' @param x,object A \linkS4class{SOC} object. #' @rdname SOC-class setMethod("as.character", "SOC", function(x) { paste("SOC(", as.character(x@t), ", ", as.character(x@X), ")", sep = "") }) #' @describeIn SOC The residual of the second-order constraint. setMethod("residual", "SOC", function(object) { t <- value(object@args[[1]]) X <- value(object@args[[2]]) if(is.na(t) || is.na(X)) return(NA) if(object@axis == 2) X <- t(X) norms <- apply(X, 1, function(row) { norm(row, "2") }) zero_indices <- which(X <= -t)[1] averaged_indices <- which(X >= abs(t))[1] X_proj <- as.matrix(X) t_proj <- as.matrix(t) X_proj[zero_indices] <- 0 t_proj[zero_indices] <- 0 avg_coeff <- 0.5*(1 + t/norms) X_proj[averaged_indices] <- avg_coeff * X[averaged_indices] t_proj[averaged_indices] <- avg_coeff * t[averaged_indices] Xt_diff <- cbind(X, t) - cbind(X_proj, t_proj) apply(Xt_diff, 1, function(col) { norm(col, "2") }) }) #' @describeIn SOC Information needed to reconstruct the object aside from the args. setMethod("get_data", "SOC", function(object) { list(object@axis) }) #' @param eq_constr A list of the equality constraints in the canonical problem. #' @param leq_constr A list of the inequality constraints in the canonical problem. #' @param dims A list with the dimensions of the conic constraints. #' @param solver A string representing the solver to be called. #' @describeIn SOC Format SOC constraints as inequalities for the solver. setMethod("format_constr", "SOC", function(object, eq_constr, leq_constr, dims, solver) { .format <- function(object) { list(list(), format_axis(object@args[[1]], object@args[[2]], object@axis)) } leq_constr <- c(leq_constr, .format(object)[[2]]) dims[[SOC_DIM]] <- c(dims[[SOC_DIM]], cone_sizes(object)) list(eq_constr = eq_constr, leq_constr = leq_constr, dims = dims) }) #' @describeIn SOC The number of elementwise cones. setMethod("num_cones", "SOC", function(object) { prod(dim(object@args[[1]])) }) #' @describeIn SOC The number of entries in the combined cones. setMethod("size", "SOC", function(object) { # TODO: Use size of dual variable(s) instead. sum(cone_sizes(object)) }) #' @describeIn SOC The dimensions of the second-order cones. setMethod("cone_sizes", "SOC", function(object) { if(object@axis == 2) # Collapse columns. idx <- 1 else if(object@axis == 1) # Collapse rows. idx <- 2 else stop("Unimplemented") cone_size <- 1 + dim(object@args[[2]])[idx] sapply(1:num_cones(object), function(i) { cone_size }) }) #' @describeIn SOC An SOC constraint is DCP if each of its arguments is affine. setMethod("is_dcp", "SOC", function(object) { all(sapply(object@args, function(arg) { is_affine(arg) })) }) #' @describeIn SOC Is the constraint DGP? setMethod("is_dgp", "SOC", function(object) { FALSE }) # TODO: Hack. #' @describeIn SOC The canonicalization of the constraint. setMethod("canonicalize", "SOC", function(object) { canon_t <- canonical_form(object@args[[1]]) t <- canon_t[[1]] t_cons <- canon_t[[2]] canon_X <- canonical_form(object@args[[2]]) X <- canon_X[[1]] X_cons <- canon_X[[2]] new_soc <- SOC(t, X, object@axis) return(list(NA, c(list(new_soc), t_cons, X_cons))) }) #' #' The SOCAxis class. #' #' This class represents a second-order cone constraint for each row/column. #' It Assumes \eqn{t} is a vector the same length as \eqn{X}'s rows (columns) for axis == 1 (2). #' #' @slot t The scalar part of the second-order constraint. #' @slot x_elems A list containing \code{X}, a matrix whose rows/columns are each a cone. #' @slot axis The dimension across which to take the slice: \code{1} indicates rows, and \code{2} indicates columns. #' @name SOCAxis-class #' @aliases SOCAxis #' @rdname SOCAxis-class .SOCAxis <- setClass("SOCAxis", representation(x_elems = "list"), prototype(x_elems = list()), contains = "SOC") #' @param t The scalar part of the second-order constraint. #' @param X A matrix whose rows/columns are each a cone. #' @param axis The dimension across which to take the slice: \code{1} indicates rows, and \code{2} indicates columns. #' @param id (Optional) A numeric value representing the constraint ID. #' @rdname SOCAxis-class ## #' @export SOCAxis <- function(t, X, axis, id = NA_integer_) { .SOCAxis(t = t, X = X, axis = axis, id = id) } setMethod("initialize", "SOCAxis", function(.Object, ...) { .Object <- callNextMethod(.Object, ...) .Object@x_elems <- list(.Object@X) .Object }) #' @param x,object A \linkS4class{SOCAxis} object. #' @rdname SOCAxis-class setMethod("as.character", "SOCAxis", function(x) { paste("SOCAxis(", as.character(x@t), ", ", as.character(x@X), ", <", paste(x@axis, collapse = ", "), ">)", sep = "") }) #' @param eq_constr A list of the equality constraints in the canonical problem. #' @param leq_constr A list of the inequality constraints in the canonical problem. #' @param dims A list with the dimensions of the conic constraints. #' @param solver A string representing the solver to be called. #' @describeIn SOCAxis Format SOC constraints as inequalities for the solver. setMethod("format_constr", "SOCAxis", function(object, eq_constr, leq_constr, dims, solver) { .format <- function(object) { list(list(), format_axis(object@t, object@x_elems[[1]], object@axis)) } leq_constr <- c(leq_constr, .format(object)[[2]]) # Update dims for(cone_size in size(object)) dims[[SOC_DIM]] <- c(dims[[SOC_DIM]], cone_size[1]) list(eq_constr = eq_constr, leq_constr = leq_constr, dims = dims) }) #' @describeIn SOCAxis The number of elementwise cones. setMethod("num_cones", "SOCAxis", function(object) { nrow(object@t) }) #' @describeIn SOCAxis The dimensions of a single cone. setMethod("cone_sizes", "SOCAxis", function(object) { if(object@axis == 1) # Return ncols if applying along each row c(1 + ncol(object@x_elems[[1]]), 1) else if(object@axis == 2) # Return nrows if applying along each column c(1 + nrow(object@x_elems[[1]]), 1) else stop("Invalid axis ", object@axis) }) #' @describeIn SOCAxis The dimensions of the (elementwise) second-order cones. setMethod("size", "SOCAxis", function(object) { cone_size <- cone_size(object) lapply(1:num_cones(object), function(i) { cone_size }) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/constraints.R
#' Global Monthly and Annual Temperature Anomalies (degrees C), 1850-2015 #' (Relative to the 1961-1990 Mean) (May 2016) #' #' @name cdiac #' @docType data #' @source \url{https://ess-dive.lbl.gov/} #' @references \url{https://ess-dive.lbl.gov/} #' @keywords data #' @format A data frame with 166 rows and 14 variables: #' \describe{ #' \item{year}{Year} #' \item{jan}{Anomaly for month of January} #' \item{feb}{Anomaly for month of February} #' \item{mar}{Anomaly for month of March} #' \item{apr}{Anomaly for month of April} #' \item{may}{Anomaly for month of May} #' \item{jun}{Anomaly for month of June} #' \item{jul}{Anomaly for month of July} #' \item{aug}{Anomaly for month of August} #' \item{sep}{Anomaly for month of September} #' \item{oct}{Anomaly for month of October} #' \item{nov}{Anomaly for month of November} #' \item{dec}{Anomaly for month of December} #' \item{annual}{Annual anomaly for the year} #' } "cdiac" #' Direct Standardization: Population #' #' Randomly generated data for direct standardization example. #' Sex was drawn from a Bernoulli distribution, and age was drawn from a uniform distribution on \eqn{10,\ldots,60}. #' The response was drawn from a normal distribution with a mean that depends on sex and age, and a variance of 1. #' #' @name dspop #' @docType data #' @keywords data #' @seealso \link[CVXR]{dssamp} #' @format A data frame with 1000 rows and 3 variables: #' \describe{ #' \item{y}{Response variable} #' \item{sex}{Sex of individual, coded male (0) and female (1)} #' \item{age}{Age of individual} #' } "dspop" #' Direct Standardization: Sample #' #' A sample of \code{\link{dspop}} for direct standardization example. #' The sample is skewed such that young males are overrepresented in comparison to the population. #' #' @name dssamp #' @docType data #' @keywords data #' @seealso \link[CVXR]{dspop} #' @format A data frame with 100 rows and 3 variables: #' \describe{ #' \item{y}{Response variable} #' \item{sex}{Sex of individual, coded male (0) and female (1)} #' \item{age}{Age of individual} #' } "dssamp"
/scratch/gouwar.j/cran-all/cranData/CVXR/R/data.R
#' #' Reduce DCP Problem to Conic Form #' #' This reduction takes as input (minimization) DCP problems and converts them into problems #' with affine objectives and conic constraints whose arguments are affine. #' #' @rdname Dcp2Cone-class .Dcp2Cone <- setClass("Dcp2Cone", contains = "Canonicalization") Dcp2Cone <- function(problem = NULL) { .Dcp2Cone(problem = problem) } setMethod("initialize", "Dcp2Cone", function(.Object, ...) { callNextMethod(.Object, ..., canon_methods = Dcp2Cone.CANON_METHODS) }) #' @param object A \linkS4class{Dcp2Cone} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn Dcp2Cone A problem is accepted if it is a minimization and is DCP. setMethod("accepts", signature(object = "Dcp2Cone", problem = "Problem"), function(object, problem) { inherits(problem@objective, "Minimize") && is_dcp(problem) }) #' @describeIn Dcp2Cone Converts a DCP problem to a conic form. setMethod("perform", signature(object = "Dcp2Cone", problem = "Problem"), function(object, problem) { if(!accepts(object, problem)) stop("Cannot reduce problem to cone program") callNextMethod(object, problem) }) #' #' Construct Matrices for Linear Cone Problems #' #' Linear cone problems are assumed to have a linear objective and cone constraints, #' which may have zero or more arguments, all of which must be affine. #' #' minimize c^Tx #' subject to cone_constr1(A_1*x + b_1, ...) #' ... #' cone_constrK(A_K*x + b_K, ...) #' #' @rdname ConeMatrixStuffing-class ConeMatrixStuffing <- setClass("ConeMatrixStuffing", contains = "MatrixStuffing") #' @param object A \linkS4class{ConeMatrixStuffing} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn ConeMatrixStuffing Is the solver accepted? setMethod("accepts", signature(object = "ConeMatrixStuffing", problem = "Problem"), function(object, problem) { return(inherits(problem@objective, "Minimize") && is_affine(expr(problem@objective)) && length(convex_attributes(variables(problem))) == 0 && are_args_affine(problem@constraints)) }) #' @param extractor Used to extract the affine coefficients of the objective. #' @describeIn ConeMatrixStuffing Returns a list of the stuffed matrices setMethod("stuffed_objective", signature(object = "ConeMatrixStuffing", problem = "Problem", extractor = "CoeffExtractor"), function(object, problem, extractor) { # Extract to t(c) %*% x, store in r CR <- affine(extractor, expr(problem@objective)) C <- CR[[1]] R <- CR[[2]] c <- matrix(C, ncol = 1) # TODO: Check if converted to dense matrix and flattened like in CVXPY boolint <- extract_mip_idx(variables(problem)) boolean <- boolint[[1]] integer <- boolint[[2]] # x <- Variable(extractor@N, boolean = boolean, integer = integer) x <- Variable(extractor@N, 1, boolean = boolean, integer = integer) new_obj <- t(c) %*% x + 0 return(list(new_obj, x, R[1])) }) # Atom canonicalizers. #' #' Dcp2Cone canonicalizer for the entropy atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from an entropy atom where #' the objective function is just the variable t with an ExpCone constraint. Dcp2Cone.entr_canon <- function(expr, args) { x <- args[[1]] expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) # -x*log(x) >= t is equivalent to x/exp(t/x) <= 1 # TODO: ExpCone requires each of its inputs to be a Variable; is this something we want to change? if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) constraints <- list(ExpCone(t, x, ones)) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the exponential atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from an exponential atom #' where the objective function is the variable t with an ExpCone constraint. Dcp2Cone.exp_canon <- function(expr, args) { expr_dim <- dim(expr) x <- promote(args[[1]], expr_dim) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) constraints <- list(ExpCone(x, ones, t)) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the geometric mean atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a geometric mean atom #' where the objective function is the variable t with geometric mean constraints Dcp2Cone.geo_mean_canon <- function(expr, args) { x <- args[[1]] w <- expr@w expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) x_list <- lapply(1:length(w), function(i) { x[i] }) # TODO: Catch cases where we have (0,0,1)? # TODO: What about curvature case (should be affine) in trivial case of (0,0,1)? # Should this behavior match with what we do in power? return(list(t, gm_constrs(t, x_list, w))) } #' #' Dcp2Cone canonicalizer for the huber atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a huber atom where the objective #' function is the variable t with square and absolute constraints Dcp2Cone.huber_canon <- function(expr, args) { M <- expr@M x <- args[[1]] expr_dim <- dim(expr) # n <- Variable(expr_dim) # s <- Variable(expr_dim) n <- new("Variable", dim = expr_dim) s <- new("Variable", dim = expr_dim) # n^2 + 2*M*|s| # TODO: Make use of recursion inherent to canonicalization process and just return a # power/abs expression for readiability's sake power_expr <- power(n,2) canon <- Dcp2Cone.power_canon(power_expr, power_expr@args) n2 <- canon[[1]] constr_sq <- canon[[2]] abs_expr <- abs(s) canon <- EliminatePwl.abs_canon(abs_expr, abs_expr@args) abs_s <- canon[[1]] constr_abs <- canon[[2]] obj <- n2 + 2*M*abs_s # x == s + n constraints <- c(constr_sq, constr_abs) constraints <- c(constraints, x == s + n) return(list(obj, constraints)) } #' #' Dcp2Cone canonicalizer for the indicator atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from an indicator atom and #' where 0 is the objective function with the given constraints #' in the function. Dcp2Cone.indicator_canon <- function(expr, args) { return(list(0, args)) } #' #' Dcp2Cone canonicalizer for the KL Divergence atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a KL divergence atom #' where t is the objective function with the ExpCone constraints. Dcp2Cone.kl_div_canon <- function(expr, args) { expr_dim <- dim(expr) x <- promote(args[[1]], expr_dim) y <- promote(args[[2]], expr_dim) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) constraints <- list(ExpCone(t, x, y), y >= 0) obj <- y - x - t return(list(obj, constraints)) } #' #' Dcp2Cone canonicalizer for the lambda maximization atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a lambda maximization atom #' where t is the objective function and a PSD constraint and a #' constraint requiring I*t to be symmetric. Dcp2Cone.lambda_max_canon <- function(expr, args) { A <- args[[1]] n <- nrow(A) t <- Variable() prom_t <- promote(t, c(n,1)) # Constraint I*t - A to be PSD; note this expression must be symmetric tmp_expr <- DiagVec(prom_t) - A constr <- list(tmp_expr == t(tmp_expr), PSDConstraint(tmp_expr)) return(list(t, constr)) } #' #' Dcp2Cone canonicalizer for the largest lambda sum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a lambda sum of the k #' largest elements atom where k*t + trace(Z) is the objective function. #' t denotes the variable subject to constraints and Z is a PSD matrix variable #' whose dimensions consist of the length of the vector at hand. The constraints #' require the the diagonal matrix of the vector to be symmetric and PSD. Dcp2Cone.lambda_sum_largest_canon <- function(expr, args) { # S_k(X) denotes lambda_sum_largest(X, k) # t >= k S_k(X - Z) + trace(Z), Z is PSD # implies # t >= ks + trace(Z) # Z is PSD # sI >= X - Z (PSD sense) # which implies # t >= ks + trace(Z) >= S_k(sI + Z) >= S_k(X) # We use the fact that # S_k(X) = sup_{sets of k orthonormal vectors u_i}\sum_{i}u_i^T X u_i # and if Z >= X in PSD sense then # \sum_{i}u_i^T Z u_i >= \sum_{i}u_i^T X u_i # # We have equality when s = lambda_k and Z diagonal # with Z_{ii} = (lambda_i - lambda_k)_+ X <- expr@args[[1]] k <- expr@k # Z <- Variable(c(nrow(X), nrow(X)), PSD = TRUE) Z <- Variable(nrow(X), ncol(X), PSD = TRUE) canon <- Dcp2Cone.lambda_max_canon(expr, list(X - Z)) obj <- canon[[1]] constr <- canon[[2]] obj <- k*obj + matrix_trace(Z) return(list(obj, constr)) } #' #' Dcp2Cone canonicalizer for the log 1p atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a log 1p atom where #' t is the objective function and the constraints consist of #' ExpCone constraints + 1. Dcp2Cone.log1p_canon <- function(expr, args) { return(Dcp2Cone.log_canon(expr, list(args[[1]] + 1))) } #' #' Dcp2Cone canonicalizer for the log atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a log atom where #' t is the objective function and the constraints consist of #' ExpCone constraints Dcp2Cone.log_canon <- function(expr, args) { x <- args[[1]] expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) # TODO: ExpCone requires each of its inputs to be a Variable; is this something that we want to change? constraints <- list(ExpCone(t, ones, x)) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the log determinant atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a log determinant atom where #' the objective function is the sum of the log of the vector D #' and the constraints consist of requiring the matrix Z to be #' diagonal and the diagonal Z to equal D, Z to be upper triangular #' and DZ; t(Z)A to be positive semidefinite, where A is a n by n #' matrix. Dcp2Cone.log_det_canon <- function(expr, args) { # Reduces the atom to an affine expression and list of constraints. # # Creates the equivalent problem:: # # maximize sum(log(D[i, i])) # subject to: D diagonal # diag(D) = diag(Z) # Z is upper triangular. # [D Z; t(Z) A] is positive semidefinite # # The problem computes the LDL factorization: # # A = (Z^TD^{-1})D(D^{-1}Z) # # This follows from the inequality: # # \det(A) >= \det(D) + \det([D, Z; Z^T, A])/\det(D) >= \det(D) # # because (Z^TD^{-1})D(D^{-1}Z) is a feasible D, Z that achieves # det(A) = det(D) and the objective maximizes det(D). # # Parameters # ---------- # expr : log_det # args : list of arguments for the expression # # Returns # ------- # (Variable for objective, list of constraints) A <- args[[1]] # n by n matrix n <- nrow(A) # Require that X and A are PSD. # X <- Variable(c(2*n, 2*n), PSD = TRUE) X <- Variable(2*n, 2*n, PSD = TRUE) constraints <- list(PSDConstraint(A)) # Fix Z as upper triangular # TODO: Represent Z as upper triangular vector # Z <- Variable(c(n,n)) Z <- Variable(n,n) Z_lower_tri <- UpperTri(t(Z)) constraints <- c(constraints, list(Z_lower_tri == 0)) # Fix diag(D) = Diag(Z): D[i,i] = Z[i,i] D <- Variable(n) constraints <- c(constraints, D == DiagMat(Z)) # Fix X using the fact that A must be affine by the DCP rules # X[1:n, 1:n] == D constraints <- c(constraints, X[1:n, 1:n] == DiagVec(D)) # X[1:n, (n+1):(2*n)] == Z constraints <- c(constraints, X[1:n, (n+1):(2*n)] == Z) # X[(n+1):(2*n), (n+1):(2*n)] == A constraints <- c(constraints, X[(n+1):(2*n), (n+1):(2*n)] == A) # Add the objective sum(log(D[i,i])) log_expr <- Log(D) canon <- Dcp2Cone.log_canon(log_expr, log_expr@args) obj <- canon[[1]] constr <- canon[[2]] constraints <- c(constraints, constr) return(list(sum(obj), constraints)) } #' #' Dcp2Cone canonicalizer for the log sum of the exp atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from the log sum #' of the exp atom where the objective is the t variable #' and the constraints consist of the ExpCone constraints and #' requiring t to be less than a matrix of ones of the same size. Dcp2Cone.log_sum_exp_canon <- function(expr, args) { x <- args[[1]] x_dim <- dim(x) expr_dim <- dim(expr) axis <- expr@axis keepdims <- expr@keepdims # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) # log(sum(exp(x))) <= t <=> sum(exp(x-t)) <= 1. if(is.na(axis)) # shape = c(1,1) promoted_t <- promote(t, x_dim) else if(axis == 2) # shape = c(1,n) promoted_t <- Constant(matrix(1, nrow = x_dim[1], ncol = 1) %*% reshape_expr(t, c(1 + x_dim[2], x_dim[3:length(x_dim)]))) else # shape = c(m,1) promoted_t <- reshape_expr(t, c(1 + x_dim[1], x_dim[2:(length(x_dim)-1)])) %*% Constant(matrix(1, nrow = 1, ncol = x_dim[2])) exp_expr <- Exp(x - promoted_t) canon <- Dcp2Cone.exp_canon(exp_expr, exp_expr@args) obj <- sum_entries(canon[[1]], axis = axis, keepdims = keepdims) if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) constraints <- c(canon[[2]], obj <= ones) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the logistic function atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from the logistic atom #' where the objective function is given by t0 and the #' constraints consist of the ExpCone constraints. Dcp2Cone.logistic_canon <- function(expr, args) { x <- args[[1]] expr_dim <- dim(expr) # log(1 + exp(x)) <= t is equivalent to exp(-t) + exp(x - t) <= 1 # t0 <- Variable(expr_dim) t0 <- new("Variable", dim = expr_dim) canon1 <- Dcp2Cone.exp_canon(expr, list(-t0)) canon2 <- Dcp2Cone.exp_canon(expr, list(x - t0)) t1 <- canon1[[1]] constr1 <- canon1[[2]] t2 <- canon2[[1]] constr2 <- canon2[[2]] if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) constraints <- c(constr1, constr2, list(t1 + t2 <= ones)) return(list(t0, constraints)) } #' #' Dcp2Cone canonicalizer for the matrix fraction atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from the matrix fraction #' atom, where the objective function is the trace of Tvar, a #' m by m matrix where the constraints consist of the matrix of #' the Schur complement of Tvar to consist of P, an n by n, given #' matrix, X, an n by m given matrix, and Tvar. Dcp2Cone.matrix_frac_canon <- function(expr, args) { X <- args[[1]] # n by m matrix P <- args[[2]] # n by n matrix if(length(dim(X)) == 1) X <- reshape_expr(X, c(nrow(X), 1)) X_dim <- dim(X) n <- X_dim[1] m <- X_dim[2] # Create a matrix with Schur complement Tvar - t(X) %*% inv(P) %*% X # M <- Variable(c(n+m, n+m), PSD = TRUE) # Tvar <- Variable(c(m,m), symmetric = TRUE) M <- Variable(n+m, n+m, PSD = TRUE) Tvar <- Variable(m, m, symmetric = TRUE) constraints <- list() # Fix M using the fact that P must be affine by the DCP rules. # M[1:n, 1:n] == P constraints <- c(constraints, M[1:n, 1:n] == P) # M[1:n, (n+1):(n+m)] == X constraints <- c(constraints, M[1:n, (n+1):(n+m)] == X) # M[(n+1):(n+m), (n+1):(n+m)] == Tvar constraints <- c(constraints, M[(n+1):(n+m), (n+1):(n+m)] == Tvar) return(list(matrix_trace(Tvar), constraints)) } #' #' Dcp2Cone canonicalizer for the nuclear norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a nuclear norm atom, #' where the objective function consists of .5 times the trace of #' a matrix X of size m+n by m+n where the constraint consist of #' the top right corner of the matrix being the original matrix. Dcp2Cone.normNuc_canon <- function(expr, args) { A <- args[[1]] A_dim <- dim(A) m <- A_dim[1] n <- A_dim[2] # Create the equivalent problem: # minimize (trace(U) + trace(V))/2 # subject to: # [U A; t(A) V] is positive semidefinite # X <- Variable(c(m+n, m+n), PSD = TRUE) X <- Variable(m+n, m+n, PSD = TRUE) constraints <- list() # Fix X using the fact that A must be affine by the DCP rules. # X[1:rows, (rows+1):(rows+cols)] == A constraints <- c(constraints, X[1:m, (m+1):(m+n)] == A) trace_value <- 0.5*matrix_trace(X) return(list(trace_value, constraints)) } #' #' Dcp2Cone canonicalizer for the p norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a pnorm atom, where #' the objective is a variable t of dimension of the original #' vector in the problem and the constraints consist of geometric #' mean constraints. Dcp2Cone.pnorm_canon <- function(expr, args) { x <- args[[1]] p <- expr@p axis <- expr@axis expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) if(p == 2) { if(is.na(axis)) { # if(!is.null(expr_dim)) # stop("Dimensions should be NULL") if(!all(expr_dim == c(1,1))) stop("Dimensions should be c(1,1)") return(list(t, list(SOC(t, vec(x))))) } else return(list(t, list(SOC(vec(t), x, axis)))) } # We need an absolute value constraint for the symmetric convex branches (p > 1) constraints <- list() if(p > 1) { # TODO: Express this more naturally (recursively) in terms of the other atoms abs_expr <- abs(x) canon <- EliminatePwl.abs_canon(abs_expr, abs_expr@args) x <- canon[[1]] abs_constraints <- canon[[2]] constraints <- c(constraints, abs_constraints) } # Now, we take care of the remaining convex and concave branches to create the # rational powers. We need a new variable, r, and the constraint sum(r) == t # r <- Variable(dim(x)) r <- new("Variable", dim = dim(x)) constraints <- c(constraints, list(sum(r) == t)) # TODO: No need to run gm_constr to form the tree each time. # We only need to form the tree once. promoted_t <- Constant(matrix(1, nrow = nrow(x), ncol = ncol(x))) %*% t p <- gmp::as.bigq(p) if(p < 0) constraints <- c(constraints, gm_constrs(promoted_t, list(x, r), c(-p/(1-p), 1/(1-p)))) else if(p > 0 && p < 1) constraints <- c(constraints, gm_constrs(r, list(x, promoted_t), c(p, 1-p))) else if(p > 1) constraints <- c(constraints, gm_constrs(x, list(r, promoted_t), c(1/p, 1-1/p))) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the power atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a power atom, where #' the objective function consists of the variable t which is #' of the dimension of the original vector from the power atom #' and the constraints consists of geometric mean constraints. Dcp2Cone.power_canon <- function(expr, args) { x <- args[[1]] p <- expr@p w <- expr@w if(p == 1) return(list(x, list())) expr_dim <- dim(expr) if(is.null(expr_dim)) ones <- Constant(1) else ones <- Constant(matrix(1, nrow = expr_dim[1], ncol = expr_dim[2])) if(p == 0) return(list(ones, list())) else { # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) # TODO: gm_constrs requires each of its inputs to be a Variable; is this something that we want to change? if(p > 0 && p < 1) return(list(t, gm_constrs(t, list(x, ones), w))) else if(p > 1) return(list(t, gm_constrs(x, list(t, ones), w))) else if(p < 0) return(list(t, gm_constrs(ones, list(x, t), w))) else stop("This power is not yet supported") } } #' #' Dcp2Cone canonicalizer for the quadratic form atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a quadratic form atom, #' where the objective function consists of the scaled objective function #' from the quadratic over linear canonicalization and same with the #' constraints. Dcp2Cone.quad_form_canon <- function(expr, args) { decomp <- .decomp_quad(value(args[[2]])) scale <- decomp[[1]] M1 <- decomp[[2]] M2 <- decomp[[3]] if(!is.null(dim(M1)) && prod(dim(M1)) > 0) expr <- sum_squares(Constant(t(M1)) %*% args[[1]]) else if(!is.null(dim(M2)) && prod(dim(M2)) > 0) { scale <- -scale expr <- sum_squares(Constant(t(M2)) %*% args[[1]]) } canon <- Dcp2Cone.quad_over_lin_canon(expr, expr@args) obj <- canon[[1]] constr <- canon[[2]] return(list(scale * obj, constr)) } #' #' Dcp2Cone canonicalizer for the quadratic over linear term atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a quadratic over linear #' term atom where the objective function consists of a one #' dimensional variable t with SOC constraints. Dcp2Cone.quad_over_lin_canon <- function(expr, args) { # quad_over_lin := sum_{ij} X^2_{ij} / y x <- args[[1]] y <- flatten(args[[2]]) # Pre-condition: dim = c() t <- Variable(1) # (y+t, y-t, 2*x) must lie in the second-order cone, where y+t is the scalar part # of the second-order cone constraint # BUG: In Python, flatten produces single dimension (n,), but in R, we always treat # these as column vectors with dimension (n,1), necessitating the use of VStack. # constraints <- list(SOC(t = y+t, X = HStack(y-t, 2*flatten(x)), axis = 2)) constraints <- list(SOC(t = y+t, X = VStack(y-t, 2*flatten(x)), axis = 2)) return(list(t, constraints)) } #' #' Dcp2Cone canonicalizer for the sigma max atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A cone program constructed from a sigma max atom #' where the objective function consists of the variable t #' that is of the same dimension as the original expression #' with specified constraints in the function. Dcp2Cone.sigma_max_canon <- function(expr, args) { A <- args[[1]] A_dim <- dim(A) n <- A_dim[1] m <- A_dim[2] # X <- Variable(c(n+m, n+m), PSD = TRUE) X <- new("Variable", dim = c(n+m, n+m), PSD = TRUE) expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = expr_dim) constraints <- list() # Fix X using the fact that A must be affine by the DCP rules. # X[1:n, 1:n] == I_n*t constraints <- c(constraints, X[1:n, 1:n] == Constant(sparseMatrix(i = 1:n, j = 1:n, x = 1)) %*% t) # X[1:n, (n+1):(n+m)] == A constraints <- c(constraints, X[1:n, (n+1):(n+m)] == A) # X[(n+1):(n+m), (n+1):(n+m)] == I_m*t constraints <- c(constraints, X[(n+1):(n+m), (n+1):(n+m)] == Constant(sparseMatrix(i = 1:m, j = 1:m, x = 1)) %*% t) return(list(t, constraints)) } # TODO: Remove pwl canonicalize methods and use EliminatePwl reduction instead. Dcp2Cone.CANON_METHODS <- list(CumMax = EliminatePwl.CANON_METHODS$CumMax, CumSum = EliminatePwl.CANON_METHODS$CumSum, GeoMean = Dcp2Cone.geo_mean_canon, LambdaMax = Dcp2Cone.lambda_max_canon, LambdaSumLargest = Dcp2Cone.lambda_sum_largest_canon, LogDet = Dcp2Cone.log_det_canon, LogSumExp = Dcp2Cone.log_sum_exp_canon, MatrixFrac = Dcp2Cone.matrix_frac_canon, MaxEntries = EliminatePwl.CANON_METHODS$MaxEntries, MinEntries = EliminatePwl.CANON_METHODS$MinEntries, Norm1 = EliminatePwl.CANON_METHODS$Norm1, NormNuc = Dcp2Cone.normNuc_canon, NormInf = EliminatePwl.CANON_METHODS$NormInf, Pnorm = Dcp2Cone.pnorm_canon, QuadForm = Dcp2Cone.quad_form_canon, QuadOverLin = Dcp2Cone.quad_over_lin_canon, SigmaMax = Dcp2Cone.sigma_max_canon, SumLargest = EliminatePwl.CANON_METHODS$SumLargest, Abs = EliminatePwl.CANON_METHODS$Abs, Entr = Dcp2Cone.entr_canon, Exp = Dcp2Cone.exp_canon, Huber = Dcp2Cone.huber_canon, KLDiv = Dcp2Cone.kl_div_canon, Log = Dcp2Cone.log_canon, Log1p = Dcp2Cone.log1p_canon, Logistic = Dcp2Cone.logistic_canon, MaxElemwise = EliminatePwl.CANON_METHODS$MaxElemwise, MinElemwise = EliminatePwl.CANON_METHODS$MinElemwise, Power = Dcp2Cone.power_canon, Indicator = Dcp2Cone.indicator_canon, SpecialIndex = special_index_canon)
/scratch/gouwar.j/cran-all/cranData/CVXR/R/dcp2cone.R
#' #' Reduce DGP problems to DCP problems. #' #' This reduction takes as input a DGP problem and returns an equivalent DCP #' problem. Because every (generalized) geometric program is a DGP problem, #' this reduction can be used to convert geometric programs into convex form. #' @rdname Dgp2Dcp-class Dgp2Dcp <- setClass("Dgp2Dcp", contains = "Canonicalization") #' @describeIn Dgp2Dcp Is the problem DGP? setMethod("accepts", signature(object = "Dgp2Dcp", problem = "Problem"), function(object, problem) { return(is_dgp(problem)) }) #' @param object A \linkS4class{Dgp2Dcp} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn Dgp2Dcp Converts the DGP problem to a DCP problem. setMethod("perform", signature(object = "Dgp2Dcp", problem = "Problem"), function(object, problem) { if(!accepts(object, problem)) stop("The supplied problem is not DGP") object@canon_methods <- DgpCanonMethods() tmp <- callNextMethod(object, problem) object <- tmp[[1]] equiv_problem <- tmp[[2]] inverse_data <- tmp[[3]] inverse_data@problem <- problem return(list(object, equiv_problem, inverse_data)) }) #' @param expr An \linkS4class{Expression} object corresponding to the DGP problem. #' @param args A list of values corresponding to the DGP expression #' @describeIn Dgp2Dcp Canonicalizes each atom within an Dgp2Dcp expression. setMethod("canonicalize_expr", "Dgp2Dcp", function(object, expr, args) { if(inherits(expr, names(object@canon_methods))) return(object@canon_methods[[class(expr)]](expr, args)) else return(list(copy(expr, args), list())) }) #' @param solution A \linkS4class{Solution} object to invert. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn Dgp2Dcp Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "Dgp2Dcp", solution = "Solution", inverse_data = "InverseData"), function(object, solution, inverse_data) { solution <- callNextMethod(object, solution, inverse_data) if(solution@status == SOLVER_ERROR) return(solution) for(vid in names(solution@primal_vars)) solution@primal_vars[[vid]] <- exp(solution@primal_vars[[vid]]) # f(x) = e^{F(u)} solution@opt_val <- exp(solution@opt_val) return(solution) }) # Atom canonicalizers # TODO: Implement sum_largest/sum_smallest. #' #' Dgp2Dcp canonicalizer for the addition atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the addition atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.add_canon <- function(expr, args) { if(is_scalar(expr)) return(list(log_sum_exp(do.call("HStack", args)), list())) rows <- list() summands <- lapply(args, function(s) { if(is_scalar(s)) promote(s, dim(expr)) else s }) if(length(dim(expr)) == 1) { for(i in 1:nrow(expr)) { summand_args <- lapply(summands, function(summand) { summand[i] }) row <- log_sum_exp(do.call("HStack", summand_args)) rows <- c(rows, list(row)) } return(list(reshape_expr(bmat(rows), dim(expr)), list())) } else { for(i in 1:nrow(expr)) { row <- list() for(j in 1:ncol(expr)) { summand_args <- lapply(summands, function(summand) { summand[i,j] }) row <- c(row, list(log_sum_exp(do.call("HStack", summand_args)))) } rows <- c(rows, list(row)) } return(list(reshape_expr(bmat(rows), dim(expr)), list())) } } #' #' Dgp2Dcp canonicalizer for the constant atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the constant atom of a DGP expression, #' where the returned expression is the DCP equivalent resulting #' from the log of the expression. Dgp2Dcp.constant_canon <- function(expr, args) { # args <- list() return(list(Constant(log(value(expr))), list())) } #' #' Dgp2Dcp canonicalizer for the division atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the division atom of a DGP expression, #' where the returned expression is the log transformed DCP equivalent. Dgp2Dcp.div_canon <- function(expr, args) { # expr <- NULL # x / y == x * y^(-1) return(list(args[[1]] - args[[2]], list())) } #' #' Dgp2Dcp canonicalizer for the exp atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the exp atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.exp_canon <- function(expr, args) { # expr <- NULL return(list(Exp(args[[1]]), list())) } #' #' Dgp2Dcp canonicalizer for the \eqn{(I - X)^{-1}} atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the \eqn{(I - X)^{-1}} atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.eye_minus_inv_canon <- function(expr, args) { X <- args[[1]] # (I - X)^(-1) <= T iff there exists 0 <= Y <= T s.t. YX + Y <= Y. # Y represents log(Y) here, hence no positivity constraint. # Y <- Variable(dim(X)) Y <- new("Variable", dim = dim(X)) prod <- MulExpression(Y, X) lhs <- Dgp2Dcp.mulexpression_canon(prod, prod@args)[[1]] lhs <- lhs + diag(1, nrow(prod)) return(list(Y, list(lhs <= Y))) } #' #' Dgp2Dcp canonicalizer for the geometric mean atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the geometric mean atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.geo_mean_canon <- function(expr, args) { out <- 0.0 for(i in seq_along(args[[1]])) { x_i <- args[[1]][i] p_i <- expr@p[i] out <- out + p_i * x_i } return(list((1 / sum(expr@p))*out, list())) } #' #' Dgp2Dcp canonicalizer for the log atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the log atom of a DGP expression, #' where the returned expression is the log of the original expression.. Dgp2Dcp.log_canon <- function(expr, args) { return(list(Log(args[[1]]), list())) } #' #' Dgp2Dcp canonicalizer for the multiplication atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the multiplication atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.mul_canon <- function(expr, args) { # expr <- NULL return(list(AddExpression(args), list())) } #' #' Dgp2Dcp canonicalizer for the multiplication expression atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the multiplication expression atom #' of a DGP expression, where the returned expression is the transformed #' DCP equivalent. Dgp2Dcp.mulexpression_canon <- function(expr, args) { lhs <- args[[1]] rhs <- args[[2]] dims <- mul_dims_promote(dim(lhs), dim(rhs)) lhs_dim <- dims[[1]] rhs_dim <- dims[[2]] lhs <- reshape_expr(lhs, lhs_dim) rhs <- reshape_expr(rhs, rhs_dim) rows <- list() # TODO: Parallelize this for large matrices. for(i in 1:nrow(lhs)) { row <- list() for(j in 1:ncol(rhs)) { hstack_args <- lapply(1:ncol(lhs), function(k) { lhs[i,k] + rhs[k,j] }) row <- c(row, list(log_sum_exp(do.call("HStack", hstack_args)))) } rows <- c(rows, list(row)) } mat <- bmat(rows) if(!all(dim(mat) == dim(expr))) mat <- reshape_expr(mat, dim(expr)) return(list(mat, list())) } #' #' Dgp2Dcp canonicalizer for the non-positive constraint atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the non-positive contraint atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.nonpos_constr_canon <- function(expr, args) { if(length(args) != 2) stop("Must have exactly 2 arguments") return(list(NonPosConstraint(args[[1]] - args[[2]], id = id(expr)), list())) } #' #' Dgp2Dcp canonicalizer for the 1 norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the norm1 atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.norm1_canon <- function(expr, args) { if(length(args) != 1) stop("Must have exactly 1 argument") tmp <- SumEntries(args[[1]], axis = expr@axis, keepdims = expr@keepdims) return(Dgp2Dcp.sum_canon(tmp, tmp@args)) } #' #' Dgp2Dcp canonicalizer for the infinite norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the infinity norm atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.norm_inf_canon <- function(expr, args) { if(length(args) != 1) stop("Must have exactly 1 argument") tmp <- MaxEntries(args[[1]], axis = expr@axis, keepdims = expr@keepdims) return(EliminatePwl.max_entries_canon(tmp, tmp@args)) } #' #' Dgp2Dcp canonicalizer for the 1-x atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the 1-x with 0 < x < 1 atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.one_minus_pos_canon <- function(expr, args) { return(list(Log([email protected] - Exp(args[[1]])), list())) } #' #' Dgp2Dcp canonicalizer for the parameter atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the parameter atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.parameter_canon <- function(expr, args) { # args <- list() return(list(Parameter(log(value(expr)), name = name(expr)), list())) } #' #' Dgp2Dcp canonicalizer for the spectral radius atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the spectral radius atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.pf_eigenvalue_canon <- function(expr, args) { X <- args[[1]] # rho(X) <= lambda iff there exists v s.t. Xv <= lambda v. # v and lambda represent log variables, hence no positivity constraints. lambd <- Variable() v <- Variable(nrow(X)) lhs <- MulExpression(X, v) rhs <- lambd*v lhs <- Dgp2Dcp.mulexpression_canon(lhs, lhs@args)[[1]] rhs <- Dgp2Dcp.mul_canon(rhs, rhs@args)[[1]] return(list(lambd, list(lhs <= rhs))) } #' #' Dgp2Dcp canonicalizer for the p norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the pnorm atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.pnorm_canon <- function(expr, args) { x <- args[[1]] p <- expr@original_p if(is.null(dim(x))) x <- promote(p, c(1)) if(is.na(expr@axis) || length(dim(x)) == 1) { x <- Vec(x) # hstack_args <- lapply(seq_len(size(x)), function(j) { x[j]^p }) # return(list((1.0/p) * log_sum_exp(do.call("HStack", hstack_args)), list())) return(list((1.0/p) * log_sum_exp(x^p), list())) } if(expr@axis == 2) x <- t(x) rows <- list() for(i in 1:nrow(x)) { row <- x[i,] # hstack_args <- lapply(seq_len(size(row)), function(j) { row[j]^p }) # rows <- c(rows, list((1.0/p)*log_sum_exp(do.call("HStack", hstack_args)))) rows <- c(rows, list((1.0/p) * log_sum_exp(row^p))) } return(list(do.call("VStack", rows), list())) } #' #' Dgp2Dcp canonicalizer for the power atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the power atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.power_canon <- function(expr, args) { # y = log(x); x^p --> exp(y^p) --> p*log(exp(y)) = p*y. return(list(expr@p*args[[1]], list())) } #' #' Dgp2Dcp canonicalizer for the product atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the product atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.prod_canon <- function(expr, args) { return(list(SumEntries(args[[1]], axis = expr@axis, keepdims = expr@keepdims), list())) } #' #' Dgp2Dcp canonicalizer for the quadratic form atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the quadratic form atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.quad_form_canon <- function(expr, args) { x <- args[[1]] P <- args[[2]] elems <- list() for(i in 1:nrow(P)) { for(j in 1:nrow(P)) elems <- c(elems, list(P[i,j] + x[i] + x[j])) } return(list(log_sum_exp(do.call("HStack", elems)), list())) } #' #' Dgp2Dcp canonicalizer for the quadratic over linear term atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the quadratic over linear atom of a #' DGP expression, where the returned expression is the transformed DCP equivalent. Dgp2Dcp.quad_over_lin_canon <- function(expr, args) { x <- Vec(args[[1]]) y <- args[[2]] numerator <- 2*sum(x) return(list(numerator - y, list())) } #' #' Dgp2Dcp canonicalizer for the sum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the sum atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.sum_canon <- function(expr, args) { X <- args[[1]] new_dim <- dim(expr) if(is.null(new_dim)) new_dim <- c(1,1) if(is.na(expr@axis)) { x <- Vec(X) summation <- sum(x) canon <- Dgp2Dcp.add_canon(summation, summation@args)[[1]] return(list(reshape_expr(canon, new_dim), list())) } if(expr@axis == 2) X <- t(X) rows <- list() for(i in 1:nrow(X)) { x <- Vec(X[i,]) summation <- sum(x) canon <- Dgp2Dcp.add_canon(summation, summation@args)[[1]] rows <- c(rows, list(canon)) } canon <- do.call("HStack", rows) return(list(reshape_expr(canon, new_dim), list())) } #' #' Dgp2Dcp canonicalizer for the trace atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the trace atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.trace_canon <- function(expr, args) { diag_sum <- sum(Diag(args[[1]])) return(Dgp2Dcp.add_canon(diag_sum, diag_sum@args)) } #' #' Dgp2Dcp canonicalizer for the zero constraint atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of values for the expr variable #' @return A canonicalization of the zero constraint atom of a DGP expression, #' where the returned expression is the transformed DCP equivalent. Dgp2Dcp.zero_constr_canon <- function(expr, args) { if(length(args) != 2) stop("Must have exactly 2 arguments") return(list(ZeroConstraint(args[[1]] - args[[2]], id = id(expr)), list())) } Dgp2Dcp.CANON_METHODS <- list(AddExpression = Dgp2Dcp.add_canon, Constant = Dgp2Dcp.constant_canon, DivExpression = Dgp2Dcp.div_canon, Exp = Dgp2Dcp.exp_canon, EyeMinusInv = Dgp2Dcp.eye_minus_inv_canon, GeoMean = Dgp2Dcp.geo_mean_canon, Log = Dgp2Dcp.log_canon, MulExpression = Dgp2Dcp.mulexpression_canon, Multiply = Dgp2Dcp.mul_canon, Norm1 = Dgp2Dcp.norm1_canon, NormInf = Dgp2Dcp.norm_inf_canon, OneMinusPos = Dgp2Dcp.one_minus_pos_canon, Parameter = Dgp2Dcp.parameter_canon, PfEigenvalue = Dgp2Dcp.pf_eigenvalue_canon, Pnorm = Dgp2Dcp.pnorm_canon, Power = Dgp2Dcp.power_canon, ProdEntries = Dgp2Dcp.prod_canon, QuadForm = Dgp2Dcp.quad_form_canon, QuadOverLin = Dgp2Dcp.quad_over_lin_canon, Trace = Dgp2Dcp.trace_canon, SumEntries = Dgp2Dcp.sum_canon, Variable = NULL, MaxEntries = EliminatePwl.CANON_METHODS$MaxEntries, MinEntries = EliminatePwl.CANON_METHODS$MinEntries, MaxElemwise = EliminatePwl.CANON_METHODS$MaxElemwise, MinElemwise = EliminatePwl.CANON_METHODS$MinElemwise) #' #' DGP canonical methods class. #' #' Canonicalization of DGPs is a stateful procedure, hence the need for a class. #' #' @rdname DgpCanonMethods-class .DgpCanonMethods <- setClass("DgpCanonMethods", representation(.variables = "list"), prototype(.variables = list()), contains = "list") DgpCanonMethods <- function(...) { .DgpCanonMethods(...) } #' @param x A \linkS4class{DgpCanonMethods} object. #' @describeIn DgpCanonMethods Returns the name of all the canonicalization methods setMethod("names", signature(x = "DgpCanonMethods"), function(x) { names(Dgp2Dcp.CANON_METHODS) }) # TODO: How to implement this with S4 setMethod? Signature is x = "DgpCanonMethods", i = "character", j = "missing". '[[.DgpCanonMethods' <- function(x, i, j, ..., exact = TRUE) { do.call("$", list(x, i)) } #' @param name The name of the atom or expression to canonicalize. #' @describeIn DgpCanonMethods Returns either a canonicalized variable or #' a corresponding Dgp2Dcp canonicalization method setMethod("$", signature(x = "DgpCanonMethods"), function(x, name) { if(name == "Variable") { # TODO: Check scoping of x here is correct. variable_canon <- function(variable, args) { args <- NULL vid <- as.character(variable@id) # Swap out positive variables for unconstrained variables. if(vid %in% names([email protected])) return(list([email protected][[vid]], list())) else { # log_variable <- Variable(dim(variable), id = variable@id) log_variable <- new("Variable", dim = dim(variable), id = variable@id) [email protected][[vid]] <- log_variable return(list(log_variable, list())) } } return(variable_canon) } else return(Dgp2Dcp.CANON_METHODS[[name]]) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/dgp2dcp.R
#' #' The Elementwise class. #' #' This virtual class represents an elementwise atom. #' #' @name Elementwise-class #' @aliases Elementwise #' @rdname Elementwise-class Elementwise <- setClass("Elementwise", contains = c("VIRTUAL", "Atom")) #' @param object An \linkS4class{Elementwise} object. #' @describeIn Elementwise Dimensions is the same as the sum of the arguments' dimensions. setMethod("dim_from_args", "Elementwise", function(object) { sum_dims(lapply(object@args, dim)) }) #' @describeIn Elementwise Verify that all the dimensions are the same or can be promoted. setMethod("validate_args", "Elementwise", function(object) { sum_dims(lapply(object@args, dim)) callNextMethod() }) #' @describeIn Elementwise Is the expression symmetric? setMethod("is_symmetric", "Elementwise", function(object) { symm_args <- all(sapply(object@args, is_symmetric)) return(nrow(object) == ncol(object) && symm_args) }) # # Gradient to Diagonal # # Converts elementwise gradient into a diagonal matrix. # # @param value A scalar value or matrix. # @return A sparse matrix. # @rdname Elementwise-elemwise_grad_to_diag Elementwise.elemwise_grad_to_diag <- function(value, rows, cols) { value <- as.vector(value) sparseMatrix(i = 1:rows, j = 1:cols, x = value, dims = c(rows, cols)) } # # Promotes LinOp # # Promotes the LinOp if necessary. # @param arg The LinOp to promote. # @param dim The desired dimensions. # @return The promoted LinOp. # @rdname Elementwise-promote Elementwise.promote <- function(arg, dim) { if(any(dim(arg) != dim)) lo.promote(arg, dim) else arg } #' #' The Abs class. #' #' This class represents the elementwise absolute value. #' #' @slot x An \linkS4class{Expression} object. #' @name Abs-class #' @aliases Abs #' @rdname Abs-class .Abs <- setClass("Abs", representation(x = "Expression"), contains = "Elementwise") #' @param x An \linkS4class{Expression} object. #' @rdname Abs-class Abs <- function(x) { .Abs(x = x) } setMethod("initialize", "Abs", function(.Object, ..., x) { .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object An \linkS4class{Abs} object. #' @param values A list of arguments to the atom. #' @describeIn Abs The elementwise absolute value of the input. setMethod("to_numeric", "Abs", function(object, values) { abs(values[[1]]) }) #' @describeIn Abs Does the atom handle complex numbers? setMethod("allow_complex", "Abs", function(object) { TRUE }) #' @describeIn Abs The atom is positive. setMethod("sign_from_args", "Abs", function(object) { c(TRUE, FALSE) }) #' @describeIn Abs The atom is convex. setMethod("is_atom_convex", "Abs", function(object) { TRUE }) #' @describeIn Abs The atom is not concave. setMethod("is_atom_concave", "Abs", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Abs A logical value indicating whether the atom is weakly increasing. setMethod("is_incr", "Abs", function(object, idx) { is_nonneg(object@args[[idx]]) }) #' @describeIn Abs A logical value indicating whether the atom is weakly decreasing. setMethod("is_decr", "Abs", function(object, idx) { is_nonpos(object@args[[idx]]) }) #' @describeIn Abs Is \code{x} piecewise linear? setMethod("is_pwl", "Abs", function(object) { is_pwl(object@args[[1]]) && (is_real(object@args[[1]]) || is_imag(object@args[[1]])) }) setMethod(".grad", "Abs", function(object, values) { # Grad: +1 if positive, -1 if negative rows <- size(expr(object)) cols <- size(object) D <- array(0, dim = dim(expr(object))) D <- D + (values[[1]] > 0) D <- D - (values[[1]] < 0) list(Elementwise.elemwise_grad_to_diag(D, rows, cols)) }) #' #' The Entr class. #' #' This class represents the elementwise operation \eqn{-xlog(x)}. #' #' @slot x An \linkS4class{Expression} or numeric constant. #' @name Entr-class #' @aliases Entr #' @rdname Entr-class .Entr <- setClass("Entr", representation(x = "ConstValORExpr"), contains = "Elementwise") #' @param x An \linkS4class{Expression} or numeric constant. #' @rdname Entr-class Entr <- function(x) { .Entr(x = x) } setMethod("initialize", "Entr", function(.Object, ..., x) { .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object An \linkS4class{Entr} object. #' @param values A list of arguments to the atom. #' @describeIn Entr The elementwise entropy function evaluated at the value. setMethod("to_numeric", "Entr", function(object, values) { xlogy <- function(x, y) { tmp <- x*log(y) tmp[x == 0] <- 0 tmp } x <- values[[1]] results <- -xlogy(x, x) # Return -Inf outside the domain results[is.na(results)] <- -Inf if(all(dim(results) == 1)) results <- as.vector(results) results }) #' @describeIn Entr The sign of the atom is unknown. setMethod("sign_from_args", "Entr", function(object) { c(FALSE, FALSE) }) #' @describeIn Entr The atom is not convex. setMethod("is_atom_convex", "Entr", function(object) { FALSE }) #' @describeIn Entr The atom is concave. setMethod("is_atom_concave", "Entr", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn Entr The atom is weakly increasing. setMethod("is_incr", "Entr", function(object, idx) { FALSE }) #' @describeIn Entr The atom is weakly decreasing. setMethod("is_decr", "Entr", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn Entr Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Entr", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) # Outside domain or on boundary if(min(values[[1]]) <= 0) return(list(NA_real_)) # Non-differentiable else { grad_vals <- -log(values[[1]]) - 1 return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))) } }) #' @describeIn Entr Returns constraints descrbing the domain of the node setMethod(".domain", "Entr", function(object) { list(object@args[[1]] >= 0) }) #' #' The Exp class. #' #' This class represents the elementwise natural exponential \eqn{e^x}. #' #' @slot x An \linkS4class{Expression} object. #' @name Exp-class #' @aliases Exp #' @rdname Exp-class .Exp <- setClass("Exp", representation(x = "Expression"), contains = "Elementwise") #' @param x An \linkS4class{Expression} object. #' @rdname Exp-class Exp <- function(x) { .Exp(x = x) } setMethod("initialize", "Exp", function(.Object, ..., x) { .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object An \linkS4class{Exp} object. #' @param values A list of arguments to the atom. #' @describeIn Exp The matrix with each element exponentiated. setMethod("to_numeric", "Exp", function(object, values) { exp(values[[1]]) }) #' @describeIn Exp The atom is positive. setMethod("sign_from_args", "Exp", function(object) { c(TRUE, FALSE) }) #' @describeIn Exp The atom is convex. setMethod("is_atom_convex", "Exp", function(object) { TRUE }) #' @describeIn Exp The atom is not concave. setMethod("is_atom_concave", "Exp", function(object) { FALSE }) #' @describeIn Exp Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Exp", function(object) { TRUE }) #' @describeIn Exp Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Exp", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Exp The atom is weakly increasing. setMethod("is_incr", "Exp", function(object, idx) { TRUE }) #' @describeIn Exp The atom is not weakly decreasing. setMethod("is_decr", "Exp", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn Exp Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Exp", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) grad_vals <- exp(values[[1]]) list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)) }) #' #' The Huber class. #' #' This class represents the elementwise Huber function, \eqn{Huber(x, M = 1)} #' \describe{ #' \item{\eqn{2M|x|-M^2}}{for \eqn{|x| \geq |M|}} #' \item{\eqn{|x|^2}}{for \eqn{|x| \leq |M|.}} #' } #' @slot x An \linkS4class{Expression} or numeric constant. #' @slot M A positive scalar value representing the threshold. Defaults to 1. #' @name Huber-class #' @aliases Huber #' @rdname Huber-class .Huber <- setClass("Huber", representation(x = "ConstValORExpr", M = "ConstValORExpr"), prototype(M = 1), contains = "Elementwise") #' @param x An \linkS4class{Expression} object. #' @param M A positive scalar value representing the threshold. Defaults to 1. #' @rdname Huber-class Huber <- function(x, M = 1) { .Huber(x = x, M = M) } setMethod("initialize", "Huber", function(.Object, ..., x, M = 1) { .Object@M <- as.Constant(M) .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object A \linkS4class{Huber} object. #' @param values A list of arguments to the atom. #' @describeIn Huber The Huber function evaluted elementwise on the input value. setMethod("to_numeric", "Huber", function(object, values) { huber_loss <- function(delta, r) { if(delta < 0) return(Inf) else if(delta >= 0 && abs(r) <= delta) return(r^2/2) else return(delta * (abs(r) - delta/2)) } M_val <- value(object@M) val <- values[[1]] if(is.null(dim(val))) result <- 2*huber_loss(M_val, val) else if(is.vector(val)) result <- 2*sapply(val, function(v) { huber_loss(M_val, v) }) else result <- 2*apply(val, 1:length(dim(val)), function(v) { huber_loss(M_val, v) }) if(all(dim(result) == 1)) result <- as.vector(result) return(result) }) #' @describeIn Huber The atom is positive. setMethod("sign_from_args", "Huber", function(object) { c(TRUE, FALSE) }) #' @describeIn Huber The atom is convex. setMethod("is_atom_convex", "Huber", function(object) { TRUE }) #' @describeIn Huber The atom is not concave. setMethod("is_atom_concave", "Huber", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Huber A logical value indicating whether the atom is weakly increasing. setMethod("is_incr", "Huber", function(object, idx) { is_nonneg(object@args[[idx]]) }) #' @describeIn Huber A logical value indicating whether the atom is weakly decreasing. setMethod("is_decr", "Huber", function(object, idx) { is_nonpos(object@args[[idx]]) }) #' @describeIn Huber The atom is quadratic if \code{x} is affine. setMethod("is_quadratic", "Huber", function(object) { is_affine(object@args[[1]]) }) #' @describeIn Huber A list containing the parameter \code{M}. setMethod("get_data", "Huber", function(object) { list(object@M) }) #' @describeIn Huber Check that \code{M} is a non-negative constant. setMethod("validate_args", "Huber", function(object) { if(!(is_nonneg(object@M) && is_constant(object@M) && is_scalar(object@M))) stop("M must be a non-negative scalar constant") callNextMethod() }) #' @param values A list of numeric values for the arguments #' @describeIn Huber Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Huber", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) val_abs <- abs(values[[1]]) M_val <- as.numeric(value(object@M)) min_val <- ifelse(val_abs >= M_val, M_val, val_abs) grad_vals <- 2*(sign(values[[1]]) * min_val) list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)) }) # x^{-1} for x > 0. InvPos <- function(x) { Power(x, -1) } #' #' The KLDiv class. #' #' The elementwise KL-divergence \eqn{x\log(x/y) - x + y}. #' #' @slot x An \linkS4class{Expression} or numeric constant. #' @slot y An \linkS4class{Expression} or numeric constant. #' @name KLDiv-class #' @aliases KLDiv #' @rdname KLDiv-class .KLDiv <- setClass("KLDiv", representation(x = "ConstValORExpr", y = "ConstValORExpr"), contains = "Elementwise") #' @param x An \linkS4class{Expression} or numeric constant. #' @param y An \linkS4class{Expression} or numeric constant. #' @rdname KLDiv-class KLDiv <- function(x, y) { .KLDiv(x = x, y = y) } setMethod("initialize", "KLDiv", function(.Object, ..., x, y) { .Object@x <- x .Object@y <- y callNextMethod(.Object, ..., atom_args = list(.Object@x, .Object@y)) }) #' @param object A \linkS4class{KLDiv} object. #' @param values A list of arguments to the atom. #' @describeIn KLDiv The KL-divergence evaluted elementwise on the input value. setMethod("to_numeric", "KLDiv", function(object, values) { x <- intf_convert_if_scalar(values[[1]]) y <- intf_convert_if_scalar(values[[2]]) # TODO: Return Inf outside domain xlogy <- function(x, y) { tmp <- x*log(y) tmp[x == 0] <- 0 tmp } xlogy(x, x/y) - x + y }) #' @describeIn KLDiv The atom is positive. setMethod("sign_from_args", "KLDiv", function(object) { c(TRUE, FALSE) }) #' @describeIn KLDiv The atom is convex. setMethod("is_atom_convex", "KLDiv", function(object) { TRUE }) #' @describeIn KLDiv The atom is not concave. setMethod("is_atom_concave", "KLDiv", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn KLDiv The atom is not monotonic in any argument. setMethod("is_incr", "KLDiv", function(object, idx) { FALSE }) #' @describeIn KLDiv The atom is not monotonic in any argument. setMethod("is_decr", "KLDiv", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn KLDiv Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "KLDiv", function(object, values) { if(min(values[[1]]) <= 0 || min(values[[2]]) <= 0) return(list(NA_real_, NA_real_)) # Non-differentiable else { div <- values[[1]]/values[[2]] grad_vals <- list(log(div), 1-div) grad_list <- list() for(idx in 1:length(values)) { rows <- size(object@args[[idx]]) cols <- size(object) grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals[[idx]], rows, cols))) } return(grad_list) } }) #' @describeIn KLDiv Returns constraints describng the domain of the node setMethod(".domain", "KLDiv", function(object) { list(object@args[[1]] >= 0, object@args[[2]] >= 0) }) #' #' The Log class. #' #' This class represents the elementwise natural logarithm \eqn{\log(x)}. #' #' @slot x An \linkS4class{Expression} or numeric constant. #' @name Log-class #' @aliases Log #' @rdname Log-class .Log <- setClass("Log", representation(x = "ConstValORExpr"), contains = "Elementwise") #' @param x An \linkS4class{Expression} or numeric constant. #' @rdname Log-class Log <- function(x) { .Log(x = x) } setMethod("initialize", "Log", function(.Object, ..., x) { .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object A \linkS4class{Log} object. #' @param values A list of arguments to the atom. #' @describeIn Log The elementwise natural logarithm of the input value. setMethod("to_numeric", "Log", function(object, values) { log(values[[1]]) }) #' @describeIn Log The sign of the atom is unknown. setMethod("sign_from_args", "Log", function(object) { c(FALSE, FALSE) }) #' @describeIn Log The atom is not convex. setMethod("is_atom_convex", "Log", function(object) { FALSE }) #' @describeIn Log The atom is concave. setMethod("is_atom_concave", "Log", function(object) { TRUE }) #' @describeIn Log Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Log", function(object) { FALSE }) #' @describeIn Log Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Log", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn Log The atom is weakly increasing. setMethod("is_incr", "Log", function(object, idx) { TRUE }) #' @describeIn Log The atom is not weakly decreasing. setMethod("is_decr", "Log", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn Log Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Log", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) # Outside domain or on boundary if(min(values[[1]]) <= 0) return(list(NA_real_)) # Non-differentiable else { grad_vals <- 1.0/values[[1]] return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))) } }) #' @describeIn Log Returns constraints describng the domain of the node setMethod(".domain", "Log", function(object) { list(object@args[[1]] >= 0) }) #' #' The Log1p class. #' #' This class represents the elementwise operation \eqn{\log(1 + x)}. #' #' @slot x An \linkS4class{Expression} or numeric constant. #' @name Log1p-class #' @aliases Log1p #' @rdname Log1p-class .Log1p <- setClass("Log1p", contains = "Log") #' @param x An \linkS4class{Expression} or numeric constant. #' @rdname Log1p-class Log1p <- function(x) { .Log1p(x = x) } #' @param object A \linkS4class{Log1p} object. #' @param values A list of arguments to the atom. #' @describeIn Log1p The elementwise natural logarithm of one plus the input value. setMethod("to_numeric", "Log1p", function(object, values) { log(1 + values[[1]]) }) #' @describeIn Log1p The sign of the atom. setMethod("sign_from_args", "Log1p", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) }) #' @param values A list of numeric values for the arguments #' @describeIn Log1p Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Log1p", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) # Outside domain or on boundary. if(min(values[[1]]) <= -1) return(list(NA_real_)) # Non-differentiable. else { grad_vals <- 1.0/(values[[1]] + 1) return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))) } }) #' @describeIn Log1p Returns constraints describng the domain of the node setMethod(".domain", "Log1p", function(object) { list(object@args[[1]] >= -1) }) #' #' The Logistic class. #' #' This class represents the elementwise operation \eqn{\log(1 + e^x)}. #' This is a special case of log(sum(exp)) that evaluates to a vector rather than to a scalar, #' which is useful for logistic regression. #' #' @slot x An \linkS4class{Expression} or numeric constant. #' @name Logistic-class #' @aliases Logistic #' @rdname Logistic-class .Logistic <- setClass("Logistic", representation(x = "ConstValORExpr"), contains = "Elementwise") #' @param x An \linkS4class{Expression} or numeric constant. #' @rdname Logistic-class Logistic <- function(x) { .Logistic(x = x) } setMethod("initialize", "Logistic", function(.Object, ..., x) { .Object@x <- x callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object A \linkS4class{Logistic} object. #' @param values A list of arguments to the atom. #' @describeIn Logistic Evaluates \code{e^x} elementwise, adds one, and takes the natural logarithm. setMethod("to_numeric", "Logistic", function(object, values) { log(1 + exp(values[[1]])) }) #' @describeIn Logistic The atom is positive. setMethod("sign_from_args", "Logistic", function(object) { c(TRUE, FALSE) }) #' @describeIn Logistic The atom is convex. setMethod("is_atom_convex", "Logistic", function(object) { TRUE }) #' @describeIn Logistic The atom is not concave. setMethod("is_atom_concave", "Logistic", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn Logistic The atom is weakly increasing. setMethod("is_incr", "Logistic", function(object, idx) { TRUE }) #' @describeIn Logistic The atom is not weakly decreasing. setMethod("is_decr", "Logistic", function(object, idx) { FALSE }) #' @param values A list of numeric values for the arguments #' @describeIn Logistic Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Logistic", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) exp_val <- exp(values[[1]]) grad_vals <- exp_val/(1 + exp_val) list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)) }) #' #' The MaxElemwise class. #' #' This class represents the elementwise maximum. #' #' @slot arg1 The first \linkS4class{Expression} in the maximum operation. #' @slot arg2 The second \linkS4class{Expression} in the maximum operation. #' @slot ... Additional \linkS4class{Expression} objects in the maximum operation. #' @name MaxElemwise-class #' @aliases MaxElemwise #' @rdname MaxElemwise-class .MaxElemwise <- setClass("MaxElemwise", validity = function(object) { if(is.null(object@args) || length(object@args) < 2) stop("[MaxElemwise: validation] args must have at least 2 arguments") return(TRUE) }, contains = "Elementwise") #' @param arg1 The first \linkS4class{Expression} in the maximum operation. #' @param arg2 The second \linkS4class{Expression} in the maximum operation. #' @param ... Additional \linkS4class{Expression} objects in the maximum operation. #' @rdname MaxElemwise-class MaxElemwise <- function(arg1, arg2, ...) { .MaxElemwise(atom_args = list(arg1, arg2, ...)) } #' @param object A \linkS4class{MaxElemwise} object. #' @param values A list of arguments to the atom. #' @describeIn MaxElemwise The elementwise maximum. setMethod("to_numeric", "MaxElemwise", function(object, values) { # Reduce(function(x, y) { ifelse(x >= y, x, y) }, values) Reduce("pmax", values) }) #' @describeIn MaxElemwise The sign of the atom. setMethod("sign_from_args", "MaxElemwise", function(object) { # Reduces the list of argument signs according to the following rules: # NONNEGATIVE, ANYTHING = NONNEGATIVE # ZERO, UNKNOWN = NONNEGATIVE # ZERO, ZERO = ZERO # ZERO, NONPOSITIVE = ZERO # UNKNOWN, NONPOSITIVE = UNKNOWN # NONPOSITIVE, NONPOSITIVE = NONPOSITIVE is_pos <- any(sapply(object@args, is_nonneg)) is_neg <- all(sapply(object@args, is_nonpos)) c(is_pos, is_neg) }) #' @describeIn MaxElemwise The atom is convex. setMethod("is_atom_convex", "MaxElemwise", function(object) { TRUE }) #' @describeIn MaxElemwise The atom is not concave. setMethod("is_atom_concave", "MaxElemwise", function(object) { FALSE }) #' @describeIn MaxElemwise Is the atom log-log convex? setMethod("is_atom_log_log_convex", "MaxElemwise", function(object) { TRUE }) #' @describeIn MaxElemwise Is the atom log-log concave? setMethod("is_atom_log_log_concave", "MaxElemwise", function(object) { FALSE }) #' @param idx An index into the atom. #' @describeIn MaxElemwise The atom is weakly increasing. setMethod("is_incr", "MaxElemwise", function(object, idx) { TRUE }) #' @describeIn MaxElemwise The atom is not weakly decreasing. setMethod("is_decr", "MaxElemwise", function(object, idx) { FALSE }) #' @describeIn MaxElemwise Are all the arguments piecewise linear? setMethod("is_pwl", "MaxElemwise", function(object) { all(sapply(object@args, is_pwl)) }) #' @param values A list of numeric values for the arguments #' @describeIn MaxElemwise Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MaxElemwise", function(object, values) { max_vals <- to_numeric(object, values) vals_dim <- dim(max_vals) if(is.null(vals_dim)) unused <- matrix(TRUE, nrow = length(max_vals), ncol = 1) else unused <- array(TRUE, dim = vals_dim) grad_list <- list() idx <- 1 for(value in values) { rows <- size(object@args[[idx]]) cols <- size(object) grad_vals <- (value == max_vals) & unused # Remove all the max_vals that were used unused[value == max_vals] <- FALSE grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))) idx <- idx + 1 } grad_list }) #' #' The MinElemwise class. #' #' This class represents the elementwise minimum. #' #' @slot arg1 The first \linkS4class{Expression} in the minimum operation. #' @slot arg2 The second \linkS4class{Expression} in the minimum operation. #' @slot ... Additional \linkS4class{Expression} objects in the minimum operation. #' @name MinElemwise-class #' @aliases MinElemwise #' @rdname MinElemwise-class .MinElemwise <- setClass("MinElemwise", validity = function(object) { if(is.null(object@args) || length(object@args) < 2) stop("[MinElemwise: validation] args must have at least 2 arguments") return(TRUE) }, contains = "Elementwise") #' @param arg1 The first \linkS4class{Expression} in the minimum operation. #' @param arg2 The second \linkS4class{Expression} in the minimum operation. #' @param ... Additional \linkS4class{Expression} objects in the minimum operation. #' @rdname MinElemwise-class MinElemwise <- function(arg1, arg2, ...) { .MinElemwise(atom_args = list(arg1, arg2, ...)) } #' @param object A \linkS4class{MinElemwise} object. #' @param values A list of arguments to the atom. #' @describeIn MinElemwise The elementwise minimum. setMethod("to_numeric", "MinElemwise", function(object, values) { # Reduce(function(x, y) { ifelse(x <= y, x, y) }, values) Reduce("pmin", values) }) #' @describeIn MinElemwise The sign of the atom. setMethod("sign_from_args", "MinElemwise", function(object) { is_pos <- all(sapply(object@args, is_nonneg)) is_neg <- any(sapply(object@args, is_nonpos)) c(is_pos, is_neg) }) #' @describeIn MinElemwise The atom is not convex. setMethod("is_atom_convex", "MinElemwise", function(object) { FALSE }) #' @describeIn MinElemwise The atom is not concave. setMethod("is_atom_concave", "MinElemwise", function(object) { TRUE }) #' @describeIn MinElemwise Is the atom log-log convex? setMethod("is_atom_log_log_convex", "MinElemwise", function(object) { FALSE }) #' @describeIn MinElemwise Is the atom log-log concave? setMethod("is_atom_log_log_concave", "MinElemwise", function(object) { TRUE }) #' @param idx An index into the atom. #' @describeIn MinElemwise The atom is weakly increasing. setMethod("is_incr", "MinElemwise", function(object, idx) { TRUE }) #' @describeIn MinElemwise The atom is not weakly decreasing. setMethod("is_decr", "MinElemwise", function(object, idx) { FALSE }) #' @describeIn MinElemwise Are all the arguments piecewise linear? setMethod("is_pwl", "MinElemwise", function(object) { all(sapply(object@args, is_pwl)) }) #' @param values A list of numeric values for the arguments #' @describeIn MinElemwise Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "MinElemwise", function(object, values) { min_vals <- to_numeric(object, values) vals_dim <- dim(min_vals) if(is.null(vals_dim)) unused <- matrix(TRUE, nrow = length(min_vals), ncol = 1) else unused <- array(TRUE, dim = vals_dim) grad_list <- list() idx <- 1 for(value in values) { rows <- size(object@args[[idx]]) cols <- size(object) grad_vals <- (value == min_vals) & unused # Remove all the min_vals that were used unused[value == min_vals] <- FALSE grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))) idx <- idx + 1 } grad_list }) #' #' An alias for -MinElemwise(x, 0) #' #' @param x An R numeric value or \linkS4class{Expression}. #' @return An alias for -MinElemwise(x, 0) #' @rdname Neg-int Neg <- function(x) { -MinElemwise(x, 0) } #' #' An alias for MaxElemwise(x, 0) #' #' @param x An R numeric value or \linkS4class{Expression}. #' @return An alias for MaxElemwise(x, 0) #' @rdname Pos-int Pos <- function(x) { MaxElemwise(x, 0) } #' #' The Power class. #' #' This class represents the elementwise power function \eqn{f(x) = x^p}. #' If \code{expr} is a CVXR expression, then \code{expr^p} is equivalent to \code{Power(expr, p)}. #' #' For \eqn{p = 0}, \eqn{f(x) = 1}, constant, positive. #' #' For \eqn{p = 1}, \eqn{f(x) = x}, affine, increasing, same sign as \eqn{x}. #' #' For \eqn{p = 2,4,8,...}, \eqn{f(x) = |x|^p}, convex, signed monotonicity, positive. #' #' For \eqn{p < 0} and \eqn{f(x) = } #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x > 0}} #' \item{\eqn{+\infty}}{\eqn{x \leq 0}} #' }, this function is convex, decreasing, and positive. #' #' For \eqn{0 < p < 1} and \eqn{f(x) =} #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x \geq 0}} #' \item{\eqn{-\infty}}{\eqn{x < 0}} #' }, this function is concave, increasing, and positive. #' #' For \eqn{p > 1, p \neq 2,4,8,\ldots} and \eqn{f(x) = } #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x \geq 0}} #' \item{\eqn{+\infty}}{\eqn{x < 0}} #' }, this function is convex, increasing, and positive. #' #' @slot x The \linkS4class{Expression} to be raised to a power. #' @slot p A numeric value indicating the scalar power. #' @slot max_denom The maximum denominator considered in forming a rational approximation of \code{p}. #' @name Power-class #' @aliases Power #' @rdname Power-class .Power <- setClass("Power", representation(x = "ConstValORExpr", p = "NumORgmp", max_denom = "numeric", w = "NumORgmp", approx_error = "numeric"), prototype(max_denom = 1024, w = NA_real_, approx_error = NA_real_), contains = "Elementwise") #' @param x The \linkS4class{Expression} to be raised to a power. #' @param p A numeric value indicating the scalar power. #' @param max_denom The maximum denominator considered in forming a rational approximation of \code{p}. #' @rdname Power-class Power <- function(x, p, max_denom = 1024) { .Power(x = x, p = p, max_denom = max_denom) } setMethod("initialize", "Power", function(.Object, ..., x, p, max_denom = 1024, w = NA_real_, approx_error = NA_real_) { p_old <- p if(length(p) != 1) stop("p must be a numeric scalar") if(is.na(p) || is.null(p)) stop("p cannot be NA or NULL") # How we convert p to a rational depends on the branch of the function if(p > 1) { pw <- pow_high(p) p <- pw[[1]] w <- pw[[2]] } else if(p > 0 && p < 1) { pw <- pow_mid(p) p <- pw[[1]] w <- pw[[2]] } else if(p < 0) { pw <- pow_neg(p) p <- pw[[1]] w <- pw[[2]] } if(p == 1) { # In case p is a fraction equivalent to 1 p <- 1 w <- NA_real_ } else if(p == 0) { p <- 0 w <- NA_real_ } .Object@p <- p .Object@w <- w .Object@approx_error <- as.double(abs(.Object@p - p_old)) .Object@x <- x .Object@max_denom <- max_denom callNextMethod(.Object, ..., atom_args = list(.Object@x)) }) #' @param object A \linkS4class{Power} object. #' @param values A list of arguments to the atom. #' @describeIn Power Throw an error if the power is negative and cannot be handled. setMethod("to_numeric", "Power", function(object, values) { # Throw error if negative and Power doesn't handle that if(object@p < 0 && min(values[[1]]) <= 0) stop("Power cannot be applied to negative or zero values") else if(!is_power2(object@p) && object@p != 0 && min(values[[1]]) < 0) stop("Power cannot be applied to negative values") else return(values[[1]]^(as.double(object@p))) }) #' @describeIn Power The sign of the atom. setMethod("sign_from_args", "Power", function(object) { if(object@p == 1) # Same as input c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) else # Always positive c(TRUE, FALSE) }) #' @describeIn Power Is \eqn{p \leq 0} or \eqn{p \geq 1}? setMethod("is_atom_convex", "Power", function(object) { # p == 0 is affine here. object@p <= 0 || object@p >= 1 }) #' @describeIn Power Is \eqn{p \geq 0} or \eqn{p \leq 1}? setMethod("is_atom_concave", "Power", function(object) { # p == 0 is affine here. object@p >= 0 && object@p <= 1 }) #' @describeIn Power Is the atom log-log convex? setMethod("is_atom_log_log_convex", "Power", function(object) { TRUE }) #' @describeIn Power Is the atom log-log concave? setMethod("is_atom_log_log_concave", "Power", function(object) { TRUE }) #' @describeIn Power A logical value indicating whether the atom is constant. setMethod("is_constant", "Power", function(object) { object@p == 0 || callNextMethod() }) #' @param idx An index into the atom. #' @describeIn Power A logical value indicating whether the atom is weakly increasing. setMethod("is_incr", "Power", function(object, idx) { if(object@p >= 0 && object@p <= 1) return(TRUE) else if(object@p > 1) { if(is_power2(object@p)) return(is_nonneg(object@args[[idx]])) else return(TRUE) } else return(FALSE) }) #' @describeIn Power A logical value indicating whether the atom is weakly decreasing. setMethod("is_decr", "Power", function(object, idx) { if(object@p <= 0) return(TRUE) else if(object@p > 1) { if(is_power2(object@p)) return(is_nonpos(object@args[[idx]])) else return(FALSE) } else return(FALSE) }) #' @describeIn Power A logical value indicating whether the atom is quadratic. setMethod("is_quadratic", "Power", function(object) { if(object@p == 0) return(TRUE) else if(object@p == 1) return(is_quadratic(object@args[[1]])) else if(object@p == 2) return(is_affine(object@args[[1]])) else return(is_constant(object@args[[1]])) }) #' @describeIn Power A logical value indicating whether the atom is quadratic of piecewise affine. setMethod("is_qpwa", "Power", function(object) { if(object@p == 0) return(TRUE) else if(object@p == 1) return(is_qpwa(object@args[[1]])) else if(object@p == 2) return(is_pwl(object@args[[1]])) else return(is_constant(object@args[[1]])) }) #' @param values A list of numeric values for the arguments #' @describeIn Power Gives the (sub/super)gradient of the atom w.r.t. each variable setMethod(".grad", "Power", function(object, values) { rows <- size(object@args[[1]]) cols <- size(object) if(object@p == 0) # All zeros return(list(sparseMatrix(i = c(), j = c(), dims = c(rows, cols)))) # Outside domain or on boundary if(!is_power2(object@p) && min(values[[1]]) <= 0) { if(object@p < 1) return(list(NA_real_)) # Non-differentiable else # Round up to zero values[[1]] <- ifelse(values[[1]] >= 0, values[[1]], 0) } grad_vals <- as.double(object@p) * (values[[1]]^(as.double(object@p) - 1)) list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)) }) #' @describeIn Power Returns constraints describng the domain of the node setMethod(".domain", "Power", function(object) { if((object@p < 1 && object@p != 0) || (object@p > 1 && !is_power2(object@p))) list(object@args[[1]] >= 0) else list() }) #' @describeIn Power A list containing the output of \code{pow_low, pow_mid}, or \code{pow_high} depending on the input power. setMethod("get_data", "Power", function(object) { list(object@p, object@w) }) #' @param args A list of arguments to reconstruct the atom. If args=NULL, use the current args of the atom #' @param id_objects Currently unused. #' @describeIn Power Returns a shallow copy of the power atom setMethod("copy", "Power", function(object, args = NULL, id_objects = list()) { if(is.null(args)) args <- object@args data <- get_data(object) copy <- do.call(class(object), args) copy@p <- data[[1]] copy@w <- data[[2]] copy@approx_error <- object@approx_error copy }) #' @describeIn Power Returns the expression in string form. setMethod("name", "Power", function(x) { paste(class(x), "(", name(x@args[[1]]), ", ", x@p, ")", sep = "") }) Scalene <- function(x, alpha, beta) { alpha*Pos(x) + beta*Neg(x) }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/elementwise.R
#' #' The EliminatePwl class. #' #' This class eliminates piecewise linear atoms. #' #' @rdname EliminatePwl-class .EliminatePwl <- setClass("EliminatePwl", contains = "Canonicalization") EliminatePwl <- function(problem = NULL) { .EliminatePwl(problem = problem) } setMethod("initialize", "EliminatePwl", function(.Object, ...) { callNextMethod(.Object, ..., canon_methods = EliminatePwl.CANON_METHODS) }) #' @param object An \linkS4class{EliminatePwl} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn EliminatePwl Does this problem contain piecewise linear atoms? setMethod("accepts", signature(object = "EliminatePwl", problem = "Problem"), function(object, problem) { atom_types <- sapply(atoms(problem), function(atom) { class(atom) }) pwl_types <- c("Abs", "MaxElemwise", "SumLargest", "MaxEntries", "Norm1", "NormInf") return(any(sapply(atom_types, function(atom) { atom %in% pwl_types }))) }) setMethod("perform", signature(object = "EliminatePwl", problem = "Problem"), function(object, problem) { if(!accepts(object, problem)) stop("Cannot canonicalize away piecewise linear atoms.") callNextMethod(object, problem) }) # Atom canonicalizers. #' #' EliminatePwl canonicalizer for the absolute atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the picewise-lienar atom #' constructed from an absolute atom where the objective function #' consists of the variable that is of the same dimension as the #' original expression and the constraints consist of splitting #' the absolute value into two inequalities. #' EliminatePwl.abs_canon <- function(expr, args) { x <- args[[1]] # t <- Variable(dim(expr)) t <- new("Variable", dim = dim(expr)) constraints <- list(t >= x, t >= -x) return(list(t, constraints)) } #' #' EliminatePwl canonicalizer for the cumulative max atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed from a cumulative max atom where the objective #' function consists of the variable Y which is of the same #' dimension as the original expression and the constraints #' consist of row/column constraints depending on the axis EliminatePwl.cummax_canon <- function(expr, args) { X <- args[[1]] axis <- expr@axis # Implicit O(n) definition: # Y_{k} = maximum(Y_{k-1}, X_k) # Y <- Variable(dim(expr)) Y <- new("Variable", dim = dim(expr)) constr <- list(X <= Y) if(axis == 2) { if(nrow(Y) > 1) constr <- c(constr, list(Y[1:(nrow(Y)-1),] <= Y[2:nrow(Y),])) } else { if(ncol(Y) > 1) constr <- c(constr, list(Y[,1:(ncol(Y)-1)] <= Y[,2:ncol(Y)])) } return(list(Y, constr)) } #' #' EliminatePwl canonicalizer for the cumulative sum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed from a cumulative sum atom where the objective #' is Y that is of the same dimension as the matrix of the expression #' and the constraints consist of various row constraints EliminatePwl.cumsum_canon <- function(expr, args) { X <- args[[1]] axis <- expr@axis # Implicit O(n) definition: # X = Y[1,:] - Y[2:nrow(Y),:] # Y <- Variable(dim(expr)) Y <- new("Variable", dim = dim(expr)) if(axis == 2) { # Cumulative sum on each column constr <- list(Y[1,] == X[1,]) if(nrow(Y) > 1) constr <- c(constr, list(X[2:nrow(X),] == Y[2:nrow(Y),] - Y[1:(nrow(Y)-1),])) } else { # Cumulative sum on each row constr <- list(Y[,1] == X[,1]) if(ncol(Y) > 1) constr <- c(constr, list(X[,2:ncol(X)] == Y[,2:ncol(Y)] - Y[,1:(ncol(Y)-1)])) } return(list(Y, constr)) } #' #' EliminatePwl canonicalizer for the max entries atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed from the max entries atom where the objective #' function consists of the variable t of the same size as #' the original expression and the constraints consist of #' a vector multiplied by a vector of 1's. EliminatePwl.max_entries_canon <- function(expr, args) { x <- args[[1]] axis <- expr@axis # expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = dim(expr)) if(is.na(axis)) # dim(expr) = c(1,1) promoted_t <- promote(t, dim(x)) else if(axis == 2) # dim(expr) = c(1,n) promoted_t <- Constant(matrix(1, nrow = nrow(x), ncol = 1) %*% reshape_expr(t, c(1, ncol(x)))) else # shape = c(m,1) promoted_t <- reshape_expr(t, c(nrow(x), 1)) %*% Constant(matrix(1, nrow = 1, ncol = ncol(x))) constraints <- list(x <= promoted_t) return(list(t, constraints)) } #' #' EliminatePwl canonicalizer for the elementwise maximum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by a elementwise maximum atom where the #' objective function is the variable t of the same dimension #' as the expression and the constraints consist of a simple #' inequality. EliminatePwl.max_elemwise_canon <- function(expr, args) { # expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = dim(expr)) constraints <- lapply(args, function(elem) { t >= elem }) return(list(t, constraints)) } #' #' EliminatePwl canonicalizer for the minimum entries atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by a minimum entries atom where the #' objective function is the negative of variable #' t produced by max_elemwise_canon of the same dimension #' as the expression and the constraints consist of a simple #' inequality. EliminatePwl.min_entries_canon <- function(expr, args) { if(length(args) != 1) stop("Length of args must be one") tmp <- MaxEntries(-args[[1]]) canon <- EliminatePwl.max_entries_canon(tmp, tmp@args) return(list(-canon[[1]], canon[[2]])) } #' #' EliminatePwl canonicalizer for the elementwise minimum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by a minimum elementwise atom where the #' objective function is the negative of variable t #' t produced by max_elemwise_canon of the same dimension #' as the expression and the constraints consist of a simple #' inequality. EliminatePwl.min_elemwise_canon <- function(expr, args) { tmp <- do.call(MaxElemwise, lapply(args, function(arg) { -arg })) canon <- EliminatePwl.max_elemwise_canon(tmp, tmp@args) return(list(-canon[[1]], canon[[2]])) } #' #' EliminatePwl canonicalizer for the 1 norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by the norm1 atom where the objective functino #' consists of the sum of the variables created by the #' abs_canon function and the constraints consist of #' constraints generated by abs_canon. EliminatePwl.norm1_canon <- function(expr, args) { x <- args[[1]] axis <- expr@axis # We need an absolute value constraint for the symmetric convex branches (p >= 1) constraints <- list() # TODO: Express this more naturally (recursively) in terms of the other atoms abs_expr <- abs(x) xconstr <- EliminatePwl.abs_canon(abs_expr, abs_expr@args) abs_x <- xconstr[[1]] abs_constraints <- xconstr[[2]] constraints <- c(constraints, abs_constraints) return(list(SumEntries(abs_x, axis = axis), constraints)) } #' #' EliminatePwl canonicalizer for the infinite norm atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by the infinite norm atom where the objective #' function consists variable t of the same dimension as the #' expression and the constraints consist of a vector #' constructed by multiplying t to a vector of 1's EliminatePwl.norm_inf_canon <- function(expr, args) { x <- args[[1]] axis <- expr@axis # expr_dim <- dim(expr) # t <- Variable(expr_dim) t <- new("Variable", dim = dim(expr)) if(is.na(axis)) # dim(expr) = c(1,1) promoted_t <- promote(t, dim(x)) else if(axis == 2) # dim(expr) = c(1,n) promoted_t <- Constant(matrix(1, nrow = nrow(x), ncol = 1) %*% reshape_expr(t, c(1, ncol(x)))) else # shape = c(m,1) promoted_t <- reshape_expr(t, c(nrow(x), 1)) %*% Constant(matrix(1, nrow = 1, ncol = ncol(x))) return(list(t, list(x <= promoted_t, x + promoted_t >= 0))) } #' #' EliminatePwl canonicalizer for the largest sum atom #' #' @param expr An \linkS4class{Expression} object #' @param args A list of \linkS4class{Constraint} objects #' @return A canonicalization of the piecewise-lienar atom #' constructed by the k largest sums atom where the objective #' function consists of the sum of variables t that is of #' the same dimension as the expression plus k EliminatePwl.sum_largest_canon <- function(expr, args) { x <- args[[1]] k <- expr@k # min sum(t) + kq # s.t. x <= t + q, 0 <= t # t <- Variable(dim(x)) t <- new("Variable", dim = dim(x)) q <- Variable() obj <- sum(t) + k*q constraints <- list(x <= t + q, t >= 0) return(list(obj, constraints)) } EliminatePwl.CANON_METHODS <- list(Abs = EliminatePwl.abs_canon, CumMax = EliminatePwl.cummax_canon, CumSum = EliminatePwl.cumsum_canon, MaxElemwise = EliminatePwl.max_elemwise_canon, MaxEntries = EliminatePwl.max_entries_canon, MinElemwise = EliminatePwl.min_elemwise_canon, MinEntries = EliminatePwl.min_entries_canon, Norm1 = EliminatePwl.norm1_canon, NormInf = EliminatePwl.norm_inf_canon, SumLargest = EliminatePwl.sum_largest_canon)
/scratch/gouwar.j/cran-all/cranData/CVXR/R/eliminate_pwl.R
# ========================= # Scalar functions # ========================= #' #' Unity Resolvent #' #' The unity resolvent of a positive matrix. For an elementwise positive matrix \eqn{X}, this atom represents \eqn{(I - X)^{-1}}, #' and it enforces the constraint that the spectral radius of \eqn{X} is at most 1. #' #' This atom is log-log convex. #' #' @param X An \linkS4class{Expression} or positive square matrix. #' @return An \linkS4class{Expression} representing the unity resolvent of the input. #' @examples #' A <- Variable(2,2, pos = TRUE) #' prob <- Problem(Minimize(matrix_trace(A)), list(eye_minus_inv(A) <=1)) #' result <- solve(prob, gp = TRUE) #' result$value #' result$getValue(A) #' @docType methods #' @name eye_minus_inv #' @rdname eye_minus_inv #' @export eye_minus_inv <- EyeMinusInv #' #' Geometric Mean #' #' The (weighted) geometric mean of vector \eqn{x} with optional powers given by \eqn{p}. #' #' \deqn{\left(x_1^{p_1} \cdots x_n^{p_n} \right)^{\frac{1}{\mathbf{1}^Tp}}} #' #' The geometric mean includes an implicit constraint that \eqn{x_i \geq 0} whenever \eqn{p_i > 0}. If \eqn{p_i = 0, x_i} will be unconstrained. #' The only exception to this rule occurs when \eqn{p} has exactly one nonzero element, say \eqn{p_i}, in which case \code{geo_mean(x,p)} is equivalent to \eqn{x_i} (without the nonnegativity constraint). #' A specific case of this is when \eqn{x \in \mathbf{R}^1}. #' #' @param x An \linkS4class{Expression} or vector. #' @param p (Optional) A vector of weights for the weighted geometric mean. Defaults to a vector of ones, giving the \strong{unweighted} geometric mean \eqn{x_1^{1/n} \cdots x_n^{1/n}}. #' @param max_denom (Optional) The maximum denominator to use in approximating \code{p/sum(p)} with \code{w}. If \code{w} is not an exact representation, increasing \code{max_denom} may offer a more accurate representation, at the cost of requiring more convex inequalities to represent the geometric mean. Defaults to 1024. #' @return An \linkS4class{Expression} representing the geometric mean of the input. #' @examples #' x <- Variable(2) #' cost <- geo_mean(x) #' prob <- Problem(Maximize(cost), list(sum(x) <= 1)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' \dontrun{ #' x <- Variable(5) #' p <- c(0.07, 0.12, 0.23, 0.19, 0.39) #' prob <- Problem(Maximize(geo_mean(x,p)), list(p_norm(x) <= 1)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' } #' @docType methods #' @name geo_mean #' @rdname geo_mean #' @export geo_mean <- GeoMean #' #' Harmonic Mean #' #' The harmonic mean, \eqn{\left(\frac{1}{n} \sum_{i=1}^n x_i^{-1}\right)^{-1}}. For a matrix, the function is applied over all entries. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the harmonic mean of the input. #' @examples #' x <- Variable() #' prob <- Problem(Maximize(harmonic_mean(x)), list(x >= 0, x <= 5)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' @docType methods #' @name harmonic_mean #' @rdname harmonic_mean #' @export harmonic_mean <- HarmonicMean #' #' Maximum Eigenvalue #' #' The maximum eigenvalue of a matrix, \eqn{\lambda_{\max}(A)}. #' @param A An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the maximum eigenvalue of the input. #' @examples #' A <- Variable(2,2) #' prob <- Problem(Minimize(lambda_max(A)), list(A >= 2)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' #' obj <- Maximize(A[2,1] - A[1,2]) #' prob <- Problem(obj, list(lambda_max(A) <= 100, A[1,1] == 2, A[2,2] == 2, A[2,1] == 2)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' @docType methods #' @name lambda_max #' @rdname lambda_max #' @export lambda_max <- LambdaMax #' #' Minimum Eigenvalue #' #' The minimum eigenvalue of a matrix, \eqn{\lambda_{\min}(A)}. #' #' @param A An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the minimum eigenvalue of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(5,7), c(7,-3)) #' prob <- Problem(Maximize(lambda_min(A)), list(A == val)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' @docType methods #' @name lambda_min #' @rdname lambda_min #' @export lambda_min <- LambdaMin #' #' Sum of Largest Eigenvalues #' #' The sum of the largest \eqn{k} eigenvalues of a matrix. #' #' @param A An \linkS4class{Expression} or matrix. #' @param k The number of eigenvalues to sum over. #' @return An \linkS4class{Expression} representing the sum of the largest \code{k} eigenvalues of the input. #' @examples #' C <- Variable(3,3) #' val <- cbind(c(1,2,3), c(2,4,5), c(3,5,6)) #' prob <- Problem(Minimize(lambda_sum_largest(C,2)), list(C == val)) #' result <- solve(prob) #' result$value #' result$getValue(C) #' @docType methods #' @name lambda_sum_largest #' @rdname lambda_sum_largest #' @export lambda_sum_largest <- LambdaSumLargest #' #' Sum of Smallest Eigenvalues #' #' The sum of the smallest \eqn{k} eigenvalues of a matrix. #' #' @param A An \linkS4class{Expression} or matrix. #' @param k The number of eigenvalues to sum over. #' @return An \linkS4class{Expression} representing the sum of the smallest \code{k} eigenvalues of the input. #' @examples #' C <- Variable(3,3) #' val <- cbind(c(1,2,3), c(2,4,5), c(3,5,6)) #' prob <- Problem(Maximize(lambda_sum_smallest(C,2)), list(C == val)) #' result <- solve(prob) #' result$value #' result$getValue(C) #' @docType methods #' @name lambda_sum_smallest #' @rdname lambda_sum_smallest #' @export lambda_sum_smallest <- LambdaSumSmallest #' #' Log-Determinant #' #' The natural logarithm of the determinant of a matrix, \eqn{\log\det(A)}. #' #' @param A An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the log-determinant of the input. #' @examples #' x <- t(data.frame(c(0.55, 0.25, -0.2, -0.25, -0.0, 0.4), #' c(0.0, 0.35, 0.2, -0.1, -0.3, -0.2))) #' n <- nrow(x) #' m <- ncol(x) #' #' A <- Variable(n,n) #' b <- Variable(n) #' obj <- Maximize(log_det(A)) #' constr <- lapply(1:m, function(i) { p_norm(A %*% as.matrix(x[,i]) + b) <= 1 }) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' result$value #' @docType methods #' @name log_det #' @rdname log_det #' @export log_det <- LogDet #' #' Log-Sum-Exponential #' #' The natural logarithm of the sum of the elementwise exponential, \eqn{\log\sum_{i=1}^n e^{x_i}}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the log-sum-exponential of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(5,7), c(0,-3)) #' prob <- Problem(Minimize(log_sum_exp(A)), list(A == val)) #' result <- solve(prob) #' result$getValue(A) #' @docType methods #' @name log_sum_exp #' @rdname log_sum_exp #' @export log_sum_exp <- LogSumExp #' #' Matrix Fraction #' #' \eqn{tr(X^T P^{-1} X)}. #' #' @param X An \linkS4class{Expression} or matrix. Must have the same number of rows as \code{P}. #' @param P An \linkS4class{Expression} or matrix. Must be an invertible square matrix. #' @return An \linkS4class{Expression} representing the matrix fraction evaluated at the input. #' @examples #' \dontrun{ #' set.seed(192) #' m <- 100 #' n <- 80 #' r <- 70 #' #' A <- matrix(stats::rnorm(m*n), nrow = m, ncol = n) #' b <- matrix(stats::rnorm(m), nrow = m, ncol = 1) #' G <- matrix(stats::rnorm(r*n), nrow = r, ncol = n) #' h <- matrix(stats::rnorm(r), nrow = r, ncol = 1) #' #' # ||Ax-b||^2 = x^T (A^T A) x - 2(A^T b)^T x + ||b||^2 #' P <- t(A) %*% A #' q <- -2 * t(A) %*% b #' r <- t(b) %*% b #' Pinv <- base::solve(P) #' #' x <- Variable(n) #' obj <- matrix_frac(x, Pinv) + t(q) %*% x + r #' constr <- list(G %*% x == h) #' prob <- Problem(Minimize(obj), constr) #' result <- solve(prob) #' result$value #' } #' @docType methods #' @name matrix_frac #' @rdname matrix_frac #' @export matrix_frac <- function(X, P) { if(is.matrix(P) && (is.vector(X) || ncol(X) == 1)) { invP <- as.matrix(base::solve(P)) return(QuadForm(x = X, P = (invP + t(Conj(invP))) / 2.0)) } else return(MatrixFrac(X = X, P = P)) } #' #' Maximum #' #' The maximum of an expression. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the maximum of the input. #' @examples #' x <- Variable(2) #' val <- matrix(c(-5,-10)) #' prob <- Problem(Minimize(max_entries(x)), list(x == val)) #' result <- solve(prob) #' result$value #' #' A <- Variable(2,2) #' val <- rbind(c(-5,2), c(-3,1)) #' prob <- Problem(Minimize(max_entries(A, axis = 1)[2,1]), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name max_entries #' @aliases max #' @rdname max_entries #' @export max_entries <- MaxEntries #' #' Minimum #' #' The minimum of an expression. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the minimum of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(-5,2), c(-3,1)) #' prob <- Problem(Maximize(min_entries(A)), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name min_entries #' @aliases min #' @rdname min_entries #' @export min_entries <- MinEntries #' #' Mixed Norm #' #' \eqn{l_{p,q}(x) = \left(\sum_{i=1}^n (\sum_{j=1}^m |x_{i,j}|)^{q/p}\right)^{1/q}}. #' #' @param X An \linkS4class{Expression}, vector, or matrix. #' @param p The type of inner norm. #' @param q The type of outer norm. #' @return An \linkS4class{Expression} representing the \eqn{l_{p,q}} norm of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(3,3), c(4,4)) #' prob <- Problem(Minimize(mixed_norm(A,2,1)), list(A == val)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' #' val <- cbind(c(1,4), c(5,6)) #' prob <- Problem(Minimize(mixed_norm(A,1,Inf)), list(A == val)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' @docType methods #' @name mixed_norm #' @rdname mixed_norm #' @export mixed_norm <- MixedNorm #' #' 1-Norm #' #' \eqn{\|x\|_1 = \sum_{i=1}^n |x_i|}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the 1-norm of the input. #' @examples #' a <- Variable() #' prob <- Problem(Minimize(norm1(a)), list(a <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' prob <- Problem(Maximize(-norm1(a)), list(a <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' x <- Variable(2) #' z <- Variable(2) #' prob <- Problem(Minimize(norm1(x - z) + 5), list(x >= c(2,3), z <= c(-1,-4))) #' result <- solve(prob) #' result$value #' result$getValue(x[1] - z[1]) #' @docType methods #' @name norm1 #' @rdname norm1 #' @export norm1 <- Norm1 #' #' Euclidean Norm #' #' \eqn{\|x\|_2 = \left(\sum_{i=1}^n x_i^2\right)^{1/2}}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the Euclidean norm of the input. #' @examples #' a <- Variable() #' prob <- Problem(Minimize(norm2(a)), list(a <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' prob <- Problem(Maximize(-norm2(a)), list(a <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' x <- Variable(2) #' z <- Variable(2) #' prob <- Problem(Minimize(norm2(x - z) + 5), list(x >= c(2,3), z <= c(-1,-4))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' result$getValue(z) #' #' prob <- Problem(Minimize(norm2(t(x - z)) + 5), list(x >= c(2,3), z <= c(-1,-4))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' result$getValue(z) #' @docType methods #' @name norm2 #' @rdname norm2 #' @export norm2 <- Norm2 #' #' Infinity-Norm #' #' \eqn{\|x\|_{\infty} = \max_{i=1,\ldots,n} |x_i|}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the infinity-norm of the input. #' @examples #' a <- Variable() #' b <- Variable() #' c <- Variable() #' #' prob <- Problem(Minimize(norm_inf(a)), list(a >= 2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' prob <- Problem(Minimize(3*norm_inf(a + 2*b) + c), list(a >= 2, b <= -1, c == 3)) #' result <- solve(prob) #' result$value #' result$getValue(a + 2*b) #' result$getValue(c) #' #' prob <- Problem(Maximize(-norm_inf(a)), list(a <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(a) #' #' x <- Variable(2) #' z <- Variable(2) #' prob <- Problem(Minimize(norm_inf(x - z) + 5), list(x >= c(2,3), z <= c(-1,-4))) #' result <- solve(prob) #' result$value #' result$getValue(x[1] - z[1]) #' @docType methods #' @name norm_inf #' @rdname norm_inf #' @export norm_inf <- NormInf #' #' Nuclear Norm #' #' The nuclear norm, i.e. sum of the singular values of a matrix. #' #' @param A An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the nuclear norm of the input. #' @examples #' C <- Variable(3,3) #' val <- cbind(3:5, 6:8, 9:11) #' prob <- Problem(Minimize(norm_nuc(C)), list(C == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name norm_nuc #' @rdname norm_nuc #' @export norm_nuc <- NormNuc #' #' Difference on Restricted Domain #' #' The difference \eqn{1 - x} with domain \eqn{\{x : 0 < x < 1\}}. #' #' This atom is log-log concave. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing one minus the input restricted to \eqn{(0,1)}. #' @examples #' x <- Variable(pos = TRUE) #' y <- Variable(pos = TRUE) #' prob <- Problem(Maximize(one_minus_pos(x*y)), list(x <= 2 * y^2, y >= .2)) #' result <- solve(prob, gp = TRUE) #' result$value #' result$getValue(x) #' result$getValue(y) #' #' @docType methods #' @name one_minus_pos #' @rdname one_minus_pos #' @export one_minus_pos <- OneMinusPos #' #' Perron-Frobenius Eigenvalue #' #' The Perron-Frobenius eigenvalue of a positive matrix. #' #' For an elementwise positive matrix \eqn{X}, this atom represents its spectral radius, i.e., the magnitude of its largest eigenvalue. #' Because \eqn{X} is positive, the spectral radius equals its largest eigenvalue, which is guaranteed to be positive. #' #' This atom is log-log convex. #' @param X An \linkS4class{Expression} or positive square matrix. #' @return An \linkS4class{Expression} representing the largest eigenvalue of the input. #' @examples #' n <- 3 #' X <- Variable(n, n, pos=TRUE) #' objective_fn <- pf_eigenvalue(X) #' constraints <- list( X[1,1]== 1.0, #' X[1,3] == 1.9, #' X[2,2] == .8, #' X[3,1] == 3.2, #' X[3,2] == 5.9, #' X[1, 2] * X[2, 1] * X[2,3] * X[3,3] == 1) #' problem <- Problem(Minimize(objective_fn), constraints) #' result <- solve(problem, gp=TRUE) #' result$value #' result$getValue(X) #' #' @docType methods #' @name pf_eigenvalue #' @rdname pf_eigenvalue #' @export pf_eigenvalue <- PfEigenvalue #' #' P-Norm #' #' The vector p-norm. If given a matrix variable, \code{p_norm} will treat it as a vector and compute the p-norm of the concatenated columns. #' #' For \eqn{p \geq 1}, the p-norm is given by \deqn{\|x\|_p = \left(\sum_{i=1}^n |x_i|^p\right)^{1/p}} with domain \eqn{x \in \mathbf{R}^n}. #' For \eqn{p < 1, p \neq 0}, the p-norm is given by \deqn{\|x\|_p = \left(\sum_{i=1}^n x_i^p\right)^{1/p}} with domain \eqn{x \in \mathbf{R}^n_+}. #' #' \itemize{ #' \item Note that the "p-norm" is actually a \strong{norm} only when \eqn{p \geq 1} or \eqn{p = +\infty}. For these cases, it is convex. #' \item The expression is undefined when \eqn{p = 0}. #' \item Otherwise, when \eqn{p < 1}, the expression is concave, but not a true norm. #' } #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param p A number greater than or equal to 1, or equal to positive infinity. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @param max_denom (Optional) The maximum denominator considered in forming a rational approximation for \eqn{p}. The default is 1024. #' @return An \linkS4class{Expression} representing the p-norm of the input. #' @examples #' x <- Variable(3) #' prob <- Problem(Minimize(p_norm(x,2))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' prob <- Problem(Minimize(p_norm(x,Inf))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' \dontrun{ #' a <- c(1.0, 2, 3) #' prob <- Problem(Minimize(p_norm(x,1.6)), list(t(x) %*% a >= 1)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' prob <- Problem(Minimize(sum(abs(x - a))), list(p_norm(x,-1) >= 0)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' } #' @docType methods #' @name p_norm #' @rdname p_norm #' @export p_norm <- Pnorm #' #' Product of Entries #' #' The product of entries in a vector or matrix. #' #' This atom is log-log affine, but it is neither convex nor concave. #' #' @param ... \linkS4class{Expression} objects, vectors, or matrices. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the product of the entries of the input. #' @examples #' #' n <- 2 #' X <- Variable(n, n, pos=TRUE) #' obj <- sum(X) #' constraints <- list(prod_entries(X) == 4) #' prob <- Problem(Minimize(obj), constraints) #' result <- solve(prob, gp=TRUE) #' result$value #' result$getValue(X) #' #' @docType methods #' @name prod_entries #' @aliases prod #' @rdname prod_entries #' @export prod_entries <- ProdEntries #' #' Quadratic Form #' #' The quadratic form, \eqn{x^TPx}. #' #' @param x An \linkS4class{Expression} or vector. #' @param P An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the quadratic form evaluated at the input. #' @examples #' x <- Variable(2) #' P <- rbind(c(4,0), c(0,9)) #' prob <- Problem(Minimize(quad_form(x,P)), list(x >= 1)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' A <- Variable(2,2) #' c <- c(1,2) #' prob <- Problem(Minimize(quad_form(c,A)), list(A >= 1)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' @docType methods #' @name quad_form #' @rdname quad_form #' @export quad_form <- function(x, P) { # x^T P x x <- as.Constant(x) P <- as.Constant(P) # Check dimensions. P_dim <- dim(P) if(ndim(P) != 2 || P_dim[1] != P_dim[2] || max(nrow(x), 1) != P_dim[1]) stop("Invalid dimensions for arguments.") # P cannot be a parameter. if(is_constant(x)) Conj(t(x)) %*% P %*% x else if(is_constant(P)) QuadForm(x, P) else stop("At least one argument to QuadForm must be constant.") } #' #' Quadratic over Linear #' #' \eqn{\sum_{i,j} X_{i,j}^2/y}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param y A scalar \linkS4class{Expression} or numeric constant. #' @return An \linkS4class{Expression} representing the quadratic over linear function value evaluated at the input. #' @examples #' x <- Variable(3,2) #' y <- Variable() #' val <- cbind(c(-1,2,-2), c(-1,2,-2)) #' prob <- Problem(Minimize(quad_over_lin(x,y)), list(x == val, y <= 2)) #' result <- solve(prob) #' result$value #' result$getValue(x) #' result$getValue(y) #' @docType methods #' @name quad_over_lin #' @rdname quad_over_lin #' @export quad_over_lin <- QuadOverLin #' #' Sum of Entries #' #' The sum of entries in a vector or matrix. #' #' @param expr An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the sum of the entries of the input. #' @examples #' x <- Variable(2) #' prob <- Problem(Minimize(sum_entries(x)), list(t(x) >= matrix(c(1,2), nrow = 1, ncol = 2))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' C <- Variable(3,2) #' prob <- Problem(Maximize(sum_entries(C)), list(C[2:3,] <= 2, C[1,] == 1)) #' result <- solve(prob) #' result$value #' result$getValue(C) #' @docType methods #' @name sum_entries #' @aliases sum #' @rdname sum_entries #' @export sum_entries <- SumEntries #' #' Sum of Largest Values #' #' The sum of the largest \eqn{k} values of a vector or matrix. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param k The number of largest values to sum over. #' @return An \linkS4class{Expression} representing the sum of the largest \code{k} values of the input. #' @examples #' set.seed(122) #' m <- 300 #' n <- 9 #' X <- matrix(stats::rnorm(m*n), nrow = m, ncol = n) #' X <- cbind(rep(1,m), X) #' b <- c(0, 0.8, 0, 1, 0.2, 0, 0.4, 1, 0, 0.7) #' y <- X %*% b + stats::rnorm(m) #' #' beta <- Variable(n+1) #' obj <- sum_largest((y - X %*% beta)^2, 100) #' prob <- Problem(Minimize(obj)) #' result <- solve(prob) #' result$getValue(beta) #' @docType methods #' @name sum_largest #' @rdname sum_largest #' @export sum_largest <- SumLargest #' #' Sum of Smallest Values #' #' The sum of the smallest k values of a vector or matrix. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param k The number of smallest values to sum over. #' @return An \linkS4class{Expression} representing the sum of the smallest k values of the input. #' @examples #' set.seed(1323) #' m <- 300 #' n <- 9 #' X <- matrix(stats::rnorm(m*n), nrow = m, ncol = n) #' X <- cbind(rep(1,m), X) #' b <- c(0, 0.8, 0, 1, 0.2, 0, 0.4, 1, 0, 0.7) #' factor <- 2*rbinom(m, size = 1, prob = 0.8) - 1 #' y <- factor * (X %*% b) + stats::rnorm(m) #' #' beta <- Variable(n+1) #' obj <- sum_smallest(y - X %*% beta, 200) #' prob <- Problem(Maximize(obj), list(0 <= beta, beta <= 1)) #' result <- solve(prob) #' result$getValue(beta) #' @docType methods #' @name sum_smallest #' @rdname sum_smallest #' @export sum_smallest <- SumSmallest #' #' Sum of Squares #' #' The sum of the squared entries in a vector or matrix. #' #' @param expr An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the sum of squares of the input. #' @examples #' set.seed(212) #' m <- 30 #' n <- 20 #' A <- matrix(stats::rnorm(m*n), nrow = m, ncol = n) #' b <- matrix(stats::rnorm(m), nrow = m, ncol = 1) #' #' x <- Variable(n) #' obj <- Minimize(sum_squares(A %*% x - b)) #' constr <- list(0 <= x, x <= 1) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' #' result$value #' result$getValue(x) #' result$getDualValue(constr[[1]]) #' @docType methods #' @name sum_squares #' @rdname sum_squares #' @export sum_squares <- SumSquares #' #' Matrix Trace #' #' The sum of the diagonal entries in a matrix. #' #' @param expr An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the trace of the input. #' @examples #' C <- Variable(3,3) #' val <- cbind(3:5, 6:8, 9:11) #' prob <- Problem(Maximize(matrix_trace(C)), list(C == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name matrix_trace #' @aliases trace tr #' @rdname matrix_trace #' @export matrix_trace <- Trace #' #' Total Variation #' #' The total variation of a vector, matrix, or list of matrices. Uses L1 norm of discrete gradients for vectors and L2 norm of discrete gradients for matrices. #' #' @param value An \linkS4class{Expression}, vector, or matrix. #' @param ... (Optional) \linkS4class{Expression} objects or numeric constants that extend the third dimension of value. #' @return An \linkS4class{Expression} representing the total variation of the input. #' @examples #' rows <- 10 #' cols <- 10 #' Uorig <- matrix(sample(0:255, size = rows * cols, replace = TRUE), nrow = rows, ncol = cols) #' #' # Known is 1 if the pixel is known, 0 if the pixel was corrupted #' Known <- matrix(0, nrow = rows, ncol = cols) #' for(i in 1:rows) { #' for(j in 1:cols) { #' if(stats::runif(1) > 0.7) #' Known[i,j] <- 1 #' } #' } #' Ucorr <- Known %*% Uorig #' #' # Recover the original image using total variation in-painting #' U <- Variable(rows, cols) #' obj <- Minimize(tv(U)) #' constraints <- list(Known * U == Known * Ucorr) #' prob <- Problem(obj, constraints) #' result <- solve(prob, solver = "SCS") #' result$getValue(U) #' @docType methods #' @name tv #' @aliases total_variation #' @rdname tv #' @export tv <- TotalVariation #' @param ... Numeric scalar, vector, matrix, or \linkS4class{Expression} objects. #' @param na.rm (Unimplemented) A logical value indicating whether missing values should be removed. #' @examples #' x <- Variable(2) #' val <- matrix(c(-5,-10)) #' prob <- Problem(Minimize(max_entries(x)), list(x == val)) #' result <- solve(prob) #' result$value #' #' A <- Variable(2,2) #' val <- rbind(c(-5,2), c(-3,1)) #' prob <- Problem(Minimize(max_entries(A, axis = 1)[2,1]), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @rdname max_entries #' @method max Expression #' @export max.Expression <- function(..., na.rm = FALSE) { if(na.rm) warning("na.rm is unimplemented for Expression objects") vals <- list(...) if(length(vals) == 0) { warning("no non-missing arguments to max; returning -Inf") return(-Inf) } is_expr <- sapply(vals, function(v) { is(v, "Expression") }) max_args <- lapply(vals[is_expr], function(expr) { MaxEntries(expr) }) if(!all(is_expr)) { max_num <- max(sapply(vals[!is_expr], function(v) { max(v, na.rm = na.rm) })) max_args <- c(max_args, max_num) } if(length(max_args) == 1) return(max_args[[1]]) .MaxElemwise(atom_args = max_args) } #' @param ... Numeric scalar, vector, matrix, or \linkS4class{Expression} objects. #' @param na.rm (Unimplemented) A logical value indicating whether missing values should be removed. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(-5,2), c(-3,1)) #' prob <- Problem(Maximize(min_entries(A)), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @rdname min_entries #' @method min Expression #' @export min.Expression <- function(..., na.rm = FALSE) { if(na.rm) warning("na.rm is unimplemented for Expression objects") vals <- list(...) if(length(vals) == 0) { warning("no non-missing arguments to min; returning Inf") return(Inf) } is_expr <- sapply(vals, function(v) { is(v, "Expression") }) min_args <- lapply(vals[is_expr], function(expr) { MinEntries(expr) }) if(!all(is_expr)) { min_num <- min(sapply(vals[!is_expr], function(v) { min(v, na.rm = na.rm) })) min_args <- c(min_args, min_num) } min_args <- lapply(min_args, function(arg) { -as.Constant(arg) }) if(length(min_args) == 1) return(-min_args[[1]]) -.MaxElemwise(atom_args = min_args) } #' #' Matrix Norm #' #' The matrix norm, which can be the 1-norm ("1"), infinity-norm ("I"), Frobenius norm ("F"), maximum modulus of all the entries ("M"), or the spectral norm ("2"), as determined by the value of type. #' #' @param x An \linkS4class{Expression}. #' @param type A character indicating the type of norm desired. #' \itemize{ #' \item "O", "o" or "1" specifies the 1-norm (maximum absolute column sum). #' \item "I" or "i" specifies the infinity-norm (maximum absolute row sum). #' \item "F" or "f" specifies the Frobenius norm (Euclidean norm of the vectorized \code{x}). #' \item "M" or "m" specifies the maximum modulus of all the elements in \code{x}. #' \item "2" specifies the spectral norm, which is the largest singular value of \code{x}. #' } #' @return An \linkS4class{Expression} representing the norm of the input. #' @seealso The \code{\link{p_norm}} function calculates the vector p-norm. #' @examples #' C <- Variable(3,2) #' val <- Constant(rbind(c(1,2), c(3,4), c(5,6))) #' prob <- Problem(Minimize(norm(C, "F")), list(C == val)) #' result <- solve(prob, solver = "SCS") #' result$value #' @docType methods #' @aliases norm #' @rdname norm #' @export setMethod("norm", signature(x = "Expression", type = "character"), function(x, type) { x <- as.Constant(x) type <- substr(type, 1, 1) # Norms for scalars same as absolute value if(type %in% c("O", "o", "1")) # Maximum absolute column sum MaxEntries(Pnorm(x = x, p = 1, axis = 2)) else if(type %in% c("I", "i")) # Maximum absolute row sum MaxEntries(Pnorm(x = x, p = 1, axis = 1)) else if(type %in% c("E", "e", "F", "f")) # Frobenius norm (Euclidean norm if x is treated as a vector) Pnorm(x = x, p = 2, axis = NA_real_) else if(type %in% c("M", "m")) # Maximum modulus (absolute value) of all elements in x MaxEntries(Abs(x = x)) else if(type == "2") # Spectral norm (largest singular value of x) SigmaMax(A = x) else stop("argument type[1]='", type, "' must be one of 'M','1','O','I','F' or 'E'") }) #' #' Matrix Norm (Alternative) #' #' A wrapper on the different norm atoms. This is different from the standard "norm" method in the R base package. #' If \code{p = 2}, \code{axis = NA}, and \code{x} is a matrix, this returns the maximium singular value. #' #' @param x An \linkS4class{Expression} or numeric constant representing a vector or matrix. #' @param p The type of norm. May be a number (p-norm), "inf" (infinity-norm), "nuc" (nuclear norm), or "fro" (Frobenius norm). The default is \code{p = 2}. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{NA}. #' @param keepdims (Optional) Should dimensions be maintained when applying the atom along an axis? If \code{FALSE}, result will be collapsed into an \eqn{n x 1} column vector. The default is \code{FALSE}. #' @return An \linkS4class{Expression} representing the norm. #' @seealso \link[CVXR]{norm} #' @docType methods #' @name cvxr_norm #' @rdname cvxr_norm #' @export cvxr_norm <- Norm #' @param ... Numeric scalar, vector, matrix, or \linkS4class{Expression} objects. #' @param na.rm (Unimplemented) A logical value indicating whether missing values should be removed. #' @examples #' x <- Variable(2) #' prob <- Problem(Minimize(sum_entries(x)), list(t(x) >= matrix(c(1,2), nrow = 1, ncol = 2))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' C <- Variable(3,2) #' prob <- Problem(Maximize(sum_entries(C)), list(C[2:3,] <= 2, C[1,] == 1)) #' result <- solve(prob) #' result$value #' result$getValue(C) #' @docType methods #' @rdname sum_entries #' @method sum Expression #' @export sum.Expression <- function(..., na.rm = FALSE) { if(na.rm) warning("na.rm is unimplemented for Expression objects") vals <- list(...) is_expr <- sapply(vals, function(v) { is(v, "Expression") }) sum_expr <- lapply(vals[is_expr], function(expr) { SumEntries(expr = expr) }) if(all(is_expr)) Reduce("+", sum_expr) else { sum_num <- sum(sapply(vals[!is_expr], function(v) { sum(v, na.rm = na.rm) })) Reduce("+", sum_expr) + sum_num } } #' @param ... Numeric scalar, vector, matrix, or \linkS4class{Expression} objects. #' @param na.rm (Unimplemented) A logical value indicating whether missing values should be removed. #' @examples #' n <- 2 #' X <- Variable(n, n, pos=TRUE) #' obj <- sum(X) #' constraints <- list(prod(X) == 4) #' prob <- Problem(Minimize(obj), constraints) #' result <- solve(prob, gp=TRUE) #' result$value #' @docType methods #' @rdname prod_entries #' @method prod Expression #' @export prod.Expression <- function(..., na.rm = FALSE) { if(na.rm) warning("na.rm is unimplemented for Expression objects") vals <- list(...) is_expr <- sapply(vals, function(v) { is(v, "Expression") }) sum_expr <- lapply(vals[is_expr], function(expr) { ProdEntries(expr = expr) }) if(all(is_expr)) Reduce("*", sum_expr) else { sum_num <- sum(sapply(vals[!is_expr], function(v) { prod(v, na.rm = na.rm) })) Reduce("*", sum_expr) + sum_num } } #' #' Arithmetic Mean #' #' The arithmetic mean of an expression. #' #' @param x An \linkS4class{Expression} object. #' @param trim (Unimplemented) The fraction (0 to 0.5) of observations to be trimmed from each end of \eqn{x} before the mean is computed. #' @param na.rm (Unimplemented) A logical value indicating whether missing values should be removed. #' @param ... (Unimplemented) Optional arguments. #' @return An \linkS4class{Expression} representing the mean of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(-5,2), c(-3,1)) #' prob <- Problem(Minimize(mean(A)), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @aliases mean #' @rdname mean #' @method mean Expression #' @export mean.Expression <- function(x, trim = 0, na.rm = FALSE, ...) { if(na.rm) stop("na.rm is unimplemented for Expression objects") if(trim != 0) stop("trim is unimplemented for Expression objects") SumEntries(expr = x) / prod(size(x)) } # ========================= # Elementwise functions # ========================= #' #' Entropy Function #' #' The elementwise entropy function, \eqn{-xlog(x)}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the entropy of the input. #' @examples #' x <- Variable(5) #' obj <- Maximize(sum(entr(x))) #' prob <- Problem(obj, list(sum(x) == 1)) #' result <- solve(prob) #' result$getValue(x) #' @docType methods #' @name entr #' @aliases entropy #' @rdname entr #' @export entr <- Entr #' #' Huber Function #' #' The elementwise Huber function, \eqn{Huber(x, M) = 1} #' \describe{ #' \item{\eqn{2M|x|-M^2}}{for \eqn{|x| \geq |M|}} #' \item{\eqn{|x|^2}}{for \eqn{|x| \leq |M|.}} #' } #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param M (Optional) A positive scalar value representing the threshold. Defaults to 1. #' @return An \linkS4class{Expression} representing the Huber function evaluated at the input. #' @examples #' set.seed(11) #' n <- 10 #' m <- 450 #' p <- 0.1 # Fraction of responses with sign flipped #' #' # Generate problem data #' beta_true <- 5*matrix(stats::rnorm(n), nrow = n) #' X <- matrix(stats::rnorm(m*n), nrow = m, ncol = n) #' y_true <- X %*% beta_true #' eps <- matrix(stats::rnorm(m), nrow = m) #' #' # Randomly flip sign of some responses #' factor <- 2*rbinom(m, size = 1, prob = 1-p) - 1 #' y <- factor * y_true + eps #' #' # Huber regression #' beta <- Variable(n) #' obj <- sum(huber(y - X %*% beta, 1)) #' prob <- Problem(Minimize(obj)) #' result <- solve(prob) #' result$getValue(beta) #' @docType methods #' @name huber #' @rdname huber #' @export huber <- Huber #' #' Reciprocal Function #' #' The elementwise reciprocal function, \eqn{\frac{1}{x}} #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the reciprocal of the input. #' @examples #' A <- Variable(2,2) #' val <- cbind(c(1,2), c(3,4)) #' prob <- Problem(Minimize(inv_pos(A)[1,2]), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name inv_pos #' @rdname inv_pos #' @export inv_pos <- InvPos #' #' Kullback-Leibler Divergence #' #' The elementwise Kullback-Leibler divergence, \eqn{x\log(x/y) - x + y}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param y An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the KL-divergence of the input. #' @examples #' n <- 5 #' alpha <- seq(10, n-1+10)/n #' beta <- seq(10, n-1+10)/n #' P_tot <- 0.5 #' W_tot <- 1.0 #' #' P <- Variable(n) #' W <- Variable(n) #' R <- kl_div(alpha*W, alpha*(W + beta*P)) - alpha*beta*P #' obj <- sum(R) #' constr <- list(P >= 0, W >= 0, sum(P) == P_tot, sum(W) == W_tot) #' prob <- Problem(Minimize(obj), constr) #' result <- solve(prob) #' #' result$value #' result$getValue(P) #' result$getValue(W) #' @docType methods #' @name kl_div #' @rdname kl_div #' @export kl_div <- KLDiv #' #' Logistic Function #' #' The elementwise logistic function, \eqn{\log(1 + e^x)}. #' This is a special case of log(sum(exp)) that evaluates to a vector rather than to a scalar, which is useful for logistic regression. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the logistic function evaluated at the input. #' @examples #' set.seed(92) #' n <- 20 #' m <- 1000 #' sigma <- 45 #' #' beta_true <- stats::rnorm(n) #' idxs <- sample(n, size = 0.8*n, replace = FALSE) #' beta_true[idxs] <- 0 #' X <- matrix(stats::rnorm(m*n, 0, 5), nrow = m, ncol = n) #' y <- sign(X %*% beta_true + stats::rnorm(m, 0, sigma)) #' #' beta <- Variable(n) #' X_sign <- apply(X, 2, function(x) { ifelse(y <= 0, -1, 1) * x }) #' obj <- -sum(logistic(-X[y <= 0,] %*% beta)) - sum(logistic(X[y == 1,] %*% beta)) #' prob <- Problem(Maximize(obj)) #' result <- solve(prob) #' #' log_odds <- result$getValue(X %*% beta) #' beta_res <- result$getValue(beta) #' y_probs <- 1/(1 + exp(-X %*% beta_res)) #' log(y_probs/(1 - y_probs)) #' @docType methods #' @name logistic #' @rdname logistic #' @export logistic <- Logistic #' #' Elementwise Maximum #' #' The elementwise maximum. #' #' @param arg1 An \linkS4class{Expression}, vector, or matrix. #' @param arg2 An \linkS4class{Expression}, vector, or matrix. #' @param ... Additional \linkS4class{Expression} objects, vectors, or matrices. #' @return An \linkS4class{Expression} representing the elementwise maximum of the inputs. #' @examples #' c <- matrix(c(1,-1)) #' prob <- Problem(Minimize(max_elemwise(t(c), 2, 2 + t(c))[2])) #' result <- solve(prob) #' result$value #' @docType methods #' @name max_elemwise #' @rdname max_elemwise #' @export max_elemwise <- MaxElemwise #' #' Elementwise Minimum #' #' The elementwise minimum. #' #' @param arg1 An \linkS4class{Expression}, vector, or matrix. #' @param arg2 An \linkS4class{Expression}, vector, or matrix. #' @param ... Additional \linkS4class{Expression} objects, vectors, or matrices. #' @return An \linkS4class{Expression} representing the elementwise minimum of the inputs. #' @examples #' a <- cbind(c(-5,2), c(-3,-1)) #' b <- cbind(c(5,4), c(-1,2)) #' prob <- Problem(Minimize(min_elemwise(a, 0, b)[1,2])) #' result <- solve(prob) #' result$value #' @docType methods #' @name min_elemwise #' @rdname min_elemwise #' @export min_elemwise <- MinElemwise #' #' Elementwise Multiplication #' #' The elementwise product of two expressions. The first expression must be constant. #' #' @param lh_exp An \linkS4class{Expression}, vector, or matrix representing the left-hand value. #' @param rh_exp An \linkS4class{Expression}, vector, or matrix representing the right-hand value. #' @return An \linkS4class{Expression} representing the elementwise product of the inputs. #' @examples #' A <- Variable(2,2) #' c <- cbind(c(1,-1), c(2,-2)) #' expr <- multiply(c, A) #' obj <- Minimize(norm_inf(expr)) #' prob <- Problem(obj, list(A == 5)) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' @docType methods #' @name multiply #' @aliases * #' @rdname multiply #' @export multiply <- Multiply #' #' Elementwise Negative #' #' The elementwise absolute negative portion of an expression, \eqn{-\min(x_i,0)}. This is equivalent to \code{-min_elemwise(x,0)}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the negative portion of the input. #' @examples #' x <- Variable(2) #' val <- matrix(c(-3,3)) #' prob <- Problem(Minimize(neg(x)[1]), list(x == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name neg #' @rdname neg #' @export neg <- Neg #' #' Elementwise Positive #' #' The elementwise positive portion of an expression, \eqn{\max(x_i,0)}. This is equivalent to \code{max_elemwise(x,0)}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @return An \linkS4class{Expression} representing the positive portion of the input. #' @examples #' x <- Variable(2) #' val <- matrix(c(-3,2)) #' prob <- Problem(Minimize(pos(x)[1]), list(x == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @name pos #' @rdname pos #' @export pos <- Pos #' #' Elementwise Power #' #' Raises each element of the input to the power \eqn{p}. #' If \code{expr} is a CVXR expression, then \code{expr^p} is equivalent to \code{power(expr,p)}. #' #' For \eqn{p = 0} and \eqn{f(x) = 1}, this function is constant and positive. #' For \eqn{p = 1} and \eqn{f(x) = x}, this function is affine, increasing, and the same sign as \eqn{x}. #' For \eqn{p = 2,4,8,\ldots} and \eqn{f(x) = |x|^p}, this function is convex, positive, with signed monotonicity. #' For \eqn{p < 0} and \eqn{f(x) = } #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x > 0}} #' \item{\eqn{+\infty}}{\eqn{x \leq 0}} #' }, this function is convex, decreasing, and positive. #' For \eqn{0 < p < 1} and \eqn{f(x) =} #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x \geq 0}} #' \item{\eqn{-\infty}}{\eqn{x < 0}} #' }, this function is concave, increasing, and positivea. #' For \eqn{p > 1, p \neq 2,4,8,\ldots} and \eqn{f(x) = } #' \describe{ #' \item{\eqn{x^p}}{ for \eqn{x \geq 0}} #' \item{\eqn{+\infty}}{\eqn{x < 0}} #' }, this function is convex, increasing, and positive. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param p A scalar value indicating the exponential power. #' @param max_denom The maximum denominator considered in forming a rational approximation of \code{p}. #' @examples #' \dontrun{ #' x <- Variable() #' prob <- Problem(Minimize(power(x,1.7) + power(x,-2.3) - power(x,0.45))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' } #' @docType methods #' @name power #' @aliases ^ #' @rdname power #' @export power <- Power #' #' Scalene Function #' #' The elementwise weighted sum of the positive and negative portions of an expression, \eqn{\alpha\max(x_i,0) - \beta\min(x_i,0)}. #' This is equivalent to \code{alpha*pos(x) + beta*neg(x)}. #' #' @param x An \linkS4class{Expression}, vector, or matrix. #' @param alpha The weight on the positive portion of \code{x}. #' @param beta The weight on othe negative portion of \code{x}. #' @return An \linkS4class{Expression} representing the scalene function evaluated at the input. #' @examples #' \dontrun{ #' A <- Variable(2,2) #' val <- cbind(c(-5,2), c(-3,1)) #' prob <- Problem(Minimize(scalene(A,2,3)[1,1]), list(A == val)) #' result <- solve(prob) #' result$value #' result$getValue(scalene(A, 0.7, 0.3)) #' } #' @docType methods #' @name scalene #' @rdname scalene #' @export scalene <- Scalene #' #' Absolute Value #' #' The elementwise absolute value. #' #' @param x An \linkS4class{Expression}. #' @return An \linkS4class{Expression} representing the absolute value of the input. #' @examples #' A <- Variable(2,2) #' prob <- Problem(Minimize(sum(abs(A))), list(A <= -2)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' @docType methods #' @aliases abs #' @rdname abs #' @export setMethod("abs", "Expression", function(x) { Abs(x = x) }) #' #' Natural Exponential #' #' The elementwise natural exponential. #' #' @param x An \linkS4class{Expression}. #' @return An \linkS4class{Expression} representing the natural exponential of the input. #' @examples #' x <- Variable(5) #' obj <- Minimize(sum(exp(x))) #' prob <- Problem(obj, list(sum(x) == 1)) #' result <- solve(prob) #' result$getValue(x) #' @docType methods #' @aliases exp #' @rdname exp #' @export setMethod("exp", "Expression", function(x) { Exp(x = x) }) #' #' Logarithms #' #' The elementwise logarithm. #' \code{log} computes the logarithm, by default the natural logarithm, \code{log10} computes the common (i.e., base 10) logarithm, and \code{log2} computes the binary (i.e., base 2) logarithms. The general form \code{log(x, base)} computes logarithms with base \code{base}. #' \code{log1p} computes elementwise the function \eqn{\log(1+x)}. #' #' @param x An \linkS4class{Expression}. #' @param base (Optional) A positive number that is the base with respect to which the logarithm is computed. Defaults to \eqn{e}. #' @return An \linkS4class{Expression} representing the exponentiated input. #' @examples #' # Log in objective #' x <- Variable(2) #' obj <- Maximize(sum(log(x))) #' constr <- list(x <= matrix(c(1, exp(1)))) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' # Log in constraint #' obj <- Minimize(sum(x)) #' constr <- list(log2(x) >= 0, x <= matrix(c(1,1))) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' result$value #' result$getValue(x) #' #' # Index into log #' obj <- Maximize(log10(x)[2]) #' constr <- list(x <= matrix(c(1, exp(1)))) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' result$value #' #' # Scalar log #' obj <- Maximize(log1p(x[2])) #' constr <- list(x <= matrix(c(1, exp(1)))) #' prob <- Problem(obj, constr) #' result <- solve(prob) #' result$value #' @docType methods #' @aliases log log10 log2 log1p #' @rdname log #' @export setMethod("log", "Expression", function(x, base = base::exp(1)) { if(base == base::exp(1)) Log(x = x) else Log(x = x)/base::log(base) }) #' @docType methods #' @rdname log #' @export setMethod("log10", "Expression", function(x) { log(x, base = 10) }) #' @docType methods #' @rdname log #' @export setMethod("log2", "Expression", function(x) { log(x, base = 2) }) #' @docType methods #' @rdname log #' @export setMethod("log1p", "Expression", function(x) { Log1p(x = x) }) log1p <- Log1p #' #' Square Root #' #' The elementwise square root. #' #' @param x An \linkS4class{Expression}. #' @return An \linkS4class{Expression} representing the square root of the input. #' A <- Variable(2,2) #' val <- cbind(c(2,4), c(16,1)) #' prob <- Problem(Maximize(sqrt(A)[1,2]), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @aliases sqrt #' @rdname sqrt #' @export setMethod("sqrt", "Expression", function(x) { Power(x = x, p = 0.5) }) #' #' Square #' #' The elementwise square. #' #' @param x An \linkS4class{Expression}. #' @return An \linkS4class{Expression} representing the square of the input. #' A <- Variable(2,2) #' val <- cbind(c(2,4), c(16,1)) #' prob <- Problem(Minimize(square(A)[1,2]), list(A == val)) #' result <- solve(prob) #' result$value #' @docType methods #' @aliases square #' @rdname square #' @export setMethod("square", "Expression", function(x) { Power(x = x, p = 2) }) # ========================= # Matrix/vector operations # ========================= #' #' Block Matrix #' #' Constructs a block matrix from a list of lists. Each internal list is stacked horizontally, and the internal lists are stacked vertically. #' #' @param block_lists A list of lists containing \linkS4class{Expression} objects, matrices, or vectors, which represent the blocks of the block matrix. #' @return An \linkS4class{Expression} representing the block matrix. #' @examples #' x <- Variable() #' expr <- bmat(list(list(matrix(1, nrow = 3, ncol = 1), matrix(2, nrow = 3, ncol = 2)), #' list(matrix(3, nrow = 1, ncol = 2), x) #' )) #' prob <- Problem(Minimize(sum_entries(expr)), list(x >= 0)) #' result <- solve(prob) #' result$value #' @docType methods #' @name bmat #' @rdname bmat #' @export bmat <- Bmat #' #' Discrete Convolution #' #' The 1-D discrete convolution of two vectors. #' #' @param lh_exp An \linkS4class{Expression} or vector representing the left-hand value. #' @param rh_exp An \linkS4class{Expression} or vector representing the right-hand value. #' @return An \linkS4class{Expression} representing the convolution of the input. #' @examples #' set.seed(129) #' x <- Variable(5) #' h <- matrix(stats::rnorm(2), nrow = 2, ncol = 1) #' prob <- Problem(Minimize(sum(conv(h, x)))) #' result <- solve(prob) #' result$value #' result$getValue(x) #' @docType methods #' @name conv #' @rdname conv #' @export conv <- Conv #' #' Horizontal Concatenation #' #' The horizontal concatenation of expressions. #' This is equivalent to \code{cbind} when applied to objects with the same number of rows. #' #' @param ... \linkS4class{Expression} objects, vectors, or matrices. All arguments must have the same number of rows. #' @return An \linkS4class{Expression} representing the concatenated inputs. #' @examples #' x <- Variable(2) #' y <- Variable(3) #' c <- matrix(1, nrow = 1, ncol = 5) #' prob <- Problem(Minimize(c %*% t(hstack(t(x), t(y)))), list(x == c(1,2), y == c(3,4,5))) #' result <- solve(prob) #' result$value #' #' c <- matrix(1, nrow = 1, ncol = 4) #' prob <- Problem(Minimize(c %*% t(hstack(t(x), t(x)))), list(x == c(1,2))) #' result <- solve(prob) #' result$value #' #' A <- Variable(2,2) #' C <- Variable(3,2) #' c <- matrix(1, nrow = 2, ncol = 2) #' prob <- Problem(Minimize(sum_entries(hstack(t(A), t(C)))), list(A >= 2*c, C == -2)) #' result <- solve(prob) #' result$value #' result$getValue(A) #' #' D <- Variable(3,3) #' expr <- hstack(C, D) #' obj <- expr[1,2] + sum(hstack(expr, expr)) #' constr <- list(C >= 0, D >= 0, D[1,1] == 2, C[1,2] == 3) #' prob <- Problem(Minimize(obj), constr) #' result <- solve(prob) #' result$value #' result$getValue(C) #' result$getValue(D) #' @docType methods #' @name hstack #' @rdname hstack #' @export hstack <- HStack #' #' Reshape an Expression #' #' This function vectorizes an expression, then unvectorizes it into a new shape. Entries are stored in column-major order. #' #' @param expr An \linkS4class{Expression}, vector, or matrix. #' @param new_dim The new dimensions. #' @return An \linkS4class{Expression} representing the reshaped input. #' @examples #' x <- Variable(4) #' mat <- cbind(c(1,-1), c(2,-2)) #' vec <- matrix(1:4) #' expr <- reshape_expr(x,c(2,2)) #' obj <- Minimize(sum(mat %*% expr)) #' prob <- Problem(obj, list(x == vec)) #' result <- solve(prob) #' result$value #' #' A <- Variable(2,2) #' c <- 1:4 #' expr <- reshape_expr(A,c(4,1)) #' obj <- Minimize(t(expr) %*% c) #' constraints <- list(A == cbind(c(-1,-2), c(3,4))) #' prob <- Problem(obj, constraints) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' result$getValue(reshape_expr(expr,c(2,2))) #' #' C <- Variable(3,2) #' expr <- reshape_expr(C,c(2,3)) #' mat <- rbind(c(1,-1), c(2,-2)) #' C_mat <- rbind(c(1,4), c(2,5), c(3,6)) #' obj <- Minimize(sum(mat %*% expr)) #' prob <- Problem(obj, list(C == C_mat)) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' #' a <- Variable() #' c <- cbind(c(1,-1), c(2,-2)) #' expr <- reshape_expr(c * a,c(1,4)) #' obj <- Minimize(expr %*% (1:4)) #' prob <- Problem(obj, list(a == 2)) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' #' expr <- reshape_expr(c * a,c(4,1)) #' obj <- Minimize(t(expr) %*% (1:4)) #' prob <- Problem(obj, list(a == 2)) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' @docType methods #' @name reshape_expr #' @aliases reshape #' @rdname reshape_expr #' @export reshape_expr <- Reshape #' #' Maximum Singular Value #' #' The maximum singular value of a matrix. #' #' @param A An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the maximum singular value. #' @examples #' C <- Variable(3,2) #' val <- rbind(c(1,2), c(3,4), c(5,6)) #' obj <- sigma_max(C) #' constr <- list(C == val) #' prob <- Problem(Minimize(obj), constr) #' result <- solve(prob, solver = "SCS") #' result$value #' result$getValue(C) #' @docType methods #' @name sigma_max #' @rdname sigma_max #' @export sigma_max <- SigmaMax #' #' Upper Triangle of a Matrix #' #' The vectorized strictly upper triangular entries of a matrix. #' #' @param expr An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the upper triangle of the input. #' @examples #' C <- Variable(3,3) #' val <- cbind(3:5, 6:8, 9:11) #' prob <- Problem(Maximize(upper_tri(C)[3,1]), list(C == val)) #' result <- solve(prob) #' result$value #' result$getValue(upper_tri(C)) #' @docType methods #' @name upper_tri #' @rdname upper_tri #' @export upper_tri <- UpperTri #' #' Vectorization of a Matrix #' #' Flattens a matrix into a vector in column-major order. #' #' @param X An \linkS4class{Expression} or matrix. #' @return An \linkS4class{Expression} representing the vectorized matrix. #' @examples #' A <- Variable(2,2) #' c <- 1:4 #' expr <- vec(A) #' obj <- Minimize(t(expr) %*% c) #' constraints <- list(A == cbind(c(-1,-2), c(3,4))) #' prob <- Problem(obj, constraints) #' result <- solve(prob) #' result$value #' result$getValue(expr) #' @docType methods #' @name vec #' @rdname vec #' @export vec <- Vec #' #' Vertical Concatenation #' #' The vertical concatenation of expressions. This is equivalent to \code{rbind} when applied to objects with the same number of columns. #' #' @param ... \linkS4class{Expression} objects, vectors, or matrices. All arguments must have the same number of columns. #' @return An \linkS4class{Expression} representing the concatenated inputs. #' @examples #' x <- Variable(2) #' y <- Variable(3) #' c <- matrix(1, nrow = 1, ncol = 5) #' prob <- Problem(Minimize(c %*% vstack(x, y)), list(x == c(1,2), y == c(3,4,5))) #' result <- solve(prob) #' result$value #' #' c <- matrix(1, nrow = 1, ncol = 4) #' prob <- Problem(Minimize(c %*% vstack(x, x)), list(x == c(1,2))) #' result <- solve(prob) #' result$value #' #' A <- Variable(2,2) #' C <- Variable(3,2) #' c <- matrix(1, nrow = 2, ncol = 2) #' prob <- Problem(Minimize(sum(vstack(A, C))), list(A >= 2*c, C == -2)) #' result <- solve(prob) #' result$value #' #' B <- Variable(2,2) #' c <- matrix(1, nrow = 1, ncol = 2) #' prob <- Problem(Minimize(sum(vstack(c %*% A, c %*% B))), list(A >= 2, B == -2)) #' result <- solve(prob) #' result$value #' @docType methods #' @name vstack #' @rdname vstack #' @export vstack <- VStack #' #' Cumulative Sum #' #' The cumulative sum, \eqn{\sum_{i=1}^k x_i} for \eqn{k=1,\ldots,n}. #' When calling \code{cumsum}, matrices are automatically flattened into column-major order before the sum is taken. #' #' @param x,expr An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @examples #' val <- cbind(c(1,2), c(3,4)) #' value(cumsum(Constant(val))) #' value(cumsum_axis(Constant(val))) #' #' x <- Variable(2,2) #' prob <- Problem(Minimize(cumsum(x)[4]), list(x == val)) #' result <- solve(prob) #' result$value #' result$getValue(cumsum(x)) #' @docType methods #' @name cumsum_axis #' @aliases cumsum_axis cumsum #' @rdname cumsum_axis #' @export cumsum_axis <- CumSum #' @docType methods #' @rdname cumsum_axis #' @export setMethod("cumsum", signature(x = "Expression"), function(x) { CumSum(expr = Vec(x)) }) #' #' Cumulative Maximum #' #' The cumulative maximum, \eqn{\max_{i=1,\ldots,k} x_i} for \eqn{k=1,\ldots,n}. #' When calling \code{cummax}, matrices are automatically flattened into column-major order before the max is taken. #' #' @param x,expr An \linkS4class{Expression}, vector, or matrix. #' @param axis (Optional) The dimension across which to apply the function: \code{1} indicates rows, and \code{2} indicates columns. The default is \code{2}. #' @examples #' val <- cbind(c(1,2), c(3,4)) #' value(cummax(Constant(val))) #' value(cummax_axis(Constant(val))) #' #' x <- Variable(2,2) #' prob <- Problem(Minimize(cummax(x)[4]), list(x == val)) #' result <- solve(prob) #' result$value #' result$getValue(cummax(x)) #' @docType methods #' @name cummax_axis #' @aliases cummax_axis cummax #' @rdname cummax_axis #' @export cummax_axis <- CumMax #' @docType methods #' @rdname cummax_axis #' @export setMethod("cummax", signature(x = "Expression"), function(x) { CumMax(expr = Vec(x)) }) #' #' Matrix Diagonal #' #' Extracts the diagonal from a matrix or makes a vector into a diagonal matrix. #' #' @param x An \linkS4class{Expression}, vector, or square matrix. #' @param nrow,ncol (Optional) Dimensions for the result when \code{x} is not a matrix. #' @return An \linkS4class{Expression} representing the diagonal vector or matrix. #' @examples #' C <- Variable(3,3) #' obj <- Maximize(C[1,3]) #' constraints <- list(diag(C) == 1, C[1,2] == 0.6, C[2,3] == -0.3, C == Variable(3,3, PSD = TRUE)) #' prob <- Problem(obj, constraints) #' result <- solve(prob) #' result$value #' result$getValue(C) #' @docType methods #' @aliases diag #' @rdname diag #' @export setMethod("diag", signature(x = "Expression"), function(x = 1, nrow, ncol) { missing_nrow <- missing(nrow) missing_ncol <- missing(ncol) if (missing_nrow && missing_ncol) { Diag(x) } else if (is_matrix(x) & ((!missing_nrow) || (!missing_ncol))) { stop("'nrow' or 'ncol' cannot be specified when 'x' is a matrix") } else { expr <- as.Constant(x) n <- length(expr) if(!missing_nrow) n <- nrow if(missing_ncol) ncol <- n expr*(base::diag(n)[1:n, 1:ncol]) } }) #' #' Lagged and Iterated Differences #' #' The lagged and iterated differences of a vector. #' If \code{x} is length \code{n}, this function returns a length \eqn{n-k} vector of the \eqn{k}th order difference between the lagged terms. #' \code{diff(x)} returns the vector of differences between adjacent elements in the vector, i.e. [x[2] - x[1], x[3] - x[2], ...]. #' \code{diff(x,1,2)} is the second-order differences vector, equivalently diff(diff(x)). \code{diff(x,1,0)} returns the vector x unchanged. #' \code{diff(x,2)} returns the vector of differences [x[3] - x[1], x[4] - x[2], ...], equivalent to \code{x[(1+lag):n] - x[1:(n-lag)]}. #' #' @param x An \linkS4class{Expression}. #' @param lag An integer indicating which lag to use. #' @param differences An integer indicating the order of the difference. #' @param ... (Optional) Addition \code{axis} argument, specifying the dimension across which to apply the function: \code{1} indicates rows, \code{2} indicates columns, and \code{NA} indicates rows and columns. The default is \code{axis = 1}. #' @return An \linkS4class{Expression} representing the \code{k}th order difference. #' @examples #' ## Problem data #' m <- 101 #' L <- 2 #' h <- L/(m-1) #' #' ## Form objective and constraints #' x <- Variable(m) #' y <- Variable(m) #' obj <- sum(y) #' constr <- list(x[1] == 0, y[1] == 1, x[m] == 1, y[m] == 1, diff(x)^2 + diff(y)^2 <= h^2) #' #' ## Solve the catenary problem #' prob <- Problem(Minimize(obj), constr) #' result <- solve(prob) #' #' ## Plot and compare with ideal catenary #' xs <- result$getValue(x) #' ys <- result$getValue(y) #' plot(c(0, 1), c(0, 1), type = 'n', xlab = "x", ylab = "y") #' lines(xs, ys, col = "blue", lwd = 2) #' grid() #' @docType methods #' @aliases diff #' @rdname diff #' @export setMethod("diff", "Expression", function(x, lag = 1, differences = 1, ...) { Diff(x = x, lag = lag, k = differences, ...) }) #' #' Kronecker Product #' #' The generalized kronecker product of two matrices. #' #' @param X An \linkS4class{Expression} or matrix. #' @param Y An \linkS4class{Expression} or matrix. #' @param FUN Hardwired to "*" for the kronecker product. #' @param make.dimnames (Unimplemented) Dimension names are not supported in \linkS4class{Expression} objects. #' @param ... (Unimplemented) Optional arguments. #' @return An \linkS4class{Expression} that represents the kronecker product. #' @examples #' X <- cbind(c(1,2), c(3,4)) #' Y <- Variable(2,2) #' val <- cbind(c(5,6), c(7,8)) #' #' obj <- X %x% Y #' prob <- Problem(Minimize(kronecker(X,Y)[1,1]), list(Y == val)) #' result <- solve(prob) #' result$value #' result$getValue(kronecker(X,Y)) #' @aliases kronecker %x% #' @rdname kronecker #' @export setMethod("kronecker", signature(X = "Expression", Y = "ANY"), function(X, Y, FUN = "*", make.dimnames = FALSE, ...) { if(FUN != "*" || make.dimnames) stop("Unimplemented") Kron(X, Y) }) #' @rdname kronecker #' @export setMethod("kronecker", signature(X = "ANY", Y = "Expression"), function(X, Y, FUN = "*", make.dimnames = FALSE, ...) { if(FUN != "*" || make.dimnames) stop("Unimplemented") Kron(X, Y) }) ## #' @rdname kronecker ## #' @export ## setMethod("%x%", signature(X = "Expression", Y = "ANY"), function(X, Y) { Kron(lh_exp = X, rh_exp = Y) }) ## #' @rdname kronecker ## #' @export ## setMethod("%x%", signature(X = "ANY", Y = "Expression"), function(X, Y) { Kron(lh_exp = X, rh_exp = Y) }) #' #' Complex Numbers #' #' Basic atoms that support complex arithmetic. #' #' @param z An \linkS4class{Expression} object. #' @return An \linkS4class{Expression} object that represents the real, imaginary, or complex conjugate. #' @name complex-atoms NULL #' @rdname complex-atoms #' @export setMethod("Re", "Expression", function(z) { Real(z) }) #' @rdname complex-atoms #' @export setMethod("Im", "Expression", function(z) { Imag(z) }) #' @rdname complex-atoms #' @export setMethod("Conj", "Expression", function(z) { if(is_real(z)) z else Conjugate(z) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/exports.R
#' #' The Expression class. #' #' This class represents a mathematical expression. #' #' @name Expression-class #' @aliases Expression #' @rdname Expression-class Expression <- setClass("Expression", contains = "Canonical") setOldClass("data.frame") setOldClass("matrix") setClassUnion("ConstSparseVal", c("CsparseMatrix", "TsparseMatrix")) setClassUnion("ConstVal", c("ConstSparseVal", "data.frame", "matrix", "numeric", "complex", "dMatrix", "bigq", "bigz")) setClassUnion("ConstValORExpr", c("ConstVal", "Expression")) setClassUnion("ConstValORNULL", c("ConstVal", "NULL")) setClassUnion("ConstValListORExpr", c("ConstVal", "list", "Expression")) setClassUnion("ListORExpr", c("list", "Expression")) setClassUnion("NumORgmp", c("numeric", "bigq", "bigz")) setClassUnion("NumORNULL", c("numeric", "NULL")) setClassUnion("NumORLogical", c("logical", "numeric")) setClassUnion("S4ORNULL", c("S4", "NULL")) # Helper function since syntax is different for LinOp (list) vs. Expression object #' @rdname size setMethod("size", "ListORExpr", function(object) { if(is.list(object)) object$size else size(object) }) # Helper function so we can flatten both Expression objects and regular matrices into a single column vector. setMethod("flatten", "numeric", function(object) { matrix(object, ncol = 1) }) # Casts the second argument of a binary operator as an Expression .cast_other <- function(binary_op) { cast_op <- function(object, other) { other <- as.Constant(other) binary_op(object, other) } cast_op } # .value_impl.Expression <- function(object) { object@value } setMethod("value_impl", "Expression", function(object) { object@value }) #' @param x,object An \linkS4class{Expression} object. #' @describeIn Expression The value of the expression. setMethod("value", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression The (sub/super)-gradient of the expression with respect to each variable. setMethod("grad", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression A list of constraints describing the closure of the region where the expression is finite. setMethod("domain", "Expression", function(object) { stop("Unimplemented") }) setMethod("show", "Expression", function(object) { cat("Expression(", curvature(object), ", ", sign(object), ", ", paste(dim(object), collapse = ", "), ")", sep = "") }) #' @describeIn Expression The string representation of the expression. #' @export setMethod("as.character", "Expression", function(x) { paste("Expression(", curvature(x), ", ", sign(x), ", ", paste(dim(x), collapse = ", "), ")", sep = "") }) #' @describeIn Expression The name of the expression. #' @export setMethod("name", "Expression", function(x) { stop("Unimplemented") }) #' @describeIn Expression The expression itself. setMethod("expr", "Expression", function(object) { object }) #' #' Curvature of Expression #' #' The curvature of an expression. #' #' @param object An \linkS4class{Expression} object. #' @return A string indicating the curvature of the expression, either "CONSTANT", "AFFINE", "CONVEX", "CONCAVE", or "UNKNOWN". #' @docType methods #' @rdname curvature #' @export setMethod("curvature", "Expression", function(object) { if(is_constant(object)) curvature_str <- CONSTANT else if(is_affine(object)) curvature_str <- AFFINE else if(is_convex(object)) curvature_str <- CONVEX else if(is_concave(object)) curvature_str <- CONCAVE else curvature_str <- UNKNOWN curvature_str }) #' #' Log-Log Curvature of Expression #' #' The log-log curvature of an expression. #' #' @param object An \linkS4class{Expression} object. #' @return A string indicating the log-log curvature of the expression, either "LOG_LOG_CONSTANT", "LOG_LOG_AFFINE", "LOG_LOG_CONVEX", "LOG_LOG_CONCAVE", or "UNKNOWN". #' @docType methods #' @rdname log_log_curvature #' @export setMethod("log_log_curvature", "Expression", function(object) { if(is_log_log_constant(object)) curvature_str <- LOG_LOG_CONSTANT else if(is_log_log_affine(object)) curvature_str <- LOG_LOG_AFFINE else if(is_log_log_convex(object)) curvature_str <- LOG_LOG_CONVEX else if(is_log_log_concave(object)) curvature_str <- LOG_LOG_CONCAVE else curvature_str <- UNKNOWN curvature_str }) #' @describeIn Expression The expression is constant if it contains no variables or is identically zero. setMethod("is_constant", "Expression", function(object) { length(variables(object)) == 0 || 0 %in% dim(object) }) #' @describeIn Expression The expression is affine if it is constant or both convex and concave. setMethod("is_affine", "Expression", function(object) { is_constant(object) || (is_convex(object) && is_concave(object)) }) #' @describeIn Expression A logical value indicating whether the expression is convex. setMethod("is_convex", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression A logical value indicating whether the expression is concave. setMethod("is_concave", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression The expression is DCP if it is convex or concave. setMethod("is_dcp", "Expression", function(object) { is_convex(object) || is_concave(object) }) #' @describeIn Expression Is the expression log-log constant, i.e., elementwise positive? setMethod("is_log_log_constant", "Expression", function(object) { if(!is_constant(object)) return(FALSE) if(is(object, "Constant") || is(object, "Parameter")) return(is_pos(object)) else return(!is.na(value(object)) && all(value(object) > 0)) }) #' @describeIn Expression Is the expression log-log affine? setMethod("is_log_log_affine", "Expression", function(object) { is_log_log_constant(object) || (is_log_log_convex(object) && is_log_log_concave(object)) }) #' @describeIn Expression Is the expression log-log convex? setMethod("is_log_log_convex", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression Is the expression log-log concave? setMethod("is_log_log_concave", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression The expression is DGP if it is log-log DCP. setMethod("is_dgp", "Expression", function(object) { is_log_log_convex(object) || is_log_log_concave(object) }) #' @describeIn Expression A logical value indicating whether the expression is a Hermitian matrix. setMethod("is_hermitian", "Expression", function(object) { is_real(object) && is_symmetric(object) }) #' @describeIn Expression A logical value indicating whether the expression is a positive semidefinite matrix. setMethod("is_psd", "Expression", function(object) { FALSE }) #' @describeIn Expression A logical value indicating whether the expression is a negative semidefinite matrix. setMethod("is_nsd", "Expression", function(object) { FALSE }) #' @describeIn Expression A logical value indicating whether the expression is quadratic. setMethod("is_quadratic", "Expression", function(object) { is_constant(object) }) #' @describeIn Expression A logical value indicating whether the expression is symmetric. setMethod("is_symmetric", "Expression", function(object) { is_scalar(object) }) #' @describeIn Expression A logical value indicating whether the expression is piecewise linear. setMethod("is_pwl", "Expression", function(object) { is_constant(object) }) #' @describeIn Expression A logical value indicating whether the expression is quadratic of piecewise affine. setMethod("is_qpwa", "Expression", function(object) { is_quadratic(object) || is_pwl(object) }) #' #' Sign of Expression #' #' The sign of an expression. #' #' @param x An \linkS4class{Expression} object. #' @return A string indicating the sign of the expression, either "ZERO", "NONNEGATIVE", "NONPOSITIVE", or "UNKNOWN". #' @docType methods #' @rdname sign #' @export setMethod("sign", "Expression", function(x) { if(!is.na(is_zero(x)) && is_zero(x)) sign_str <- ZERO else if(!is.na(is_nonneg(x)) && is_nonneg(x)) sign_str <- NONNEG else if(!is.na(is_nonpos(x)) && is_nonpos(x)) sign_str <- NONPOS else sign_str <- UNKNOWN sign_str }) #' @describeIn Expression The expression is zero if it is both nonnegative and nonpositive. setMethod("is_zero", "Expression", function(object) { is_nonneg(object) && is_nonpos(object) }) #' @describeIn Expression A logical value indicating whether the expression is nonnegative. setMethod("is_nonneg", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression A logical value indicating whether the expression is nonpositive. setMethod("is_nonpos", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression The \code{c(row, col)} dimensions of the expression. setMethod("dim", "Expression", function(x) { stop("Unimplemented") }) #' @describeIn Expression A logical value indicating whether the expression is real. setMethod("is_real", "Expression", function(object) { !is_complex(object) }) #' @describeIn Expression A logical value indicating whether the expression is imaginary. setMethod("is_imag", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression A logical value indicating whether the expression is complex. setMethod("is_complex", "Expression", function(object) { stop("Unimplemented") }) #' @describeIn Expression The number of entries in the expression. setMethod("size", "Expression", function(object) { as.integer(prod(dim(object))) }) #' @describeIn Expression The number of dimensions of the expression. setMethod("ndim", "Expression", function(object) { length(dim(object)) }) #' @describeIn Expression Vectorizes the expression. setMethod("flatten", "Expression", function(object) { Vec(object) }) #' @describeIn Expression A logical value indicating whether the expression is a scalar. setMethod("is_scalar", "Expression", function(object) { all(dim(object) == 1) }) #' @describeIn Expression A logical value indicating whether the expression is a row or column vector. setMethod("is_vector", "Expression", function(object) { ndim(object) <= 1 || (ndim(object) == 2 && min(dim(object)) == 1) }) #' @describeIn Expression A logical value indicating whether the expression is a matrix. setMethod("is_matrix", "Expression", function(object) { ndim(object) == 2 && nrow(object) > 1 && ncol(object) > 1 }) #' @describeIn Expression Number of rows in the expression. #' @export setMethod("nrow", "Expression", function(x) { dim(x)[1] }) #' @describeIn Expression Number of columns in the expression. #' @export setMethod("ncol", "Expression", function(x) { dim(x)[2] }) # Slice operators #' @param x A \linkS4class{Expression} object. #' @param i,j The row and column indices of the slice. #' @param ... (Unimplemented) Optional arguments. #' @param drop (Unimplemented) A logical value indicating whether the result should be coerced to the lowest possible dimension. #' @rdname Index-class #' @export setMethod("[", signature(x = "Expression", i = "missing", j = "missing", drop = "ANY"), function(x, i, j, ..., drop) { x }) #' @rdname Index-class #' @export setMethod("[", signature(x = "Expression", i = "numeric", j = "missing", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { if(is_vector(x) && nrow(x) < ncol(x)) Index(x, Key(NULL, i)) # If only first index given, apply it along longer dimension of vector else Index(x, Key(i, NULL)) }) #' @rdname Index-class #' @export setMethod("[", signature(x = "Expression", i = "missing", j = "numeric", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { Index(x, Key(NULL, j)) }) #' @rdname Index-class #' @export setMethod("[", signature(x = "Expression", i = "numeric", j = "numeric", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { Index(x, Key(i, j)) }) #' @param i,j The row and column indices of the slice. #' @param ... (Unimplemented) Optional arguments. #' @param drop (Unimplemented) A logical value indicating whether the result should be coerced to the lowest possible dimension. #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "index", j = "missing", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { if(is_vector(x) && nrow(x) < ncol(x)) SpecialIndex(x, Key(NULL, i)) # If only first index given, apply it along longer dimension of vector else SpecialIndex(x, Key(i, NULL)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "missing", j = "index", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { SpecialIndex(x, Key(NULL, j)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "index", j = "index", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { SpecialIndex(x, Key(i, j)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "matrix", j = "index", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { SpecialIndex(x, Key(i, j)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "index", j = "matrix", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { SpecialIndex(x, Key(i, j)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "matrix", j = "matrix", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { SpecialIndex(x, Key(i, j)) }) #' @rdname SpecialIndex-class #' @export setMethod("[", signature(x = "Expression", i = "matrix", j = "missing", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { # This follows conventions in Matrix package, but differs from base handling of matrices SpecialIndex(x, Key(i, NULL)) }) # @rdname Index-class # setMethod("[", signature(x = "Expression", i = "ANY", j = "ANY", drop = "ANY"), function(x, i, j, ..., drop = TRUE) { # stop("Invalid or unimplemented Expression slice operation") # }) # Arithmetic operators #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to add. #' @rdname AddExpression-class setMethod("+", signature(e1 = "Expression", e2 = "missing"), function(e1, e2) { e1 }) #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to subtract. #' @rdname NegExpression-class setMethod("-", signature(e1 = "Expression", e2 = "missing"), function(e1, e2) { NegExpression(expr = e1) }) #' @rdname AddExpression-class setMethod("+", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { AddExpression(arg_groups = list(e1, e2)) }) #' @rdname AddExpression-class setMethod("+", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { AddExpression(arg_groups = list(e1, e2)) }) #' @rdname AddExpression-class setMethod("+", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { e2 + e1 }) #' @rdname NegExpression-class setMethod("-", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { e1 + NegExpression(expr = e2) }) #' @rdname NegExpression-class setMethod("-", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 + (-e2) }) #' @rdname NegExpression-class setMethod("-", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { e1 + NegExpression(expr = e2) }) #' #' Elementwise multiplication operator #' #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to multiply elementwise. #' @docType methods #' @rdname mul_elemwise setMethod("*", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { e1_dim <- dim(e1) e2_dim <- dim(e2) # if(is.null(e1_dim) || is.null(e2_dim) || is_scalar(e1) || is_scalar(e2)) if(is.null(e1_dim) || is.null(e2_dim) || (e1_dim[length(e1_dim)] != e2_dim[1] || e1_dim[1] != e2_dim[length(e2_dim)] && (is_scalar(e1) || is_scalar(e2))) || all(e1_dim == e2_dim)) Multiply(lh_exp = e1, rh_exp = e2) else stop("Incompatible dimensions for elementwise multiplication, use '%*%' for matrix multiplication") }) #' @docType methods #' @rdname mul_elemwise setMethod("*", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { as.Constant(e2) * e1 }) #' @docType methods #' @rdname mul_elemwise setMethod("*", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) * e2 }) #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to divide. The denominator, \code{e2}, must be a scalar constant. #' @rdname DivExpression-class setMethod("/", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { if((is_scalar(e1) || is_scalar(e2)) || all(dim(e1) == dim(e2))) DivExpression(lh_exp = e1, rh_exp = e2) else stop("Incompatible dimensions for division") }) #' @rdname DivExpression-class setMethod("/", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 / as.Constant(e2) }) #' @rdname DivExpression-class setMethod("/", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) / e2 }) #' @param e1 An \linkS4class{Expression} object to exponentiate. #' @param e2 The power of the exponential. Must be a numeric scalar. #' @docType methods #' @rdname power setMethod("^", signature(e1 = "Expression", e2 = "numeric"), function(e1, e2) { Power(x = e1, p = e2) }) # Matrix operators #' Matrix Transpose #' #' The transpose of a matrix. #' #' @param x An \linkS4class{Expression} representing a matrix. #' @return An \linkS4class{Expression} representing the transposed matrix. #' @docType methods #' @aliases t #' @rdname transpose #' @method t Expression #' @export t.Expression <- function(x) { if(ndim(x) <= 1) x else Transpose(x) } # Need S3 method dispatch as well #' @docType methods #' @rdname transpose #' @examples #' x <- Variable(3, 4) #' t(x) #' @export setMethod("t", signature(x = "Expression"), function(x) { if(ndim(x) <= 1) x else Transpose(x) }) #' @param x,y The \linkS4class{Expression} objects or numeric constants to multiply. #' @rdname MulExpression-class setMethod("%*%", signature(x = "Expression", y = "Expression"), function(x, y) { x_dim <- dim(x) y_dim <- dim(y) # if(is.null(x_dim) || is.null(y_dim)) # stop("Scalar operands are not allowed, use '*' instead") # else if(x_dim[length(x_dim)] != y_dim[1] && (is_scalar(x) || is_scalar(y))) # stop("Matrix multiplication is not allowed, use '*' for elementwise multiplication") if(is.null(x_dim) || is.null(y_dim) || is_scalar(x) || is_scalar(y)) # stop("Scalar operands are not allowed, use '*' instead") Multiply(lh_exp = x, rh_exp = y) else if(is_constant(x) || is_constant(y)) MulExpression(lh_exp = x, rh_exp = y) else { warning("Forming a non-convex expression") MulExpression(lh_exp = x, rh_exp = y) } }) #' @rdname MulExpression-class setMethod("%*%", signature(x = "Expression", y = "ConstVal"), function(x, y) { x %*% as.Constant(y) }) #' @rdname MulExpression-class setMethod("%*%", signature(x = "ConstVal", y = "Expression"), function(x, y) { as.Constant(x) %*% y }) # Comparison operators #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to compare. #' @rdname EqConstraint-class setMethod("==", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { EqConstraint(e1, e2) }) #' @rdname EqConstraint-class setMethod("==", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 == as.Constant(e2) }) #' @rdname EqConstraint-class setMethod("==", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) == e2 }) #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to compare. #' @rdname IneqConstraint-class setMethod("<=", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { IneqConstraint(e1, e2) }) #' @rdname IneqConstraint-class setMethod("<=", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 <= as.Constant(e2) }) #' @rdname IneqConstraint-class setMethod("<=", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) <= e2 }) #' @rdname IneqConstraint-class setMethod("<", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { stop("Unimplemented: Strict inequalities are not allowed.") }) #' @rdname IneqConstraint-class setMethod("<", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 < as.Constant(e2) }) #' @rdname IneqConstraint-class setMethod("<", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) < e2 }) #' @rdname IneqConstraint-class setMethod(">=", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { e2 <= e1 }) #' @rdname IneqConstraint-class setMethod(">=", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 >= as.Constant(e2) }) #' @rdname IneqConstraint-class setMethod(">=", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) >= e2 }) #' @rdname IneqConstraint-class setMethod(">", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { stop("Unimplemented: Strict inequalities are not allowed.") }) #' @rdname IneqConstraint-class setMethod(">", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 > as.Constant(e2) }) #' @rdname IneqConstraint-class setMethod(">", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) > e2 }) # Positive definite inequalities #' @param e1,e2 The \linkS4class{Expression} objects or numeric constants to compare. #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%>>%", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { PSDConstraint(e1 - e2) }) #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%>>%", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 %>>% as.Constant(e2) }) #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%>>%", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) %>>% e2 }) #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%<<%", signature(e1 = "Expression", e2 = "Expression"), function(e1, e2) { PSDConstraint(e2 - e1) }) #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%<<%", signature(e1 = "Expression", e2 = "ConstVal"), function(e1, e2) { e1 %<<% as.Constant(e2) }) #' @docType methods #' @rdname PSDConstraint-class #' @export setMethod("%<<%", signature(e1 = "ConstVal", e2 = "Expression"), function(e1, e2) { as.Constant(e1) %<<% e2 }) #' #' The Leaf class. #' #' This class represents a leaf node, i.e. a Variable, Constant, or Parameter. #' #' @slot id (Internal) A unique integer identification number used internally. #' @slot dim The dimensions of the leaf. #' @slot value The numeric value of the leaf. #' @slot nonneg Is the leaf nonnegative? #' @slot nonpos Is the leaf nonpositive? #' @slot complex Is the leaf a complex number? #' @slot imag Is the leaf imaginary? #' @slot symmetric Is the leaf a symmetric matrix? #' @slot diag Is the leaf a diagonal matrix? #' @slot PSD Is the leaf positive semidefinite? #' @slot NSD Is the leaf negative semidefinite? #' @slot hermitian Is the leaf hermitian? #' @slot boolean Is the leaf boolean? Is the variable boolean? May be \code{TRUE} = entire leaf is boolean, \code{FALSE} = entire leaf is not boolean, or a vector of #' indices which should be constrained as boolean, where each index is a vector of length exactly equal to the length of \code{dim}. #' @slot integer Is the leaf integer? The semantics are the same as the \code{boolean} argument. #' @slot sparsity A matrix representing the fixed sparsity pattern of the leaf. #' @slot pos Is the leaf strictly positive? #' @slot neg Is the leaf strictly negative? #' @name Leaf-class #' @aliases Leaf #' @rdname Leaf-class Leaf <- setClass("Leaf", representation(dim = "NumORNULL", value = "ConstVal", nonneg = "logical", nonpos = "logical", complex = "logical", imag = "logical", symmetric = "logical", diag = "logical", PSD = "logical", NSD = "logical", hermitian = "logical", boolean = "NumORLogical", integer = "NumORLogical", sparsity = "matrix", pos = "logical", neg = "logical", attributes = "list", boolean_idx = "matrix", integer_idx = "matrix"), prototype(value = NA_real_, nonneg = FALSE, nonpos = FALSE, complex = FALSE, imag = FALSE, symmetric = FALSE, diag = FALSE, PSD = FALSE, NSD = FALSE, hermitian = FALSE, boolean = FALSE, integer = FALSE, sparsity = matrix(0, nrow = 0, ncol = 1), pos = FALSE, neg = FALSE, attributes = list(), boolean_idx = matrix(0, nrow = 0, ncol = 1), integer_idx = matrix(0, nrow = 0, ncol = 1)), contains = "Expression") setMethod("initialize", "Leaf", function(.Object, ..., dim, value = NA_real_, nonneg = FALSE, nonpos = FALSE, complex = FALSE, imag = FALSE, symmetric = FALSE, diag = FALSE, PSD = FALSE, NSD = FALSE, hermitian = FALSE, boolean = FALSE, integer = FALSE, sparsity = matrix(0, nrow = 0, ncol = 1), pos = FALSE, neg = FALSE, attributes = list(), boolean_idx = matrix(0, nrow = 0, ncol = 1), integer_idx = matrix(0, nrow = 0, ncol = 1)) { if(length(dim) > 2) stop("Expressions of dimension greater than 2 are not supported.") for(d in dim) { if(!intf_is_integer(d) || d <= 0) stop("Invalid dimensions ", dim) } .Object@dim <- as.integer(dim) if((PSD || NSD || symmetric || diag || hermitian) && (length(dim) != 2 || dim[1] != dim[2])) stop("Invalid dimensions ", dim, ". Must be a square matrix.") # Construct matrix of boolean/integer-constrained indices. if(is.logical(boolean)) { if(boolean) .Object@boolean_idx <- as.matrix(do.call(expand.grid, lapply(dim, function(k) { 1:k }))) else .Object@boolean_idx <- matrix(0, nrow = 0, ncol = length(dim)) bool_attr <- boolean } else { .Object@boolean_idx <- boolean bool_attr <- (nrow(boolean) > 0) } if(is.logical(integer)) { if(integer) .Object@integer_idx <- as.matrix(do.call(expand.grid, lapply(dim, function(k) { 1:k }))) else .Object@integer_idx <- matrix(0, nrow = 0, ncol = length(dim)) int_attr <- integer } else { .Object@integer_idx <- integer int_attr <- (nrow(integer) > 0) } # Process attributes. .Object@attributes <- list(nonneg = nonneg, nonpos = nonpos, pos = pos, neg = neg, complex = complex, imag = imag, symmetric = symmetric, diag = diag, PSD = PSD, NSD = NSD, hermitian = hermitian, boolean = bool_attr, integer = int_attr, sparsity = sparsity) # Only one attribute can be TRUE (except boolean and integer). attrs <- .Object@attributes attrs$sparsity <- prod(dim(attrs$sparsity)) != 0 true_attr <- sum(unlist(attrs)) if(bool_attr && int_attr) true_attr <- true_attr - 1 if(true_attr > 1) stop("Cannot set more than one special attribute.") if(!any(is.na(value))) value(.Object) <- value callNextMethod(.Object, ...) }) setMethod("get_attr_str", "Leaf", function(object) { # Get a string representing the attributes attr_str <- "" for(attr in names(object@attributes)) { val <- object@attributes[[attr]] if(attr != "real" && !is.null(val)) { if(nchar(attr_str) == 0) attr_str <- sprintf("%s=%s", attr, val) else attr_str <- paste(attr_str, sprintf("%s=%s", attr, val), sep = ", ") } } attr_str }) # TODO: Get rid of this and just skip calling copy on Leaf objects. setMethod("copy", "Leaf", function(object, args = NULL, id_objects = list()) { # if("id" %in% names(attributes(object)) && as.character(object@id) %in% names(id_objects)) if(!is.na(object@id) && as.character(object@id) %in% names(id_objects)) return(id_objects[[as.character(object@id)]]) return(object) # Leaves are not deep copied. }) #' @param object,x A \linkS4class{Leaf} object. #' @describeIn Leaf Leaves are not copied. setMethod("get_data", "Leaf", function(object) { list() }) #' @describeIn Leaf The dimensions of the leaf node. setMethod("dim", "Leaf", function(x) { x@dim }) #' @describeIn Leaf List of \linkS4class{Variable} objects in the leaf node. setMethod("variables", "Leaf", function(object) { list() }) #' @describeIn Leaf List of \linkS4class{Parameter} objects in the leaf node. setMethod("parameters", "Leaf", function(object) { list() }) #' @describeIn Leaf List of \linkS4class{Constant} objects in the leaf node. setMethod("constants", "Leaf", function(object) { list() }) #' @describeIn Leaf List of \linkS4class{Atom} objects in the leaf node. setMethod("atoms", "Leaf", function(object) { list() }) #' @describeIn Leaf A logical value indicating whether the leaf node is convex. setMethod("is_convex", "Leaf", function(object) { TRUE }) #' @describeIn Leaf A logical value indicating whether the leaf node is concave. setMethod("is_concave", "Leaf", function(object) { TRUE }) #' @describeIn Leaf Is the expression log-log convex? setMethod("is_log_log_convex", "Leaf", function(object) { is_pos(object) }) #' @describeIn Leaf Is the expression log-log concave? setMethod("is_log_log_concave", "Leaf", function(object) { is_pos(object) }) #' @describeIn Leaf A logical value indicating whether the leaf node is nonnegative. setMethod("is_nonneg", "Leaf", function(object) { object@attributes$nonneg || object@attributes$pos || object@attributes$boolean }) #' @describeIn Leaf A logical value indicating whether the leaf node is nonpositive. setMethod("is_nonpos", "Leaf", function(object) { object@attributes$nonpos || object@attributes$neg }) #' @describeIn Leaf Is the expression positive? setMethod("is_pos", "Leaf", function(object) { object@attributes$pos }) #' @describeIn Leaf Is the expression negative? setMethod("is_neg", "Leaf", function(object) { object@attributes$neg }) #' @describeIn Leaf A logical value indicating whether the leaf node is hermitian. setMethod("is_hermitian", "Leaf", function(object) { (is_real(object) && is_symmetric(object)) || object@attributes$hermitian || is_psd(object) || is_nsd(object) }) #' @describeIn Leaf A logical value indicating whether the leaf node is symmetric. setMethod("is_symmetric", "Leaf", function(object) { is_scalar(object) || any(sapply(c("diag", "symmetric", "PSD", "NSD"), function(key) { object@attributes[[key]] })) }) #' @describeIn Leaf A logical value indicating whether the leaf node is imaginary. setMethod("is_imag", "Leaf", function(object) { object@attributes$imag }) #' @describeIn Leaf A logical value indicating whether the leaf node is complex. setMethod("is_complex", "Leaf", function(object) { object@attributes$complex || is_imag(object) || object@attributes$hermitian }) #' @describeIn Leaf A list of constraints describing the closure of the region where the leaf node is finite. Default is the full domain. setMethod("domain", "Leaf", function(object) { domain <- list() if(object@attributes$nonneg) domain <- c(domain, object >= 0) else if(object@attributes$nonpos) domain <- c(domain, object <= 0) else if(object@attributes$PSD) domain <- c(domain, object %>>% 0) else if(object@attributes$NSD) domain <- c(domain, object %<<% 0) return(domain) }) #' @param value A numeric scalar, vector, or matrix. #' @describeIn Leaf Project value onto the attribute set of the leaf. setMethod("project", "Leaf", function(object, value) { if(!is_complex(object)) value <- Re(value) if(object@attributes$nonpos && object@attributes$nonneg) return(0*value) else if(object@attributes$nonpos || object@attributes$neg) return(pmin(value, 0)) else if(object@attributes$nonneg || object@attributes$pos) return(pmax(value, 0)) else if(object@attributes$imag) return(Im(value)*1i) else if(object@attributes$complex) return(as.complex(value)) else if(object@attributes$boolean) # TODO: Respect the boolean indices. return(round(pmax(pmin(value, 1), 0))) else if(object@attributes$integer) # TODO: Respect the integer indices. Also, variable may be integer in some indices and boolean in others. return(round(value)) else if(object@attributes$diag) { val <- diag(value) return(sparseMatrix(i = 1:length(val), j = 1:length(val), x = val)) } else if(object@attributes$hermitian) return((value + t(Conj(value)))/2) else if(any(sapply(c("symmetric", "PSD", "NSD"), function(key) { object@attributes[[key]] }))) { value <- value + t(value) value <- value/2 if(object@attributes$symmetric) return(value) wV <- eigen(value, symmetric = TRUE, only.values = FALSE) w <- wV$values V <- wV$vectors if(object@attributes$PSD) { bad <- w < 0 if(!any(bad)) return(value) w[bad] <- 0 } else { # NSD bad <- w > 0 if(!any(bad)) return(value) w[bad] <- 0 } return((V %*% diag(w)) %*% t(V)) } else return(value) }) #' @describeIn Leaf Project and assign a value to the leaf. setMethod("project_and_assign", "Leaf", function(object, value) { object@value <- project(object, value) return(object) }) #' @describeIn Leaf Get the value of the leaf. setMethod("value", "Leaf", function(object) { object@value }) #' @describeIn Leaf Set the value of the leaf. setReplaceMethod("value", "Leaf", function(object, value) { object@value <- validate_val(object, value) return(object) }) #' @param val The assigned value. #' @describeIn Leaf Check that \code{val} satisfies symbolic attributes of leaf. setMethod("validate_val", "Leaf", function(object, val) { if(!any(is.na(val))) { val <- intf_convert(val) if(any(intf_dim(val) != dim(object))) stop("Invalid dimensions (", paste(intf_dim(val), collapse = ","), ") for value") projection <- project(object, val) delta <- abs(val - projection) if(is(delta, "sparseMatrix")) close_enough <- all(abs(delta@x) <= SPARSE_PROJECTION_TOL) else { delta <- as.matrix(delta) if(object@attributes$PSD || object@attributes$NSD) close_enough <- norm(delta, type = "2") <= PSD_NSD_PROJECTION_TOL else close_enough <- all(abs(delta) <= GENERAL_PROJECTION_TOL) } if(!close_enough) { if(object@attributes$nonneg) attr_str <- "nonnegative" else if(object@attributes$pos) attr_str <- "positive" else if(object@attributes$nonpos) attr_str <- "nonpositive" else if(object@attributes$neg) attr_str <- "negative" else if(object@attributes$diag) attr_str <- "diagonal" else if(object@attributes$PSD) attr_str <- "positive semidefinite" else if(object@attributes$NSD) attr_str <- "negative semidefinite" else if(object@attributes$imag) attr_str <- "imaginary" else { attr_str <- names(object@attributes)[unlist(object@attributes) == 1] attr_str <- c(attr_str, "real")[1] } stop("Value must be ", attr_str) } } return(val) }) #' @describeIn Leaf A logical value indicating whether the leaf node is a positive semidefinite matrix. setMethod("is_psd", "Leaf", function(object) { object@attributes$PSD }) #' @describeIn Leaf A logical value indicating whether the leaf node is a negative semidefinite matrix. setMethod("is_nsd", "Leaf", function(object) { object@attributes$NSD }) #' @describeIn Leaf Leaf nodes are always quadratic. setMethod("is_quadratic", "Leaf", function(object) { TRUE }) #' @describeIn Leaf Leaf nodes are always piecewise linear. setMethod("is_pwl", "Leaf", function(object) { TRUE })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/expressions.R
#' #' Sign Properties #' #' Determine if an expression is positive, negative, or zero. #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @examples #' pos <- Constant(1) #' neg <- Constant(-1) #' zero <- Constant(0) #' unknown <- Variable() #' #' is_zero(pos) #' is_zero(-zero) #' is_zero(unknown) #' is_zero(pos + neg) #' #' is_nonneg(pos + zero) #' is_nonneg(pos * neg) #' is_nonneg(pos - neg) #' is_nonneg(unknown) #' #' is_nonpos(-pos) #' is_nonpos(pos + neg) #' is_nonpos(neg * zero) #' is_nonpos(neg - pos) #' @name sign-methods NULL #' @rdname sign-methods #' @export setGeneric("is_zero", function(object) { standardGeneric("is_zero") }) #' @rdname sign-methods #' @export setGeneric("is_nonneg", function(object) { standardGeneric("is_nonneg") }) #' @rdname sign-methods #' @export setGeneric("is_nonpos", function(object) { standardGeneric("is_nonpos") }) #' #' Complex Properties #' #' Determine if an expression is real, imaginary, or complex. #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @name complex-methods NULL #' @rdname complex-methods #' @export setGeneric("is_real", function(object) { standardGeneric("is_real") }) #' @rdname complex-methods #' @export setGeneric("is_imag", function(object) { standardGeneric("is_imag") }) #' @rdname complex-methods #' @export setGeneric("is_complex", function(object) { standardGeneric("is_complex") }) #' #' Curvature of Expression #' #' The curvature of an expression. #' #' @param object An \linkS4class{Expression} object. #' @return A string indicating the curvature of the expression, either "CONSTANT", "AFFINE", "CONVEX, "CONCAVE", or "UNKNOWN". #' @examples #' x <- Variable() #' c <- Constant(5) #' #' curvature(c) #' curvature(x) #' curvature(x^2) #' curvature(sqrt(x)) #' curvature(log(x^3) + sqrt(x)) #' @docType methods #' @rdname curvature #' @export setGeneric("curvature", function(object) { standardGeneric("curvature") }) #' #' Curvature Properties #' #' Determine if an expression is constant, affine, convex, concave, quadratic, piecewise linear (pwl), or quadratic/piecewise affine (qpwa). #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @examples #' x <- Variable() #' c <- Constant(5) #' #' is_constant(c) #' is_constant(x) #' #' is_affine(c) #' is_affine(x) #' is_affine(x^2) #' #' is_convex(c) #' is_convex(x) #' is_convex(x^2) #' is_convex(sqrt(x)) #' #' is_concave(c) #' is_concave(x) #' is_concave(x^2) #' is_concave(sqrt(x)) #' #' is_quadratic(x^2) #' is_quadratic(sqrt(x)) #' #' is_pwl(c) #' is_pwl(x) #' is_pwl(x^2) #' @name curvature-methods NULL #' @rdname curvature-methods #' @export setGeneric("is_constant", function(object) { standardGeneric("is_constant") }) #' @rdname curvature-methods #' @export setGeneric("is_affine", function(object) { standardGeneric("is_affine") }) #' @rdname curvature-methods #' @export setGeneric("is_convex", function(object) { standardGeneric("is_convex") }) #' @rdname curvature-methods #' @export setGeneric("is_concave", function(object) { standardGeneric("is_concave") }) #' @rdname curvature-methods #' @export setGeneric("is_quadratic", function(object) { standardGeneric("is_quadratic") }) #' @rdname curvature-methods #' @export setGeneric("is_pwl", function(object) { standardGeneric("is_pwl") }) #' @rdname curvature-methods #' @export setGeneric("is_qpwa", function(object) { standardGeneric("is_qpwa") }) #' #' Log-Log Curvature of Expression #' #' The log-log curvature of an expression. #' #' @param object An \linkS4class{Expression} object. #' @return A string indicating the log-log curvature of the expression, either "LOG_LOG_CONSTANT", "LOG_LOG_AFFINE", "LOG_LOG_CONVEX, "LOG_LOG_CONCAVE", or "UNKNOWN". #' @docType methods #' @rdname log_log_curvature setGeneric("log_log_curvature", function(object) { standardGeneric("log_log_curvature") }) #' #' Log-Log Curvature Properties #' #' Determine if an expression is log-log constant, log-log affine, log-log convex, or log-log concave. #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @name log_log_curvature-methods NULL #' @rdname log_log_curvature-methods #' @export setGeneric("is_log_log_constant", function(object) { standardGeneric("is_log_log_constant") }) #' @rdname log_log_curvature-methods #' @export setGeneric("is_log_log_affine", function(object) { standardGeneric("is_log_log_affine") }) #' @rdname log_log_curvature-methods #' @export setGeneric("is_log_log_convex", function(object) { standardGeneric("is_log_log_convex") }) #' @rdname log_log_curvature-methods #' @export setGeneric("is_log_log_concave", function(object) { standardGeneric("is_log_log_concave") }) #' #' DCP Compliance #' #' Determine if a problem or expression complies with the disciplined convex programming rules. #' #' @param object A \linkS4class{Problem} or \linkS4class{Expression} object. #' @return A logical value indicating whether the problem or expression is DCP compliant, i.e. no unknown curvatures. #' @examples #' x <- Variable() #' prob <- Problem(Minimize(x^2), list(x >= 5)) #' is_dcp(prob) #' solve(prob) #' @docType methods #' @rdname is_dcp #' @export setGeneric("is_dcp", function(object) { standardGeneric("is_dcp") }) #' #' DGP Compliance #' #' Determine if a problem or expression complies with the disciplined geometric programming rules. #' #' @param object A \linkS4class{Problem} or \linkS4class{Expression} object. #' @return A logical value indicating whether the problem or expression is DCP compliant, i.e. no unknown curvatures. #' @examples #' x <- Variable(pos = TRUE) #' y <- Variable(pos = TRUE) #' prob <- Problem(Minimize(x*y), list(x >= 5, y >= 5)) #' is_dgp(prob) #' solve(prob, gp = TRUE) #' @docType methods #' @rdname is_dgp #' @export setGeneric("is_dgp", function(object) { standardGeneric("is_dgp") }) #' #' Size of Expression #' #' The size of an expression. #' #' @param object An \linkS4class{Expression} object. #' @return A vector with two elements \code{c(row, col)} representing the dimensions of the expression. #' @examples #' x <- Variable() #' y <- Variable(3) #' z <- Variable(3,2) #' #' size(x) #' size(y) #' size(z) #' size(x + y) #' size(z - x) #' @docType methods #' @rdname size #' @export setGeneric("size", function(object) { standardGeneric("size") }) #' #' Size Properties #' #' Determine if an expression is a scalar, vector, or matrix. #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @examples #' x <- Variable() #' y <- Variable(3) #' z <- Variable(3,2) #' #' is_scalar(x) #' is_scalar(y) #' is_scalar(x + y) #' #' is_vector(x) #' is_vector(y) #' is_vector(2*z) #' #' is_matrix(x) #' is_matrix(y) #' is_matrix(z) #' is_matrix(z - x) #' @name size-methods NULL #' @rdname size-methods #' @export setGeneric("is_scalar", function(object) { standardGeneric("is_scalar") }) #' @rdname size-methods #' @export setGeneric("is_vector", function(object) { standardGeneric("is_vector") }) #' @rdname size-methods #' @export setGeneric("is_matrix", function(object) { standardGeneric("is_matrix") }) #' #' Matrix Properties #' #' Determine if an expression is positive semidefinite, negative semidefinite, hermitian, and/or symmetric. #' #' @param object An \linkS4class{Expression} object. #' @return A logical value. #' @name matrix_prop-methods NULL #' @rdname matrix_prop-methods #' @export setGeneric("is_psd", function(object) { standardGeneric("is_psd") }) #' @rdname matrix_prop-methods #' @export setGeneric("is_nsd", function(object) { standardGeneric("is_nsd") }) #' @rdname matrix_prop-methods #' @export setGeneric("is_hermitian", function(object) { standardGeneric("is_hermitian") }) #' @rdname matrix_prop-methods #' @export setGeneric("is_symmetric", function(object) { standardGeneric("is_symmetric") }) # The value of the objective given the solver primal value. setGeneric("primal_to_result", function(object, result) { standardGeneric("primal_to_result") }) #' #' Get or Set Value #' #' Get or set the value of a variable, parameter, expression, or problem. #' #' @param object A \linkS4class{Variable}, \linkS4class{Parameter}, \linkS4class{Expression}, or \linkS4class{Problem} object. #' @param value A numeric scalar, vector, or matrix to assign to the object. #' @return The numeric value of the variable, parameter, or expression. If any part of the mathematical object is unknown, return \code{NA}. #' @examples #' lambda <- Parameter() #' value(lambda) #' #' value(lambda) <- 5 #' value(lambda) #' @name value-methods NULL #' @rdname value-methods #' @export setGeneric("value", function(object) { standardGeneric("value") }) #' @rdname value-methods #' @export setGeneric("value<-", function(object, value) { standardGeneric("value<-") }) # Internal method for saving the value of an expression setGeneric("save_value", function(object, value) { standardGeneric("save_value") }) #' #' Is Constraint Violated? #' #' Checks whether the constraint violation is less than a tolerance. #' #' @param object A \linkS4class{Constraint} object. #' @param tolerance A numeric scalar representing the absolute tolerance to impose on the violation. #' @return A logical value indicating whether the violation is less than the \code{tolerance}. Raises an error if the residual is \code{NA}. #' @docType methods #' @rdname constr_value #' @export setGeneric("constr_value", function(object, tolerance = 1e-8) { standardGeneric("constr_value") }) #' #' Get Expression Data #' #' Get information needed to reconstruct the expression aside from its arguments. #' #' @param object A \linkS4class{Expression} object. #' @return A list containing data. #' @docType methods #' @rdname get_data #' @export setGeneric("get_data", function(object) { standardGeneric("get_data") }) #' #' Variable, Parameter, or Expression Name #' #' The string representation of a variable, parameter, or expression. #' #' @param x A \linkS4class{Variable}, \linkS4class{Parameter}, or \linkS4class{Expression} object. #' @return For \linkS4class{Variable} or \linkS4class{Parameter} objects, the value in the name slot. For \linkS4class{Expression} objects, a string indicating the nested atoms and their respective arguments. #' @docType methods #' @rdname name #' @examples #' x <- Variable() #' y <- Variable(3, name = "yVar") #' #' name(x) #' name(y) #' @export setGeneric("name", function(x) { standardGeneric("name") }) #' #' Parts of an Expression Leaf #' #' List the variables, parameters, constants, or atoms in a canonical expression. #' #' @param object A \linkS4class{Leaf} object. #' @return A list of \linkS4class{Variable}, \linkS4class{Parameter}, \linkS4class{Constant}, or \linkS4class{Atom} objects. #' @examples #' set.seed(67) #' m <- 50 #' n <- 10 #' beta <- Variable(n) #' y <- matrix(rnorm(m), nrow = m) #' X <- matrix(rnorm(m*n), nrow = m, ncol = n) #' lambda <- Parameter() #' #' expr <- sum_squares(y - X %*% beta) + lambda*p_norm(beta, 1) #' variables(expr) #' parameters(expr) #' constants(expr) #' lapply(constants(expr), function(c) { value(c) }) #' @name expression-parts NULL #' @rdname expression-parts #' @export setGeneric("variables", function(object) { standardGeneric("variables") }) #' @rdname expression-parts #' @export setGeneric("parameters", function(object) { standardGeneric("parameters") }) #' @rdname expression-parts #' @export setGeneric("constants", function(object) { standardGeneric("constants") }) #' @rdname expression-parts #' @export setGeneric("atoms", function(object) { standardGeneric("atoms") }) #' #' Attributes of an Expression Leaf #' #' Determine if an expression is positive or negative. #' #' @param object A \linkS4class{Leaf} object. #' @return A logical value. #' @name leaf-attr NULL #' @rdname leaf-attr #' @export setGeneric("is_pos", function(object) { standardGeneric("is_pos") }) #' @rdname leaf-attr #' @export setGeneric("is_neg", function(object) { standardGeneric("is_neg") }) #' #' Sub/Super-Gradient #' #' The (sub/super)-gradient of the expression with respect to each variable. #' Matrix expressions are vectorized, so the gradient is a matrix. \code{NA} indicates variable values are unknown or outside the domain. #' #' @param object An \linkS4class{Expression} object. #' @return A list mapping each variable to a sparse matrix. #' @examples #' x <- Variable(2, name = "x") #' A <- Variable(2, 2, name = "A") #' #' value(x) <- c(-3,4) #' expr <- p_norm(x, 2) #' grad(expr) #' #' value(A) <- rbind(c(3,-4), c(4,3)) #' expr <- p_norm(A, 0.5) #' grad(expr) #' #' value(A) <- cbind(c(1,2), c(-1,0)) #' expr <- abs(A) #' grad(expr) #' @docType methods #' @rdname grad #' @export setGeneric("grad", function(object) { standardGeneric("grad") }) #' #' Domain #' #' A list of constraints describing the closure of the region where the expression is finite. #' #' @param object An \linkS4class{Expression} object. #' @return A list of \linkS4class{Constraint} objects. #' @examples #' a <- Variable(name = "a") #' dom <- domain(p_norm(a, -0.5)) #' prob <- Problem(Minimize(a), dom) #' result <- solve(prob) #' result$value #' #' b <- Variable() #' dom <- domain(kl_div(a, b)) #' result <- solve(Problem(Minimize(a + b), dom)) #' result$getValue(a) #' result$getValue(b) #' #' A <- Variable(2, 2, name = "A") #' dom <- domain(lambda_max(A)) #' A0 <- rbind(c(1,2), c(3,4)) #' result <- solve(Problem(Minimize(norm2(A - A0)), dom)) #' result$getValue(A) #' #' dom <- domain(log_det(A + diag(rep(1,2)))) #' prob <- Problem(Minimize(sum(diag(A))), dom) #' result <- solve(prob, solver = "SCS") #' result$value #' @docType methods #' @rdname domain #' @export setGeneric("domain", function(object) { standardGeneric("domain") }) #' #' Project Value #' #' Project a value onto the attribute set of a \linkS4class{Leaf}. #' A sensible idiom is \code{value(leaf) = project(leaf, val)}. #' #' @param object A \linkS4class{Leaf} object. #' @param value The assigned value. #' @return The value rounded to the attribute type. #' @name project-methods NULL #' #' Project a value onto the attribute set of a \linkS4class{Leaf}. #' #' @rdname project-methods #' @export setGeneric("project", function(object, value) { standardGeneric("project") }) #' #' Projects and assigns a value onto the attribute set of a \linkS4class{Leaf}. #' #' @rdname project-methods #' @export setGeneric("project_and_assign", function(object, value) { standardGeneric("project_and_assign") }) #' #' Validate Value #' #' Check that the value satisfies a \linkS4class{Leaf}'s symbolic attributes. #' #' @param object A \linkS4class{Leaf} object. #' @param val The assigned value. #' @return The value converted to proper matrix type. #' @docType methods #' @rdname validate_val setGeneric("validate_val", function(object, val) { standardGeneric("validate_val") }) #' #' Canonicalize #' #' Computes the graph implementation of a canonical expression. #' #' @param object A \linkS4class{Canonical} object. #' @return A list of \code{list(affine expression, list(constraints))}. #' @docType methods #' @name canonicalize NULL #' @rdname canonicalize #' @export setGeneric("canonicalize", function(object) { standardGeneric("canonicalize") }) #' @rdname canonicalize setGeneric("canonical_form", function(object) { standardGeneric("canonical_form") }) # # Gradient of an Atom # # The (sub/super) gradient of the atom with respect to each argument. Matrix expressions are vectorized, so the gradient is a matrix. # # @param object An \linkS4class{Atom} object. # @param values A list of numeric values for the arguments. # @return A list of sparse matrices or \code{NA}. setGeneric(".grad", function(object, values) { standardGeneric(".grad") }) # # Domain of an Atom # # The constraints describing the domain of the atom. # # @param object An \linkS4class{Atom} object. # @return A list of \linkS4class{Constraint} objects. setGeneric(".domain", function(object) { standardGeneric(".domain") }) # # Gradient of an AxisAtom # # The (sub/super) gradient of the atom with respect to each argument. Matrix expressions are vectorized, so the gradient is a matrix. Takes the axis into account. # # @param values A list of numeric values for the arguments. # @return A list of sparse matrices or \code{NA}. setGeneric(".axis_grad", function(object, values) { standardGeneric(".axis_grad") }) # # Column Gradient of an Atom # # The (sub/super) gradient of the atom with respect to a column argument. Matrix expressions are vectorized, so the gradient is a matrix. # @param value A numeric value for a column. # @return A sparse matrix or \code{NA}. setGeneric(".column_grad", function(object, value) { standardGeneric(".column_grad") }) # Positive definite inequalities #' @rdname PSDConstraint-class #' @export setGeneric("%>>%", function(e1, e2) { standardGeneric("%>>%") }) #' @rdname PSDConstraint-class #' @export setGeneric("%<<%", function(e1, e2) { standardGeneric("%<<%") }) #' #' Atom Dimensions #' #' Determine the dimensions of an atom based on its arguments. #' #' @param object A \linkS4class{Atom} object. #' @return A numeric vector \code{c(row, col)} indicating the dimensions of the atom. #' @rdname dim_from_args setGeneric("dim_from_args", function(object) { standardGeneric("dim_from_args") }) #' #' Atom Sign #' #' Determine the sign of an atom based on its arguments. #' #' @param object An \linkS4class{Atom} object. #' @return A logical vector \code{c(is positive, is negative)} indicating the sign of the atom. #' @rdname sign_from_args setGeneric("sign_from_args", function(object) { standardGeneric("sign_from_args") }) #' #' Validate Arguments #' #' Validate an atom's arguments, returning an error if any are invalid. #' #' @param object An \linkS4class{Atom} object. #' @docType methods #' @rdname validate_args setGeneric("validate_args", function(object) { standardGeneric("validate_args") }) #' #' Numeric Value of Atom #' #' Returns the numeric value of the atom evaluated on the specified arguments. #' #' @param object An \linkS4class{Atom} object. #' @param values A list of arguments to the atom. #' @return A numeric scalar, vector, or matrix. #' @docType methods #' @rdname to_numeric setGeneric("to_numeric", function(object, values) { standardGeneric("to_numeric") }) #' #' Curvature of an Atom #' #' Determine if an atom is convex, concave, or affine. #' #' @param object A \linkS4class{Atom} object. #' @return A logical value. #' @examples #' x <- Variable() #' #' is_atom_convex(x^2) #' is_atom_convex(sqrt(x)) #' is_atom_convex(log(x)) #' #' is_atom_concave(-abs(x)) #' is_atom_concave(x^2) #' is_atom_concave(sqrt(x)) #' #' is_atom_affine(2*x) #' is_atom_affine(x^2) #' @name curvature-atom NULL #' @rdname curvature-atom #' @export setGeneric("is_atom_convex", function(object) { standardGeneric("is_atom_convex") }) #' @rdname curvature-atom #' @export setGeneric("is_atom_concave", function(object) { standardGeneric("is_atom_concave") }) #' @rdname curvature-atom #' @export setGeneric("is_atom_affine", function(object) { standardGeneric("is_atom_affine") }) #' #' Log-Log Curvature of an Atom #' #' Determine if an atom is log-log convex, concave, or affine. #' #' @param object A \linkS4class{Atom} object. #' @return A logical value. #' @name log_log_curvature-atom NULL #' @rdname log_log_curvature-atom #' @export setGeneric("is_atom_log_log_convex", function(object) { standardGeneric("is_atom_log_log_convex") }) #' @rdname log_log_curvature-atom #' @export setGeneric("is_atom_log_log_concave", function(object) { standardGeneric("is_atom_log_log_concave") }) #' @rdname log_log_curvature-atom #' @export setGeneric("is_atom_log_log_affine", function(object) { standardGeneric("is_atom_log_log_affine") }) #' #' Curvature of Composition #' #' Determine whether a composition is non-decreasing or non-increasing in an index. #' #' @param object A \linkS4class{Atom} object. #' @param idx An index into the atom. #' @return A logical value. #' @examples #' x <- Variable() #' is_incr(log(x), 1) #' is_incr(x^2, 1) #' is_decr(min(x), 1) #' is_decr(abs(x), 1) #' @name curvature-comp NULL #' @rdname curvature-comp #' @export setGeneric("is_incr", function(object, idx) { standardGeneric("is_incr") }) #' @rdname curvature-comp #' @export setGeneric("is_decr", function(object, idx) { standardGeneric("is_decr") }) #' #' Graph Implementation #' #' Reduces the atom to an affine expression and list of constraints. #' #' @param object An \linkS4class{Expression} object. #' @param arg_objs A list of linear expressions for each argument. #' @param dim A vector representing the dimensions of the resulting expression. #' @param data A list of additional data required by the atom. #' @return A list of \code{list(LinOp for objective, list of constraints)}, where LinOp is a list representing the linear operator. #' @docType methods #' @rdname graph_implementation setGeneric("graph_implementation", function(object, arg_objs, dim, data) { standardGeneric("graph_implementation") }) #' #' Identification Number #' #' A unique identification number used internally to keep track of variables and constraints. Should not be modified by the user. #' #' @param object A \linkS4class{Variable} or \linkS4class{Constraint} object. #' @return A non-negative integer identifier. #' @seealso \code{\link[CVXR]{get_id}} \code{\link[CVXR]{setIdCounter}} #' @examples #' x <- Variable() #' constr <- (x >= 5) #' id(x) #' id(constr) #' @docType methods #' @rdname id #' @export setGeneric("id", function(object) { standardGeneric("id") }) #' #' Constraint Residual #' #' The residual expression of a constraint, i.e. the amount by which it is violated, and the value of that violation. #' For instance, if our constraint is \eqn{g(x) \leq 0}, the residual is \eqn{max(g(x), 0)} applied elementwise. #' #' @param object A \linkS4class{Constraint} object. #' @return A \linkS4class{Expression} representing the residual, or the value of this expression. #' @docType methods #' @name residual-methods NULL #' @rdname residual-methods #' @export setGeneric("residual", function(object) { standardGeneric("residual") }) #' @rdname residual-methods #' @export setGeneric("violation", function(object) { standardGeneric("violation") }) #' #' Second-Order Cone Methods #' #' The number of elementwise cones or a list of the sizes of the elementwise cones. #' #' @param object An \linkS4class{SOCAxis} object. #' @return The number of cones, or the size of a cone. #' @docType methods #' @name cone-methods NULL #' @rdname cone-methods setGeneric("num_cones", function(object) { standardGeneric("num_cones") }) #' @rdname cone-methods setGeneric("cone_sizes", function(object) { standardGeneric("cone_sizes") }) #' #' Get and Set Dual Value #' #' Get and set the value of the dual variable in a constraint. #' #' @param object A \linkS4class{Constraint} object. #' @param value A numeric scalar, vector, or matrix to assign to the object. #' @name dual_value-methods NULL #' #' Get and set the value of the dual variable in a constraint. #' #' @rdname dual_value-methods #' @export setGeneric("dual_value", function(object) { standardGeneric("dual_value") }) #' @rdname dual_value-methods #' @export setGeneric("dual_value<-", function(object, value) { standardGeneric("dual_value<-") }) #' #' Format Constraints #' #' Format constraints for the solver. #' #' @param object A \linkS4class{Constraint} object. #' @param eq_constr A list of the equality constraints in the canonical problem. #' @param leq_constr A list of the inequality constraints in the canonical problem. #' @param dims A list with the dimensions of the conic constraints. #' @param solver A string representing the solver to be called. #' @return A list containing equality constraints, inequality constraints, and dimensions. #' @rdname format_constr setGeneric("format_constr", function(object, eq_constr, leq_constr, dims, solver) { standardGeneric("format_constr") }) # Constraint generic methods setGeneric("constr_type", function(object) { standardGeneric("constr_type") }) setGeneric("constr_id", function(object) { standardGeneric("constr_id") }) # Nonlinear constraint generic methods setGeneric("block_add", function(object, mat, block, vert_offset, horiz_offset, rows, cols, vert_step, horiz_step) { standardGeneric("block_add") }) setGeneric("place_x0", function(object, big_x, var_offsets) { standardGeneric("place_x0") }) setGeneric("place_Df", function(object, big_Df, Df, var_offsets, vert_offset) { standardGeneric("place_Df") }) setGeneric("place_H", function(object, big_H, H, var_offsets) { standardGeneric("place_H") }) setGeneric("extract_variables", function(object, x, var_offsets) { standardGeneric("extract_variables") }) # Problem generic methods #' #' Parts of a Problem #' #' Get and set the objective, constraints, or size metrics (get only) of a problem. #' #' @param object A \linkS4class{Problem} object. #' @param value The value to assign to the slot. #' @return For getter functions, the requested slot of the object. #' x <- Variable() #' prob <- Problem(Minimize(x^2), list(x >= 5)) #' objective(prob) #' constraints(prob) #' size_metrics(prob) #' #' objective(prob) <- Maximize(sqrt(x)) #' constraints(prob) <- list(x <= 10) #' objective(prob) #' constraints(prob) #' @name problem-parts NULL #' @rdname problem-parts #' @export setGeneric("objective", function(object) { standardGeneric("objective") }) #' @rdname problem-parts #' @export setGeneric("objective<-", function(object, value) { standardGeneric("objective<-") }) #' @rdname problem-parts #' @export setGeneric("constraints", function(object) { standardGeneric("constraints") }) #' @rdname problem-parts #' @export setGeneric("constraints<-", function(object, value) { standardGeneric("constraints<-") }) #' @rdname problem-parts #' @export setGeneric("size_metrics", function(object) { standardGeneric("size_metrics") }) setGeneric("status", function(object) { standardGeneric("status") }) setGeneric("status<-", function(object, value) { standardGeneric("status<-") }) setGeneric("solver_stats", function(object) { standardGeneric("solver_stats") }) setGeneric("solver_stats<-", function(object, value) { standardGeneric("solver_stats<-") }) #' #' Get Problem Data #' #' Get the problem data used in the call to the solver. #' #' @param object A \linkS4class{Problem} object. #' @param solver A string indicating the solver that the problem data is for. Call \code{installed_solvers()} to see all available. #' @param gp (Optional) A logical value indicating whether the problem is a geometric program. #' @return A list containing the data for the solver, the solving chain for the problem, and the inverse data needed to invert the solution. #' @examples #' a <- Variable(name = "a") #' data <- get_problem_data(Problem(Minimize(exp(a) + 2)), "SCS")[[1]] #' data[["dims"]] #' data[["c"]] #' data[["A"]] #' #' x <- Variable(2, name = "x") #' data <- get_problem_data(Problem(Minimize(p_norm(x) + 3)), "ECOS")[[1]] #' data[["dims"]] #' data[["c"]] #' data[["A"]] #' data[["G"]] #' @rdname get_problem_data #' @export setGeneric("get_problem_data", function(object, solver, gp) { standardGeneric("get_problem_data") }) #' #' Solve a DCP Problem #' #' Solve a DCP compliant optimization problem. #' #' @param object,a A \linkS4class{Problem} object. #' @param solver,b (Optional) A string indicating the solver to use. Defaults to "ECOS". #' @param ignore_dcp (Optional) A logical value indicating whether to override the DCP check for a problem. #' @param warm_start (Optional) A logical value indicating whether the previous solver result should be used to warm start. #' @param verbose (Optional) A logical value indicating whether to print additional solver output. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param parallel (Optional) A logical value indicating whether to solve in parallel if the problem is separable. #' @param gp (Optional) A logical value indicating whether the problem is a geometric program. Defaults to \code{FALSE}. #' @param ... Additional options that will be passed to the specific solver. In general, these options will override any default settings imposed by CVXR. #' @return A list containing the solution to the problem: #' \describe{ #' \item{\code{status}}{The status of the solution. Can be "optimal", "optimal_inaccurate", "infeasible", "infeasible_inaccurate", "unbounded", "unbounded_inaccurate", or "solver_error".} #' \item{\code{value}}{The optimal value of the objective function.} #' \item{\code{solver}}{The name of the solver.} #' \item{\code{solve_time}}{The time (in seconds) it took for the solver to solve the problem.} #' \item{\code{setup_time}}{The time (in seconds) it took for the solver to set up the problem.} #' \item{\code{num_iters}}{The number of iterations the solver had to go through to find a solution.} #' \item{\code{getValue}}{A function that takes a \linkS4class{Variable} object and retrieves its primal value.} #' \item{\code{getDualValue}}{A function that takes a \linkS4class{Constraint} object and retrieves its dual value(s).} #' } #' @examples #' a <- Variable(name = "a") #' prob <- Problem(Minimize(norm_inf(a)), list(a >= 2)) #' result <- psolve(prob, solver = "ECOS", verbose = TRUE) #' result$status #' result$value #' result$getValue(a) #' result$getDualValue(constraints(prob)[[1]]) #' @docType methods #' @aliases psolve solve #' @rdname psolve #' @export setGeneric("psolve", function(object, solver = NA, ignore_dcp = FALSE, warm_start = FALSE, verbose = FALSE, parallel = FALSE, gp = FALSE, feastol = NULL, reltol = NULL, abstol = NULL, num_iter = NULL, ...) { standardGeneric("psolve") }) #' #' Is Problem a QP? #' #' Determine if a problem is a quadratic program. #' #' @param object A \linkS4class{Problem} object. #' @return A logical value indicating whether the problem is a quadratic program. #' @docType methods #' @rdname is_qp #' @export setGeneric("is_qp", function(object) { standardGeneric("is_qp") }) #' #' Is Problem Mixed Integer? #' #' Determine if a problem is a mixed-integer program. #' #' @param object A \linkS4class{Problem} object. #' @return A logical value indicating whether the problem is a mixed-integer program #' @docType methods #' @rdname is_mixed_integer #' @export setGeneric("is_mixed_integer", function(object) { standardGeneric("is_mixed_integer") }) #' #' Parse output from a solver and updates problem state #' #' Updates problem status, problem value, and primal and dual variable values #' #' @param object A \linkS4class{Problem} object. #' @param solution A \linkS4class{Solution} object. #' @param chain The corresponding solving \linkS4class{Chain}. #' @param inverse_data A \linkS4class{InverseData} object or list containing data necessary for the inversion. #' @return A list containing the solution to the problem: #' \describe{ #' \item{\code{status}}{The status of the solution. Can be "optimal", "optimal_inaccurate", "infeasible", "infeasible_inaccurate", "unbounded", "unbounded_inaccurate", or "solver_error".} #' \item{\code{value}}{The optimal value of the objective function.} #' \item{\code{solver}}{The name of the solver.} #' \item{\code{solve_time}}{The time (in seconds) it took for the solver to solve the problem.} #' \item{\code{setup_time}}{The time (in seconds) it took for the solver to set up the problem.} #' \item{\code{num_iters}}{The number of iterations the solver had to go through to find a solution.} #' \item{\code{getValue}}{A function that takes a \linkS4class{Variable} object and retrieves its primal value.} #' \item{\code{getDualValue}}{A function that takes a \linkS4class{Constraint} object and retrieves its dual value(s).} #' } #' @examples #' \dontrun{ #' x <- Variable(2) #' obj <- Minimize(x[1] + cvxr_norm(x, 1)) #' constraints <- list(x >= 2) #' prob1 <- Problem(obj, constraints) #' # Solve with ECOS. #' ecos_data <- get_problem_data(prob1, "ECOS") #' # Call ECOS solver interface directly #' ecos_output <- ECOSolveR::ECOS_csolve( #' c = ecos_data[["c"]], #' G = ecos_data[["G"]], #' h = ecos_data[["h"]], #' dims = ecos_data[["dims"]], #' A = ecos_data[["A"]], #' b = ecos_data[["b"]] #' ) #' # Unpack raw solver output. #' res1 <- unpack_results(prob1, "ECOS", ecos_output) #' # Without DCP validation (so be sure of your math), above is equivalent to: #' # res1 <- solve(prob1, solver = "ECOS") #' X <- Variable(2,2, PSD = TRUE) #' Fmat <- rbind(c(1,0), c(0,-1)) #' obj <- Minimize(sum_squares(X - Fmat)) #' prob2 <- Problem(obj) #' scs_data <- get_problem_data(prob2, "SCS") #' scs_output <- scs::scs( #' A = scs_data[['A']], #' b = scs_data[['b']], #' obj = scs_data[['c']], #' cone = scs_data[['dims']] #' ) #' res2 <- unpack_results(prob2, "SCS", scs_output) #' # Without DCP validation (so be sure of your math), above is equivalent to: #' # res2 <- solve(prob2, solver = "SCS") #' } #' @docType methods #' @rdname unpack_results #' @export setGeneric("unpack_results", function(object, solver, results_dict) { standardGeneric("unpack_results") }) setGeneric(".handle_no_solution", function(object, status) { standardGeneric(".handle_no_solution") }) setGeneric("Problem.save_values", function(object, result_vec, objstore, offset_map) { standardGeneric("Problem.save_values") }) setGeneric(".save_dual_values", function(object, result_vec, constraints, constr_types) { standardGeneric(".save_dual_values") }) setGeneric(".update_problem_state", function(object, results_dict, sym_data, solver) { standardGeneric(".update_problem_state") }) # Problem data generic methods setGeneric("get_objective", function(object) { standardGeneric("get_objective") }) setGeneric("get_eq_constr", function(object) { standardGeneric("get_eq_constr") }) setGeneric("get_ineq_constr", function(object) { standardGeneric("get_ineq_constr") }) setGeneric("get_nonlin_constr", function(object) { standardGeneric("get_nonlin_constr") }) # Solver generic methods #' #' Import Solver #' #' Import the R library that interfaces with the specified solver. #' #' @param solver A \linkS4class{ReductionSolver} object. #' @examples #' import_solver(ECOS()) #' import_solver(SCS()) #' @rdname import_solver #' @docType methods #' @export setGeneric("import_solver", function(solver) { standardGeneric("import_solver") }) setGeneric("is_installed", function(solver) { standardGeneric("is_installed") }) #' #' Solver Capabilities #' #' Determine if a solver is capable of solving a mixed-integer program (MIP). #' #' @param solver A \linkS4class{ReductionSolver} object. #' @return A logical value. #' @examples #' mip_capable(ECOS()) #' @rdname mip_capable #' @docType methods #' @export setGeneric("mip_capable", function(solver) { standardGeneric("mip_capable") }) # Map of solver status code to CVXR status. setGeneric("status_map", function(solver, status) { standardGeneric("status_map") }) # Map of CBC MIP/LP status to CVXR status. setGeneric("status_map_mip", function(solver, status) { standardGeneric("status_map_mip") }) setGeneric("status_map_lp", function(solver, status) { standardGeneric("status_map_lp") }) #' #' Reduction Acceptance #' #' Determine whether the reduction accepts a problem. #' #' @param object A \linkS4class{Reduction} object. #' @param problem A \linkS4class{Problem} to check. #' @return A logical value indicating whether the reduction can be applied. #' @docType methods #' @rdname accepts setGeneric("accepts", function(object, problem) { standardGeneric("accepts") }) #' #' Reduce a Problem #' #' Reduces the owned problem to an equivalent problem. #' #' @param object A \linkS4class{Reduction} object. #' @return An equivalent problem, encoded either as a \linkS4class{Problem} object or a list. #' @docType methods #' @rdname reduce setGeneric("reduce", function(object) { standardGeneric("reduce") }) #' #' Retrieve Solution #' #' Retrieves a solution to the owned problem. #' #' @param object A \linkS4class{Reduction} object. #' @param solution A \linkS4class{Solution} object. #' @return A \linkS4class{Solution} to the problem emitted by \code{\link{reduce}}. #' @docType methods #' @rdname retrieve setGeneric("retrieve", function(object, solution) { standardGeneric("retrieve") }) #' #' Perform Reduction #' #' Performs the reduction on a problem and returns an equivalent problem. #' #' @param object A \linkS4class{Reduction} object. #' @param problem A \linkS4class{Problem} on which the reduction will be performed. #' @return A list containing #' \describe{ #' \item{"problem"}{A \linkS4class{Problem} or list representing the equivalent problem.} #' \item{"inverse_data"}{A \linkS4class{InverseData} or list containing the data needed to invert this particular reduction.} #' } #' @docType methods #' @rdname perform setGeneric("perform", function(object, problem) { standardGeneric("perform") }) #' #' Return Original Solution #' #' Returns a solution to the original problem given the inverse data. #' #' @param object A \linkS4class{Reduction} object. #' @param solution A \linkS4class{Solution} to a problem that generated \code{inverse_data}. #' @param inverse_data A \linkS4class{InverseData} object encoding the original problem. #' @return A \linkS4class{Solution} to the original problem. #' @docType methods #' @rdname invert setGeneric("invert", function(object, solution, inverse_data) { standardGeneric("invert") }) ##setGeneric("alt_invert", function(object, results, inverse_data) { standardGeneric("alt_invert") }) ## Version 1.0 edits setGeneric("square", function(x) { standardGeneric("square") }) ## Start of newly added generics setGeneric("expr", function(object) { standardGeneric("expr") }) setGeneric("ndim", function(object) { standardGeneric("ndim") }) setGeneric("flatten", function(object) { standardGeneric("flatten") }) setGeneric("value_impl", function(object) { standardGeneric("value_impl") }) setGeneric("var_id", function(object) { standardGeneric("var_id") }) setGeneric("get_attr_str", function(object) { standardGeneric("get_attr_str") }) setGeneric("get_var_offsets", function(object, variables) { standardGeneric("get_var_offsets") }) setGeneric("allow_complex", function(object) { standardGeneric("allow_complex") }) setGeneric("canonicalize_tree", function(object, expr) { standardGeneric("canonicalize_tree") }) setGeneric("canonicalize_expr", function(object, expr, args) { standardGeneric("canonicalize_expr") }) setGeneric("stuffed_objective", function(object, problem, extractor) { standardGeneric("stuffed_objective") }) setGeneric("prepend", function(object, chain) { standardGeneric("prepend") }) setGeneric("group_coeff_offset", function(object, problem, constraints, exp_cone_order) { standardGeneric("group_coeff_offset") }) setGeneric("construct_intermediate_chain", function(problem, candidates, gp) { standardGeneric("construct_intermediate_chain") }) setGeneric("solve_via_data", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { standardGeneric("solve_via_data") }) setGeneric("unpack_problem", function(object, solution) { standardGeneric("unpack_problem") }) setGeneric("unpack_results", function(object, solution, chain, inverse_data) { standardGeneric("unpack_results") }) setGeneric(".construct_dual_variables", function(object, args) { standardGeneric(".construct_dual_variables") }) setGeneric("reduction_solve", function(object, problem, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts) { standardGeneric("reduction_solve") }) setGeneric("reduction_solve_via_data", function(object, problem, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts) { standardGeneric("reduction_solve_via_data") }) setGeneric("reduction_format_constr", function(object, problem, constr, exp_cone_order) { standardGeneric("reduction_format_constr") }) setGeneric("block_format", function(object, problem, constraints, exp_cone_order) { standardGeneric("block_format") }) setGeneric("suitable", function(solver, problem) { standardGeneric("suitable") }) setGeneric("ls_solve", function(object, objective, constraints, cached_data, warm_start, verbose, solver_opts) { standardGeneric("ls_solve") }) setGeneric("supported_constraints", function(solver) { standardGeneric("supported_constraints") }) setGeneric("requires_constr", function(solver) { standardGeneric("requires_constr") }) setGeneric("get_coeffs", function(object, expr) { standardGeneric("get_coeffs") }) setGeneric("constant", function(object, expr) { standardGeneric("constant") }) setGeneric("affine", function(object, expr) { standardGeneric("affine") }) setGeneric("extract_quadratic_coeffs", function(object, affine_expr, quad_forms) { standardGeneric("extract_quadratic_coeffs") }) setGeneric("coeff_quad_form", function(object, expr) { standardGeneric("coeff_quad_form") }) setGeneric("copy", function(object, args = NULL, id_objects = list()) { standardGeneric("copy") }) setGeneric("tree_copy", function(object, id_objects = list()) { standardGeneric("tree_copy") }) setGeneric("op_name", function(object) { standardGeneric("op_name") }) setGeneric("op_func", function(object) { standardGeneric("op_func") }) ## End of newly added generics
/scratch/gouwar.j/cran-all/cranData/CVXR/R/generics.R
#' @importFrom utils assignInMyNamespace #' @importFrom Rmpfr mpfr getPrec #' @importFrom gmp as.bigq as.bigz is.bigq is.bigz is.whole numerator denominator asNumeric #' @importFrom bit64 as.integer64 as.bitstring #' @importClassesFrom gmp bigq bigz ## ## Global variable for package CVXR ## idCounter, numpy handle, scipy.sparse handle ## .CVXR.options <- list(idCounter = 0L, np = NULL, sp = NULL, mosekglue = NULL) #' #' Set ID Counter #' #' Set the CVXR variable/constraint identification number counter. #' #' @param value The value to assign as ID. #' @return the changed value of the package global \code{.CVXR.options}. #' @export #' @examples #' \dontrun{ #' setIdCounter(value = 0L) #' } setIdCounter <- function(value = 0L) { .CVXR.options$idCounter <- value assignInMyNamespace(".CVXR.options", .CVXR.options) .CVXR.options } #' #' Reset Options #' #' Reset the global package variable \code{.CVXR.options}. #' #' @return The default value of CVXR package global \code{.CVXR.options}. #' @export #' @examples #' \dontrun{ #' resetOptions() #' } resetOptions <- function() { assignInMyNamespace(".CVXR.options", list(idCounter = 0L, np = NULL, sp = NULL, mosekglue = NULL)) .CVXR.options } #' #' Get ID #' #' Get the next identifier value. #' #' @return A new unique integer identifier. #' @export #' @examples #' \dontrun{ #' get_id() #' } get_id <- function() { id <- .CVXR.options$idCounter <- .CVXR.options$idCounter + 1L assignInMyNamespace(".CVXR.options", .CVXR.options) id } #' #' Get scipy handle #' #' Get the scipy handle or fail if not available #' #' @return the scipy handle #' @export #' @examples #' \dontrun{ #' get_sp #' } get_sp <- function() { sp <- .CVXR.options$sp if (is.null(sp)) { stop("Scipy not available") } sp } #' #' Get numpy handle #' #' Get the numpy handle or fail if not available #' #' @return the numpy handle #' @export #' @examples #' \dontrun{ #' get_np #' } get_np <- function() { np <- .CVXR.options$np if (is.null(np)) { stop("Numpy not available") } np } flatten_list <- function(x) { y <- list() rapply(x, function(x) y <<- c(y,x)) y } #' #' The Rdict class. #' #' A simple, internal dictionary composed of a list of keys and a list of values. These keys/values can be any type, including nested lists, S4 objects, etc. #' Incredibly inefficient hack, but necessary for the geometric mean atom, since it requires mixed numeric/gmp objects. #' #' @slot keys A list of keys. #' @slot values A list of values corresponding to the keys. #' @name Rdict-class #' @aliases Rdict #' @rdname Rdict-class setClass("Rdict", representation(keys = "list", values = "list"), prototype(keys = list(), values = list()), validity = function(object) { if(length(object@keys) != length(object@values)) return("Number of keys must match number of values") if(!all(unique(object@keys) != object@keys)) return("Keys must be unique") return(TRUE) }) #' @param keys A list of keys. #' @param values A list of values corresponding to the keys. #' @rdname Rdict-class Rdict <- function(keys = list(), values = list()) { new("Rdict", keys = keys, values = values) } #' @param x,set A \linkS4class{Rdict} object. #' @param name Either "keys" for a list of keys, "values" for a list of values, or "items" for a list of lists where each nested list is a (key, value) pair. #' @rdname Rdict-class setMethod("$", signature(x = "Rdict"), function(x, name) { if(name == "items") { items <- rep(list(list()), length(x)) for(i in 1:length(x)) { tmp <- list(key = x@keys[[i]], value = x@values[[i]]) items[[i]] <- tmp } return(items) } else slot(x, name) }) #' @rdname Rdict-class setMethod("length", signature(x = "Rdict"), function(x) { length(x@keys) }) #' @param el The element to search the dictionary of values for. #' @rdname Rdict-class setMethod("is.element", signature(el = "ANY", set = "Rdict"), function(el, set) { for(k in set@keys) { if(identical(k, el)) return(TRUE) } return(FALSE) }) #' @param i A key into the dictionary. #' @param j,drop,... Unused arguments. #' @rdname Rdict-class setMethod("[", signature(x = "Rdict"), function(x, i, j, ..., drop = TRUE) { for(k in 1:length(x@keys)) { if(length(x@keys[[k]]) == length(i) && all(x@keys[[k]] == i)) return(x@values[[k]]) } stop("key ", i, " was not found") }) #' @param value The value to assign to key \code{i}. #' @rdname Rdict-class setMethod("[<-", signature(x = "Rdict"), function(x, i, j, ..., value) { if(is.element(i, x)) x@values[[i]] <- value else { x@keys <- c(x@keys, list(i)) x@values <- c(x@values, list(value)) } return(x) }) #' #' The Rdictdefault class. #' #' This is a subclass of \linkS4class{Rdict} that contains an additional slot for a default function, which assigns a value to an input key. #' Only partially implemented, but working well enough for the geometric mean. Will be combined with \linkS4class{Rdict} later. #' #' @slot keys A list of keys. #' @slot values A list of values corresponding to the keys. #' @slot default A function that takes as input a key and outputs a value to assign to that key. #' @seealso \linkS4class{Rdict} #' @name Rdictdefault-class #' @aliases Rdictdefault #' @rdname Rdictdefault-class setClass("Rdictdefault", representation(default = "function"), contains = "Rdict") #' @param keys A list of keys. #' @param values A list of values corresponding to the keys. #' @param default A function that takes as input a key and outputs a value to assign to that key. #' @rdname Rdictdefault-class Rdictdefault <- function(keys = list(), values = list(), default) { new("Rdictdefault", keys = keys, values = values, default = default) } #' @param x A \linkS4class{Rdictdefault} object. #' @param i A key into the dictionary. #' @param j,drop,... Unused arguments. #' @rdname Rdictdefault-class setMethod("[", signature(x = "Rdictdefault"), function(x, i, j, ..., drop = TRUE) { if(length(x@keys) > 0) { for(k in 1:length(x@keys)) { if(length(x@keys[[k]]) == length(i) && all(x@keys[[k]] == i)) return(x@values[[k]]) } } # TODO: Can't update in place. If key doesn't exist, want to create it with default function value. stop("Unimplemented: For now, user must manually create key and set its value to default(key)") x@keys <- c(x@keys, list(i)) x@values <- c(x@values, list(x@default(i))) return(x@values[[length(x@values)]]) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/globals.R
# Get the dimensions of the constant. intf_dim <- function(constant) { if((is.null(dim(constant)) && length(constant) == 1) || (!is.null(dim(constant)) && all(dim(constant) == c(1,1)))) return(c(1,1)) else if(is.bigq(constant) || is.bigz(constant) || (is.vector(constant) && !is.list(constant))) return(c(1,length(constant))) else if(is.matrix(constant) || is(constant, "Matrix")) return(dim(constant)) else stop("Unknown class: ", class(constant)) } # Is the constant a column vector? intf_is_vector <- function(constant) { dim(constant)[2] == 1 } # Is the constant a scalar? intf_is_scalar <- function(constant) { all(dim(constant) == c(1,1)) } # Return the collective sign of the matrix entries. intf_sign <- function(constant) { if(any(is.na(constant))) return(c(FALSE, FALSE)) c(min(constant) >= 0, max(constant) <= 0) } # Return (is real, is imaginary). intf_is_complex <- function(constant, tol = 1e-5) { if(!is.complex(constant)) return(c(TRUE, FALSE)) real_max <- max(abs(Re(constant))) imag_max <- max(abs(Im(constant))) c(real_max >= tol, imag_max >= tol) } # Check if a matrix is Hermitian and/or symmetric intf_is_hermitian <- function(constant, rtol = 1e-5, atol = 1e-8) { # I'm replicating np.allclose here to match CVXPY. May want to use base::isSymmetric later. # is_herm <- isSymmetric(constant) # This returns TRUE iff a complex matrix is Hermitian. if(is.complex(constant)) { # TODO: Catch complex symmetric, but not Hermitian? is_symm <- FALSE is_herm <- all(abs(constant - Conj(t(constant))) <= atol + rtol*abs(Conj(t(constant)))) } else { is_symm <- all(abs(constant - t(constant)) <= atol + rtol*abs(t(constant))) is_herm <- is_symm } # is_symm <- all(abs(constant - t(constant)) <= atol + rtol*abs(t(constant))) # is_herm <- all(abs(constant - Conj(t(constant))) <= atol + rtol*abs(Conj(t(constant)))) c(is_symm, is_herm) } # Check if x is an integer, i.e., a whole number. See is.integer documentation Note and Examples. intf_is_integer <- function(x, tol = .Machine$double.eps^0.5) { abs(x - round(x)) < tol } intf_convert <- function(constant, sparse = FALSE) { if(sparse) return(Matrix(constant, sparse = TRUE)) else as.matrix(constant) } intf_scalar_value <- function(constant) { if(is.list(constant)) constant[[1]] else as.vector(constant)[1] } intf_convert_if_scalar <- function(constant) { if(all(intf_dim(constant) == c(1,1))) intf_scalar_value(constant) else constant } intf_block_add <- function(mat, block, vert_offset, horiz_offset, rows, cols, vert_step = 1, horiz_step = 1) { block <- matrix(block, nrow = rows, ncol = cols) vert_idx <- seq(vert_offset + 1, vert_offset + rows, vert_step) horiz_idx <- seq(horiz_offset + 1, horiz_offset + cols, horiz_step) mat[vert_idx, horiz_idx] <- mat[vert_idx, horiz_idx] + block mat }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/interface.R
# Types of linear operators VARIABLE = "variable" PROMOTE = "promote" MUL_EXPR = "mul_expr" RMUL_EXPR = "rmul_expr" MUL_ELEM = "mul_elem" DIV = "div" SUM = "sum" NEG = "neg" INDEX = "index" TRANSPOSE = "transpose" SUM_ENTRIES = "sum_entries" TRACE = "trace" RESHAPE_EXPR = "reshape_expr" DIAG_VEC = "diag_vec" DIAG_MAT = "diag_mat" UPPER_TRI = "upper_tri" CONV = "conv" KRON = "kron" HSTACK = "hstack" VSTACK = "vstack" SCALAR_CONST = "scalar_const" DENSE_CONST = "dense_const" SPARSE_CONST = "sparse_const" PARAM = "param" NO_OP = "no_op" CONSTANT_ID = "constant_id" LINOP_TYPES <- c(VARIABLE = "VARIABLE", PROMOTE = "PROMOTE", MUL_EXPR = "MUL_EXPR", RMUL_EXPR = "RMUL_EXPR", MUL_ELEM = "MUL_ELEM", DIV = "DIV", SUM = "SUM", NEG = "NEG", INDEX = "INDEX", TRANSPOSE = "TRANSPOSE", SUM_ENTRIES = "SUM_ENTRIES", TRACE = "TRACE", RESHAPE_EXPR = "RESHAPE_EXPR", DIAG_VEC = "DIAG_VEC", DIAG_MAT = "DIAG_MAT", UPPER_TRI = "UPPER_TRI", CONV = "CONV", KRON = "KRON", HSTACK = "HSTACK", VSTACK = "VSTACK", SCALAR_CONST = "SCALAR_CONST", DENSE_CONST = "DENSE_CONST", SPARSE_CONST = "SPARSE_CONST", PARAM = "PARAM", NO_OP = "NO_OP", CONSTANT_ID = "CONSTANT_ID") # Create lists to represent linear operators and constraints LinOp <- function(type, dim, args = list(), data = NULL, class = "LinOp") { if(is.null(dim)) dim <- c(1,1) # TODO: Get rid of this with proper multi-dimensional handling. if(!is.character(type)) stop("type must be a character string") if(!is.numeric(dim)) stop("dim must be a numeric vector") if(!is.list(args)) stop("args must be a list of arguments") list(type = type, dim = dim, args = args, data = data, class = "LinOp") } LinConstr <- function(expr, constr_id, dim, class = "LinConstr") { if(is.null(dim)) dim <- c(1,1) # TODO: Get rid of this with proper multi-dimensional handling. ##if(!is.character(constr_id)) stop("constr_id must be a character string") if(!is.integer(constr_id)) stop("constr_id must be an integer") if(!is.numeric(dim)) stop("dim must be a numeric vector") list(expr = expr, constr_id = constr_id, dim = dim, class = class) } LinEqConstr <- function(expr, constr_id, dim) { LinConstr(expr, constr_id, dim, class = "LinEqConstr") } LinLeqConstr <- function(expr, constr_id, dim) { LinConstr(expr, constr_id, dim, class = "LinLeqConstr") } ## get_id <- function() { ## # sample.int(.Machine$integer.max, 1) ## uuid::UUIDgenerate() ## } create_var <- function(dim, var_id = get_id()) { LinOp(VARIABLE, dim, list(), var_id) } create_param <- function(value, dim) { LinOp(PARAM, dim, list(), value) } create_const <- function(value, dim, sparse = FALSE) { if(all(dim == c(1,1))) op_type <- SCALAR_CONST else if(sparse) op_type <- SPARSE_CONST else op_type <- DENSE_CONST LinOp(op_type, dim, list(), value) } lo.is_scalar <- function(operator) { length(operator$dim) == 0 || as.integer(prod(operator$dim)) == 1 } lo.is_const <- function(operator) { operator$type %in% c(SCALAR_CONST, SPARSE_CONST, DENSE_CONST) } lo.sum_expr <- function(operators) { LinOp(SUM, operators[[1]]$dim, operators) } lo.neg_expr <- function(operator) { LinOp(NEG, operator$dim, list(operator)) } lo.sub_expr <- function(lh_op, rh_op) { lo.sum_expr(list(lh_op, lo.neg_expr(rh_op))) } lo.promote_lin_ops_for_mul <- function(lh_op, rh_op) { tmp <- mul_dims_promote(lh_op$dim, rh_op$dim) lh_dim <- tmp[[1]] rh_dim <- tmp[[2]] new_dim <- tmp[[3]] lh_op <- LinOp(lh_op$type, lh_dim, lh_op$args, lh_op$data) rh_op <- LinOp(rh_op$type, rh_dim, rh_op$args, rh_op$data) list(lh_op, rh_op, new_dim) } lo.mul_expr <- function(lh_op, rh_op, dim) { LinOp(MUL_EXPR, dim, list(rh_op), lh_op) } lo.rmul_expr <- function(lh_op, rh_op, dim) { LinOp(RMUL_EXPR, dim, list(lh_op), rh_op) } lo.multiply <- function(lh_op, rh_op) { LinOp(MUL_ELEM, lh_op$dim, list(rh_op), lh_op) } lo.kron <- function(lh_op, rh_op, dim) { LinOp(KRON, dim, list(rh_op), lh_op) } lo.div_expr <- function(lh_op, rh_op) { LinOp(DIV, lh_op$dim, list(lh_op), rh_op) } lo.promote <- function(operator, dim) { LinOp(PROMOTE, dim, list(operator)) } lo.sum_entries <- function(operator, dim) { LinOp(SUM_ENTRIES, dim, list(operator)) } lo.trace <- function(operator) { LinOp(TRACE, c(1,1), list(operator)) } lo.index <- function(operator, dim, keys) { LinOp(INDEX, dim, list(operator), keys) } lo.conv <- function(lh_op, rh_op, dim) { LinOp(CONV, dim, list(rh_op), lh_op) } lo.transpose <- function(operator) { if(length(operator$dim) < 2) operator else if(length(operator$dim) > 2) stop("Unimplemented") else { new_dim = c(operator$dim[2], operator$dim[1]) LinOp(TRANSPOSE, new_dim, list(operator)) } } lo.reshape <- function(operator, dim) { LinOp(RESHAPE_EXPR, dim, list(operator)) } lo.diag_vec <- function(operator) { new_dim <- c(operator$dim[1], operator$dim[1]) LinOp(DIAG_VEC, new_dim, list(operator)) } lo.diag_mat <- function(operator) { new_dim = c(operator$dim[1], 1) LinOp(DIAG_MAT, new_dim, list(operator)) } lo.upper_tri <- function(operator) { entries <- operator$dim[1] * operator$dim[2] new_dim <- c(floor((entries - operator$dim[1])/2), 1) LinOp(UPPER_TRI, new_dim, list(operator)) } lo.hstack <- function(operators, dim) { LinOp(HSTACK, dim, operators) } lo.vstack <- function(operators, dim) { LinOp(VSTACK, dim, operators) } get_constr_expr <- function(lh_op, rh_op) { if(missing(rh_op)) lh_op else lo.sum_expr(list(lh_op, lo.neg_expr(rh_op))) } create_eq <- function(lh_op, rh_op, constr_id = get_id()) { expr <- get_constr_expr(lh_op, rh_op) LinEqConstr(expr, constr_id, lh_op$dim) } create_leq <- function(lh_op, rh_op, constr_id = get_id()) { expr <- get_constr_expr(lh_op, rh_op) LinLeqConstr(expr, constr_id, lh_op$dim) } create_geq <- function(lh_op, rh_op, constr_id = get_id()) { if(!missing(rh_op)) rh_op <- lo.neg_expr(rh_op) create_leq(lo.neg_expr(lh_op), rh_op, constr_id) } get_expr_vars <- function(operator) { if(operator$type == VARIABLE) list(list(operator$data, operator$dim)) else { vars_ <- list() for(arg in operator$args) vars_ <- c(vars_, get_expr_vars(arg)) vars_ } } get_expr_params <- function(operator) { if(operator$type == PARAM) parameters(operator$data) else { params <- list() for(arg in operator$args) params <- c(params, get_expr_params(arg)) if(is(operator$data, "LinOp")) params <- c(params, get_expr_params(operator$data)) params } } copy_constr <- function(constr, func) { expr <- func(constr$expr) new(class(constr), expr, constr$constr_id, constr$dim) } replace_new_vars <- function(expr, id_to_new_var) { if(expr$type == VARIABLE && expr$data %in% id_to_new_var) id_to_new_var[expr$data] else { new_args <- list() for(arg in expr$args) new_args <- c(new_args, replace_new_vars(arg, id_to_new_var)) LinOp(expr$type, expr$dim, new_args, expr$data) } } replace_params_with_consts <- function(expr) { if(expr$type == PARAM) create_const(expr$data$value, expr$dim) else { new_args <- list() for(arg in expr$args) new_args <- c(new_args, replace_params_with_consts(arg)) # Data could also be a parameter if(is(expr$data, "LinOp") && expr$data$type == PARAM) { data_lin_op <- expr$data data <- create_const(data_lin_op$data$value, data_lin_op$dim) } else data <- expr$data LinOp(expr$type, expr$dim, new_args, data) } }
/scratch/gouwar.j/cran-all/cranData/CVXR/R/lin_ops.R
#' #' The Objective class. #' #' This class represents an optimization objective. #' #' @slot expr A scalar \linkS4class{Expression} to optimize. #' @name Objective-class #' @aliases Objective #' @rdname Objective-class .Objective <- setClass("Objective", representation(expr = "ConstValORExpr"), contains = "Canonical") #' @param expr A scalar \linkS4class{Expression} to optimize. #' @rdname Objective-class Objective <- function(expr) { .Objective(expr = expr) } setMethod("initialize", "Objective", function(.Object, ..., expr) { .Object@expr <- expr .Object@args <- list(as.Constant(expr)) # .Object <- callNextMethod(.Object, ..., args = list(as.Constant(expr))) # Validate that the objective resolves to a scalar. if(!is_scalar(.Object@args[[1]])) stop("The objective must resolve to a scalar") if(!is_real(.Object@args[[1]])) stop("The objective must be real valued") return(.Object) }) #' @param object An \linkS4class{Objective} object. #' @describeIn Objective The value of the objective expression. setMethod("value", "Objective", function(object) { v <- value(object@args[[1]]) if(is.na(v)) return(NA_real_) else return(intf_scalar_value(v)) }) #' @describeIn Objective Is the objective a quadratic function? setMethod("is_quadratic", "Objective", function(object) { is_quadratic(object@args[[1]]) }) #' @describeIn Objective Is the objective a quadratic of piecewise affine function? setMethod("is_qpwa", "Objective", function(object) { is_qpwa(object@args[[1]]) }) #' #' The Minimize class. #' #' This class represents an optimization objective for minimization. #' #' @slot expr A scalar \linkS4class{Expression} to minimize. #' @name Minimize-class #' @aliases Minimize #' @rdname Minimize-class .Minimize <- setClass("Minimize", representation(expr = "ConstValORExpr"), contains = "Objective") #' @param expr A scalar \linkS4class{Expression} to minimize. #' @rdname Minimize-class #' @export Minimize <- function(expr) { .Minimize(expr = expr) } #' @param object A \linkS4class{Minimize} object. #' @describeIn Minimize Pass on the target expression's objective and constraints. setMethod("canonicalize", "Minimize", function(object) { canonical_form(object@args[[1]]) }) #' @describeIn Minimize A logical value indicating whether the objective is convex. setMethod("is_dcp", "Minimize", function(object) { is_convex(object@args[[1]]) }) #' @describeIn Minimize A logical value indicating whether the objective is log-log convex. setMethod("is_dgp", "Minimize", function(object) { is_log_log_convex(object@args[[1]]) }) # The value of the objective given the solver primal value. setMethod("primal_to_result", "Minimize", function(object, result) { result }) #' #' The Maximize class. #' #' This class represents an optimization objective for maximization. #' #' @slot expr A scalar \linkS4class{Expression} to maximize. #' @examples #' x <- Variable(3) #' alpha <- c(0.8,1.0,1.2) #' obj <- sum(log(alpha + x)) #' constr <- list(x >= 0, sum(x) == 1) #' prob <- Problem(Maximize(obj), constr) #' result <- solve(prob) #' result$value #' result$getValue(x) #' @name Maximize-class #' @aliases Maximize #' @rdname Maximize-class .Maximize <- setClass("Maximize", contains = "Objective") #' @param expr A scalar \linkS4class{Expression} to maximize. #' @rdname Maximize-class #' @export Maximize <- function(expr) { .Maximize(expr = expr) } #' @param object A \linkS4class{Maximize} object. #' @describeIn Maximize Negates the target expression's objective. setMethod("canonicalize", "Maximize", function(object) { canon <- canonical_form(object@args[[1]]) list(lo.neg_expr(canon[[1]]), canon[[2]]) }) #' @describeIn Maximize A logical value indicating whether the objective is concave. setMethod("is_dcp", "Maximize", function(object) { is_concave(object@args[[1]]) }) #' @describeIn Maximize A logical value indicating whether the objective is log-log concave. setMethod("is_dgp", "Maximize", function(object) { is_log_log_concave(object@args[[1]]) }) # The value of the objective given the solver primal value. setMethod("primal_to_result", "Maximize", function(object, result) { -result }) #' #' Arithmetic Operations on Objectives #' #' Add, subtract, multiply, or divide optimization objectives. #' #' @param e1 The left-hand \linkS4class{Minimize}, \linkS4class{Maximize}, or numeric value. #' @param e2 The right-hand \linkS4class{Minimize}, \linkS4class{Maximize}, or numeric value. #' @return A \linkS4class{Minimize} or \linkS4class{Maximize} object. #' @name Objective-arith NULL #' @rdname Objective-arith setMethod("+", signature(e1 = "Objective", e2 = "numeric"), function(e1, e2) { if(length(e2) == 1 && e2 == 0) e1 else stop("Unimplemented") }) #' @rdname Objective-arith setMethod("+", signature(e1 = "numeric", e2 = "Objective"), function(e1, e2) { e2 + e1 }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Minimize", e2 = "missing"), function(e1, e2) { Maximize(expr = -e1@args[[1]]) }) #' @rdname Objective-arith setMethod("+", signature(e1 = "Minimize", e2 = "Minimize"), function(e1, e2) { Minimize(e1@args[[1]] + e2@args[[1]]) }) #' @rdname Objective-arith setMethod("+", signature(e1 = "Minimize", e2 = "Maximize"), function(e1, e2) { stop("Problem does not follow DCP rules") }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Objective", e2 = "Minimize"), function(e1, e2) { e1 + (-e2) }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Objective", e2 = "Maximize"), function(e1, e2) { e1 + (-e2) }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Minimize", e2 = "Objective"), function(e1, e2) { (-e2) + e1 }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Maximize", e2 = "Objective"), function(e1, e2) { (-e2) + e1 }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Objective", e2 = "numeric"), function(e1, e2) { if(length(e2) == 1 && e2 == 0) e1 else stop("Unimplemented") }) #' @rdname Objective-arith setMethod("-", signature(e1 = "numeric", e2 = "Objective"), function(e1, e2) { e2 - e1 }) #' @rdname Objective-arith setMethod("*", signature(e1 = "Minimize", e2 = "numeric"), function(e1, e2) { if(e2 >= 0) Minimize(expr = e1@args[[1]] * e2) else Maximize(expr = e1@args[[1]] * e2) }) #' @rdname Objective-arith setMethod("*", signature(e1 = "Maximize", e2 = "numeric"), function(e1, e2) { if(e2 < 0) Minimize(expr = e1@args[[1]] * e2) else Maximize(expr = e1@args[[1]] * e2) }) #' @rdname Objective-arith setMethod("*", signature(e1 = "numeric", e2 = "Minimize"), function(e1, e2) { e2 * e1 }) #' @rdname Objective-arith setMethod("*", signature(e1 = "numeric", e2 = "Maximize"), function(e1, e2) { e2 * e1 }) #' @rdname Objective-arith setMethod("/", signature(e1 = "Objective", e2 = "numeric"), function(e1, e2) { e1 * (1.0/e2) }) #' @rdname Objective-arith setMethod("-", signature(e1 = "Maximize", e2 = "missing"), function(e1, e2) { Minimize(expr = -e1@args[[1]]) }) #' @rdname Objective-arith setMethod("+", signature(e1 = "Maximize", e2 = "Maximize"), function(e1, e2) { Maximize(expr = e1@args[[1]] + e2@args[[1]]) }) #' @rdname Objective-arith setMethod("+", signature(e1 = "Maximize", e2 = "Minimize"), function(e1, e2) { stop("Problem does not follow DCP rules") }) #' #' The SolverStats class. #' #' This class contains the miscellaneous information that is returned by a solver after solving, but that is not captured directly by the \linkS4class{Problem} object. #' #' @slot solver_name The name of the solver. #' @slot solve_time The time (in seconds) it took for the solver to solve the problem. #' @slot setup_time The time (in seconds) it took for the solver to set up the problem. #' @slot num_iters The number of iterations the solver had to go through to find a solution. #' @name SolverStats-class #' @aliases SolverStats #' @rdname SolverStats-class .SolverStats <- setClass("SolverStats", representation(solver_name = "character", solve_time = "numeric", setup_time = "numeric", num_iters = "numeric"), prototype(solver_name = NA_character_, solve_time = NA_real_, setup_time = NA_real_, num_iters = NA_real_)) #' @param results_dict A list containing the results returned by the solver. #' @param solver_name The name of the solver. #' @return A list containing #' \describe{ #' \item{\code{solver_name}}{The name of the solver.} #' \item{\code{solve_time}}{The time (in seconds) it took for the solver to solve the problem.} #' \item{\code{setup_time}}{The time (in seconds) it took for the solver to set up the problem.} #' \item{\code{num_iters}}{The number of iterations the solver had to go through to find a solution.} #' } #' @rdname SolverStats-class SolverStats <- function(results_dict = list(), solver_name = NA_character_) { solve_time <- NA_real_ setup_time <- NA_real_ num_iters <- NA_real_ if(SOLVE_TIME %in% names(results_dict)) solve_time <- results_dict[[SOLVE_TIME]] if(SETUP_TIME %in% names(results_dict)) setup_time <- results_dict[[SETUP_TIME]] if(NUM_ITERS %in% names(results_dict)) num_iters <- results_dict[[NUM_ITERS]] solver_stats <- list(solver_name, solve_time, setup_time, num_iters) names(solver_stats) <- c(SOLVER_NAME, SOLVE_TIME, SETUP_TIME, NUM_ITERS) return(solver_stats) ## .SolverStats(solver_name = solver_name, solve_time = solve_time, setup_time = setup_time, num_iters = num_iters) } #' #' The SizeMetrics class. #' #' This class contains various metrics regarding the problem size. #' #' @slot num_scalar_variables The number of scalar variables in the problem. #' @slot num_scalar_data The number of constants used across all matrices and vectors in the problem. Some constants are not apparent when the problem is constructed. For example, the \code{sum_squares} expression is a wrapper for a \code{quad_over_lin} expression with a constant \code{1} in the denominator. #' @slot num_scalar_eq_constr The number of scalar equality constraints in the problem. #' @slot num_scalar_leq_constr The number of scalar inequality constraints in the problem. #' @slot max_data_dimension The longest dimension of any data block constraint or parameter. #' @slot max_big_small_squared The maximum value of (big)(small)^2 over all data blocks of the problem, where (big) is the larger dimension and (small) is the smaller dimension for each data block. #' @name SizeMetrics-class #' @aliases SizeMetrics #' @rdname SizeMetrics-class .SizeMetrics <- setClass("SizeMetrics", representation(num_scalar_variables = "numeric", num_scalar_data = "numeric", num_scalar_eq_constr = "numeric", num_scalar_leq_constr = "numeric", max_data_dimension = "numeric", max_big_small_squared = "numeric"), prototype(num_scalar_variables = NA_real_, num_scalar_data = NA_real_, num_scalar_eq_constr = NA_real_, num_scalar_leq_constr = NA_real_, max_data_dimension = NA_real_, max_big_small_squared = NA_real_)) #' @param problem A \linkS4class{Problem} object. #' @rdname SizeMetrics-class SizeMetrics <- function(problem) { # num_scalar_variables num_scalar_variables <- 0 for(var in variables(problem)) num_scalar_variables <- num_scalar_variables + size(var) # num_scalar_data, max_data_dimension, and max_big_small_squared max_data_dimension <- 0 num_scalar_data <- 0 max_big_small_squared <- 0 for(const in c(constants(problem), parameters(problem))) { big <- 0 # Compute number of data num_scalar_data <- num_scalar_data + size(const) big <- ifelse(length(dim(const)) == 0, 1, max(dim(const))) small <- ifelse(length(dim(const)) == 0, 1, min(dim(const))) # Get max data dimension if(max_data_dimension < big) max_data_dimension <- big if(max_big_small_squared < as.numeric(big)*small*small) max_big_small_squared <- as.numeric(big)*small*small } # num_scalar_eq_constr num_scalar_eq_constr <- 0 for(constraint in problem@constraints) { if(is(constraint, "EqConstraint") || is(constraint, "ZeroConstraint")) num_scalar_eq_constr <- num_scalar_eq_constr + size(expr(constraint)) } # num_scalar_leq_constr num_scalar_leq_constr <- 0 for(constraint in problem@constraints) { if(is(constraint, "IneqConstraint") || is(constraint, "NonPosConstraint")) num_scalar_leq_constr <- num_scalar_leq_constr + size(expr(constraint)) } .SizeMetrics(num_scalar_variables = num_scalar_variables, num_scalar_data = num_scalar_data, num_scalar_eq_constr = num_scalar_eq_constr, num_scalar_leq_constr = num_scalar_leq_constr, max_data_dimension = max_data_dimension, max_big_small_squared = max_big_small_squared) } setClassUnion("SizeMetricsORNULL", c("SizeMetrics", "NULL")) #' #' The Solution class. #' #' This class represents a solution to an optimization problem. #' #' @rdname Solution-class .Solution <- setClass("Solution", representation(status = "character", opt_val = "numeric", primal_vars = "list", dual_vars = "list", attr = "list"), prototype(primal_vars = list(), dual_vars = list(), attr = list())) Solution <- function(status, opt_val, primal_vars, dual_vars, attr) { .Solution(status = status, opt_val = opt_val, primal_vars = primal_vars, dual_vars = dual_vars, attr = attr) } setMethod("show", "Solution", function(object) { cat("Solution(", object@status, ", (", paste(object@primal_vars, collapse = ", "), "), (", paste(object@dual_vars, collapse = ", "), "), (", paste(object@attr, collapse = ", "), "))", sep = "") }) # TODO: Get rid of this and just skip calling copy on Solution objects. setMethod("copy", "Solution", function(object, args = NULL, id_objects = list()) { return(object) }) #' @param x A \linkS4class{Solution} object. #' @rdname Solution-class setMethod("as.character", "Solution", function(x) { paste("Solution(", x@status, ", (", paste(x@primal_vars, collapse = ", "), "), (", paste(x@dual_vars, collapse = ", "), "), (", paste(x@attr, collapse = ", "), "))", sep = "") }) setClassUnion("SolutionORList", c("Solution", "list")) #' #' The Problem class. #' #' This class represents a convex optimization problem. #' #' @slot objective A \linkS4class{Minimize} or \linkS4class{Maximize} object representing the optimization objective. #' @slot constraints (Optional) A list of constraints on the optimization variables. #' @slot value (Internal) Used internally to hold the value of the optimization objective at the solution. #' @slot status (Internal) Used internally to hold the status of the problem solution. #' @slot .cached_data (Internal) Used internally to hold cached matrix data. #' @slot .separable_problems (Internal) Used internally to hold separable problem data. #' @slot .size_metrics (Internal) Used internally to hold size metrics. #' @slot .solver_stats (Internal) Used internally to hold solver statistics. #' @name Problem-class #' @aliases Problem #' @rdname Problem-class .Problem <- setClass("Problem", representation(objective = "Objective", constraints = "list", variables = "list", value = "numeric", status = "character", solution = "ANY", .intermediate_chain = "ANY", .solving_chain = "ANY", .cached_chain_key = "list", .separable_problems = "list", .size_metrics = "SizeMetricsORNULL", .solver_stats = "list", args = "list", .solver_cache = "environment", .intermediate_problem = "ANY", .intermediate_inverse_data = "ANY"), prototype(constraints = list(), value = NA_real_, status = NA_character_, solution = NULL, .intermediate_chain = NULL, .solving_chain = NULL, .cached_chain_key = list(), .separable_problems = list(), .size_metrics = NULL, .solver_stats = NULL, args = list(), .solver_cache = new.env(parent=emptyenv()), .intermediate_problem = NULL, .intermediate_inverse_data = NULL), ## CLEANUP NOTE: The prototype should probably be ## removed in future versions since we never use ## it In particular, initializing the solver_cache ## environment at argument level poses problems in ## R 3.6 at least validity = function(object) { if(!inherits(object@objective, c("Minimize", "Maximize"))) stop("[Problem: objective] objective must be Minimize or Maximize") if(!is.na(object@value)) stop("[Problem: value] value should not be set by user") if(!is.na(object@status)) stop("[Problem: status] status should not be set by user") if(!is.null(object@solution)) stop("[Problem: solution] solution should not be set by user") if(!is.null([email protected]_chain)) stop("[Problem: .intermediate_chain] .intermediate_chain is an internal slot and should not be set by user") if(!is.null([email protected]_chain)) stop("[Problem: .solving_chain] .solving_chain is an internal slot and should not be set by user") if(length([email protected]_chain_key) > 0) stop("[Problem: .cached_chain_key] .cached_chain_key is an internal slot and should not be set by user") if(length([email protected]_problems) > 0) stop("[Problem: .separable_problems] .separable_problems is an internal slot and should not be set by user") if(!is.null([email protected]_metrics)) stop("[Problem: .size_metrics] .size_metrics is an internal slot and should not be set by user") if(length([email protected]_stats) > 0) stop("[Problem: .solver_stats] .solver_stats is an internal slot and should not be set by user") if(length(object@args) > 0) stop("[Problem: args] args is an internal slot and should not be set by user") if(length([email protected]_cache) > 0) stop("[Problem: .solver_cache] .solver_cache is an internal slot and should not be set by user") if(!is.null([email protected]_problem)) stop("[Problem: .intermediate_problem] .intermediate_problem is an internal slot and should not be set by user") if(!is.null([email protected]_inverse_data)) stop("[Problem: .intermediate_inverse_data] .intermediate_inverse_data is an internal slot and should not be set by user") return(TRUE) }, contains = "Canonical") #' @param objective A \linkS4class{Minimize} or \linkS4class{Maximize} object representing the optimization objective. #' @param constraints (Optional) A list of \linkS4class{Constraint} objects representing constraints on the optimization variables. #' @rdname Problem-class #' @export Problem <- function(objective, constraints = list()) { .Problem(objective = objective, constraints = constraints) } # Used by pool.map to send solve result back. Unsure if this is necessary for multithreaded operation in R. SolveResult <- function(opt_value, status, primal_values, dual_values) { list(opt_value = opt_value, status = status, primal_values = primal_values, dual_values = dual_values, class = "SolveResult") } setMethod("initialize", "Problem", function(.Object, ..., objective, constraints = list(), variables, value = NA_real_, status = NA_character_, solution = NULL, .intermediate_chain = NULL, .solving_chain = NULL, .cached_chain_key = list(), .separable_problems = list(), .size_metrics = SizeMetrics(), .solver_stats = list(), args = list(), .solver_cache, .intermediate_problem = NULL, .intermediate_inverse_data = NULL) { .Object@objective <- objective .Object@constraints <- constraints .Object@variables <- Problem.build_variables(.Object) .Object@value <- value .Object@status <- status .Object@solution <- solution [email protected]_problem <- .intermediate_problem [email protected]_inverse_data <- .intermediate_inverse_data # The intermediate and solving chains to canonicalize and solve the problem. [email protected]_chain <- .intermediate_chain [email protected]_chain <- .solving_chain [email protected]_chain_key <- .cached_chain_key # List of separable (sub)problems [email protected]_problems <- .separable_problems # Information about the dimensions of the problem and its constituent parts [email protected]_metrics <- SizeMetrics(.Object) # Benchmarks reported by the solver. [email protected]_stats <- .solver_stats .Object@args <- list(.Object@objective, .Object@constraints) # Cache for warm start. [email protected]_cache <- new.env(parent=emptyenv()) .Object }) #' @param object A \linkS4class{Problem} object. #' @describeIn Problem The objective of the problem. setMethod("objective", "Problem", function(object) { object@objective }) #' @describeIn Problem Set the value of the problem objective. setReplaceMethod("objective", "Problem", function(object, value) { object@objective <- value object }) #' @describeIn Problem A list of the constraints of the problem. setMethod("constraints", "Problem", function(object) { object@constraints }) #' @describeIn Problem Set the value of the problem constraints. setReplaceMethod("constraints", "Problem", function(object, value) { object@constraints <- value object }) #' @describeIn Problem The value from the last time the problem was solved (or NA if not solved). setMethod("value", "Problem", function(object) { if(is.na(object@value)) return(NA_real_) else return(intf_scalar_value(object@value)) }) #' @param value A \linkS4class{Minimize} or \linkS4class{Maximize} object (objective), list of \linkS4class{Constraint} objects (constraints), or numeric scalar (value). #' @describeIn Problem Set the value of the optimal objective. setReplaceMethod("value", "Problem", function(object, value) { object@value <- value object }) #' @describeIn Problem The status from the last time the problem was solved. setMethod("status", "Problem", function(object) { object@status }) # Set the status of the problem. setReplaceMethod("status", "Problem", function(object, value) { object@status <- value object }) #' @describeIn Problem A logical value indicating whether the problem statisfies DCP rules. #' @examples #' x <- Variable(2) #' p <- Problem(Minimize(p_norm(x, 2)), list(x >= 0)) #' is_dcp(p) setMethod("is_dcp", "Problem", function(object) { all(sapply(c(object@constraints, list(object@objective)), is_dcp)) }) #' @describeIn Problem A logical value indicating whether the problem statisfies DGP rules. setMethod("is_dgp", "Problem", function(object) { all(sapply(c(object@constraints, list(object@objective)), is_dgp)) }) #' @describeIn Problem A logical value indicating whether the problem is a quadratic program. #' @examples #' x <- Variable(2) #' A <- matrix(c(1,-1,-1, 1), nrow = 2) #' p <- Problem(Minimize(quad_form(x, A)), list(x >= 0)) #' is_qp(p) setMethod("is_qp", "Problem", function(object) { for(c in object@constraints) { if(!(is(c, "EqConstraint") || is(c, "ZeroConstraint") || is_pwl(c@args[[1]]))) return(FALSE) } for(var in variables(object)) { if(is_psd(var) || is_nsd(var)) return(FALSE) } return(is_dcp(object) && is_qpwa(object@objective@args[[1]])) }) #' @describeIn Problem The graph implementation of the problem. setMethod("canonicalize", "Problem", function(object) { obj_canon <- canonical_form(object@objective) canon_constr <- obj_canon[[2]] for(constr in object@constraints) canon_constr <- c(canon_constr, canonical_form(constr)[[2]]) list(obj_canon[[1]], canon_constr) }) #' @describeIn Problem logical value indicating whether the problem is a mixed integer program. setMethod("is_mixed_integer", "Problem", function(object) { any(sapply(variables(object), function(v) { v@attributes$boolean || v@attributes$integer })) }) #' @describeIn Problem List of \linkS4class{Variable} objects in the problem. setMethod("variables", "Problem", function(object) { object@variables }) Problem.build_variables <- function(object) { vars_ <- variables(object@objective) constrs_ <- lapply(object@constraints, function(constr) { variables(constr) }) unique(flatten_list(c(vars_, constrs_))) # Remove duplicates } #' @describeIn Problem List of \linkS4class{Parameter} objects in the problem. setMethod("parameters", "Problem", function(object) { params <- parameters(object@objective) constrs_ <- lapply(object@constraints, function(constr) { parameters(constr) }) unique(flatten_list(c(params, constrs_))) # Remove duplicates }) #' @describeIn Problem List of \linkS4class{Constant} objects in the problem. setMethod("constants", "Problem", function(object) { constants_ <- lapply(object@constraints, function(constr) { constants(constr) }) constants_ <- c(constants(object@objective), constants_) unique(flatten_list(constants_)) # TODO: Check duplicated constants are removed correctly }) #' @describeIn Problem List of \linkS4class{Atom} objects in the problem. setMethod("atoms", "Problem", function(object) { atoms_ <- lapply(object@constraints, function(constr) { atoms(constr) }) atoms_ <- c(atoms_, atoms(object@objective)) unique(flatten_list(atoms_)) }) #' @describeIn Problem Information about the size of the problem. setMethod("size_metrics", "Problem", function(object) { [email protected]_metrics }) #' @describeIn Problem Additional information returned by the solver. setMethod("solver_stats", "Problem", function(object) { [email protected]_stats }) #' @describeIn Problem Set the additional information returned by the solver in the problem. setMethod("solver_stats<-", "Problem", function(object, value) { [email protected]_stats <- value object }) # solve.Problem <- function(object, method, ...) { # if(missing(method)) # .solve(object, ...) # else { # func <- Problem.REGISTERED_SOLVE_METHODS[func_name] # func(object, ...) # } # } # Problem.register_solve <- function(name, func) { # Problem.REGISTERED_SOLVE_METHODS[name] <- func # } #' #' @param object A \linkS4class{Problem} class. #' @param solver A string indicating the solver that the problem data is for. Call \code{installed_solvers()} to see all available. #' @param gp A logical value indicating whether the problem is a geometric program. #' @describeIn Problem Get the problem data passed to the specified solver. setMethod("get_problem_data", signature(object = "Problem", solver = "character", gp = "logical"), function(object, solver, gp) { object <- .construct_chains(object, solver = solver, gp = gp) tmp <- perform([email protected]_chain, [email protected]_problem) [email protected]_chain <- tmp[[1]] data <- tmp[[2]] solving_inverse_data <- tmp[[3]] full_chain <- prepend([email protected]_chain, [email protected]_chain) inverse_data <- c([email protected]_inverse_data, solving_inverse_data) return(list(data = data, chain = full_chain, inverse_data = inverse_data)) }) .find_candidate_solvers <- function(object, solver = NA, gp = FALSE) { candidates <- list(qp_solvers = list(), conic_solvers = list()) INSTALLED_SOLVERS <- installed_solvers() INSTALLED_CONIC_SOLVERS <- INSTALLED_SOLVERS[INSTALLED_SOLVERS %in% CONIC_SOLVERS] if(!is.na(solver)) { if(!(solver %in% INSTALLED_SOLVERS)) stop("The solver ", solver, " is not installed") if(solver %in% CONIC_SOLVERS) candidates$conic_solvers <- c(candidates$conic_solvers, solver) if(solver %in% QP_SOLVERS) candidates$qp_solvers <- c(candidates$qp_solvers, solver) } else { candidates$qp_solvers <- INSTALLED_SOLVERS[INSTALLED_SOLVERS %in% QP_SOLVERS] candidates$conic_solvers <- INSTALLED_SOLVERS[INSTALLED_SOLVERS %in% CONIC_SOLVERS] } # If gp, we must have only conic solvers. if(gp) { if(!is.na(solver) && !(solver %in% CONIC_SOLVERS)) stop("When gp = TRUE, solver must be a conic solver. Try calling solve() with solver = ECOS()") else if(is.na(solver)) candidates$qp_solvers <- list() # No QP solvers allowed. } if(is_mixed_integer(object)) { if(length(candidates$qp_solvers) > 0) { qp_filter <- sapply(candidates$qp_solvers, function(s) { mip_capable(SOLVER_MAP_QP[[s]]) }) candidates$qp_solvers <- candidates$qp_solvers[qp_filter] } if(length(candidates$conic_solvers) > 0) { conic_filter <- sapply(candidates$conic_solvers, function(s) { mip_capable(SOLVER_MAP_CONIC[[s]]) }) candidates$conic_solvers <- candidates$conic_solvers[conic_filter] } if(length(candidates$conic_solvers) == 0 && length(candidates$qp_solvers) == 0) stop("Problem is mixed-integer, but candidate QP/Conic solvers are not MIP-capable") } return(candidates) } #' #' @param object A \linkS4class{Problem} class. #' @param solver A string indicating the solver that the problem data is for. Call \code{installed_solvers()} to see all available. #' @param gp Is the problem a geometric problem? #' @describeIn Problem Get the problem data passed to the specified solver. setMethod("get_problem_data", signature(object = "Problem", solver = "character", gp = "missing"), function(object, solver, gp) { get_problem_data(object, solver, gp = FALSE) }) .construct_chains <- function(object, solver = NA, gp = FALSE) { chain_key <- list(solver, gp) if(!identical(chain_key, [email protected]_chain_key)) { candidate_solvers <- .find_candidate_solvers(object, solver = solver, gp = gp) [email protected]_chain <- construct_intermediate_chain(object, candidate_solvers, gp = gp) tmp <- perform([email protected]_chain, object) [email protected]_chain <- tmp[[1]] [email protected]_problem <- tmp[[2]] [email protected]_inverse_data <- tmp[[3]] [email protected]_chain <- construct_solving_chain([email protected]_problem, candidate_solvers) [email protected]_chain_key <- chain_key } return(object) } #' @docType methods #' @rdname psolve #' @export setMethod("psolve", "Problem", function(object, solver = NA, ignore_dcp = FALSE, warm_start = FALSE, verbose = FALSE, parallel = FALSE, gp = FALSE, feastol = NULL, reltol = NULL, abstol = NULL, num_iter = NULL, ...) { if(parallel) stop("Unimplemented") object <- .construct_chains(object, solver = solver, gp = gp) tmp <- perform([email protected]_chain, [email protected]_problem) [email protected]_chain <- tmp[[1]] data <- tmp[[2]] solving_inverse_data <- tmp[[3]] solution <- reduction_solve_via_data([email protected]_chain, object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, list(...)) full_chain <- prepend([email protected]_chain, [email protected]_chain) inverse_data <- c([email protected]_inverse_data, solving_inverse_data) # object <- unpack_results(object, solution, full_chain, inverse_data) # return(value(object)) unpack_results(object, solution, full_chain, inverse_data) }) #' @docType methods #' @rdname psolve #' @method solve Problem #' @export setMethod("solve", signature(a = "Problem", b = "ANY"), function(a, b = NA, ...) { kwargs <- list(...) if(missing(b)) { if("solver" %in% names(kwargs)) psolve(a, ...) else psolve(a, solver = NA, ...) } else psolve(a, b, ...) }) # # TODO: Finish implementation of parallel solve. # .parallel_solve.Problem <- function(object, solver = NULL, ignore_dcp = FALSE, warm_start = FALSE, verbose = FALSE, ...) { # .solve_problem <- function(problem) { # result <- solve(problem, solver = solver, ignore_dcp = ignore_dcp, warm_start = warm_start, verbose = verbose, parallel = FALSE, ...) # opt_value <- result$optimal_value # status <- result$status # primal_values <- result$primal_values # dual_values <- result$dual_values # return(SolveResults(opt_value, status, primal_values, dual_values)) # } # # # TODO: Finish implementation of parallel solve # statuses <- sapply(solve_results, function(solve_result) { solve_result$status }) # # # Check if at least one subproblem is infeasible or inaccurate # for(status in INF_OR_UNB) { # if(status %in% statuses) { # .handle_no_solution(object, status) # break # } else { # for(i in 1:length(solve_results)) { # subproblem <- object@separable_problems[i] # solve_result <- solve_results[i] # # for(j in 1:length(solve_result$primal_values)) { # var <- variables(subproblem)[j] # primal_value <- solve_result$primal_values[j] # subproblem <- save_value(var, primal_value) # TODO: Fix this since R makes copies # } # # for(j in 1:length(solve_result$dual_values)) { # constr <- subproblem@constraints[j] # dual_value <- solve_result$dual_values[j] # subproblem <- save_value(constr, dual_value) # TODO: Fix this since R makes copies # } # } # # object@value <- sum(sapply(solve_results, function(solve_result) { solve_result$optimal_value })) # if(OPTIMAL_INACCURATE %in% statuses) # object@status <- OPTIMAL_INACCURATE # else # object@status <- OPTIMAL # } # } # object # } valuesById <- function(object, results_dict, sym_data, solver) { if(results_dict[[STATUS]] %in% SOLUTION_PRESENT) { outList <- list(value = results_dict[[VALUE]]) ## Save values for variables in object tmp <- saveValuesById(variables(object), [email protected]_offsets, results_dict[[PRIMAL]]) outList <- c(outList, tmp) ## Not all solvers provide dual variables if(EQ_DUAL %in% names(results_dict)) { tmp <- saveDualValues(object, results_dict[[EQ_DUAL]], [email protected]_map[[EQ_MAP]], c("EqConstraint")) outList <- c(outList, tmp) } if(INEQ_DUAL %in% names(results_dict)) { tmp <- saveDualValues(object, results_dict[[INEQ_DUAL]], [email protected]_map[[LEQ_MAP]], c("LeqConstraint", "PSDConstraint")) outList <- c(outList, tmp) } } else if(results_dict[[STATUS]] %in% INF_OR_UNB) # Infeasible or unbounded outList <- handleNoSolution(object, results_dict[[STATUS]]) else # Solver failed to solve stop("Solver failed. Try another.") solve_time <- NA_real_ setup_time <- NA_real_ num_iters <- NA_real_ if(SOLVE_TIME %in% names(results_dict)) solve_time <- results_dict[[SOLVE_TIME]] if(SETUP_TIME %in% names(results_dict)) setup_time <- results_dict[[SETUP_TIME]] if(NUM_ITERS %in% names(results_dict)) num_iters <- results_dict[[NUM_ITERS]] result <- c(list(status = results_dict[[STATUS]]), outList, list(solver = name(solver), solve_time = solve_time, setup_time = setup_time, num_iters = num_iters)) ##value <- function(cvxObj) result[[ as.character(id(cvxObj)) ]] getValue <- function(objet) { ## We go French! if(is(objet, "Variable") || is(objet, "Constraint")) return(result[[as.character(id(objet))]]) if(is_zero(objet)) { dims <- dim(objet) valResult <- matrix(0, nrow = dims[1], ncol = dims[2]) } else { arg_values <- list() idx <- 1 for(arg in objet@args) { ## An argument without a value makes all higher level values NA. ## But if the atom is constant with non-constant arguments, it doesn't depend on its arguments, so it isn't NA. arg_val <- if(is_constant(arg)) value(arg) else { ## result[[as.character(id(arg))]] getValue(arg) } if(is.null(arg_val) || (any(is.na(arg_val)) && !is_constant(objet))) return(NA) else { arg_values[[idx]] <- arg_val idx <- idx + 1 } } valResult <- to_numeric(objet, arg_values) } ## Reduce to scalar if possible if(all(intf_dim(valResult) == c(1, 1))) intf_scalar_value(valResult) else valResult } getDualValue <- function(objet) { if(!is(objet, "Constraint")) { stop("getDualValue: argument should be a Constraint!") } getValue(objet) } result$getValue <- getValue result$getDualValue <- getDualValue result } # .clear_solution.Problem <- function(object) { # for(v in variables(object)) # object <- save_value(v, NA) # for(c in constraints(object)) # object <- save_value(c, NA) # object@value <- NA # object@status <- NA # object@solution <- NA # return(object) # } setMethod("unpack_problem", signature(object = "Problem", solution = "Solution"), function(object, solution) { # if(solution@status %in% SOLUTION_PRESENT) { # for(v in variables(object)) # object <- save_value(v, solution@primal_vars[id(v)]) # for(c in object@constraints) { # if(id(c) %in% solution@dual_vars) # object <- save_value(c, solution@dual_vars[id(c)]) # } # } else if(solution@status %in% INF_OR_UNB) { # for(v in variables(object)) # object <- save_value(v, NA) # for(constr in object@constraints) # object <- save_value(constr, NA) # } else # stop("Cannot unpack invalid solution") # object@value <- solution@opt_val # object@status <- solution@status # object@solution <- solution # return(object) result <- list() if(solution@status %in% SOLUTION_PRESENT) { for(v in variables(object)) { vid <- as.character(id(v)) val <- solution@primal_vars[[vid]] if(is.null(dim(val)) || all(dim(val) == 1)) val <- as.vector(val) result[[vid]] <- val # result[[vid]] <- solution@primal_vars[[vid]] } for(c in object@constraints) { cid <- as.character(id(c)) if(cid %in% names(solution@dual_vars)) { val <- solution@dual_vars[[cid]] if(is.null(dim(val)) || all(dim(val) == 1)) val <- as.vector(val) result[[cid]] <- val # result[[cid]] <- solution@dual_vars[[cid]] } } } else if(solution@status %in% INF_OR_UNB) { for(v in variables(object)) result[[as.character(id(v))]] <- NA for(c in object@constraints) result[[as.character(id(c))]] <- NA } else if(solution@status %in% ERROR) { warning("Solver returned with status ", solution@status) result$status <- solution@status return(result) } else stop("Cannot unpack invalid solution") result$value <- solution@opt_val result$status <- solution@status # result$solution <- solution # Helper functions. getValue <- function(objet) { ## We go French! if(is(objet, "Variable") || is(objet, "Constraint")) return(result[[as.character(id(objet))]]) if(is_zero(objet)) { dims <- dim(objet) valResult <- matrix(0, nrow = dims[1], ncol = dims[2]) } else { arg_values <- list() idx <- 1 for(arg in objet@args) { ## An argument without a value makes all higher level values NA. ## But if the atom is constant with non-constant arguments, it doesn't depend on its arguments, so it isn't NA. arg_val <- if(is_constant(arg)) value(arg) else { ## result[[as.character(id(arg))]] getValue(arg) } if(is.null(arg_val) || (any(is.na(arg_val)) && !is_constant(objet))) return(NA) else { arg_values[[idx]] <- arg_val idx <- idx + 1 } } valResult <- to_numeric(objet, arg_values) } ## Reduce to scalar if possible if(all(intf_dim(valResult) == c(1, 1))) intf_scalar_value(valResult) else valResult } getDualValue <- function(objet) { if(!is(objet, "Constraint")) stop("getDualValue: argument should be a Constraint!") getValue(objet) } result$getValue <- getValue result$getDualValue <- getDualValue return(result) }) #' @describeIn Problem #' Parses the output from a solver and updates the problem state, including the status, #' objective value, and values of the primal and dual variables. #' Assumes the results are from the given solver. #' @param solution A \linkS4class{Solution} object. #' @param chain The corresponding solving \linkS4class{Chain}. #' @param inverse_data A \linkS4class{InverseData} object or list containing data necessary for the inversion. #' @docType methods setMethod("unpack_results", "Problem", function(object, solution, chain, inverse_data) { solution <- invert(chain, solution, inverse_data) # object <- unpack_problem(object, solution) # [email protected]_stats <- SolverStats(object@solution@attr, name(chain@solver)) # return(object) results <- unpack_problem(object, solution) solver_stats <- SolverStats(solution@attr, name(chain@solver)) return(c(results, solver_stats)) }) handleNoSolution <- function(object, status) { ## Set all primal and dual variable values to NA ## TODO: This won't work since R creates copies result <- list() for(var_ in variables(object)) result[[as.character(id(var_))]] <- NA for(constraint in object@constraints) result[[as.character(id(constraint))]] <- NA ## Set the problem value if(tolower(status) %in% c("infeasible", "infeasible_inaccurate")) result[[VALUE]] <- primal_to_result(object@objective, Inf) else if(tolower(status) %in% c("unbounded", "unbounded_inaccurate")) result[[VALUE]] <- primal_to_result(object@objective, -Inf) result } saveDualValues <- function(object, result_vec, constraints, constr_types) { constr_offsets <- integer(0) offset <- 0L for(constr in constraints) { constr_offsets[as.character(id(constr))] <- offset offset <- offset + prod(size(constr)) } active_constraints <- list() for(constr in object@constraints) { # Ignore constraints of the wrong type if(inherits(constr, constr_types)) active_constraints <- c(active_constraints, constr) } saveValuesById(active_constraints, constr_offsets, result_vec) } saveValuesById <- function(variables, offset_map, result_vec) { offset_names <- names(offset_map) result <- lapply(variables, function(var) { id <- as.character(id(var)) size <- size(var) rows <- size[1L] cols <- size[2L] if (id %in% offset_names) { offset <- offset_map[[id]] ## Handle scalars if (all(c(rows, cols) == c(1L , 1L))) { value <- result_vec[offset + 1L] } else { value <- matrix(result_vec[(offset + 1L):(offset + rows * cols)], nrow = rows, ncol = cols) } } else { ## The variable was multiplied by zero value <- matrix(0, nrow = rows, ncol = cols) } ## Convert matrix back to scalar/vector when appropriate. # if([email protected]_vector) # value <- as.vector(value) value }) names(result) = sapply(variables, function(x) as.character(id(x))) result } #' #' Arithmetic Operations on Problems #' #' Add, subtract, multiply, or divide DCP optimization problems. #' #' @param e1 The left-hand \linkS4class{Problem} object. #' @param e2 The right-hand \linkS4class{Problem} object. #' @return A \linkS4class{Problem} object. #' @name Problem-arith NULL #' @rdname Problem-arith setMethod("+", signature(e1 = "Problem", e2 = "missing"), function(e1, e2) { Problem(objective = e1@objective, constraints = e1@constraints) }) #' @rdname Problem-arith setMethod("-", signature(e1 = "Problem", e2 = "missing"), function(e1, e2) { Problem(objective = -e1@objective, constraints = e1@constraints) }) #' @rdname Problem-arith setMethod("+", signature(e1 = "Problem", e2 = "numeric"), function(e1, e2) { if(length(e2) == 1 && e2 == 0) e1 else stop("Unimplemented") }) #' @rdname Problem-arith setMethod("+", signature(e1 = "numeric", e2 = "Problem"), function(e1, e2) { e2 + e1 }) #' @rdname Problem-arith setMethod("+", signature(e1 = "Problem", e2 = "Problem"), function(e1, e2) { Problem(objective = e1@objective + e2@objective, constraints = unique(c(e1@constraints, e2@constraints))) }) #' @rdname Problem-arith setMethod("-", signature(e1 = "Problem", e2 = "numeric"), function(e1, e2) { e1 + (-e2) }) #' @rdname Problem-arith setMethod("-", signature(e1 = "numeric", e2 = "Problem"), function(e1, e2) { if(length(e1) == 1 && e2 == 0) -e2 else stop("Unimplemented") }) #' @rdname Problem-arith setMethod("-", signature(e1 = "Problem", e2 = "Problem"), function(e1, e2) { Problem(objective = e1@objective - e2@objective, constraints = unique(c(e1@constraints, e2@constraints))) }) #' @rdname Problem-arith setMethod("*", signature(e1 = "Problem", e2 = "numeric"), function(e1, e2) { Problem(objective = e1@objective * e2, constraints = e1@constraints) }) #' @rdname Problem-arith setMethod("*", signature(e1 = "numeric", e2 = "Problem"), function(e1, e2) { e2 * e1 }) #' @rdname Problem-arith setMethod("/", signature(e1 = "Problem", e2 = "numeric"), function(e1, e2) { Problem(objective = e1@objective * (1.0/e2), constraints = e1@constraints) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/problem.R
#' #' The Qp2SymbolicQp class. #' #' This class reduces a quadratic problem to a problem that consists of affine #' expressions and symbolic quadratic forms. #' #' @rdname Qp2SymbolicQp-class .Qp2SymbolicQp <- setClass("Qp2SymbolicQp", contains = "Canonicalization") Qp2SymbolicQp <- function(problem = NULL) { .Qp2SymbolicQp(problem = problem) } setMethod("initialize", "Qp2SymbolicQp", function(.Object, ...) { callNextMethod(.Object, ..., canon_methods = Qp2QuadForm.CANON_METHODS) }) Qp2SymbolicQp.accepts <- function(problem) { is_qpwa(expr(problem@objective)) && length(intersect(c("PSD", "NSD"), convex_attributes(variables(problem)))) == 0 && all(sapply(problem@constraints, function(c) { (inherits(c, c("NonPosConstraint", "IneqConstraint")) && is_pwl(expr(c))) || (inherits(c, c("ZeroConstraint", "EqConstraint")) && are_args_affine(list(c))) })) } # Problems with quadratic, piecewise affine objectives, piecewise-linear constraints, inequality constraints, # and affine equality constraints are accepted. setMethod("accepts", signature(object = "Qp2SymbolicQp", problem = "Problem"), function(object, problem) { Qp2SymbolicQp.accepts(problem) }) # Converts a QP to an even more symbolic form. setMethod("perform", signature(object = "Qp2SymbolicQp", problem = "Problem"), function(object, problem) { if(!accepts(object, problem)) stop("Cannot reduce problem to symbolic QP") callNextMethod(object, problem) }) #' #' The QpMatrixStuffing class. #' #' This class fills in numeric values for the problem instance and #' outputs a DCP-compliant minimization problem with an objective #' of the form #' #' QuadForm(x, p) + t(q) %*% x #' #' and Zero/NonPos constraints, both of which exclusively carry #' affine arguments #' #' @rdname QpMatrixStuffing-class QpMatrixStuffing <- setClass("QpMatrixStuffing", contains = "MatrixStuffing") setMethod("accepts", signature(object = "QpMatrixStuffing", problem = "Problem"), function(object, problem) { inherits(problem@objective, "Minimize") && is_quadratic(problem@objective) && is_dcp(problem) && length(convex_attributes(variables(problem))) == 0 && are_args_affine(problem@constraints) && all(sapply(problem@constraints, inherits, what = c("ZeroConstraint", "NonPosConstraint", "EqConstraint", "IneqConstraint") )) }) setMethod("stuffed_objective", signature(object = "QpMatrixStuffing", problem = "Problem", extractor = "CoeffExtractor"), function(object, problem, extractor) { # Extract to t(x) %*% P %*% x + t(q) %*% x, and store r expr <- copy(expr(problem@objective)) # TODO: Need to copy objective? Pqr <- coeff_quad_form(extractor, expr) P <- Pqr[[1]] q <- Pqr[[2]] r <- Pqr[[3]] # Concatenate all variables in one vector boolint <- extract_mip_idx(variables(problem)) boolean <- boolint[[1]] integer <- boolint[[2]] # x <- Variable(extractor@N, boolean = boolean, integer = integer) # new_obj <- quad_form(x, P) + t(q) %*% x x <- Variable(extractor@N, 1, boolean = boolean, integer = integer) new_obj <- new("QuadForm", x = x, P = P) + t(q) %*% x return(list(new_obj, x, r)) }) # Atom canonicalizers Qp2QuadForm.huber_canon <- function(expr, args) { M <- expr@M x <- args[[1]] expr_dim <- dim(expr) # n <- Variable(expr_dim) # s <- Variable(expr_dim) n <- new("Variable", dim = expr_dim) s <- new("Variable", dim = expr_dim) # n^2 + 2*M*|s| # TODO: Make use of recursion inherent to canonicalization process and just return a power / abs expression for readability's sake. power_expr <- Power(n, 2) canon <- Qp2QuadForm.power_canon(power_expr, power_expr@args) n2 <- canon[[1]] constr_sq <- canon[[2]] abs_expr <- abs(s) canon <- EliminatePwl.abs_canon(abs_expr, abs_expr@args) abs_s <- canon[[1]] constr_abs <- canon[[2]] obj <- n2 + 2*M*abs_s constraints <- c(constr_sq, constr_abs) constraints <- c(constraints, list(x == s + n)) return(list(obj, constraints)) } Qp2QuadForm.power_canon <- function(expr, args) { affine_expr <- args[[1]] p <- expr@p if(is_constant(expr)) return(list(Constant(value(expr)), list())) else if(p == 0) return(list(matrix(1, nrow = nrow(affine_expr), ncol = ncol(affine_expr)), list())) else if(p == 1) return(list(affine_expr, list())) else if(p == 2) { if(is(affine_expr, "Variable")) return(list(SymbolicQuadForm(affine_expr, diag(size(affine_expr)), expr), list())) else { # t <- Variable(dim(affine_expr)) t <- new("Variable", dim = dim(affine_expr)) return(list(SymbolicQuadForm(t, diag(size(t)), expr), list(affine_expr == t))) } } stop("Non-constant quadratic forms cannot be raised to a power greater than 2.") } Qp2QuadForm.quad_form_canon <- function(expr, args) { affine_expr <- expr@args[[1]] P <- expr@args[[2]] if(is(affine_expr, "Variable")) return(list(SymbolicQuadForm(affine_expr, P, expr), list())) else { # t <- Variable(dim(affine_expr)) t <- new("Variable", dim = dim(affine_expr)) return(list(SymbolicQuadForm(t, P, expr), list(affine_expr == t))) } } Qp2QuadForm.quad_over_lin_canon <- function(expr, args) { affine_expr <- args[[1]] y <- args[[2]] if(is(affine_expr, "Variable")) return(list(SymbolicQuadForm(affine_expr, diag(size(affine_expr))/y, expr), list())) else { # t <- Variable(dim(affine_expr)) t <- new("Variable", dim = dim(affine_expr)) return(list(SymbolicQuadForm(t, diag(size(affine_expr))/y, expr), list(affine_expr == t))) } } Qp2QuadForm.CANON_METHODS <- list( # Reuse cone canonicalization methods. Abs = Dcp2Cone.CANON_METHODS$Abs, CumSum = Dcp2Cone.CANON_METHODS$CumSum, MaxElemwise = Dcp2Cone.CANON_METHODS$MaxElemwise, MinElemwise = Dcp2Cone.CANON_METHODS$MinElemwise, SumLargest = Dcp2Cone.CANON_METHODS$SumLargest, MaxEntries = Dcp2Cone.CANON_METHODS$MaxEntries, MinEntries = Dcp2Cone.CANON_METHODS$MinEntries, Norm1 = Dcp2Cone.CANON_METHODS$Norm1, NormInf = Dcp2Cone.CANON_METHODS$NormInf, Indicator = Dcp2Cone.CANON_METHODS$Indicator, SpecialIndex = Dcp2Cone.CANON_METHODS$SpecialIndex, # Canonicalizations that are different for QPs. QuadOverLin = Qp2QuadForm.quad_over_lin_canon, Power = Qp2QuadForm.power_canon, Huber = Qp2QuadForm.huber_canon, QuadForm = Qp2QuadForm.quad_form_canon)
/scratch/gouwar.j/cran-all/cranData/CVXR/R/qp2quad_form.R
# QPSolver requires objectives to be stuffed in the following way. #' #' Is the QP objective stuffed? #' #' @param objective A \linkS4class{Minimize} or \linkS4class{Maximize} object representing the optimization objective. #' @return Is the objective a stuffed QP? is_stuffed_qp_objective <- function(objective) { expr <- expr(objective) return(inherits(expr, "AddExpression") && length(expr@args) == 2 && inherits(expr@args[[1]], "QuadForm") && inherits(expr@args[[2]], "MulExpression") && is_affine(expr@args[[2]])) } #' #' A QP solver interface. #' setClass("QpSolver", contains = "ReductionSolver") #' @param object A \linkS4class{QpSolver} object. #' @param problem A \linkS4class{Problem} object. #' @describeIn QpSolver Is this a QP problem? setMethod("accepts", signature(object = "QpSolver", problem = "Problem"), function(object, problem) { return(inherits(problem@objective, "Minimize") && is_stuffed_qp_objective(problem@objective) && are_args_affine(problem@constraints) && all(sapply(problem@constraints, inherits, what = c("ZeroConstraint", "NonPosConstraint" )))) }) #' @describeIn QpSolver Constructs a QP problem data stored in a list setMethod("perform", signature(object = "QpSolver", problem = "Problem"), function(object, problem) { # Construct QP problem data stored in a dictionary. # The QP has the following form # minimize 1/2 x' P x + q' x # subject to A x = b # F x <= g inverse_data <- InverseData(problem) obj <- problem@objective # quadratic part of objective is t(x) %*% P %*% x, but solvers expect 0.5*t(x) %*% P %*% x. P <- 2*value(expr(obj)@args[[1]]@args[[2]]) q <- as.vector(value(expr(obj)@args[[2]]@args[[1]])) # Get number of variables. n <- [email protected]_metrics@num_scalar_variables if(length(problem@constraints) == 0) { eq_cons <- list() ineq_cons <- list() } else { eq_cons <- problem@constraints[sapply(problem@constraints, inherits, what = "ZeroConstraint" )] ineq_cons <- problem@constraints[sapply(problem@constraints, inherits, what = "NonPosConstraint" )] } # TODO: This dependence on ConicSolver is hacky; something should change here. if(length(eq_cons) > 0) { eq_coeffs <- list(list(), c()) for(con in eq_cons) { coeff_offset <- ConicSolver.get_coeff_offset(expr(con)) eq_coeffs[[1]] <- c(eq_coeffs[[1]], list(coeff_offset[[1]])) eq_coeffs[[2]] <- c(eq_coeffs[[2]], coeff_offset[[2]]) } #A <- Matrix(do.call(rbind, eq_coeffs[[1]]), sparse = TRUE) A <- do.call(rbind, eq_coeffs[[1]]) b <- -eq_coeffs[[2]] } else { A <- Matrix(nrow = 0, ncol = n, sparse = TRUE) b <- -matrix(nrow = 0, ncol = 0) } if(length(ineq_cons) > 0) { ineq_coeffs <- list(list(), c()) for(con in ineq_cons) { coeff_offset <- ConicSolver.get_coeff_offset(expr(con)) ineq_coeffs[[1]] <- c(ineq_coeffs[[1]], list(coeff_offset[[1]])) ineq_coeffs[[2]] <- c(ineq_coeffs[[2]], coeff_offset[[2]]) } #Fmat <- Matrix(do.call(rbind, ineq_coeffs[[1]]), sparse = TRUE) Fmat <- do.call(rbind, ineq_coeffs[[1]]) g <- -ineq_coeffs[[2]] } else { Fmat <- Matrix(nrow = 0, ncol = n, sparse = TRUE) g <- -matrix(nrow = 0, ncol = 0) } # Create dictionary with problem data. variables <- variables(problem)[[1]] ## Ensure A, P and Fmat are all sparse if (!is(A, "dgCMatrix")) { A <- as(as(A, "CsparseMatrix"), "generalMatrix") } if (!is(P, "dgCMatrix")) { P <- as(as(P, "CsparseMatrix"), "generalMatrix") } if (!is(Fmat, "dgCMatrix")) { Fmat <- as(as(Fmat, "CsparseMatrix"), "generalMatrix") } data <- list() data[[P_KEY]] <- P data[[Q_KEY]] <- q data[[A_KEY]] <- A data[[B_KEY]] <- b data[[F_KEY]] <- Fmat data[[G_KEY]] <- g data[[BOOL_IDX]] <- sapply(variables@boolean_idx, function(t) { t[[1]] }) data[[INT_IDX]] <- sapply(variables@integer_idx, function(t) { t[[1]] }) data$n_var <- n data$n_eq <- nrow(A) data$n_ineq <- nrow(Fmat) inverse_data@sorted_constraints <- c(eq_cons, ineq_cons) # Add information about integer variables. inverse_data@is_mip <- length(data[[BOOL_IDX]]) > 0 || length(data[[INT_IDX]]) > 0 return(list(object, data, inverse_data)) }) #' #' An interface for the CPLEX solver. #' #' @name CPLEX_QP-class #' @aliases CPLEX_QP #' @rdname CPLEX_QP-class #' @export setClass("CPLEX_QP", contains = "QpSolver") #' @rdname CPLEX_QP-class #' @export CPLEX_QP <- function() { new("CPLEX_QP") } #' @param x,object,solver A \linkS4class{CPLEX_QP} object. #' @describeIn CPLEX_QP Can the solver handle mixed-integer programs? setMethod("mip_capable", "CPLEX_QP", function(solver) { TRUE }) # TODO: Add more! #' @param status A status code returned by the solver. #' @describeIn CPLEX_QP Converts status returned by the CPLEX solver to its respective CVXPY status. setMethod("status_map", "CPLEX_QP", function(solver, status) { if(status %in% c(1, 101, 102)) OPTIMAL else if(status %in% c(3, 22, 4, 103)) INFEASIBLE else if(status %in% c(2, 21, 118)) UNBOUNDED else if(status %in% c(10, 107)) USER_LIMIT else stop("CPLEX status unrecognized: ", status) }) #' @describeIn CPLEX_QP Returns the name of the solver. setMethod("name", "CPLEX_QP", function(x) { CPLEX_NAME }) #' @describeIn CPLEX_QP Imports the solver. setMethod("import_solver", "CPLEX_QP", function(solver) { requireNamespace("Rcplex", quietly = TRUE) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn CPLEX_QP Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "CPLEX_QP", solution = "list", inverse_data = "InverseData"), function(object, solution, inverse_data){ model <- solution$model attr <- list() #Can't seem to find a way to increase verbosity of cplex. Can't get cputime #if("cputime" %in% names(solution)) # attr[SOLVE_TIME] <- results$cputime #attr[NUM_ITERS] <- as.integer(get_num_barrier_iterations(model@solution@progress)) status <- status_map(object, solution$model$status) if(status %in% SOLUTION_PRESENT) { # Get objective value. opt_val <- model$obj # Get solution. primal_vars <- list() primal_vars[[names(inverse_data@id_map)[1]]] <- model$xopt # Only add duals if not a MIP. dual_vars <- list() if(!inverse_data@is_mip) { y <- -as.matrix(model$extra$lambda) #there's a negative here, should we keep this? dual_vars <- get_dual_values(y, extract_dual_value, inverse_data@sorted_constraints) } } else { primal_vars <- list() dual_vars <- list() opt_val <- Inf if(status == UNBOUNDED) opt_val <- -Inf } return(Solution(status, opt_val, primal_vars, dual_vars, attr)) }) ## Do we need this function? ## @DK: no, we don't (BN) ## setMethod("invert", "CPLEX_QP", function(object, solution, inverse_data) { ## model <- solution$model ## attr <- list() ## if("cputime" %in% names(solution)) ## attr[[SOLVE_TIME]] <- solution$cputime ## attr[[NUM_ITERS]] <- as.integer(get_num_barrier_iterations(model@solution@progress)) ## status <- status_map(object, get_status(model@solution)) ## if(status %in% SOLUTION_PRESENT) { ## # Get objective value. ## opt_val <- get_objective_value(model@solution) ## # Get solution. ## x <- as.matrix(get_values(model@solution)) ## primal_vars <- list() ## primal_vars[names(inverse_data@id_map)[1]] <- x ## # Only add duals if not a MIP. ## dual_vars <- list() ## if(!inverse_data@is_mip) { ## y <- -as.matrix(get_dual_values(model@solution)) ## dual_vars <- get_dual_values(y, extract_dual_value, inverse_data@sorted_constraints) ## } ## } else { ## primal_vars <- list() ## primal_vars[names(inverse_data@id_map)[1]] <- NA_real_ ## dual_vars <- list() ## if(!inverse_data@is_mip) { ## dual_var_ids <- sapply(inverse_data@sorted_constraints, function(constr) { constr@id }) ## dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) ## names(dual_vars) <- dual_var_ids ## } ## opt_val <- Inf ## if(status == UNBOUNDED) ## opt_val <- -Inf ## } ## return(Solution(status, opt_val, primal_vars, dual_vars, attr)) ## }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance on the primal and dual residual. #' @param reltol The relative tolerance on the duality gap. #' @param abstol The absolute tolerance on the duality gap. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn CPLEX_QP Solve a problem represented by data returned from apply. setMethod("solve_via_data", "CPLEX_QP", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) #P <- Matrix(data[[P_KEY]], byrow = TRUE, sparse = TRUE) P <- data[[P_KEY]] q <- data[[Q_KEY]] #A <- Matrix(data[[A_KEY]], byrow = TRUE, sparse = TRUE) #Equality constraints A <- data[[A_KEY]] b <- data[[B_KEY]] #Equality constraint RHS #Fmat <- Matrix(data[[F_KEY]], byrow = TRUE, sparse = TRUE) #Inequality constraints Fmat <- data[[F_KEY]] g <- data[[G_KEY]] #inequality constraint RHS n_var <- data$n_var n_eq <- data$n_eq n_ineq <- data$n_ineq #In case the b and g variables are empty if( (0 %in% dim(b)) & (0 %in% dim(g)) ){ bvec <- rep(0, n_var) } else{ bvec <- c(b, g) } #Create one big constraint matrix with both inequalities and equalities Amat <- rbind(A, Fmat) if(n_eq + n_ineq == 0){ #If both number of equalities and inequalities are 0, then constraints dont matter so set equal sense_vec <- c(rep("E", n_var)) } else{ sense_vec = c(rep("E", n_eq), rep("L", n_ineq)) } #Initializing variable types vtype <- rep("C", n_var) #Setting Boolean variable types for(i in seq_along(data[BOOL_IDX]$bool_vars_idx)){ vtype[data[BOOL_IDX]$bool_vars_idx[[i]]] <- "B" } #Setting Integer variable types for(i in seq_along(data[INT_IDX]$int_vars_idx)){ vtype[data[INT_IDX]$int_vars_idx[[i]]] <- "I" } # Throw parameter warnings if(!all(c(is.null(feastol), is.null(reltol), is.null(abstol)))) { warning("Ignoring inapplicable parameters feastol/reltol/abstol for CPLEX.") } if (is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$CPLEX$itlim } #Setting verbosity off control <- list(trace = verbose, itlim = num_iter) #Setting rest of the parameters control[names(solver_opts)] <- solver_opts # Solve problem. results_dict <- list() #In case A matrix is empty if(0 %in% dim(Amat)){ Amat <- matrix(0, nrow = length(q), ncol = length(q)) } tryCatch({ # Define CPLEX problem and solve model <- Rcplex::Rcplex(cvec=q, Amat=Amat, bvec=bvec, Qmat=P, lb=-Inf, ub=Inf, control=control, objsense="min", sense=sense_vec, vtype=vtype) #control parameter would be used to set specific solver arguments. See cran Rcplex documentation }, error = function(e) { results_dict$status <- SOLVER_ERROR } ) results_dict$model <- model return(results_dict) }) #' #' An interface for the GUROBI_QP solver. #' #' @name GUROBI_QP-class #' @aliases GUROBI_QP #' @rdname GUROBI_QP-class #' @export setClass("GUROBI_QP", contains = "QpSolver") #' @rdname GUROBI_QP-class #' @export GUROBI_QP <- function() { new("GUROBI_QP") } #' @param solver,object,x A \linkS4class{GUROBI_QP} object. #' @describeIn GUROBI_QP Can the solver handle mixed-integer programs? setMethod("mip_capable", "GUROBI_QP", function(solver) { TRUE }) #' @param status A status code returned by the solver. #' @describeIn GUROBI_QP Converts status returned by the GUROBI solver to its respective CVXPY status. setMethod("status_map", "GUROBI_QP", function(solver, status) { if(status == 2 || status == "OPTIMAL") OPTIMAL else if(status == 3 || status == 6 || status == "INFEASIBLE") #DK: I added the words because the GUROBI solver seems to return the words INFEASIBLE else if(status == 5 || status == "UNBOUNDED") UNBOUNDED else if(status == 4 | status == "INF_OR_UNBD") INFEASIBLE_INACCURATE else if(status %in% c(7,8,9,10,11,12)) SOLVER_ERROR # TODO: Could be anything else if(status == 13) OPTIMAL_INACCURATE # Means time expired. else stop("GUROBI status unrecognized: ", status) }) #' @describeIn GUROBI_QP Returns the name of the solver. setMethod("name", "GUROBI_QP", function(x) { GUROBI_NAME }) #' @describeIn GUROBI_QP Imports the solver. setMethod("import_solver", "GUROBI_QP", function(solver) { requireNamespace("gurobi", quietly = TRUE) }) ##DK: IS THIS FUNCTION NECESSARY ANYMORE WITH invert? ## @DK: No, not necessary (BN) ## setMethod("alt_invert", "GUROBI_QP", function(object, results, inverse_data) { ## model <- results$model ## x_grb <- getVars(model) ## n <- length(x_grb) ## constraints_grb <- getConstrs(model) ## m <- length(constraints_grb) ## # Start populating attribute dictionary. ## attr <- list() ## attr[[SOLVE_TIME]] <- model@Runtime ## attr[[NUM_ITERS]] <- model@BarIterCount ## # Map GUROBI statuses back to CVXR statuses. ## status <- status_map(object, model@Status) ## if(status %in% SOLUTION_PRESENT) { ## opt_val <- model@objVal ## x <- as.matrix(sapply(1:n, function(i) { x_grb[i]@X })) ## primal_vars <- list() ## primal_vars[names(inverse_data@id_map)[1]] <- x ## # Only add duals if not a MIP. ## dual_vars <- list() ## if(!inverse_data@is_mip) { ## y <- -as.matrix(sapply(1:m, function(i) { constraints_grb[i]@Pi })) ## dual_vars <- get_dual_values(y, extract_dual_value, inverse_data@sorted_constraints) ## } else { ## primal_vars <- list() ## primal_vars[names(inverse_data@id_map)[1]] <- NA_real_ ## dual_vars <- list() ## if(!inverse_data@is_mip) { ## dual_var_ids <- sapply(inverse_data@sorted_constraints, function(constr) { constr@id }) ## dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) ## names(dual_vars) <- dual_var_ids ## } ## opt_val <- Inf ## if(status == UNBOUNDED) ## opt_val <- -Inf ## } ## } ## return(Solution(status, opt_val, primal_vars, dual_vars, attr)) ## }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn GUROBI_QP Solve a problem represented by data returned from apply. setMethod("solve_via_data", "GUROBI_QP", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) # N.B. Here we assume that the matrices in data are in CSC format. P <- data[[P_KEY]] # TODO: Convert P matrix to COO format? q <- data[[Q_KEY]] A <- data[[A_KEY]] # TODO: Convert A matrix to CSR format? b <- data[[B_KEY]] Fmat <- data[[F_KEY]] # TODO: Convert F matrix to CSR format? g <- data[[G_KEY]] n <- data$n_var # Create a new model. model <- list() #Doesn't seem like adding variables exists in the R version, but setting var type is # Add variables. #Add variable types vtype <- character(n) for(i in seq_along(data[[BOOL_IDX]])){ vtype[data[[BOOL_IDX]][[i]]] <- 'B' #B for binary } for(i in seq_along(data[[INT_IDX]])){ vtype[data[[INT_IDX]][[i]]] <- 'I' #I for integer } for(i in 1:n) { if(vtype[i] == ""){ vtype[i] <- 'C' #C for continuous } #addVar(model, ub = Inf, lb = -Inf, vtype = vtype): don't need in R } model$vtype <- vtype #put in variable types model$lb <- rep(-Inf, n) model$ub <- rep(Inf, n) #update(model): doesn't exist in R #x <- getVars(model) # Add equality constraints: iterate over the rows of A, # adding each row into the model. model$A <- rbind(A, Fmat) model$rhs <- c(b, g) model$sense <- c(rep('=', dim(A)[1]), rep('<', dim(Fmat)[1])) #in their documentation they just have < than not <=? # if(!is.null(model$v811_addMConstrs)) { # # @e can pass all of A == b at once. # sense <- rep(GRB.EQUAL, nrow(A)) # model <- model$v811_addMConstrs(A, sense, b) What is the R equivalent of this?? # } else if(nrow(A) > 0) { # for(i in 1:nrow(A)) { Is this bit ever necessary in R? # start <- A@p[i] # end <- A@p[i+1] # # variables <- mapply(function(i, j) { x[i,j] }, A@i[start:end], A@j[start:end]) # Get nnz. # variables <- x[A@i[start:end]] # coeff <- A@x[start:end] # expr <- gurobi::LinExpr(coeff, variables) # addConstr(model, expr, "equal", b[i]) # } # } # update(model) # Add inequality constraints: iterate over the rows of F, # adding each row into the model. # if(!is.null(model$v811_addMConstrs)) { # # We can pass all of F <= g at once. # sense <- rep(GRB.LESS_EQUAL, nrow(Fmat)) # model <- model$v811_addMConstrs(Fmat, sense, g) # } else if(nrow(Fmat) > 0) { # for(i in nrow(Fmat)) { # start <- Fmat@p[i] # end <- Fmat@p[i+1] # # variables <- mapply(function(i, j) { x[i,j] }, Fmat@i[start:end], Fmat@j[start:end]) # Get nnz. # variables <- x[Fmat@i[start:end]] # coeff <- Fmat@x[start:end] # expr <- gurobi::LinExpr(coeff, variables) # addConstr(model, expr, "less_equal", g[i]) # } # } #update(model) Not in R # Define objective. ####CHECK MATH#### #Conjecture P is Q matrix and q is c, which is obj for gurobi model$Q <- P*.5 model$obj <- q # obj <- gurobi::QuadExpr() # if(!is.null(model$v811_setMObjective)) # model <- model$v811_setMObjective(0.5*P, q) # else { # nnz <- nnzero(P) # if(nnz > 0) { # If there are any nonzero elements in P. # for(i in 1:nnz) # gurobi_add(obj, 0.5*P@x[i]*x[P@i[i]]*x[P@j[i]]) # } # gurobi_add(obj, gurobi::LinExpr(q, x)) # Add linear part. # setObjective(model, obj) # Set objective. # } # update(model) # Throw parameter warnings if(!all(c(is.null(reltol), is.null(abstol)))) { warning("Ignoring inapplicable parameters reltol/abstol for GUROBI.") } if (is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$GUROBI$num_iter } if (is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$GUROBI$FeasibilityTol } ## Set verbosity and other parameters. params <- list( OutputFlag = as.numeric(verbose), ## TODO: User option to not compute duals. QCPDual = 1, #equivalent to TRUE IterationLimit = num_iter, FeasibilityTol = feastol, OptimalityTol = feastol ) params[names(solver_opts)] <- solver_opts # Update model. Not a thing in R #update(model) # Solve problem. #results_dict <- gurobi(model, params) results_dict <- list() tryCatch({ results_dict$solution <- gurobi::gurobi(model, params) # Solve. }, error = function(e) { # Error in the solution. results_dict$status <- 'SOLVER_ERROR' }) results_dict$model <- model return(results_dict) }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn GUROBI_QP Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "GUROBI_QP", solution = "list", inverse_data = "InverseData"), function(object, solution, inverse_data){ model <- solution$model solution <- solution$solution x_grb <- model$x n <- length(x_grb) constraints_grb <- model$rhs m = length(constraints_grb) attr <- list() attr[[SOLVE_TIME]] <- solution$runtime attr[[NUM_ITERS]] <- solution$baritercount status <- status_map(object, solution$status) if(status %in% SOLUTION_PRESENT) { opt_val <- solution$objval x <- solution$x primal_vars <- list() primal_vars[[names(inverse_data@id_map)[1]]] <- x #Only add duals if not a MIP dual_vars <- list() if(!inverse_data@is_mip) { if(!is.null(solution$pi)){ y <- -solution$pi dual_vars <- get_dual_values(y, extract_dual_value, inverse_data@sorted_constraints) } } } else { primal_vars <- list() primal_vars[names(inverse_data@id_map)[1]] <- NA_real_ dual_vars <- list() if(!inverse_data@is_mip) { dual_var_ids <- sapply(inverse_data@sorted_constraints, function(constr) { constr@id }) dual_vars <- as.list(rep(NA_real_, length(dual_var_ids))) names(dual_vars) <- dual_var_ids } opt_val <- Inf if(status == UNBOUNDED) opt_val <- -Inf } return(Solution(status, opt_val, primal_vars, dual_vars, attr)) }) #' #' An interface for the OSQP solver. #' #' @name OSQP-class #' @aliases OSQP #' @rdname OSQP-class #' @export setClass("OSQP", contains = "QpSolver") #' @rdname OSQP-class #' @export OSQP <- function() { new("OSQP") } #' @param solver,object,x A \linkS4class{OSQP} object. #' @param status A status code returned by the solver. #' @describeIn OSQP Converts status returned by the OSQP solver to its respective CVXPY status. setMethod("status_map", "OSQP", function(solver, status) { if(status == 1) OPTIMAL else if(status == 2) OPTIMAL_INACCURATE else if(status == -3) INFEASIBLE else if(status == 3) INFEASIBLE_INACCURATE else if(status == -4) UNBOUNDED else if(status == 4) UNBOUNDED_INACCURATE else if(status == -2 || status == -5 || status == -10) # -2: Maxiter reached. -5: Interrupted by user. -10: Unsolved. SOLVER_ERROR else stop("OSQP status unrecognized: ", status) }) #' @describeIn OSQP Returns the name of the solver. setMethod("name", "OSQP", function(x) { OSQP_NAME }) #' @describeIn OSQP Imports the solver. ##setMethod("import_solver", "OSQP", function(solver) { requireNamespace("osqp", quietly = TRUE) }) ## Since OSQP is a requirement, this is always TRUE setMethod("import_solver", "OSQP", function(solver) { TRUE }) #' @param solution The raw solution returned by the solver. #' @param inverse_data A \linkS4class{InverseData} object containing data necessary for the inversion. #' @describeIn OSQP Returns the solution to the original problem given the inverse_data. setMethod("invert", signature(object = "OSQP", solution = "list", inverse_data = "InverseData"), function(object, solution, inverse_data) { attr <- list() ## DWK CHANGES Below ## Change slots to list elements attr[[SOLVE_TIME]] <- solution$info$run_time # Map OSQP statuses back to CVXR statuses. status <- status_map(object, solution$info$status_val) ## DWK CHANGE END if(status %in% SOLUTION_PRESENT) { ## DWK CHANGES Below opt_val <- solution$info$obj_val ## DWK CHANGE END primal_vars <- list() ## DWK CHANGE ## primal_vars[names(inverse_data@id_map)] <- solution@x primal_vars[[names(inverse_data@id_map)]] <- solution$x dual_vars <- get_dual_values(solution$y, extract_dual_value, inverse_data@sorted_constraints) attr[[NUM_ITERS]] <- solution$info$iter return(Solution(status, opt_val, primal_vars, dual_vars, attr)) ## DWK CHANGE END } else return(failure_solution(status)) }) #' @param data Data generated via an apply call. #' @param warm_start A boolean of whether to warm start the solver. #' @param verbose A boolean of whether to enable solver verbosity. #' @param feastol The feasible tolerance. #' @param reltol The relative tolerance. #' @param abstol The absolute tolerance. #' @param num_iter The maximum number of iterations. #' @param solver_opts A list of Solver specific options #' @param solver_cache Cache for the solver. #' @describeIn OSQP Solve a problem represented by data returned from apply. setMethod("solve_via_data", "OSQP", function(object, data, warm_start, verbose, feastol, reltol, abstol, num_iter, solver_opts, solver_cache) { if (missing(solver_cache)) solver_cache <- new.env(parent=emptyenv()) P <- data[[P_KEY]] q <- data[[Q_KEY]] #A <- Matrix(do.call(rbind, list(data[[A_KEY]], data[[F_KEY]])), sparse = TRUE) ## Since we have ensured that these matrices are sparse above, can ignore coercing! A <- do.call(rbind, list(data[[A_KEY]], data[[F_KEY]])) data$full_A <- A uA <- c(data[[B_KEY]], data[[G_KEY]]) data$u <- uA lA <- c(data[[B_KEY]], rep(-Inf, length(data[[G_KEY]]))) data$l <- lA if(is.null(feastol)) { feastol <- SOLVER_DEFAULT_PARAM$OSQP$eps_prim_inf } if(is.null(reltol)) { reltol <- SOLVER_DEFAULT_PARAM$OSQP$eps_rel } if(is.null(abstol)) { abstol <- SOLVER_DEFAULT_PARAM$OSQP$eps_abs } if(is.null(num_iter)) { num_iter <- SOLVER_DEFAULT_PARAM$OSQP$max_iter } else { num_iter <- as.integer(num_iter) } control <- list(max_iter = num_iter, eps_abs = abstol, eps_rel = reltol, eps_prim_inf = feastol, eps_dual_inf = feastol, verbose = verbose) control[names(solver_opts)] <- solver_opts if(length(solver_cache$cache) > 0 && name(object) %in% names(solver_cache$cache)) { # Use cached data. cache <- solver_cache$cache[[name(object)]] solver <- cache[[1]] old_data <- cache[[2]] results <- cache[[3]] same_pattern <- all(dim(P) == dim(old_data[[P_KEY]])) && all(P@p == old_data[[P_KEY]]@p) && all(P@i == old_data[[P_KEY]]@i) && all(dim(A) == dim(old_data$full_A)) && all(A@p == old_data$full_A@p) && all(A@i == old_data$full_A@i) } else same_pattern <- FALSE # If sparsity pattern differs, need to do setup. if(warm_start && same_pattern) { new_args <- list() for(key in c("q", "l", "u")) { if(any(data[[key]] != old_data[[key]])) new_args[[key]] <- data[[key]] } factorizing <- FALSE if(any(P@x != old_data[[P_KEY]]@x)) { P_triu <- triu(P) new_args$Px <- P_triu@x factorizing <- TRUE } if(any(A@x != old_data$full_A@x)) { new_args$Ax <- A@x factorizing <- TRUE } if(length(new_args) > 0) do.call(solver$Update, new_args) ## Map OSQP statuses back to CVXR statuses. #status <- status_map(object, results@info@status_val) #if(status == OPTIMAL) # warm_start(solver, results@x, results@y) ## Polish if factorizing. if(is.null(control$polish)){ control$polish <- factorizing } #Update Parameters solver$UpdateSettings(control) } else { if(is.null(control$polish)) control$polish <- TRUE # Initialize and solve problem. solver <- osqp::osqp(P, q, A, lA, uA, control) } results <- solver$Solve() if (length(solver_cache) == 0L) { solver_cache$cache[[name(object)]] <- list(solver, data, results) } return(results) })
/scratch/gouwar.j/cran-all/cranData/CVXR/R/qp_solvers.R