m2geval / r /InverseL0TF_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
07a3434 verified
Raw
History Blame Contribute Delete
200 kB
{"repo_name": "InverseL0TF", "file_name": "/InverseL0TF/R/invL0TF.R", "inference_info": {"prefix_code": "\n\nybeta <- function(beta=beta,q=q){\n if(q == 0){\n return(cumsum(beta))\n }\n if(q == 1){\n return(cumsum(cumsum(beta)))\n }\n}\n\nDy <- function(y=y,q=q,U=U){\n if(q == 0){\n D = U-rev(cumsum(rev(y)))\n return(D)\n }\n if(q == 1){\n D = U-rev(cumsum(cumsum(rev(y))))\n return(D)\n }\n}\n\nSplicing <- ", "suffix_code": "\n\nInvL0TFk <- function(A0=A0,y=y,q=q,k=k,H=H,U=U,first=first,last=last,max.step=50){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n I0 = setdiff(AS,A0)\n for(j in 1:max.step){\n m = Splicing(A=A0,I=I0,k=k,y=y,q=q,H=H,U=U,first=first,last=last)\n A = m$A\n I = m$I\n beta = m$beta\n if(identical(A,A0) & identical(I,I0)){\n break\n }else{\n A0 = A\n I0 = I\n }\n }\n yhat = ybeta(beta=beta,q=q)\n Ahat = sort(A,decreasing = FALSE)\n return(list(betak=beta,yk=yhat,Ak=Ahat))\n}\n\nInverseL0TF <- function(y=y,kmax=kmax,q=q,first=0,last=1){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n A0 = NULL\n I0 = setdiff(AS,A0)\n\n beta.all = NULL\n y.all = NULL\n A.all = list()\n mse = as.numeric(kmax)\n sic = as.numeric(kmax)\n eps = as.numeric(n)\n if(q == 0){\n H = n:1/n\n U = rev(cumsum(rev(y)))\n }\n if(q == 1){\n H = sapply(n:1, function(x) x*(x+1)*(2*x+1)/6)/n\n U = rev(cumsum(cumsum(rev(y))))\n }\n Al = sort(union(S,A0),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n for(j in 1:kmax){\n result = InvL0TFk(A0=A0,y=y,q=q,k=j,H=H,U=U,first=first,last=last)\n beta.all = cbind(beta.all,result$betak)\n y.all = cbind(y.all,result$yk)\n A0 = result$Ak\n I0 = setdiff(AS,A0)\n A.all[[j]] = A0 - 1\n D = Dy(y=as.vector(y.all[,j]),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n }\n mse = colMeans((y-y.all)^2)\n df = 1:kmax + q + 1\n sic = n*log(mse) + 2*log(log(n))*log(n)*df\n bic = n*log(mse) + 2*log(n)*df\n return(list(beta.all=beta.all,y.all=y.all,A.all=A.all,\n sic=sic,bic=bic,mse=mse))\n}\n\n\n#' @title The inverse L0 trend filtering with fixed change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with a given number of change points.\n#' @param y The input data points\n#' @param k The given number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @return\n#' An S3 object of type \"L0TFinvfix\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betak}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with the number of change points being \\eqn{k} }\n#' \\item{yk}{The fitted trend with the number of change points being \\eqn{k}}\n#' \\item{Ak}{The set of position indicators of the fitted change points with the number of change points being \\eqn{k}}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.fix(y=BlocksData$y, k=5, q=0, first=0.01, last=1)\n#' print(res$Ak)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yk, col = \"lightgreen\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=5, q=1, first=0, last=0.99)\n#' print(res1$Ak)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yk, col = \"lightgreen\")\n#'\n#' @seealso \\code{\\link{L0TFinv.opt}}\n#' @export\nL0TFinv.fix <- function(y=y, k=k, q=q, first=0, last=1){\n if ( !(q %in% c(0,1)) ){\n stop(\"The order is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= k+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=k, q=q, first=first, last=last)\n betak = res$beta.all[,k]\n Ak = sort(res$A.all[[k]])\n yk = res$y.all[,k]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betak=betak,yk=yk,Ak=Ak,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvfix\"\n return(G)\n}\n\n\n\n#' @title The inverse L0 trend filtering with optimal change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with optimal change points.\n#' @param y The input data points\n#' @param kmax The maximum number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @param penalty 'sic' or 'bic' penalty\n#' @return\n#' An S3 object of type \"L0TFinvopt\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betaopt}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with optimal change points }\n#' \\item{yopt}{The fitted trend with optimal change points}\n#' \\item{Aopt}{The set of position indicators of the fitted change points with optimal change points}\n#' \\item{kopt}{Optimal number of change points}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k_{\\text{max}}}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @details\n#' Let the fitted trend be denoted as \\eqn{\\hat{\\boldsymbol{y}}}, then \\deqn{\\text{sic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\log(\\log(n)) \\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}})} and \\deqn{\\text{bic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}}).}\n#' The term \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})} represents the degrees of freedom for the estimated trend, where \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})=k+q+1}. Here, \\eqn{k} refers to the number of change points in the estimated trend.\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=20, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res$Aopt)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yopt, col = \"lightgreen\")\n#'\n#' tau1 = c(0.4, 0.6, 0.7)\n#' h1 = c(-3, 5, -4, 6)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 500, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.opt(y=WaveData$y, kmax=10, q=1, first=0, last=0.99, penalty=\"sic\")\n#' print(res1$Aopt)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yopt, col = \"lightgreen\")\n#'\n#' @export\nL0TFinv.opt <- function(y=y, kmax=kmax, q=q, first=0, last=1, penalty=\"bic\"){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if ( !(penalty %in% c(\"bic\",\"sic\")) ){\n stop(\"The specified penalty is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= kmax+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=kmax, q=q, first=first, last=last)\n if(penalty == \"bic\"){\n kopt = which.min(res$bic)\n }\n if(penalty == \"sic\"){\n kopt = which.min(res$sic)\n }\n betaopt = res$beta.all[,kopt]\n Aopt = sort(res$A.all[[kopt]])\n yopt = res$y.all[,kopt]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betaopt=betaopt,yopt=yopt,Aopt=Aopt,kopt=kopt,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvopt\"\n return(G)\n}\n\n \n\n", "middle_code": "function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/InverseL0TF/R/TFmetrics.R", "\n#' @title Print four metrics about change point detection results\n#' @description Prints four metrics to compare the quality of change point detection results.\n#' @param y0 The underlying trend\n#' @param tau The locations of change points in the underlying trend\n#' @param yhat The fitted trend\n#' @param cpts The positions of the fitted change points\n#' @return\n#' \\item{MSE}{The mean square error between the fitted trend and the underlying trend}\n#' \\item{MAD}{The median absolute deviation between the fitted trend and the underlying trend}\n#' \\item{dH}{Hausdorff Distance (dH) measures the accuracy of the estimated change points}\n#' \\item{nknot}{The number of detected change points}\n#' @details\n#' \\eqn{\\hat{\\boldsymbol{\\tau}}} represents the estimated change point positions, while \\eqn{\\boldsymbol{\\tau}} denotes the locations of change points in the underlying trend.\n#' \\deqn{d_H=\\frac{1}{n} \\max \\{\\max_k \\min_j |\\tau_j-\\hat{\\tau}_k|,\\max_j \\min_k |\\tau_j-\\hat{\\tau}_k|\\}.}\n#' Note that the number of \\eqn{\\hat{\\boldsymbol{\\tau}}} and \\eqn{\\boldsymbol{\\tau}} does not need to be the same.\n#' @examples\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' n = 500\n#' BlocksData <- SimuBlocksInv(n = n, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' metrics <- TFmetrics(BlocksData$y0,BlocksData$tau,res$yopt,res$Aopt/n)\n#' print(metrics)\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' n1 = 2000\n#' WaveData <- SimuWaveInv(n = n1, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' metrics1 <- TFmetrics(WaveData$y0,WaveData$tau,res1$y.all[,5],res1$A.all[[5]]/n1)\n#' print(metrics1)\n#'\n#' @export\nTFmetrics <- function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}\n\n\n\n\n\n\n\n\n"], ["/InverseL0TF/R/dataSimu.R", "#' @title Simulate Blocks Data\n#' @description This function generates data points of piecewise constant trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The constant values of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @return\n#' A list containing the piecewise constant simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1}\\}}\n#' \\item{y}{The piecewise constant simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @details\n#' \\itemize{\n#' \\item{}{To simplify the analysis, normalize the change point positions to a range between 0 and 1. Require that all elements of the input \\eqn{tau} are within this range. Consequently, the change point positions in simulated data forms a subset of the set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, 1\\}.}\n#' \\item{}{In fact, \\eqn{length(tau)} change points can divide the interval into \\eqn{length(tau)+1} segments of constant function values. Therefore, ensure that the length of vector \\eqn{h} is \\eqn{length(tau)+1}.}\n#' }\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.1, seed = 50, tau = tau ,h = h)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' print(BlocksData$setA)\n#' print(BlocksData$tau)\n#' @importFrom stats rnorm\n#' @export\nSimuBlocksInv <- function (n, sigma, seed = NA, tau, h ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+1){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = h[1]\n beta[A+1] = diff(h)\n y0 = cumsum(beta)\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n\n\n#' @title Simulate Wave Data\n#' @description This function generates data points of piecewise linear trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The slope of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @param a0 The initial point value\n#' @return\n#' A list containing the piecewise linear simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1} \\}}\n#' \\item{y}{The piecewise linear simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 650, sigma = 0.1, seed = 50, tau = tau, h = h, a0 = a0)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' print(WaveData$setA)\n#' print(WaveData$tau)\n#' @seealso \\code{\\link{SimuBlocksInv}}\n#' @importFrom stats rnorm\n#' @export\nSimuWaveInv <- function (n, sigma, seed = NA, tau, h, a0 = 0 ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+2){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = a0\n beta[2] = h[1]/n-beta[1]\n beta[A+1] = (diff(h))/n\n y0 = cumsum(cumsum(beta))\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n \n"], ["/InverseL0TF/R/plot.R", "\n#' @title Plot L0TFinvfix or L0TFinvopt object\n#'\n#' @description Plots a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param type The values are taken as c(\"\\eqn{mse}\", \"\\eqn{sic}\", \"\\eqn{bic}\", \"\\eqn{yhat}\"). If \\eqn{type} is \"\\eqn{mse}\", plot the mse as it changes with change points.\n#' The same applies to \"\\eqn{sic}\" and \"\\eqn{bic}\". If \\eqn{type} is \"\\eqn{yhat}\", plot the trend of the estimated values against the input data.\n#' @param k Only used for \\eqn{type} = \"\\eqn{yhat}\". The given number of change points.\n#' By default, the L0TFinvfix object outputs the estimated trend that corresponds to the fixed number of change points within the model. Conversely, the L0TFinvopt object provides the estimated trend based on the optimal change points.\n#' @param ... ignore\n#' @method plot L0TFinvfix\n#' @import ggplot2\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\nplot.L0TFinvfix <- function(x, type = NULL, k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = length(x$mse)\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n\n\n#' @rdname plot.L0TFinvfix\n#' @method plot L0TFinvopt\n#' @export\nplot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n"], ["/InverseL0TF/R/print.R", "\n#' @title Print L0TFinvfix or L0TFinvopt object\n#' @description Prints a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param ... ignore\n#' @method print L0TFinvfix\n#' @examples\n#' library(ggplot2)\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res)\n#' coef(res,k=res$kopt)\n#' plot(res,type=\"yhat\")\n#' plot(res,type=\"bic\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' print(res1)\n#' coef(res1,k=5)\n#' plot(res1,type=\"yhat\",k=5)\n#' plot(res1,type=\"mse\")\n#'\n#' @export\nprint.L0TFinvfix <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n#' @rdname print.L0TFinvfix\n#' @method print L0TFinvopt\n#' @export\nprint.L0TFinvopt <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,kopt=x$kopt,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n\n"], ["/InverseL0TF/R/intro.R", "#' @_PACKAGE\n#'\n#' @name L0TFinv-package\n#' @title A package for L0-regularized sparse approximation\n#' @description\n#' Trend filtering is a typical method for nonparametric regression.\n#' The commonly used trend filtering models is the L1 trend filtering model \\eqn{(a)} based on the difference matrix \\eqn{\\boldsymbol{D}^{(q+1)}}, as illustrated below.\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_1}, \\quad q=0,1,2, \\ldots. \\quad (a) }\n#' L0 trend filtering \\eqn{(b)} has a advantage over other trend filtering methods, especially in the detection of change points.\n#' The expression for L0 trend filtering is as follows:\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_0}. \\quad (b) }\n#' We explore transforming the problem \\eqn{(b)} into a L0-regularized sparse format \\eqn{(c)} by introducing an artificial design matrix \\eqn{\\boldsymbol{X}^{(q+1)}} that corresponds to the difference matrix, thereby reformulating the L0 trend filtering problem into the following format.\n#' \\deqn{\\min _{\\boldsymbol{\\beta} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2 + \\lambda \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0}. \\quad (c) }\n#' In our practical approach, we consider the maximum number of change points \\eqn{k_{\\text{max}}} as a constraint, transforming the aforementioned L0 penalty problem \\eqn{(c)} into the following L0 constraint problem.\n#' \\deqn{\\text{ minimize }\\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2,\\quad \\text{ subject to } \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0} \\leq k_{\\text{max}}. \\quad (d)}\n#' For such L0 constraint problems \\eqn{(d)}, we employ a splicing-based approach to design algorithms for processing.\n#' This package has the following seven main methods:\n#' \\itemize{\n#' \\item{\\strong{matrix with special structure }}{\\eqn{\\quad}Generate \\eqn{\\boldsymbol{X}^{(q+1)}} or \\eqn{\\boldsymbol{D}^{(q+1)}} matrix.}\n#' \\item{\\strong{inverse of the crossprod matrix }}{\\eqn{\\quad}Simplify the calculation of the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, which is frequently used in splicing algorithms.}\n#' \\item{\\strong{inverse L0 trend filtering with fixed change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a given number of change points.}\n#' \\item{\\strong{inverse L0 trend filtering with optimal change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a maximum number of change points, and select the optimal estimated trend using appropriate information criteria.}\n#' \\item{\\strong{simulated data }}{\\eqn{\\quad}Generate piecewise constant or piecewise linear data.}\n#' \\item{\\strong{print/coef}}{\\eqn{\\quad}Print a summary of the trend estimation results.}\n#' \\item{\\strong{plot }}{\\eqn{\\quad}Plot a summary of the trend estimation results.}\n#' }\n#' @details\n#' \\itemize{\n#' \\item{}{In previous studies, algorithms solving trend filtering problems \\eqn{(a)} necessitate the computation of \\eqn{((\\boldsymbol{D}^{(q+1)})^T \\boldsymbol{D}^{(q+1)})^{-1}}.\n#' When \\eqn{n} is large, just fitting the matrix into memory becomes an issue.}\n#' \\item{}{In L0 trend filtering \\eqn{(b)}, the positions of non-zero elements in the L0 norm correspond with the locations of change points.\n#' We consider two subsets: the active set \\eqn{A} for non-zero elements and the inactive set \\eqn{I} for zero elements.\n#' Despite this, computing \\eqn{((\\boldsymbol{D}^{(q+1)}_I)^T \\boldsymbol{D}^{(q+1)}_I)^{-1}} remains a task involving a substantial matrix.}\n#' \\item{}{Due to the connection between L0 constraint problems and L0 penalty problems, and considering that the sparsity of \\eqn{\\boldsymbol{\\beta}} is is more meaningful in practical applications than the selection of the hyperparameter \\eqn{\\lambda}.\n#' We focus on the constraint that reflects our aim to achieve an estimated trend with a given number of change points.\n#' So we transform the L0 penalty problem \\eqn{(c)} into the L0 constraint problem \\eqn{(d)}.}\n#' }\n#' @references\n#' Kim SJ, Koh K, Boyd SP and Gorinevsky DM. L1 Trend Filtering. Society for Industrial and Applied Mathematics (2009).\n#'\n#' Wen C, Wang X and Zhang A. L0 Trend Filtering. INFORMS Journal on Computing (2023).\nNULL\n\n"], ["/InverseL0TF/R/solveMatrix.R", "#' @title Generate the inverse of the crossprod matrix\n#' @description Generate the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, commonly employed in splicing algorithms. Note that an explicit solution exists for the inverse when \\eqn{q=0}, but not when \\eqn{q=1}.\n#' @param n The number of data points\n#' @param q The order of the difference, 0 or 1\n#' @param A The set of indicators, a subset of \\eqn{\\{1,2,3,\\dots,n\\}}\n#' @return The inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=} 0 or 1.\n#' @examples\n#' Mat1 <- XMat(n = 10, q = 0)\n#' A1 = c(1,2,5,8)\n#' mat1 = as.matrix(Mat1[,A1])\n#' S1 <- solMat(n = 10, q = 0, A = A1)\n#' print(S1)\n#' print(round(S1%*%t(mat1)%*%mat1,10))\n#'\n#' Mat2 <- XMat(n = 15, q = 1)\n#' A2 = c(1,3,8,10,15)\n#' mat2 = as.matrix(Mat2[,A2])\n#' S2 <- solMat(n = 15, q = 1, A = A2)\n#' print(S2)\n#' print(round(S2%*%t(mat2)%*%mat2,10))\n#' @importFrom Matrix solve\n#' @export\nsolMat <- function(n, q, A){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if( min(A)<1 | max(A)>n ){\n stop(\"\nThe maximum possible range for the set indicators should be within {1,2,...,n}\")\n }\n k = length(A)\n m = as.numeric(k)\n m = n + 1 - A\n phi = matrix(0, k, k)\n if(q == 0){\n if(k == 1){\n phi[1,1] = 1/m[1]\n return(phi)\n }\n if(k == 2){\n phi[1,1] = m[2]\n phi[1,2] = -m[2]\n phi[2,1] = -m[2]\n phi[2,2] = m[1]\n phi = phi/(m[2]*(m[1]-m[2]))\n return(phi)\n }\n for(i in 1:k){\n if(i == 1){\n phi[1,1] = 1/(m[1]-m[2])\n phi[1,2] = -1/(m[1]-m[2])\n next\n }\n if(i == k){\n phi[k,(k-1)] = -1/(m[(k-1)]-m[k])\n phi[k,k] = 1/(m[(k-1)]-m[k])+1/m[k]\n break\n }\n phi[i,(i-1)] = -1/(m[(i-1)]-m[i])\n phi[i,i] = 1/(m[(i-1)]-m[i])+1/(m[i]-m[(i+1)])\n phi[i,(i+1)] = -1/(m[i]-m[(i+1)])\n }\n return(phi)\n }\n if (q == 1) {\n for (j in 1:k) {\n for (i in j:k) {\n if (j == i) {\n phi[i, j] <- m[j] * (m[j] + 1) * (2 * m[j] + 1) / 6\n } else {\n phi[i, j] <- m[i] * (m[i] + 1) * (3 * m[j] - m[i] + 1) / 6\n }\n }\n }\n phi <- phi + t(phi) - diag(diag(phi))\n phi <- solve(phi)\n return(phi)\n }\n}\n\n\n\n"], ["/InverseL0TF/R/sMatrix.R", "#' @title Generate a difference matrix\n#' @description This function generates a matrix for computing differences of a certain order, useful in numerical methods and for creating specific matrix patterns.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n-q-1} by \\eqn{n}, whose elements correspond to the combinatorial values of \\eqn{q}.\n#' @examples\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' print(Mat1)\n#'\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' print(Mat2)\n#'\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat3)\n#'\n#' @seealso \\code{\\link{XMat}}\n#' @export\nDiffMat <- function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}\n\n\n\n#' @title Generate an artificial design matrix\n#' @description This matrix corresponds to the difference matrix, transforming the L0 trend filtering model into an inverse statistical problem.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n} by \\eqn{n}, whose elements correspond to the difference matrix.\n#' @examples\n#' mat1 <- XMat(n = 10, q = 0)\n#' print(mat1)\n#'\n#' mat2 <- XMat(n = 15, q = 1)\n#' print(mat2)\n#'\n#' mat3 <- XMat(n = 15, q = 2)\n#' print(mat3)\n#'\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat1%*%mat1)\n#' print(Mat2%*%mat2)\n#' print(Mat3%*%mat3)\n#' @details Noticing the correspondence between \\eqn{\\boldsymbol{D}^{(q+1)}} and \\eqn{\\boldsymbol{X}^{(q+1)}}, the result of their matrix multiplication is a combination of a zero matrix and an identity matrix. Expressed as \\eqn{\\boldsymbol{D}^{(q+1)} \\boldsymbol{X}^{(q+1)}=(\\boldsymbol{O}_{(n-q-1)\\times(q+1)},\\quad \\boldsymbol{I}_{(n-q-1)\\times(n-q-1)})}. The result is advantageous for the invertible processing of the original L0 trend filtering problem.\n#' @export\nXMat <- function(n, q){\n X <- matrix(0,n,n)\n if(q == 0){\n for(i in 1:n){\n for(j in 1:i){\n X[i,j] <- 1\n }\n }\n return(X)\n }else{\n return(apply(XMat(n, q-1),2,cumsum))\n }\n}\n\n\n\n\n\n"], ["/InverseL0TF/R/coef.R", "\n#' @title Extract estimated trends\n#' @description Extract the coefficients of the estimated trends under the constraint of a given number of change points.\n#' @param object The output of L0TFinvfix or L0TFinvopt\n#' @param k The given number of change points\n#' @method coef L0TFinvfix\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\ncoef.L0TFinvfix <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n\n#' @rdname coef.L0TFinvfix\n#' @method coef L0TFinvopt\n#' @export\ncoef.L0TFinvopt <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:02:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last) {}", "code_description": "This code segment functions to: Iteratively refine model components by exchanging elements between active and candidate sets based on error metrics, optimizing coefficients to minimize residual error while respecting positional constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nSplicing <- function(A=A, I=I, k=k, y=y, q=q, H=H, U=U, first=first, last=last){\n n = length(y)\n S = 1:(q+1)\n A_combined = sort(union(S,A))\n beta = rep(0,n)\n beta[A_combined] = solMat(n=n,q=q,A=A_combined)%*%U[A_combined]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,(q+2):n)\n I0 = intersect(I,AS0)\n if(length(I0) > 0){\n i1 = I0[which.max(eps[I0])]\n A = union(A,i1)\n I = setdiff(I,i1)\n }\n A_candidate = setdiff(A,S)\n if(length(A_candidate) > k){\n A_eps = eps[A_candidate]\n remove = A_candidate[order(A_eps)[1:(length(A_candidate)-k)]]\n A = setdiff(A,remove)\n I = union(I,remove)\n }\n return(list(A=A,I=I,beta=beta))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-03-38"}, "editdistance_info": {"edit_distance": 27.1784, "calculate_time": "2025-08-21 01:03:38", "true_code_clean": "function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}", "predict_code_clean": "Splicing <- function(A=A, I=I, k=k, y=y, q=q, H=H, U=U, first=first, last=last){\n n = length(y)\n S = 1:(q+1)\n A_combined = sort(union(S,A))\n beta = rep(0,n)\n beta[A_combined] = solMat(n=n,q=q,A=A_combined)%*%U[A_combined]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,(q+2):n)\n I0 = intersect(I,AS0)\n if(length(I0) > 0){\n i1 = I0[which.max(eps[I0])]\n A = union(A,i1)\n I = setdiff(I,i1)\n }\n A_candidate = setdiff(A,S)\n if(length(A_candidate) > k){\n A_eps = eps[A_candidate]\n remove = A_candidate[order(A_eps)[1:(length(A_candidate)-k)]]\n A = setdiff(A,remove)\n I = union(I,remove)\n }\n return(list(A=A,I=I,beta=beta))\n}"}}
{"repo_name": "InverseL0TF", "file_name": "/InverseL0TF/R/TFmetrics.R", "inference_info": {"prefix_code": "\n#' @title Print four metrics about change point detection results\n#' @description Prints four metrics to compare the quality of change point detection results.\n#' @param y0 The underlying trend\n#' @param tau The locations of change points in the underlying trend\n#' @param yhat The fitted trend\n#' @param cpts The positions of the fitted change points\n#' @return\n#' \\item{MSE}{The mean square error between the fitted trend and the underlying trend}\n#' \\item{MAD}{The median absolute deviation between the fitted trend and the underlying trend}\n#' \\item{dH}{Hausdorff Distance (dH) measures the accuracy of the estimated change points}\n#' \\item{nknot}{The number of detected change points}\n#' @details\n#' \\eqn{\\hat{\\boldsymbol{\\tau}}} represents the estimated change point positions, while \\eqn{\\boldsymbol{\\tau}} denotes the locations of change points in the underlying trend.\n#' \\deqn{d_H=\\frac{1}{n} \\max \\{\\max_k \\min_j |\\tau_j-\\hat{\\tau}_k|,\\max_j \\min_k |\\tau_j-\\hat{\\tau}_k|\\}.}\n#' Note that the number of \\eqn{\\hat{\\boldsymbol{\\tau}}} and \\eqn{\\boldsymbol{\\tau}} does not need to be the same.\n#' @examples\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' n = 500\n#' BlocksData <- SimuBlocksInv(n = n, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' metrics <- TFmetrics(BlocksData$y0,BlocksData$tau,res$yopt,res$Aopt/n)\n#' print(metrics)\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' n1 = 2000\n#' WaveData <- SimuWaveInv(n = n1, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' metrics1 <- TFmetrics(WaveData$y0,WaveData$tau,res1$y.all[,5],res1$A.all[[5]]/n1)\n#' print(metrics1)\n#'\n#' @export\nTFmetrics <- ", "suffix_code": "\n\n\n\n\n\n\n\n\n", "middle_code": "function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/InverseL0TF/R/invL0TF.R", "\n\nybeta <- function(beta=beta,q=q){\n if(q == 0){\n return(cumsum(beta))\n }\n if(q == 1){\n return(cumsum(cumsum(beta)))\n }\n}\n\nDy <- function(y=y,q=q,U=U){\n if(q == 0){\n D = U-rev(cumsum(rev(y)))\n return(D)\n }\n if(q == 1){\n D = U-rev(cumsum(cumsum(rev(y))))\n return(D)\n }\n}\n\nSplicing <- function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}\n\nInvL0TFk <- function(A0=A0,y=y,q=q,k=k,H=H,U=U,first=first,last=last,max.step=50){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n I0 = setdiff(AS,A0)\n for(j in 1:max.step){\n m = Splicing(A=A0,I=I0,k=k,y=y,q=q,H=H,U=U,first=first,last=last)\n A = m$A\n I = m$I\n beta = m$beta\n if(identical(A,A0) & identical(I,I0)){\n break\n }else{\n A0 = A\n I0 = I\n }\n }\n yhat = ybeta(beta=beta,q=q)\n Ahat = sort(A,decreasing = FALSE)\n return(list(betak=beta,yk=yhat,Ak=Ahat))\n}\n\nInverseL0TF <- function(y=y,kmax=kmax,q=q,first=0,last=1){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n A0 = NULL\n I0 = setdiff(AS,A0)\n\n beta.all = NULL\n y.all = NULL\n A.all = list()\n mse = as.numeric(kmax)\n sic = as.numeric(kmax)\n eps = as.numeric(n)\n if(q == 0){\n H = n:1/n\n U = rev(cumsum(rev(y)))\n }\n if(q == 1){\n H = sapply(n:1, function(x) x*(x+1)*(2*x+1)/6)/n\n U = rev(cumsum(cumsum(rev(y))))\n }\n Al = sort(union(S,A0),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n for(j in 1:kmax){\n result = InvL0TFk(A0=A0,y=y,q=q,k=j,H=H,U=U,first=first,last=last)\n beta.all = cbind(beta.all,result$betak)\n y.all = cbind(y.all,result$yk)\n A0 = result$Ak\n I0 = setdiff(AS,A0)\n A.all[[j]] = A0 - 1\n D = Dy(y=as.vector(y.all[,j]),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n }\n mse = colMeans((y-y.all)^2)\n df = 1:kmax + q + 1\n sic = n*log(mse) + 2*log(log(n))*log(n)*df\n bic = n*log(mse) + 2*log(n)*df\n return(list(beta.all=beta.all,y.all=y.all,A.all=A.all,\n sic=sic,bic=bic,mse=mse))\n}\n\n\n#' @title The inverse L0 trend filtering with fixed change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with a given number of change points.\n#' @param y The input data points\n#' @param k The given number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @return\n#' An S3 object of type \"L0TFinvfix\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betak}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with the number of change points being \\eqn{k} }\n#' \\item{yk}{The fitted trend with the number of change points being \\eqn{k}}\n#' \\item{Ak}{The set of position indicators of the fitted change points with the number of change points being \\eqn{k}}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.fix(y=BlocksData$y, k=5, q=0, first=0.01, last=1)\n#' print(res$Ak)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yk, col = \"lightgreen\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=5, q=1, first=0, last=0.99)\n#' print(res1$Ak)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yk, col = \"lightgreen\")\n#'\n#' @seealso \\code{\\link{L0TFinv.opt}}\n#' @export\nL0TFinv.fix <- function(y=y, k=k, q=q, first=0, last=1){\n if ( !(q %in% c(0,1)) ){\n stop(\"The order is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= k+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=k, q=q, first=first, last=last)\n betak = res$beta.all[,k]\n Ak = sort(res$A.all[[k]])\n yk = res$y.all[,k]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betak=betak,yk=yk,Ak=Ak,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvfix\"\n return(G)\n}\n\n\n\n#' @title The inverse L0 trend filtering with optimal change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with optimal change points.\n#' @param y The input data points\n#' @param kmax The maximum number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @param penalty 'sic' or 'bic' penalty\n#' @return\n#' An S3 object of type \"L0TFinvopt\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betaopt}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with optimal change points }\n#' \\item{yopt}{The fitted trend with optimal change points}\n#' \\item{Aopt}{The set of position indicators of the fitted change points with optimal change points}\n#' \\item{kopt}{Optimal number of change points}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k_{\\text{max}}}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @details\n#' Let the fitted trend be denoted as \\eqn{\\hat{\\boldsymbol{y}}}, then \\deqn{\\text{sic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\log(\\log(n)) \\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}})} and \\deqn{\\text{bic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}}).}\n#' The term \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})} represents the degrees of freedom for the estimated trend, where \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})=k+q+1}. Here, \\eqn{k} refers to the number of change points in the estimated trend.\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=20, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res$Aopt)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yopt, col = \"lightgreen\")\n#'\n#' tau1 = c(0.4, 0.6, 0.7)\n#' h1 = c(-3, 5, -4, 6)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 500, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.opt(y=WaveData$y, kmax=10, q=1, first=0, last=0.99, penalty=\"sic\")\n#' print(res1$Aopt)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yopt, col = \"lightgreen\")\n#'\n#' @export\nL0TFinv.opt <- function(y=y, kmax=kmax, q=q, first=0, last=1, penalty=\"bic\"){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if ( !(penalty %in% c(\"bic\",\"sic\")) ){\n stop(\"The specified penalty is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= kmax+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=kmax, q=q, first=first, last=last)\n if(penalty == \"bic\"){\n kopt = which.min(res$bic)\n }\n if(penalty == \"sic\"){\n kopt = which.min(res$sic)\n }\n betaopt = res$beta.all[,kopt]\n Aopt = sort(res$A.all[[kopt]])\n yopt = res$y.all[,kopt]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betaopt=betaopt,yopt=yopt,Aopt=Aopt,kopt=kopt,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvopt\"\n return(G)\n}\n\n \n\n"], ["/InverseL0TF/R/dataSimu.R", "#' @title Simulate Blocks Data\n#' @description This function generates data points of piecewise constant trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The constant values of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @return\n#' A list containing the piecewise constant simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1}\\}}\n#' \\item{y}{The piecewise constant simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @details\n#' \\itemize{\n#' \\item{}{To simplify the analysis, normalize the change point positions to a range between 0 and 1. Require that all elements of the input \\eqn{tau} are within this range. Consequently, the change point positions in simulated data forms a subset of the set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, 1\\}.}\n#' \\item{}{In fact, \\eqn{length(tau)} change points can divide the interval into \\eqn{length(tau)+1} segments of constant function values. Therefore, ensure that the length of vector \\eqn{h} is \\eqn{length(tau)+1}.}\n#' }\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.1, seed = 50, tau = tau ,h = h)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' print(BlocksData$setA)\n#' print(BlocksData$tau)\n#' @importFrom stats rnorm\n#' @export\nSimuBlocksInv <- function (n, sigma, seed = NA, tau, h ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+1){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = h[1]\n beta[A+1] = diff(h)\n y0 = cumsum(beta)\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n\n\n#' @title Simulate Wave Data\n#' @description This function generates data points of piecewise linear trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The slope of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @param a0 The initial point value\n#' @return\n#' A list containing the piecewise linear simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1} \\}}\n#' \\item{y}{The piecewise linear simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 650, sigma = 0.1, seed = 50, tau = tau, h = h, a0 = a0)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' print(WaveData$setA)\n#' print(WaveData$tau)\n#' @seealso \\code{\\link{SimuBlocksInv}}\n#' @importFrom stats rnorm\n#' @export\nSimuWaveInv <- function (n, sigma, seed = NA, tau, h, a0 = 0 ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+2){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = a0\n beta[2] = h[1]/n-beta[1]\n beta[A+1] = (diff(h))/n\n y0 = cumsum(cumsum(beta))\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n \n"], ["/InverseL0TF/R/print.R", "\n#' @title Print L0TFinvfix or L0TFinvopt object\n#' @description Prints a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param ... ignore\n#' @method print L0TFinvfix\n#' @examples\n#' library(ggplot2)\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res)\n#' coef(res,k=res$kopt)\n#' plot(res,type=\"yhat\")\n#' plot(res,type=\"bic\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' print(res1)\n#' coef(res1,k=5)\n#' plot(res1,type=\"yhat\",k=5)\n#' plot(res1,type=\"mse\")\n#'\n#' @export\nprint.L0TFinvfix <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n#' @rdname print.L0TFinvfix\n#' @method print L0TFinvopt\n#' @export\nprint.L0TFinvopt <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,kopt=x$kopt,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n\n"], ["/InverseL0TF/R/plot.R", "\n#' @title Plot L0TFinvfix or L0TFinvopt object\n#'\n#' @description Plots a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param type The values are taken as c(\"\\eqn{mse}\", \"\\eqn{sic}\", \"\\eqn{bic}\", \"\\eqn{yhat}\"). If \\eqn{type} is \"\\eqn{mse}\", plot the mse as it changes with change points.\n#' The same applies to \"\\eqn{sic}\" and \"\\eqn{bic}\". If \\eqn{type} is \"\\eqn{yhat}\", plot the trend of the estimated values against the input data.\n#' @param k Only used for \\eqn{type} = \"\\eqn{yhat}\". The given number of change points.\n#' By default, the L0TFinvfix object outputs the estimated trend that corresponds to the fixed number of change points within the model. Conversely, the L0TFinvopt object provides the estimated trend based on the optimal change points.\n#' @param ... ignore\n#' @method plot L0TFinvfix\n#' @import ggplot2\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\nplot.L0TFinvfix <- function(x, type = NULL, k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = length(x$mse)\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n\n\n#' @rdname plot.L0TFinvfix\n#' @method plot L0TFinvopt\n#' @export\nplot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n"], ["/InverseL0TF/R/intro.R", "#' @_PACKAGE\n#'\n#' @name L0TFinv-package\n#' @title A package for L0-regularized sparse approximation\n#' @description\n#' Trend filtering is a typical method for nonparametric regression.\n#' The commonly used trend filtering models is the L1 trend filtering model \\eqn{(a)} based on the difference matrix \\eqn{\\boldsymbol{D}^{(q+1)}}, as illustrated below.\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_1}, \\quad q=0,1,2, \\ldots. \\quad (a) }\n#' L0 trend filtering \\eqn{(b)} has a advantage over other trend filtering methods, especially in the detection of change points.\n#' The expression for L0 trend filtering is as follows:\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_0}. \\quad (b) }\n#' We explore transforming the problem \\eqn{(b)} into a L0-regularized sparse format \\eqn{(c)} by introducing an artificial design matrix \\eqn{\\boldsymbol{X}^{(q+1)}} that corresponds to the difference matrix, thereby reformulating the L0 trend filtering problem into the following format.\n#' \\deqn{\\min _{\\boldsymbol{\\beta} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2 + \\lambda \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0}. \\quad (c) }\n#' In our practical approach, we consider the maximum number of change points \\eqn{k_{\\text{max}}} as a constraint, transforming the aforementioned L0 penalty problem \\eqn{(c)} into the following L0 constraint problem.\n#' \\deqn{\\text{ minimize }\\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2,\\quad \\text{ subject to } \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0} \\leq k_{\\text{max}}. \\quad (d)}\n#' For such L0 constraint problems \\eqn{(d)}, we employ a splicing-based approach to design algorithms for processing.\n#' This package has the following seven main methods:\n#' \\itemize{\n#' \\item{\\strong{matrix with special structure }}{\\eqn{\\quad}Generate \\eqn{\\boldsymbol{X}^{(q+1)}} or \\eqn{\\boldsymbol{D}^{(q+1)}} matrix.}\n#' \\item{\\strong{inverse of the crossprod matrix }}{\\eqn{\\quad}Simplify the calculation of the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, which is frequently used in splicing algorithms.}\n#' \\item{\\strong{inverse L0 trend filtering with fixed change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a given number of change points.}\n#' \\item{\\strong{inverse L0 trend filtering with optimal change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a maximum number of change points, and select the optimal estimated trend using appropriate information criteria.}\n#' \\item{\\strong{simulated data }}{\\eqn{\\quad}Generate piecewise constant or piecewise linear data.}\n#' \\item{\\strong{print/coef}}{\\eqn{\\quad}Print a summary of the trend estimation results.}\n#' \\item{\\strong{plot }}{\\eqn{\\quad}Plot a summary of the trend estimation results.}\n#' }\n#' @details\n#' \\itemize{\n#' \\item{}{In previous studies, algorithms solving trend filtering problems \\eqn{(a)} necessitate the computation of \\eqn{((\\boldsymbol{D}^{(q+1)})^T \\boldsymbol{D}^{(q+1)})^{-1}}.\n#' When \\eqn{n} is large, just fitting the matrix into memory becomes an issue.}\n#' \\item{}{In L0 trend filtering \\eqn{(b)}, the positions of non-zero elements in the L0 norm correspond with the locations of change points.\n#' We consider two subsets: the active set \\eqn{A} for non-zero elements and the inactive set \\eqn{I} for zero elements.\n#' Despite this, computing \\eqn{((\\boldsymbol{D}^{(q+1)}_I)^T \\boldsymbol{D}^{(q+1)}_I)^{-1}} remains a task involving a substantial matrix.}\n#' \\item{}{Due to the connection between L0 constraint problems and L0 penalty problems, and considering that the sparsity of \\eqn{\\boldsymbol{\\beta}} is is more meaningful in practical applications than the selection of the hyperparameter \\eqn{\\lambda}.\n#' We focus on the constraint that reflects our aim to achieve an estimated trend with a given number of change points.\n#' So we transform the L0 penalty problem \\eqn{(c)} into the L0 constraint problem \\eqn{(d)}.}\n#' }\n#' @references\n#' Kim SJ, Koh K, Boyd SP and Gorinevsky DM. L1 Trend Filtering. Society for Industrial and Applied Mathematics (2009).\n#'\n#' Wen C, Wang X and Zhang A. L0 Trend Filtering. INFORMS Journal on Computing (2023).\nNULL\n\n"], ["/InverseL0TF/R/solveMatrix.R", "#' @title Generate the inverse of the crossprod matrix\n#' @description Generate the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, commonly employed in splicing algorithms. Note that an explicit solution exists for the inverse when \\eqn{q=0}, but not when \\eqn{q=1}.\n#' @param n The number of data points\n#' @param q The order of the difference, 0 or 1\n#' @param A The set of indicators, a subset of \\eqn{\\{1,2,3,\\dots,n\\}}\n#' @return The inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=} 0 or 1.\n#' @examples\n#' Mat1 <- XMat(n = 10, q = 0)\n#' A1 = c(1,2,5,8)\n#' mat1 = as.matrix(Mat1[,A1])\n#' S1 <- solMat(n = 10, q = 0, A = A1)\n#' print(S1)\n#' print(round(S1%*%t(mat1)%*%mat1,10))\n#'\n#' Mat2 <- XMat(n = 15, q = 1)\n#' A2 = c(1,3,8,10,15)\n#' mat2 = as.matrix(Mat2[,A2])\n#' S2 <- solMat(n = 15, q = 1, A = A2)\n#' print(S2)\n#' print(round(S2%*%t(mat2)%*%mat2,10))\n#' @importFrom Matrix solve\n#' @export\nsolMat <- function(n, q, A){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if( min(A)<1 | max(A)>n ){\n stop(\"\nThe maximum possible range for the set indicators should be within {1,2,...,n}\")\n }\n k = length(A)\n m = as.numeric(k)\n m = n + 1 - A\n phi = matrix(0, k, k)\n if(q == 0){\n if(k == 1){\n phi[1,1] = 1/m[1]\n return(phi)\n }\n if(k == 2){\n phi[1,1] = m[2]\n phi[1,2] = -m[2]\n phi[2,1] = -m[2]\n phi[2,2] = m[1]\n phi = phi/(m[2]*(m[1]-m[2]))\n return(phi)\n }\n for(i in 1:k){\n if(i == 1){\n phi[1,1] = 1/(m[1]-m[2])\n phi[1,2] = -1/(m[1]-m[2])\n next\n }\n if(i == k){\n phi[k,(k-1)] = -1/(m[(k-1)]-m[k])\n phi[k,k] = 1/(m[(k-1)]-m[k])+1/m[k]\n break\n }\n phi[i,(i-1)] = -1/(m[(i-1)]-m[i])\n phi[i,i] = 1/(m[(i-1)]-m[i])+1/(m[i]-m[(i+1)])\n phi[i,(i+1)] = -1/(m[i]-m[(i+1)])\n }\n return(phi)\n }\n if (q == 1) {\n for (j in 1:k) {\n for (i in j:k) {\n if (j == i) {\n phi[i, j] <- m[j] * (m[j] + 1) * (2 * m[j] + 1) / 6\n } else {\n phi[i, j] <- m[i] * (m[i] + 1) * (3 * m[j] - m[i] + 1) / 6\n }\n }\n }\n phi <- phi + t(phi) - diag(diag(phi))\n phi <- solve(phi)\n return(phi)\n }\n}\n\n\n\n"], ["/InverseL0TF/R/sMatrix.R", "#' @title Generate a difference matrix\n#' @description This function generates a matrix for computing differences of a certain order, useful in numerical methods and for creating specific matrix patterns.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n-q-1} by \\eqn{n}, whose elements correspond to the combinatorial values of \\eqn{q}.\n#' @examples\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' print(Mat1)\n#'\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' print(Mat2)\n#'\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat3)\n#'\n#' @seealso \\code{\\link{XMat}}\n#' @export\nDiffMat <- function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}\n\n\n\n#' @title Generate an artificial design matrix\n#' @description This matrix corresponds to the difference matrix, transforming the L0 trend filtering model into an inverse statistical problem.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n} by \\eqn{n}, whose elements correspond to the difference matrix.\n#' @examples\n#' mat1 <- XMat(n = 10, q = 0)\n#' print(mat1)\n#'\n#' mat2 <- XMat(n = 15, q = 1)\n#' print(mat2)\n#'\n#' mat3 <- XMat(n = 15, q = 2)\n#' print(mat3)\n#'\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat1%*%mat1)\n#' print(Mat2%*%mat2)\n#' print(Mat3%*%mat3)\n#' @details Noticing the correspondence between \\eqn{\\boldsymbol{D}^{(q+1)}} and \\eqn{\\boldsymbol{X}^{(q+1)}}, the result of their matrix multiplication is a combination of a zero matrix and an identity matrix. Expressed as \\eqn{\\boldsymbol{D}^{(q+1)} \\boldsymbol{X}^{(q+1)}=(\\boldsymbol{O}_{(n-q-1)\\times(q+1)},\\quad \\boldsymbol{I}_{(n-q-1)\\times(n-q-1)})}. The result is advantageous for the invertible processing of the original L0 trend filtering problem.\n#' @export\nXMat <- function(n, q){\n X <- matrix(0,n,n)\n if(q == 0){\n for(i in 1:n){\n for(j in 1:i){\n X[i,j] <- 1\n }\n }\n return(X)\n }else{\n return(apply(XMat(n, q-1),2,cumsum))\n }\n}\n\n\n\n\n\n"], ["/InverseL0TF/R/coef.R", "\n#' @title Extract estimated trends\n#' @description Extract the coefficients of the estimated trends under the constraint of a given number of change points.\n#' @param object The output of L0TFinvfix or L0TFinvopt\n#' @param k The given number of change points\n#' @method coef L0TFinvfix\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\ncoef.L0TFinvfix <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n\n#' @rdname coef.L0TFinvfix\n#' @method coef L0TFinvopt\n#' @export\ncoef.L0TFinvopt <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:02:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(y0, tau=NULL, yhat, cpts = NULL) {}", "code_description": "This code segment functions to: Compute statistical measures to evaluate the accuracy of trend estimation and change point detection by comparing fitted results against ground truth values while accounting for positional discrepancies between detected and reference events."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(y0, tau = NULL, yhat, cpts = NULL) {\n MSE <- mean((y0 - yhat)^2)\n MAD <- median(abs(y0 - yhat))\n \n if (is.null(tau) || is.null(cpts)) {\n dH <- NA\n } else {\n term1 <- max(sapply(cpts, function(x) min(abs(tau - x))))\n term2 <- max(sapply(tau, function(x) min(abs(cpts - x))))\n dH <- max(term1, term2) / length(y0)\n }\n \n nknot <- ifelse(is.null(cpts), 0, length(cpts))\n \n list(MSE = MSE, MAD = MAD, dH = dH, nknot = nknot)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-04-03"}, "editdistance_info": {"edit_distance": 20.5021, "calculate_time": "2025-08-21 01:04:03", "true_code_clean": "function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}", "predict_code_clean": "function(y0, tau = NULL, yhat, cpts = NULL) {\n MSE <- mean((y0 - yhat)^2)\n MAD <- median(abs(y0 - yhat))\n if (is.null(tau) || is.null(cpts)) {\n dH <- NA\n } else {\n term1 <- max(sapply(cpts, function(x) min(abs(tau - x))))\n term2 <- max(sapply(tau, function(x) min(abs(cpts - x))))\n dH <- max(term1, term2) / length(y0)\n }\n nknot <- ifelse(is.null(cpts), 0, length(cpts))\n list(MSE = MSE, MAD = MAD, dH = dH, nknot = nknot)\n}"}}
{"repo_name": "InverseL0TF", "file_name": "/InverseL0TF/R/sMatrix.R", "inference_info": {"prefix_code": "#' @title Generate a difference matrix\n#' @description This function generates a matrix for computing differences of a certain order, useful in numerical methods and for creating specific matrix patterns.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n-q-1} by \\eqn{n}, whose elements correspond to the combinatorial values of \\eqn{q}.\n#' @examples\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' print(Mat1)\n#'\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' print(Mat2)\n#'\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat3)\n#'\n#' @seealso \\code{\\link{XMat}}\n#' @export\nDiffMat <- ", "suffix_code": "\n\n\n\n#' @title Generate an artificial design matrix\n#' @description This matrix corresponds to the difference matrix, transforming the L0 trend filtering model into an inverse statistical problem.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n} by \\eqn{n}, whose elements correspond to the difference matrix.\n#' @examples\n#' mat1 <- XMat(n = 10, q = 0)\n#' print(mat1)\n#'\n#' mat2 <- XMat(n = 15, q = 1)\n#' print(mat2)\n#'\n#' mat3 <- XMat(n = 15, q = 2)\n#' print(mat3)\n#'\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat1%*%mat1)\n#' print(Mat2%*%mat2)\n#' print(Mat3%*%mat3)\n#' @details Noticing the correspondence between \\eqn{\\boldsymbol{D}^{(q+1)}} and \\eqn{\\boldsymbol{X}^{(q+1)}}, the result of their matrix multiplication is a combination of a zero matrix and an identity matrix. Expressed as \\eqn{\\boldsymbol{D}^{(q+1)} \\boldsymbol{X}^{(q+1)}=(\\boldsymbol{O}_{(n-q-1)\\times(q+1)},\\quad \\boldsymbol{I}_{(n-q-1)\\times(n-q-1)})}. The result is advantageous for the invertible processing of the original L0 trend filtering problem.\n#' @export\nXMat <- function(n, q){\n X <- matrix(0,n,n)\n if(q == 0){\n for(i in 1:n){\n for(j in 1:i){\n X[i,j] <- 1\n }\n }\n return(X)\n }else{\n return(apply(XMat(n, q-1),2,cumsum))\n }\n}\n\n\n\n\n\n", "middle_code": "function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/InverseL0TF/R/solveMatrix.R", "#' @title Generate the inverse of the crossprod matrix\n#' @description Generate the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, commonly employed in splicing algorithms. Note that an explicit solution exists for the inverse when \\eqn{q=0}, but not when \\eqn{q=1}.\n#' @param n The number of data points\n#' @param q The order of the difference, 0 or 1\n#' @param A The set of indicators, a subset of \\eqn{\\{1,2,3,\\dots,n\\}}\n#' @return The inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=} 0 or 1.\n#' @examples\n#' Mat1 <- XMat(n = 10, q = 0)\n#' A1 = c(1,2,5,8)\n#' mat1 = as.matrix(Mat1[,A1])\n#' S1 <- solMat(n = 10, q = 0, A = A1)\n#' print(S1)\n#' print(round(S1%*%t(mat1)%*%mat1,10))\n#'\n#' Mat2 <- XMat(n = 15, q = 1)\n#' A2 = c(1,3,8,10,15)\n#' mat2 = as.matrix(Mat2[,A2])\n#' S2 <- solMat(n = 15, q = 1, A = A2)\n#' print(S2)\n#' print(round(S2%*%t(mat2)%*%mat2,10))\n#' @importFrom Matrix solve\n#' @export\nsolMat <- function(n, q, A){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if( min(A)<1 | max(A)>n ){\n stop(\"\nThe maximum possible range for the set indicators should be within {1,2,...,n}\")\n }\n k = length(A)\n m = as.numeric(k)\n m = n + 1 - A\n phi = matrix(0, k, k)\n if(q == 0){\n if(k == 1){\n phi[1,1] = 1/m[1]\n return(phi)\n }\n if(k == 2){\n phi[1,1] = m[2]\n phi[1,2] = -m[2]\n phi[2,1] = -m[2]\n phi[2,2] = m[1]\n phi = phi/(m[2]*(m[1]-m[2]))\n return(phi)\n }\n for(i in 1:k){\n if(i == 1){\n phi[1,1] = 1/(m[1]-m[2])\n phi[1,2] = -1/(m[1]-m[2])\n next\n }\n if(i == k){\n phi[k,(k-1)] = -1/(m[(k-1)]-m[k])\n phi[k,k] = 1/(m[(k-1)]-m[k])+1/m[k]\n break\n }\n phi[i,(i-1)] = -1/(m[(i-1)]-m[i])\n phi[i,i] = 1/(m[(i-1)]-m[i])+1/(m[i]-m[(i+1)])\n phi[i,(i+1)] = -1/(m[i]-m[(i+1)])\n }\n return(phi)\n }\n if (q == 1) {\n for (j in 1:k) {\n for (i in j:k) {\n if (j == i) {\n phi[i, j] <- m[j] * (m[j] + 1) * (2 * m[j] + 1) / 6\n } else {\n phi[i, j] <- m[i] * (m[i] + 1) * (3 * m[j] - m[i] + 1) / 6\n }\n }\n }\n phi <- phi + t(phi) - diag(diag(phi))\n phi <- solve(phi)\n return(phi)\n }\n}\n\n\n\n"], ["/InverseL0TF/R/invL0TF.R", "\n\nybeta <- function(beta=beta,q=q){\n if(q == 0){\n return(cumsum(beta))\n }\n if(q == 1){\n return(cumsum(cumsum(beta)))\n }\n}\n\nDy <- function(y=y,q=q,U=U){\n if(q == 0){\n D = U-rev(cumsum(rev(y)))\n return(D)\n }\n if(q == 1){\n D = U-rev(cumsum(cumsum(rev(y))))\n return(D)\n }\n}\n\nSplicing <- function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}\n\nInvL0TFk <- function(A0=A0,y=y,q=q,k=k,H=H,U=U,first=first,last=last,max.step=50){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n I0 = setdiff(AS,A0)\n for(j in 1:max.step){\n m = Splicing(A=A0,I=I0,k=k,y=y,q=q,H=H,U=U,first=first,last=last)\n A = m$A\n I = m$I\n beta = m$beta\n if(identical(A,A0) & identical(I,I0)){\n break\n }else{\n A0 = A\n I0 = I\n }\n }\n yhat = ybeta(beta=beta,q=q)\n Ahat = sort(A,decreasing = FALSE)\n return(list(betak=beta,yk=yhat,Ak=Ahat))\n}\n\nInverseL0TF <- function(y=y,kmax=kmax,q=q,first=0,last=1){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n A0 = NULL\n I0 = setdiff(AS,A0)\n\n beta.all = NULL\n y.all = NULL\n A.all = list()\n mse = as.numeric(kmax)\n sic = as.numeric(kmax)\n eps = as.numeric(n)\n if(q == 0){\n H = n:1/n\n U = rev(cumsum(rev(y)))\n }\n if(q == 1){\n H = sapply(n:1, function(x) x*(x+1)*(2*x+1)/6)/n\n U = rev(cumsum(cumsum(rev(y))))\n }\n Al = sort(union(S,A0),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n for(j in 1:kmax){\n result = InvL0TFk(A0=A0,y=y,q=q,k=j,H=H,U=U,first=first,last=last)\n beta.all = cbind(beta.all,result$betak)\n y.all = cbind(y.all,result$yk)\n A0 = result$Ak\n I0 = setdiff(AS,A0)\n A.all[[j]] = A0 - 1\n D = Dy(y=as.vector(y.all[,j]),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n }\n mse = colMeans((y-y.all)^2)\n df = 1:kmax + q + 1\n sic = n*log(mse) + 2*log(log(n))*log(n)*df\n bic = n*log(mse) + 2*log(n)*df\n return(list(beta.all=beta.all,y.all=y.all,A.all=A.all,\n sic=sic,bic=bic,mse=mse))\n}\n\n\n#' @title The inverse L0 trend filtering with fixed change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with a given number of change points.\n#' @param y The input data points\n#' @param k The given number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @return\n#' An S3 object of type \"L0TFinvfix\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betak}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with the number of change points being \\eqn{k} }\n#' \\item{yk}{The fitted trend with the number of change points being \\eqn{k}}\n#' \\item{Ak}{The set of position indicators of the fitted change points with the number of change points being \\eqn{k}}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.fix(y=BlocksData$y, k=5, q=0, first=0.01, last=1)\n#' print(res$Ak)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yk, col = \"lightgreen\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=5, q=1, first=0, last=0.99)\n#' print(res1$Ak)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yk, col = \"lightgreen\")\n#'\n#' @seealso \\code{\\link{L0TFinv.opt}}\n#' @export\nL0TFinv.fix <- function(y=y, k=k, q=q, first=0, last=1){\n if ( !(q %in% c(0,1)) ){\n stop(\"The order is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= k+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=k, q=q, first=first, last=last)\n betak = res$beta.all[,k]\n Ak = sort(res$A.all[[k]])\n yk = res$y.all[,k]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betak=betak,yk=yk,Ak=Ak,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvfix\"\n return(G)\n}\n\n\n\n#' @title The inverse L0 trend filtering with optimal change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with optimal change points.\n#' @param y The input data points\n#' @param kmax The maximum number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @param penalty 'sic' or 'bic' penalty\n#' @return\n#' An S3 object of type \"L0TFinvopt\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betaopt}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with optimal change points }\n#' \\item{yopt}{The fitted trend with optimal change points}\n#' \\item{Aopt}{The set of position indicators of the fitted change points with optimal change points}\n#' \\item{kopt}{Optimal number of change points}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k_{\\text{max}}}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @details\n#' Let the fitted trend be denoted as \\eqn{\\hat{\\boldsymbol{y}}}, then \\deqn{\\text{sic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\log(\\log(n)) \\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}})} and \\deqn{\\text{bic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}}).}\n#' The term \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})} represents the degrees of freedom for the estimated trend, where \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})=k+q+1}. Here, \\eqn{k} refers to the number of change points in the estimated trend.\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=20, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res$Aopt)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yopt, col = \"lightgreen\")\n#'\n#' tau1 = c(0.4, 0.6, 0.7)\n#' h1 = c(-3, 5, -4, 6)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 500, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.opt(y=WaveData$y, kmax=10, q=1, first=0, last=0.99, penalty=\"sic\")\n#' print(res1$Aopt)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yopt, col = \"lightgreen\")\n#'\n#' @export\nL0TFinv.opt <- function(y=y, kmax=kmax, q=q, first=0, last=1, penalty=\"bic\"){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if ( !(penalty %in% c(\"bic\",\"sic\")) ){\n stop(\"The specified penalty is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= kmax+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=kmax, q=q, first=first, last=last)\n if(penalty == \"bic\"){\n kopt = which.min(res$bic)\n }\n if(penalty == \"sic\"){\n kopt = which.min(res$sic)\n }\n betaopt = res$beta.all[,kopt]\n Aopt = sort(res$A.all[[kopt]])\n yopt = res$y.all[,kopt]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betaopt=betaopt,yopt=yopt,Aopt=Aopt,kopt=kopt,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvopt\"\n return(G)\n}\n\n \n\n"], ["/InverseL0TF/R/intro.R", "#' @_PACKAGE\n#'\n#' @name L0TFinv-package\n#' @title A package for L0-regularized sparse approximation\n#' @description\n#' Trend filtering is a typical method for nonparametric regression.\n#' The commonly used trend filtering models is the L1 trend filtering model \\eqn{(a)} based on the difference matrix \\eqn{\\boldsymbol{D}^{(q+1)}}, as illustrated below.\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_1}, \\quad q=0,1,2, \\ldots. \\quad (a) }\n#' L0 trend filtering \\eqn{(b)} has a advantage over other trend filtering methods, especially in the detection of change points.\n#' The expression for L0 trend filtering is as follows:\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_0}. \\quad (b) }\n#' We explore transforming the problem \\eqn{(b)} into a L0-regularized sparse format \\eqn{(c)} by introducing an artificial design matrix \\eqn{\\boldsymbol{X}^{(q+1)}} that corresponds to the difference matrix, thereby reformulating the L0 trend filtering problem into the following format.\n#' \\deqn{\\min _{\\boldsymbol{\\beta} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2 + \\lambda \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0}. \\quad (c) }\n#' In our practical approach, we consider the maximum number of change points \\eqn{k_{\\text{max}}} as a constraint, transforming the aforementioned L0 penalty problem \\eqn{(c)} into the following L0 constraint problem.\n#' \\deqn{\\text{ minimize }\\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2,\\quad \\text{ subject to } \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0} \\leq k_{\\text{max}}. \\quad (d)}\n#' For such L0 constraint problems \\eqn{(d)}, we employ a splicing-based approach to design algorithms for processing.\n#' This package has the following seven main methods:\n#' \\itemize{\n#' \\item{\\strong{matrix with special structure }}{\\eqn{\\quad}Generate \\eqn{\\boldsymbol{X}^{(q+1)}} or \\eqn{\\boldsymbol{D}^{(q+1)}} matrix.}\n#' \\item{\\strong{inverse of the crossprod matrix }}{\\eqn{\\quad}Simplify the calculation of the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, which is frequently used in splicing algorithms.}\n#' \\item{\\strong{inverse L0 trend filtering with fixed change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a given number of change points.}\n#' \\item{\\strong{inverse L0 trend filtering with optimal change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a maximum number of change points, and select the optimal estimated trend using appropriate information criteria.}\n#' \\item{\\strong{simulated data }}{\\eqn{\\quad}Generate piecewise constant or piecewise linear data.}\n#' \\item{\\strong{print/coef}}{\\eqn{\\quad}Print a summary of the trend estimation results.}\n#' \\item{\\strong{plot }}{\\eqn{\\quad}Plot a summary of the trend estimation results.}\n#' }\n#' @details\n#' \\itemize{\n#' \\item{}{In previous studies, algorithms solving trend filtering problems \\eqn{(a)} necessitate the computation of \\eqn{((\\boldsymbol{D}^{(q+1)})^T \\boldsymbol{D}^{(q+1)})^{-1}}.\n#' When \\eqn{n} is large, just fitting the matrix into memory becomes an issue.}\n#' \\item{}{In L0 trend filtering \\eqn{(b)}, the positions of non-zero elements in the L0 norm correspond with the locations of change points.\n#' We consider two subsets: the active set \\eqn{A} for non-zero elements and the inactive set \\eqn{I} for zero elements.\n#' Despite this, computing \\eqn{((\\boldsymbol{D}^{(q+1)}_I)^T \\boldsymbol{D}^{(q+1)}_I)^{-1}} remains a task involving a substantial matrix.}\n#' \\item{}{Due to the connection between L0 constraint problems and L0 penalty problems, and considering that the sparsity of \\eqn{\\boldsymbol{\\beta}} is is more meaningful in practical applications than the selection of the hyperparameter \\eqn{\\lambda}.\n#' We focus on the constraint that reflects our aim to achieve an estimated trend with a given number of change points.\n#' So we transform the L0 penalty problem \\eqn{(c)} into the L0 constraint problem \\eqn{(d)}.}\n#' }\n#' @references\n#' Kim SJ, Koh K, Boyd SP and Gorinevsky DM. L1 Trend Filtering. Society for Industrial and Applied Mathematics (2009).\n#'\n#' Wen C, Wang X and Zhang A. L0 Trend Filtering. INFORMS Journal on Computing (2023).\nNULL\n\n"], ["/InverseL0TF/R/dataSimu.R", "#' @title Simulate Blocks Data\n#' @description This function generates data points of piecewise constant trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The constant values of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @return\n#' A list containing the piecewise constant simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1}\\}}\n#' \\item{y}{The piecewise constant simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @details\n#' \\itemize{\n#' \\item{}{To simplify the analysis, normalize the change point positions to a range between 0 and 1. Require that all elements of the input \\eqn{tau} are within this range. Consequently, the change point positions in simulated data forms a subset of the set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, 1\\}.}\n#' \\item{}{In fact, \\eqn{length(tau)} change points can divide the interval into \\eqn{length(tau)+1} segments of constant function values. Therefore, ensure that the length of vector \\eqn{h} is \\eqn{length(tau)+1}.}\n#' }\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.1, seed = 50, tau = tau ,h = h)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' print(BlocksData$setA)\n#' print(BlocksData$tau)\n#' @importFrom stats rnorm\n#' @export\nSimuBlocksInv <- function (n, sigma, seed = NA, tau, h ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+1){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = h[1]\n beta[A+1] = diff(h)\n y0 = cumsum(beta)\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n\n\n#' @title Simulate Wave Data\n#' @description This function generates data points of piecewise linear trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The slope of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @param a0 The initial point value\n#' @return\n#' A list containing the piecewise linear simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1} \\}}\n#' \\item{y}{The piecewise linear simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 650, sigma = 0.1, seed = 50, tau = tau, h = h, a0 = a0)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' print(WaveData$setA)\n#' print(WaveData$tau)\n#' @seealso \\code{\\link{SimuBlocksInv}}\n#' @importFrom stats rnorm\n#' @export\nSimuWaveInv <- function (n, sigma, seed = NA, tau, h, a0 = 0 ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+2){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = a0\n beta[2] = h[1]/n-beta[1]\n beta[A+1] = (diff(h))/n\n y0 = cumsum(cumsum(beta))\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n \n"], ["/InverseL0TF/R/TFmetrics.R", "\n#' @title Print four metrics about change point detection results\n#' @description Prints four metrics to compare the quality of change point detection results.\n#' @param y0 The underlying trend\n#' @param tau The locations of change points in the underlying trend\n#' @param yhat The fitted trend\n#' @param cpts The positions of the fitted change points\n#' @return\n#' \\item{MSE}{The mean square error between the fitted trend and the underlying trend}\n#' \\item{MAD}{The median absolute deviation between the fitted trend and the underlying trend}\n#' \\item{dH}{Hausdorff Distance (dH) measures the accuracy of the estimated change points}\n#' \\item{nknot}{The number of detected change points}\n#' @details\n#' \\eqn{\\hat{\\boldsymbol{\\tau}}} represents the estimated change point positions, while \\eqn{\\boldsymbol{\\tau}} denotes the locations of change points in the underlying trend.\n#' \\deqn{d_H=\\frac{1}{n} \\max \\{\\max_k \\min_j |\\tau_j-\\hat{\\tau}_k|,\\max_j \\min_k |\\tau_j-\\hat{\\tau}_k|\\}.}\n#' Note that the number of \\eqn{\\hat{\\boldsymbol{\\tau}}} and \\eqn{\\boldsymbol{\\tau}} does not need to be the same.\n#' @examples\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' n = 500\n#' BlocksData <- SimuBlocksInv(n = n, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' metrics <- TFmetrics(BlocksData$y0,BlocksData$tau,res$yopt,res$Aopt/n)\n#' print(metrics)\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' n1 = 2000\n#' WaveData <- SimuWaveInv(n = n1, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' metrics1 <- TFmetrics(WaveData$y0,WaveData$tau,res1$y.all[,5],res1$A.all[[5]]/n1)\n#' print(metrics1)\n#'\n#' @export\nTFmetrics <- function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}\n\n\n\n\n\n\n\n\n"], ["/InverseL0TF/R/plot.R", "\n#' @title Plot L0TFinvfix or L0TFinvopt object\n#'\n#' @description Plots a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param type The values are taken as c(\"\\eqn{mse}\", \"\\eqn{sic}\", \"\\eqn{bic}\", \"\\eqn{yhat}\"). If \\eqn{type} is \"\\eqn{mse}\", plot the mse as it changes with change points.\n#' The same applies to \"\\eqn{sic}\" and \"\\eqn{bic}\". If \\eqn{type} is \"\\eqn{yhat}\", plot the trend of the estimated values against the input data.\n#' @param k Only used for \\eqn{type} = \"\\eqn{yhat}\". The given number of change points.\n#' By default, the L0TFinvfix object outputs the estimated trend that corresponds to the fixed number of change points within the model. Conversely, the L0TFinvopt object provides the estimated trend based on the optimal change points.\n#' @param ... ignore\n#' @method plot L0TFinvfix\n#' @import ggplot2\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\nplot.L0TFinvfix <- function(x, type = NULL, k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = length(x$mse)\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n\n\n#' @rdname plot.L0TFinvfix\n#' @method plot L0TFinvopt\n#' @export\nplot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n"], ["/InverseL0TF/R/print.R", "\n#' @title Print L0TFinvfix or L0TFinvopt object\n#' @description Prints a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param ... ignore\n#' @method print L0TFinvfix\n#' @examples\n#' library(ggplot2)\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res)\n#' coef(res,k=res$kopt)\n#' plot(res,type=\"yhat\")\n#' plot(res,type=\"bic\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' print(res1)\n#' coef(res1,k=5)\n#' plot(res1,type=\"yhat\",k=5)\n#' plot(res1,type=\"mse\")\n#'\n#' @export\nprint.L0TFinvfix <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n#' @rdname print.L0TFinvfix\n#' @method print L0TFinvopt\n#' @export\nprint.L0TFinvopt <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,kopt=x$kopt,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n\n"], ["/InverseL0TF/R/coef.R", "\n#' @title Extract estimated trends\n#' @description Extract the coefficients of the estimated trends under the constraint of a given number of change points.\n#' @param object The output of L0TFinvfix or L0TFinvopt\n#' @param k The given number of change points\n#' @method coef L0TFinvfix\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\ncoef.L0TFinvfix <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n\n#' @rdname coef.L0TFinvfix\n#' @method coef L0TFinvopt\n#' @export\ncoef.L0TFinvopt <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:02:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(n, q) {}", "code_description": "This code segment functions to: Construct a finite difference operator matrix for specified order calculations by applying combinatorial coefficients with alternating signs to sequential element groups, ensuring dimensional compatibility through input validation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(n, q) {\n d <- q + 1\n nr <- n - q -1\n if(nr <= 0) return(matrix(0,0,n))\n \n D <- matrix(0, nrow = nr, ncol = n)\n coeffs <- (-1)^(0:d) * choose(d, 0:d)\n \n for(i in 1:nr) {\n cols <- i:(i+d)\n D[i, cols] <- coeffs\n }\n \n return(D)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-04-09"}, "editdistance_info": {"edit_distance": 19.084, "calculate_time": "2025-08-21 01:04:09", "true_code_clean": "function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}", "predict_code_clean": "function(n, q) {\n d <- q + 1\n nr <- n - q -1\n if(nr <= 0) return(matrix(0,0,n))\n D <- matrix(0, nrow = nr, ncol = n)\n coeffs <- (-1)^(0:d) * choose(d, 0:d)\n for(i in 1:nr) {\n cols <- i:(i+d)\n D[i, cols] <- coeffs\n }\n return(D)\n}"}}
{"repo_name": "InverseL0TF", "file_name": "/InverseL0TF/R/TFmetrics.R", "inference_info": {"prefix_code": "\n#' @title Print four metrics about change point detection results\n#' @description Prints four metrics to compare the quality of change point detection results.\n#' @param y0 The underlying trend\n#' @param tau The locations of change points in the underlying trend\n#' @param yhat The fitted trend\n#' @param cpts The positions of the fitted change points\n#' @return\n#' \\item{MSE}{The mean square error between the fitted trend and the underlying trend}\n#' \\item{MAD}{The median absolute deviation between the fitted trend and the underlying trend}\n#' \\item{dH}{Hausdorff Distance (dH) measures the accuracy of the estimated change points}\n#' \\item{nknot}{The number of detected change points}\n#' @details\n#' \\eqn{\\hat{\\boldsymbol{\\tau}}} represents the estimated change point positions, while \\eqn{\\boldsymbol{\\tau}} denotes the locations of change points in the underlying trend.\n#' \\deqn{d_H=\\frac{1}{n} \\max \\{\\max_k \\min_j |\\tau_j-\\hat{\\tau}_k|,\\max_j \\min_k |\\tau_j-\\hat{\\tau}_k|\\}.}\n#' Note that the number of \\eqn{\\hat{\\boldsymbol{\\tau}}} and \\eqn{\\boldsymbol{\\tau}} does not need to be the same.\n#' @examples\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' n = 500\n#' BlocksData <- SimuBlocksInv(n = n, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' metrics <- TFmetrics(BlocksData$y0,BlocksData$tau,res$yopt,res$Aopt/n)\n#' print(metrics)\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' n1 = 2000\n#' WaveData <- SimuWaveInv(n = n1, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' metrics1 <- TFmetrics(WaveData$y0,WaveData$tau,res1$y.all[,5],res1$A.all[[5]]/n1)\n#' print(metrics1)\n#'\n#' @export\nTFmetrics <- ", "suffix_code": "\n\n\n\n\n\n\n\n\n", "middle_code": "function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/InverseL0TF/R/invL0TF.R", "\n\nybeta <- function(beta=beta,q=q){\n if(q == 0){\n return(cumsum(beta))\n }\n if(q == 1){\n return(cumsum(cumsum(beta)))\n }\n}\n\nDy <- function(y=y,q=q,U=U){\n if(q == 0){\n D = U-rev(cumsum(rev(y)))\n return(D)\n }\n if(q == 1){\n D = U-rev(cumsum(cumsum(rev(y))))\n return(D)\n }\n}\n\nSplicing <- function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}\n\nInvL0TFk <- function(A0=A0,y=y,q=q,k=k,H=H,U=U,first=first,last=last,max.step=50){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n I0 = setdiff(AS,A0)\n for(j in 1:max.step){\n m = Splicing(A=A0,I=I0,k=k,y=y,q=q,H=H,U=U,first=first,last=last)\n A = m$A\n I = m$I\n beta = m$beta\n if(identical(A,A0) & identical(I,I0)){\n break\n }else{\n A0 = A\n I0 = I\n }\n }\n yhat = ybeta(beta=beta,q=q)\n Ahat = sort(A,decreasing = FALSE)\n return(list(betak=beta,yk=yhat,Ak=Ahat))\n}\n\nInverseL0TF <- function(y=y,kmax=kmax,q=q,first=0,last=1){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n A0 = NULL\n I0 = setdiff(AS,A0)\n\n beta.all = NULL\n y.all = NULL\n A.all = list()\n mse = as.numeric(kmax)\n sic = as.numeric(kmax)\n eps = as.numeric(n)\n if(q == 0){\n H = n:1/n\n U = rev(cumsum(rev(y)))\n }\n if(q == 1){\n H = sapply(n:1, function(x) x*(x+1)*(2*x+1)/6)/n\n U = rev(cumsum(cumsum(rev(y))))\n }\n Al = sort(union(S,A0),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n for(j in 1:kmax){\n result = InvL0TFk(A0=A0,y=y,q=q,k=j,H=H,U=U,first=first,last=last)\n beta.all = cbind(beta.all,result$betak)\n y.all = cbind(y.all,result$yk)\n A0 = result$Ak\n I0 = setdiff(AS,A0)\n A.all[[j]] = A0 - 1\n D = Dy(y=as.vector(y.all[,j]),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n }\n mse = colMeans((y-y.all)^2)\n df = 1:kmax + q + 1\n sic = n*log(mse) + 2*log(log(n))*log(n)*df\n bic = n*log(mse) + 2*log(n)*df\n return(list(beta.all=beta.all,y.all=y.all,A.all=A.all,\n sic=sic,bic=bic,mse=mse))\n}\n\n\n#' @title The inverse L0 trend filtering with fixed change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with a given number of change points.\n#' @param y The input data points\n#' @param k The given number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @return\n#' An S3 object of type \"L0TFinvfix\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betak}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with the number of change points being \\eqn{k} }\n#' \\item{yk}{The fitted trend with the number of change points being \\eqn{k}}\n#' \\item{Ak}{The set of position indicators of the fitted change points with the number of change points being \\eqn{k}}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.fix(y=BlocksData$y, k=5, q=0, first=0.01, last=1)\n#' print(res$Ak)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yk, col = \"lightgreen\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=5, q=1, first=0, last=0.99)\n#' print(res1$Ak)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yk, col = \"lightgreen\")\n#'\n#' @seealso \\code{\\link{L0TFinv.opt}}\n#' @export\nL0TFinv.fix <- function(y=y, k=k, q=q, first=0, last=1){\n if ( !(q %in% c(0,1)) ){\n stop(\"The order is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= k+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=k, q=q, first=first, last=last)\n betak = res$beta.all[,k]\n Ak = sort(res$A.all[[k]])\n yk = res$y.all[,k]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betak=betak,yk=yk,Ak=Ak,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvfix\"\n return(G)\n}\n\n\n\n#' @title The inverse L0 trend filtering with optimal change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with optimal change points.\n#' @param y The input data points\n#' @param kmax The maximum number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @param penalty 'sic' or 'bic' penalty\n#' @return\n#' An S3 object of type \"L0TFinvopt\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betaopt}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with optimal change points }\n#' \\item{yopt}{The fitted trend with optimal change points}\n#' \\item{Aopt}{The set of position indicators of the fitted change points with optimal change points}\n#' \\item{kopt}{Optimal number of change points}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k_{\\text{max}}}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @details\n#' Let the fitted trend be denoted as \\eqn{\\hat{\\boldsymbol{y}}}, then \\deqn{\\text{sic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\log(\\log(n)) \\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}})} and \\deqn{\\text{bic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}}).}\n#' The term \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})} represents the degrees of freedom for the estimated trend, where \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})=k+q+1}. Here, \\eqn{k} refers to the number of change points in the estimated trend.\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=20, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res$Aopt)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yopt, col = \"lightgreen\")\n#'\n#' tau1 = c(0.4, 0.6, 0.7)\n#' h1 = c(-3, 5, -4, 6)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 500, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.opt(y=WaveData$y, kmax=10, q=1, first=0, last=0.99, penalty=\"sic\")\n#' print(res1$Aopt)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yopt, col = \"lightgreen\")\n#'\n#' @export\nL0TFinv.opt <- function(y=y, kmax=kmax, q=q, first=0, last=1, penalty=\"bic\"){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if ( !(penalty %in% c(\"bic\",\"sic\")) ){\n stop(\"The specified penalty is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= kmax+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=kmax, q=q, first=first, last=last)\n if(penalty == \"bic\"){\n kopt = which.min(res$bic)\n }\n if(penalty == \"sic\"){\n kopt = which.min(res$sic)\n }\n betaopt = res$beta.all[,kopt]\n Aopt = sort(res$A.all[[kopt]])\n yopt = res$y.all[,kopt]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betaopt=betaopt,yopt=yopt,Aopt=Aopt,kopt=kopt,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvopt\"\n return(G)\n}\n\n \n\n"], ["/InverseL0TF/R/dataSimu.R", "#' @title Simulate Blocks Data\n#' @description This function generates data points of piecewise constant trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The constant values of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @return\n#' A list containing the piecewise constant simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1}\\}}\n#' \\item{y}{The piecewise constant simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @details\n#' \\itemize{\n#' \\item{}{To simplify the analysis, normalize the change point positions to a range between 0 and 1. Require that all elements of the input \\eqn{tau} are within this range. Consequently, the change point positions in simulated data forms a subset of the set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, 1\\}.}\n#' \\item{}{In fact, \\eqn{length(tau)} change points can divide the interval into \\eqn{length(tau)+1} segments of constant function values. Therefore, ensure that the length of vector \\eqn{h} is \\eqn{length(tau)+1}.}\n#' }\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.1, seed = 50, tau = tau ,h = h)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' print(BlocksData$setA)\n#' print(BlocksData$tau)\n#' @importFrom stats rnorm\n#' @export\nSimuBlocksInv <- function (n, sigma, seed = NA, tau, h ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+1){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = h[1]\n beta[A+1] = diff(h)\n y0 = cumsum(beta)\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n\n\n#' @title Simulate Wave Data\n#' @description This function generates data points of piecewise linear trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The slope of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @param a0 The initial point value\n#' @return\n#' A list containing the piecewise linear simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1} \\}}\n#' \\item{y}{The piecewise linear simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 650, sigma = 0.1, seed = 50, tau = tau, h = h, a0 = a0)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' print(WaveData$setA)\n#' print(WaveData$tau)\n#' @seealso \\code{\\link{SimuBlocksInv}}\n#' @importFrom stats rnorm\n#' @export\nSimuWaveInv <- function (n, sigma, seed = NA, tau, h, a0 = 0 ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+2){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = a0\n beta[2] = h[1]/n-beta[1]\n beta[A+1] = (diff(h))/n\n y0 = cumsum(cumsum(beta))\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n \n"], ["/InverseL0TF/R/print.R", "\n#' @title Print L0TFinvfix or L0TFinvopt object\n#' @description Prints a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param ... ignore\n#' @method print L0TFinvfix\n#' @examples\n#' library(ggplot2)\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res)\n#' coef(res,k=res$kopt)\n#' plot(res,type=\"yhat\")\n#' plot(res,type=\"bic\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' print(res1)\n#' coef(res1,k=5)\n#' plot(res1,type=\"yhat\",k=5)\n#' plot(res1,type=\"mse\")\n#'\n#' @export\nprint.L0TFinvfix <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n#' @rdname print.L0TFinvfix\n#' @method print L0TFinvopt\n#' @export\nprint.L0TFinvopt <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,kopt=x$kopt,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n\n"], ["/InverseL0TF/R/plot.R", "\n#' @title Plot L0TFinvfix or L0TFinvopt object\n#'\n#' @description Plots a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param type The values are taken as c(\"\\eqn{mse}\", \"\\eqn{sic}\", \"\\eqn{bic}\", \"\\eqn{yhat}\"). If \\eqn{type} is \"\\eqn{mse}\", plot the mse as it changes with change points.\n#' The same applies to \"\\eqn{sic}\" and \"\\eqn{bic}\". If \\eqn{type} is \"\\eqn{yhat}\", plot the trend of the estimated values against the input data.\n#' @param k Only used for \\eqn{type} = \"\\eqn{yhat}\". The given number of change points.\n#' By default, the L0TFinvfix object outputs the estimated trend that corresponds to the fixed number of change points within the model. Conversely, the L0TFinvopt object provides the estimated trend based on the optimal change points.\n#' @param ... ignore\n#' @method plot L0TFinvfix\n#' @import ggplot2\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\nplot.L0TFinvfix <- function(x, type = NULL, k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = length(x$mse)\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n\n\n#' @rdname plot.L0TFinvfix\n#' @method plot L0TFinvopt\n#' @export\nplot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n"], ["/InverseL0TF/R/intro.R", "#' @_PACKAGE\n#'\n#' @name L0TFinv-package\n#' @title A package for L0-regularized sparse approximation\n#' @description\n#' Trend filtering is a typical method for nonparametric regression.\n#' The commonly used trend filtering models is the L1 trend filtering model \\eqn{(a)} based on the difference matrix \\eqn{\\boldsymbol{D}^{(q+1)}}, as illustrated below.\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_1}, \\quad q=0,1,2, \\ldots. \\quad (a) }\n#' L0 trend filtering \\eqn{(b)} has a advantage over other trend filtering methods, especially in the detection of change points.\n#' The expression for L0 trend filtering is as follows:\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_0}. \\quad (b) }\n#' We explore transforming the problem \\eqn{(b)} into a L0-regularized sparse format \\eqn{(c)} by introducing an artificial design matrix \\eqn{\\boldsymbol{X}^{(q+1)}} that corresponds to the difference matrix, thereby reformulating the L0 trend filtering problem into the following format.\n#' \\deqn{\\min _{\\boldsymbol{\\beta} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2 + \\lambda \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0}. \\quad (c) }\n#' In our practical approach, we consider the maximum number of change points \\eqn{k_{\\text{max}}} as a constraint, transforming the aforementioned L0 penalty problem \\eqn{(c)} into the following L0 constraint problem.\n#' \\deqn{\\text{ minimize }\\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2,\\quad \\text{ subject to } \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0} \\leq k_{\\text{max}}. \\quad (d)}\n#' For such L0 constraint problems \\eqn{(d)}, we employ a splicing-based approach to design algorithms for processing.\n#' This package has the following seven main methods:\n#' \\itemize{\n#' \\item{\\strong{matrix with special structure }}{\\eqn{\\quad}Generate \\eqn{\\boldsymbol{X}^{(q+1)}} or \\eqn{\\boldsymbol{D}^{(q+1)}} matrix.}\n#' \\item{\\strong{inverse of the crossprod matrix }}{\\eqn{\\quad}Simplify the calculation of the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, which is frequently used in splicing algorithms.}\n#' \\item{\\strong{inverse L0 trend filtering with fixed change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a given number of change points.}\n#' \\item{\\strong{inverse L0 trend filtering with optimal change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a maximum number of change points, and select the optimal estimated trend using appropriate information criteria.}\n#' \\item{\\strong{simulated data }}{\\eqn{\\quad}Generate piecewise constant or piecewise linear data.}\n#' \\item{\\strong{print/coef}}{\\eqn{\\quad}Print a summary of the trend estimation results.}\n#' \\item{\\strong{plot }}{\\eqn{\\quad}Plot a summary of the trend estimation results.}\n#' }\n#' @details\n#' \\itemize{\n#' \\item{}{In previous studies, algorithms solving trend filtering problems \\eqn{(a)} necessitate the computation of \\eqn{((\\boldsymbol{D}^{(q+1)})^T \\boldsymbol{D}^{(q+1)})^{-1}}.\n#' When \\eqn{n} is large, just fitting the matrix into memory becomes an issue.}\n#' \\item{}{In L0 trend filtering \\eqn{(b)}, the positions of non-zero elements in the L0 norm correspond with the locations of change points.\n#' We consider two subsets: the active set \\eqn{A} for non-zero elements and the inactive set \\eqn{I} for zero elements.\n#' Despite this, computing \\eqn{((\\boldsymbol{D}^{(q+1)}_I)^T \\boldsymbol{D}^{(q+1)}_I)^{-1}} remains a task involving a substantial matrix.}\n#' \\item{}{Due to the connection between L0 constraint problems and L0 penalty problems, and considering that the sparsity of \\eqn{\\boldsymbol{\\beta}} is is more meaningful in practical applications than the selection of the hyperparameter \\eqn{\\lambda}.\n#' We focus on the constraint that reflects our aim to achieve an estimated trend with a given number of change points.\n#' So we transform the L0 penalty problem \\eqn{(c)} into the L0 constraint problem \\eqn{(d)}.}\n#' }\n#' @references\n#' Kim SJ, Koh K, Boyd SP and Gorinevsky DM. L1 Trend Filtering. Society for Industrial and Applied Mathematics (2009).\n#'\n#' Wen C, Wang X and Zhang A. L0 Trend Filtering. INFORMS Journal on Computing (2023).\nNULL\n\n"], ["/InverseL0TF/R/solveMatrix.R", "#' @title Generate the inverse of the crossprod matrix\n#' @description Generate the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, commonly employed in splicing algorithms. Note that an explicit solution exists for the inverse when \\eqn{q=0}, but not when \\eqn{q=1}.\n#' @param n The number of data points\n#' @param q The order of the difference, 0 or 1\n#' @param A The set of indicators, a subset of \\eqn{\\{1,2,3,\\dots,n\\}}\n#' @return The inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=} 0 or 1.\n#' @examples\n#' Mat1 <- XMat(n = 10, q = 0)\n#' A1 = c(1,2,5,8)\n#' mat1 = as.matrix(Mat1[,A1])\n#' S1 <- solMat(n = 10, q = 0, A = A1)\n#' print(S1)\n#' print(round(S1%*%t(mat1)%*%mat1,10))\n#'\n#' Mat2 <- XMat(n = 15, q = 1)\n#' A2 = c(1,3,8,10,15)\n#' mat2 = as.matrix(Mat2[,A2])\n#' S2 <- solMat(n = 15, q = 1, A = A2)\n#' print(S2)\n#' print(round(S2%*%t(mat2)%*%mat2,10))\n#' @importFrom Matrix solve\n#' @export\nsolMat <- function(n, q, A){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if( min(A)<1 | max(A)>n ){\n stop(\"\nThe maximum possible range for the set indicators should be within {1,2,...,n}\")\n }\n k = length(A)\n m = as.numeric(k)\n m = n + 1 - A\n phi = matrix(0, k, k)\n if(q == 0){\n if(k == 1){\n phi[1,1] = 1/m[1]\n return(phi)\n }\n if(k == 2){\n phi[1,1] = m[2]\n phi[1,2] = -m[2]\n phi[2,1] = -m[2]\n phi[2,2] = m[1]\n phi = phi/(m[2]*(m[1]-m[2]))\n return(phi)\n }\n for(i in 1:k){\n if(i == 1){\n phi[1,1] = 1/(m[1]-m[2])\n phi[1,2] = -1/(m[1]-m[2])\n next\n }\n if(i == k){\n phi[k,(k-1)] = -1/(m[(k-1)]-m[k])\n phi[k,k] = 1/(m[(k-1)]-m[k])+1/m[k]\n break\n }\n phi[i,(i-1)] = -1/(m[(i-1)]-m[i])\n phi[i,i] = 1/(m[(i-1)]-m[i])+1/(m[i]-m[(i+1)])\n phi[i,(i+1)] = -1/(m[i]-m[(i+1)])\n }\n return(phi)\n }\n if (q == 1) {\n for (j in 1:k) {\n for (i in j:k) {\n if (j == i) {\n phi[i, j] <- m[j] * (m[j] + 1) * (2 * m[j] + 1) / 6\n } else {\n phi[i, j] <- m[i] * (m[i] + 1) * (3 * m[j] - m[i] + 1) / 6\n }\n }\n }\n phi <- phi + t(phi) - diag(diag(phi))\n phi <- solve(phi)\n return(phi)\n }\n}\n\n\n\n"], ["/InverseL0TF/R/sMatrix.R", "#' @title Generate a difference matrix\n#' @description This function generates a matrix for computing differences of a certain order, useful in numerical methods and for creating specific matrix patterns.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n-q-1} by \\eqn{n}, whose elements correspond to the combinatorial values of \\eqn{q}.\n#' @examples\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' print(Mat1)\n#'\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' print(Mat2)\n#'\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat3)\n#'\n#' @seealso \\code{\\link{XMat}}\n#' @export\nDiffMat <- function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}\n\n\n\n#' @title Generate an artificial design matrix\n#' @description This matrix corresponds to the difference matrix, transforming the L0 trend filtering model into an inverse statistical problem.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n} by \\eqn{n}, whose elements correspond to the difference matrix.\n#' @examples\n#' mat1 <- XMat(n = 10, q = 0)\n#' print(mat1)\n#'\n#' mat2 <- XMat(n = 15, q = 1)\n#' print(mat2)\n#'\n#' mat3 <- XMat(n = 15, q = 2)\n#' print(mat3)\n#'\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat1%*%mat1)\n#' print(Mat2%*%mat2)\n#' print(Mat3%*%mat3)\n#' @details Noticing the correspondence between \\eqn{\\boldsymbol{D}^{(q+1)}} and \\eqn{\\boldsymbol{X}^{(q+1)}}, the result of their matrix multiplication is a combination of a zero matrix and an identity matrix. Expressed as \\eqn{\\boldsymbol{D}^{(q+1)} \\boldsymbol{X}^{(q+1)}=(\\boldsymbol{O}_{(n-q-1)\\times(q+1)},\\quad \\boldsymbol{I}_{(n-q-1)\\times(n-q-1)})}. The result is advantageous for the invertible processing of the original L0 trend filtering problem.\n#' @export\nXMat <- function(n, q){\n X <- matrix(0,n,n)\n if(q == 0){\n for(i in 1:n){\n for(j in 1:i){\n X[i,j] <- 1\n }\n }\n return(X)\n }else{\n return(apply(XMat(n, q-1),2,cumsum))\n }\n}\n\n\n\n\n\n"], ["/InverseL0TF/R/coef.R", "\n#' @title Extract estimated trends\n#' @description Extract the coefficients of the estimated trends under the constraint of a given number of change points.\n#' @param object The output of L0TFinvfix or L0TFinvopt\n#' @param k The given number of change points\n#' @method coef L0TFinvfix\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\ncoef.L0TFinvfix <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n\n#' @rdname coef.L0TFinvfix\n#' @method coef L0TFinvopt\n#' @export\ncoef.L0TFinvopt <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:02:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(y0, tau=NULL, yhat, cpts = NULL) {}", "code_description": "This code segment functions to: Calculate error metrics between observed and predicted trends, including discrepancy measures for fitted values and detected change point positions, while returning a structured summary of accuracy assessments."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nTFmetrics <- function(y0, tau = NULL, yhat, cpts = NULL) {\n \n MSE <- mean( (y0 - yhat)^2 )\n MAD <- median( abs(y0 - yhat) )\n \n n <- length(y0)\n \n # Handle cases where either tau or cpts are missing/empty\n if ((is.null(tau) || length(tau) == 0) || (is.null(cpts) || length(cpts) == 0)) {\n dH <- NA\n } else {\n # Convert fractional positions to actual indices\n tau_pos <- tau * n\n cpts_pos <- cpts * n\n \n # Calculate directional Hausdorff distances\n d1 <- max(sapply(tau_pos, function(t) min(abs(t - cpts_pos))))\n d2 <- max(sapply(cpts_pos, function(c) min(abs(c - tau_pos))))\n dH <- max(d1, d2)/n\n }\n \n nknot <- ifelse(is.null(cpts), 0, length(cpts))\n \n return(list(MSE = MSE, MAD = MAD, dH = dH, nknot = nknot))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-04-33"}, "editdistance_info": {"edit_distance": 14.6444, "calculate_time": "2025-08-21 01:04:33", "true_code_clean": "function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}", "predict_code_clean": "TFmetrics <- function(y0, tau = NULL, yhat, cpts = NULL) {\n MSE <- mean( (y0 - yhat)^2 )\n MAD <- median( abs(y0 - yhat) )\n n <- length(y0)\n if ((is.null(tau) || length(tau) == 0) || (is.null(cpts) || length(cpts) == 0)) {\n dH <- NA\n } else {\n tau_pos <- tau * n\n cpts_pos <- cpts * n\n d1 <- max(sapply(tau_pos, function(t) min(abs(t - cpts_pos))))\n d2 <- max(sapply(cpts_pos, function(c) min(abs(c - tau_pos))))\n dH <- max(d1, d2)/n\n }\n nknot <- ifelse(is.null(cpts), 0, length(cpts))\n return(list(MSE = MSE, MAD = MAD, dH = dH, nknot = nknot))\n}"}}
{"repo_name": "InverseL0TF", "file_name": "/InverseL0TF/R/plot.R", "inference_info": {"prefix_code": "\n#' @title Plot L0TFinvfix or L0TFinvopt object\n#'\n#' @description Plots a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param type The values are taken as c(\"\\eqn{mse}\", \"\\eqn{sic}\", \"\\eqn{bic}\", \"\\eqn{yhat}\"). If \\eqn{type} is \"\\eqn{mse}\", plot the mse as it changes with change points.\n#' The same applies to \"\\eqn{sic}\" and \"\\eqn{bic}\". If \\eqn{type} is \"\\eqn{yhat}\", plot the trend of the estimated values against the input data.\n#' @param k Only used for \\eqn{type} = \"\\eqn{yhat}\". The given number of change points.\n#' By default, the L0TFinvfix object outputs the estimated trend that corresponds to the fixed number of change points within the model. Conversely, the L0TFinvopt object provides the estimated trend based on the optimal change points.\n#' @param ... ignore\n#' @method plot L0TFinvfix\n#' @import ggplot2\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\nplot.L0TFinvfix <- function(x, type = NULL, k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = length(x$mse)\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n\n\n#' @rdname plot.L0TFinvfix\n#' @method plot L0TFinvopt\n#' @export\nplot.L0TFinvopt <- ", "suffix_code": "\n", "middle_code": "function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/InverseL0TF/R/invL0TF.R", "\n\nybeta <- function(beta=beta,q=q){\n if(q == 0){\n return(cumsum(beta))\n }\n if(q == 1){\n return(cumsum(cumsum(beta)))\n }\n}\n\nDy <- function(y=y,q=q,U=U){\n if(q == 0){\n D = U-rev(cumsum(rev(y)))\n return(D)\n }\n if(q == 1){\n D = U-rev(cumsum(cumsum(rev(y))))\n return(D)\n }\n}\n\nSplicing <- function(A=A,I=I,k=k,y=y,q=q,H=H,U=U,first=first,last=last){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n\n eps1 = rep(0,n)\n eps2 = rep(0,n)\n Al = sort(union(S,A),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n L = sum((y-yhat)^2)\n for(j in 1:(k%/%4)){\n A0 = as.vector(A[order(eps1[A],decreasing = F)[1:j]])\n I00 = intersect(I,AS0)\n I0 = as.vector(I00[order(eps2[I00],decreasing = T)[1:j]])\n Anew = c(setdiff(A,A0),I0)\n Inew = c(setdiff(I,I0),A0)\n Alnew = sort(union(Anew,S),decreasing = FALSE)\n betanew = rep(0,n)\n betanew[Alnew] = solMat(n=n,q=q,A=Alnew)%*%U[Alnew]\n yhatnew = ybeta(beta=betanew,q=q)\n Lnew = sum((y-yhatnew)^2)\n if(L-Lnew>0){\n A = Anew\n I = Inew\n beta = betanew\n L = Lnew\n yhat = ybeta(beta=beta,q=q)\n D = Dy(y=yhat,q=q,U=U)/n\n eps1 = ((beta)^2)*H\n eps2 = D^2/H\n }\n }\n return(list(A=A,I=I,beta=beta))\n}\n\nInvL0TFk <- function(A0=A0,y=y,q=q,k=k,H=H,U=U,first=first,last=last,max.step=50){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n I0 = setdiff(AS,A0)\n for(j in 1:max.step){\n m = Splicing(A=A0,I=I0,k=k,y=y,q=q,H=H,U=U,first=first,last=last)\n A = m$A\n I = m$I\n beta = m$beta\n if(identical(A,A0) & identical(I,I0)){\n break\n }else{\n A0 = A\n I0 = I\n }\n }\n yhat = ybeta(beta=beta,q=q)\n Ahat = sort(A,decreasing = FALSE)\n return(list(betak=beta,yk=yhat,Ak=Ahat))\n}\n\nInverseL0TF <- function(y=y,kmax=kmax,q=q,first=0,last=1){\n n = length(y)\n All = 1:n\n S = 1:(q+1)\n AS = (q+2):n\n low = ceiling(first*n)\n high = floor(last*n)\n AS0 = intersect(low:high,AS)\n A0 = NULL\n I0 = setdiff(AS,A0)\n\n beta.all = NULL\n y.all = NULL\n A.all = list()\n mse = as.numeric(kmax)\n sic = as.numeric(kmax)\n eps = as.numeric(n)\n if(q == 0){\n H = n:1/n\n U = rev(cumsum(rev(y)))\n }\n if(q == 1){\n H = sapply(n:1, function(x) x*(x+1)*(2*x+1)/6)/n\n U = rev(cumsum(cumsum(rev(y))))\n }\n Al = sort(union(S,A0),decreasing = FALSE)\n beta = rep(0,n)\n beta[Al] = solMat(n=n,q=q,A=Al)%*%U[Al]\n D = Dy(y=ybeta(beta=beta,q=q),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n for(j in 1:kmax){\n result = InvL0TFk(A0=A0,y=y,q=q,k=j,H=H,U=U,first=first,last=last)\n beta.all = cbind(beta.all,result$betak)\n y.all = cbind(y.all,result$yk)\n A0 = result$Ak\n I0 = setdiff(AS,A0)\n A.all[[j]] = A0 - 1\n D = Dy(y=as.vector(y.all[,j]),q=q,U=U)/n\n eps = D^2/H\n I00 = intersect(I0,AS0)\n A0 = union(A0,I00[which.max(eps[I00])])\n }\n mse = colMeans((y-y.all)^2)\n df = 1:kmax + q + 1\n sic = n*log(mse) + 2*log(log(n))*log(n)*df\n bic = n*log(mse) + 2*log(n)*df\n return(list(beta.all=beta.all,y.all=y.all,A.all=A.all,\n sic=sic,bic=bic,mse=mse))\n}\n\n\n#' @title The inverse L0 trend filtering with fixed change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with a given number of change points.\n#' @param y The input data points\n#' @param k The given number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @return\n#' An S3 object of type \"L0TFinvfix\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betak}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with the number of change points being \\eqn{k} }\n#' \\item{yk}{The fitted trend with the number of change points being \\eqn{k}}\n#' \\item{Ak}{The set of position indicators of the fitted change points with the number of change points being \\eqn{k}}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.fix(y=BlocksData$y, k=5, q=0, first=0.01, last=1)\n#' print(res$Ak)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yk, col = \"lightgreen\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=5, q=1, first=0, last=0.99)\n#' print(res1$Ak)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yk, col = \"lightgreen\")\n#'\n#' @seealso \\code{\\link{L0TFinv.opt}}\n#' @export\nL0TFinv.fix <- function(y=y, k=k, q=q, first=0, last=1){\n if ( !(q %in% c(0,1)) ){\n stop(\"The order is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= k+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=k, q=q, first=first, last=last)\n betak = res$beta.all[,k]\n Ak = sort(res$A.all[[k]])\n yk = res$y.all[,k]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betak=betak,yk=yk,Ak=Ak,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvfix\"\n return(G)\n}\n\n\n\n#' @title The inverse L0 trend filtering with optimal change points\n#' @description Fit the input data points to a piecewise constant or piecewise linear trend with optimal change points.\n#' @param y The input data points\n#' @param kmax The maximum number of change points\n#' @param q 0 or 1. Correspond to a piecewise constant or piecewise linear trend\n#' @param first The value ranges from 0 to 1. Represent the minimum percentile point where a change point may occur. If 'first' = 0.01, it means that change points cannot appear in the first 1\\% of the data points. If 'first' = 0, there is no constraint on the position of the change point.\n#' @param last The value ranges from 0 to 1. Represent the maximum percentile point where a change point may occur. If 'last' = 0.99, it means that change points cannot appear in the last 1\\% of the data points. If 'last' = 1, there is no constraint on the position of the change point.\n#' @param penalty 'sic' or 'bic' penalty\n#' @return\n#' An S3 object of type \"L0TFinvopt\". A list containing the fitted trend results:\n#' \\item{sic}{Information criterion value with a penalty term of \\eqn{2\\log(\\log(n)) \\times \\log(n)}}\n#' \\item{bic}{Information criterion value with a penalty term of \\eqn{2 \\times \\log(n)}}\n#' \\item{mse}{The mean square error between the fitted trend and the input data}\n#' \\item{y}{The input data points}\n#' \\item{betaopt}{The fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients with optimal change points }\n#' \\item{yopt}{The fitted trend with optimal change points}\n#' \\item{Aopt}{The set of position indicators of the fitted change points with optimal change points}\n#' \\item{kopt}{Optimal number of change points}\n#' \\item{beta.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted \\eqn{\\hat{\\boldsymbol{\\beta}}} coefficients corresponding to a given number of change points}\n#' \\item{y.all}{A data frame with dimensions \\eqn{n \\times k_{\\text{max}}}, where each column represents the fitted estimated trend corresponding to a given number of change points}\n#' \\item{A.all}{A list of length \\eqn{k_{\\text{max}}}, where each element corresponds to the set of position indicators of change points under a given number }\n#'\n#' @details\n#' Let the fitted trend be denoted as \\eqn{\\hat{\\boldsymbol{y}}}, then \\deqn{\\text{sic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\log(\\log(n)) \\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}})} and \\deqn{\\text{bic} = n \\times \\log(\\frac{1}{n}\\|\\boldsymbol{y}-\\hat{\\boldsymbol{y}}\\|_2^2)+2\\times \\log(n) \\times \\text{df}(\\hat{\\boldsymbol{y}}).}\n#' The term \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})} represents the degrees of freedom for the estimated trend, where \\eqn{\\text{df}(\\hat{\\boldsymbol{y}})=k+q+1}. Here, \\eqn{k} refers to the number of change points in the estimated trend.\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=20, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res$Aopt)\n#' print(BlocksData$setA)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' lines(BlocksData$x, res$yopt, col = \"lightgreen\")\n#'\n#' tau1 = c(0.4, 0.6, 0.7)\n#' h1 = c(-3, 5, -4, 6)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 500, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.opt(y=WaveData$y, kmax=10, q=1, first=0, last=0.99, penalty=\"sic\")\n#' print(res1$Aopt)\n#' print(WaveData$setA)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' lines(WaveData$x, res1$yopt, col = \"lightgreen\")\n#'\n#' @export\nL0TFinv.opt <- function(y=y, kmax=kmax, q=q, first=0, last=1, penalty=\"bic\"){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if ( !(penalty %in% c(\"bic\",\"sic\")) ){\n stop(\"The specified penalty is not supported\")\n }\n if( first<0 | last>1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if( length(y) <= kmax+q+1 ){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n res <- InverseL0TF(y=y, kmax=kmax, q=q, first=first, last=last)\n if(penalty == \"bic\"){\n kopt = which.min(res$bic)\n }\n if(penalty == \"sic\"){\n kopt = which.min(res$sic)\n }\n betaopt = res$beta.all[,kopt]\n Aopt = sort(res$A.all[[kopt]])\n yopt = res$y.all[,kopt]\n G = list(sic=res$sic,bic=res$bic,mse=res$mse,\n y=y,\n betaopt=betaopt,yopt=yopt,Aopt=Aopt,kopt=kopt,\n beta.all=res$beta.all,y.all=res$y.all,A.all=res$A.all)\n class(G) <- \"L0TFinvopt\"\n return(G)\n}\n\n \n\n"], ["/InverseL0TF/R/dataSimu.R", "#' @title Simulate Blocks Data\n#' @description This function generates data points of piecewise constant trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The constant values of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @return\n#' A list containing the piecewise constant simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1}\\}}\n#' \\item{y}{The piecewise constant simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @details\n#' \\itemize{\n#' \\item{}{To simplify the analysis, normalize the change point positions to a range between 0 and 1. Require that all elements of the input \\eqn{tau} are within this range. Consequently, the change point positions in simulated data forms a subset of the set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, 1\\}.}\n#' \\item{}{In fact, \\eqn{length(tau)} change points can divide the interval into \\eqn{length(tau)+1} segments of constant function values. Therefore, ensure that the length of vector \\eqn{h} is \\eqn{length(tau)+1}.}\n#' }\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 350, sigma = 0.1, seed = 50, tau = tau ,h = h)\n#' plot(BlocksData$x, BlocksData$y, xlab=\"\", ylab=\"\")\n#' lines(BlocksData$x, BlocksData$y0, col = \"red\")\n#' print(BlocksData$setA)\n#' print(BlocksData$tau)\n#' @importFrom stats rnorm\n#' @export\nSimuBlocksInv <- function (n, sigma, seed = NA, tau, h ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+1){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = h[1]\n beta[A+1] = diff(h)\n y0 = cumsum(beta)\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n\n\n#' @title Simulate Wave Data\n#' @description This function generates data points of piecewise linear trends.\n#' @param n Number of data points\n#' @param sigma Standard deviation of the noise added to the signal\n#' @param seed An optional seed for random number generation to make results reproducible\n#' @param tau The locations of change points in the underlying trend\n#' @param h The slope of the \\eqn{length(tau)+1} segments of the underlying trend\n#' @param a0 The initial point value\n#' @return\n#' A list containing the piecewise linear simulated data and the underlying trend:\n#' \\item{x}{The set \\{ \\eqn{\\frac{1}{n}}, \\eqn{\\frac{2}{n}}, \\eqn{\\frac{3}{n}},\\dots, \\eqn{1} \\}}\n#' \\item{y}{The piecewise linear simulated data of length \\eqn{n}}\n#' \\item{y0}{The underlying trend of length \\eqn{n}}\n#' \\item{setA}{The set of position indicators of change points in the simulated data}\n#' \\item{tau}{The locations of change points in the underlying trend}\n#'\n#' @examples\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 650, sigma = 0.1, seed = 50, tau = tau, h = h, a0 = a0)\n#' plot(WaveData$x, WaveData$y, xlab=\"\", ylab=\"\")\n#' lines(WaveData$x, WaveData$y0, col = \"red\")\n#' print(WaveData$setA)\n#' print(WaveData$tau)\n#' @seealso \\code{\\link{SimuBlocksInv}}\n#' @importFrom stats rnorm\n#' @export\nSimuWaveInv <- function (n, sigma, seed = NA, tau, h, a0 = 0 ){\n if (!is.na(seed)) set.seed(seed)\n if( min(tau)<=0 | max(tau)>=1 ){\n stop(\"\nThe maximum possible range for the change points should be within [0,1]\")\n }\n if (n < length(tau)+2){\n stop(\"The number of data points should be greater than the number of change points\")\n }\n if (length(h)!=length(tau)+1){\n stop(\"The length of the vector does not meet the condition\")\n }\n x = seq(1/n, 1,length.out = n)\n A = sapply(tau, function(z) which(x>=z)[1])\n beta = rep(0,n)\n beta[1] = a0\n beta[2] = h[1]/n-beta[1]\n beta[A+1] = (diff(h))/n\n y0 = cumsum(cumsum(beta))\n y = y0 + sigma*rnorm(n)\n return(list(x = x, y = y, y0 = y0, setA = A, tau = tau))\n}\n\n \n"], ["/InverseL0TF/R/print.R", "\n#' @title Print L0TFinvfix or L0TFinvopt object\n#' @description Prints a summary of L0TFinvfix or L0TFinvopt\n#' @param x The output of L0TFinvfix or L0TFinvopt\n#' @param ... ignore\n#' @method print L0TFinvfix\n#' @examples\n#' library(ggplot2)\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' BlocksData <- SimuBlocksInv(n = 500, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' print(res)\n#' coef(res,k=res$kopt)\n#' plot(res,type=\"yhat\")\n#' plot(res,type=\"bic\")\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' WaveData <- SimuWaveInv(n = 2000, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' print(res1)\n#' coef(res1,k=5)\n#' plot(res1,type=\"yhat\",k=5)\n#' plot(res1,type=\"mse\")\n#'\n#' @export\nprint.L0TFinvfix <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n#' @rdname print.L0TFinvfix\n#' @method print L0TFinvopt\n#' @export\nprint.L0TFinvopt <- function(x, ...){\n return(list(sic=x$sic,bic=x$bic,mse=x$mse,kopt=x$kopt,\n A.all=x$A.all,beta.all=x$beta.all,y.all=x$y.all))\n}\n\n\n"], ["/InverseL0TF/R/TFmetrics.R", "\n#' @title Print four metrics about change point detection results\n#' @description Prints four metrics to compare the quality of change point detection results.\n#' @param y0 The underlying trend\n#' @param tau The locations of change points in the underlying trend\n#' @param yhat The fitted trend\n#' @param cpts The positions of the fitted change points\n#' @return\n#' \\item{MSE}{The mean square error between the fitted trend and the underlying trend}\n#' \\item{MAD}{The median absolute deviation between the fitted trend and the underlying trend}\n#' \\item{dH}{Hausdorff Distance (dH) measures the accuracy of the estimated change points}\n#' \\item{nknot}{The number of detected change points}\n#' @details\n#' \\eqn{\\hat{\\boldsymbol{\\tau}}} represents the estimated change point positions, while \\eqn{\\boldsymbol{\\tau}} denotes the locations of change points in the underlying trend.\n#' \\deqn{d_H=\\frac{1}{n} \\max \\{\\max_k \\min_j |\\tau_j-\\hat{\\tau}_k|,\\max_j \\min_k |\\tau_j-\\hat{\\tau}_k|\\}.}\n#' Note that the number of \\eqn{\\hat{\\boldsymbol{\\tau}}} and \\eqn{\\boldsymbol{\\tau}} does not need to be the same.\n#' @examples\n#'\n#' tau = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h = c(-1, 5, 3, 0, -1, 2)\n#' n = 500\n#' BlocksData <- SimuBlocksInv(n = n, sigma = 0.2, seed = 50, tau = tau ,h = h)\n#' res <- L0TFinv.opt(y=BlocksData$y, kmax=10, q=0, first=0.01, last=1, penalty=\"bic\")\n#' metrics <- TFmetrics(BlocksData$y0,BlocksData$tau,res$yopt,res$Aopt/n)\n#' print(metrics)\n#'\n#' tau1 = c(0.1, 0.3, 0.4, 0.7, 0.85)\n#' h1 = c(-1, 5, 3, 0, -1, 2)\n#' a0 = -10\n#' n1 = 2000\n#' WaveData <- SimuWaveInv(n = n1, sigma = 0.1, seed = 50, tau = tau1, h = h1, a0 = a0)\n#' res1 <- L0TFinv.fix(y=WaveData$y, k=20, q=1, first=0, last=0.99)\n#' metrics1 <- TFmetrics(WaveData$y0,WaveData$tau,res1$y.all[,5],res1$A.all[[5]]/n1)\n#' print(metrics1)\n#'\n#' @export\nTFmetrics <- function(y0, tau=NULL, yhat, cpts = NULL){\n mse = mean((yhat-y0)^2)\n mad = mean(abs(yhat-y0))\n if(is.null(cpts)){\n tab = data.frame(MSE=mse, MAD=mad)\n }else{\n n = length(yhat)\n n.cpts = length(cpts)\n segments.endpoints.true = sort(unique(tau))\n segments.endpoints.est = sort(unique(cpts))\n distm = abs(matrix(rep(segments.endpoints.est, length(segments.endpoints.true)),\n nrow=length(segments.endpoints.est))-matrix(rep(segments.endpoints.true,\n length(segments.endpoints.est)), nrow=length(segments.endpoints.est), byrow=TRUE))\n screening.dist = max(apply(distm, 2, min))/n\n precision.dist = max(apply(distm, 1, min))/n\n haus.dist = max(screening.dist, precision.dist)\n tab = data.frame(MSE=mse, MAD=mad, dH=haus.dist, nknot=n.cpts)\n }\n return(tab)\n}\n\n\n\n\n\n\n\n\n"], ["/InverseL0TF/R/coef.R", "\n#' @title Extract estimated trends\n#' @description Extract the coefficients of the estimated trends under the constraint of a given number of change points.\n#' @param object The output of L0TFinvfix or L0TFinvopt\n#' @param k The given number of change points\n#' @method coef L0TFinvfix\n#' @seealso \\code{\\link{print.L0TFinvfix}}\n#' @export\ncoef.L0TFinvfix <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n\n#' @rdname coef.L0TFinvfix\n#' @method coef L0TFinvopt\n#' @export\ncoef.L0TFinvopt <- function(object, k=NULL) {\n if(is.null(k)){\n return(list(A.all=object$A.all,beta.all=object$beta.all,y.all=object$y.all))\n }else{\n if(k > ncol(object$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }else{\n return(list(A=object$A.all[[k]],beta=object$beta.all[,k],yhat=object$y.all[,k]))\n }\n }\n}\n"], ["/InverseL0TF/R/solveMatrix.R", "#' @title Generate the inverse of the crossprod matrix\n#' @description Generate the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, commonly employed in splicing algorithms. Note that an explicit solution exists for the inverse when \\eqn{q=0}, but not when \\eqn{q=1}.\n#' @param n The number of data points\n#' @param q The order of the difference, 0 or 1\n#' @param A The set of indicators, a subset of \\eqn{\\{1,2,3,\\dots,n\\}}\n#' @return The inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=} 0 or 1.\n#' @examples\n#' Mat1 <- XMat(n = 10, q = 0)\n#' A1 = c(1,2,5,8)\n#' mat1 = as.matrix(Mat1[,A1])\n#' S1 <- solMat(n = 10, q = 0, A = A1)\n#' print(S1)\n#' print(round(S1%*%t(mat1)%*%mat1,10))\n#'\n#' Mat2 <- XMat(n = 15, q = 1)\n#' A2 = c(1,3,8,10,15)\n#' mat2 = as.matrix(Mat2[,A2])\n#' S2 <- solMat(n = 15, q = 1, A = A2)\n#' print(S2)\n#' print(round(S2%*%t(mat2)%*%mat2,10))\n#' @importFrom Matrix solve\n#' @export\nsolMat <- function(n, q, A){\n if ( !(q %in% c(0,1)) ){\n stop(\"The specified order is not supported\")\n }\n if( min(A)<1 | max(A)>n ){\n stop(\"\nThe maximum possible range for the set indicators should be within {1,2,...,n}\")\n }\n k = length(A)\n m = as.numeric(k)\n m = n + 1 - A\n phi = matrix(0, k, k)\n if(q == 0){\n if(k == 1){\n phi[1,1] = 1/m[1]\n return(phi)\n }\n if(k == 2){\n phi[1,1] = m[2]\n phi[1,2] = -m[2]\n phi[2,1] = -m[2]\n phi[2,2] = m[1]\n phi = phi/(m[2]*(m[1]-m[2]))\n return(phi)\n }\n for(i in 1:k){\n if(i == 1){\n phi[1,1] = 1/(m[1]-m[2])\n phi[1,2] = -1/(m[1]-m[2])\n next\n }\n if(i == k){\n phi[k,(k-1)] = -1/(m[(k-1)]-m[k])\n phi[k,k] = 1/(m[(k-1)]-m[k])+1/m[k]\n break\n }\n phi[i,(i-1)] = -1/(m[(i-1)]-m[i])\n phi[i,i] = 1/(m[(i-1)]-m[i])+1/(m[i]-m[(i+1)])\n phi[i,(i+1)] = -1/(m[i]-m[(i+1)])\n }\n return(phi)\n }\n if (q == 1) {\n for (j in 1:k) {\n for (i in j:k) {\n if (j == i) {\n phi[i, j] <- m[j] * (m[j] + 1) * (2 * m[j] + 1) / 6\n } else {\n phi[i, j] <- m[i] * (m[i] + 1) * (3 * m[j] - m[i] + 1) / 6\n }\n }\n }\n phi <- phi + t(phi) - diag(diag(phi))\n phi <- solve(phi)\n return(phi)\n }\n}\n\n\n\n"], ["/InverseL0TF/R/sMatrix.R", "#' @title Generate a difference matrix\n#' @description This function generates a matrix for computing differences of a certain order, useful in numerical methods and for creating specific matrix patterns.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n-q-1} by \\eqn{n}, whose elements correspond to the combinatorial values of \\eqn{q}.\n#' @examples\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' print(Mat1)\n#'\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' print(Mat2)\n#'\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat3)\n#'\n#' @seealso \\code{\\link{XMat}}\n#' @export\nDiffMat <- function(n, q) {\n if( n <= q+1 ){\n stop(\"The number n should be greater than the order of the difference\")\n }\n X <- matrix(0, (n-q-1), n)\n for (i in 1:(n-q-1)) {\n for (j in 1:n) {\n if (j >= i && j <= i + q + 1) {\n X[i, j] <- (-1)^(j - i + q - 1) * choose(q + 1, j - i)\n }\n }\n }\n return(X)\n}\n\n\n\n#' @title Generate an artificial design matrix\n#' @description This matrix corresponds to the difference matrix, transforming the L0 trend filtering model into an inverse statistical problem.\n#' @param n The number of data points\n#' @param q The order of the difference\n#' @return A matrix with dimensions \\eqn{n} by \\eqn{n}, whose elements correspond to the difference matrix.\n#' @examples\n#' mat1 <- XMat(n = 10, q = 0)\n#' print(mat1)\n#'\n#' mat2 <- XMat(n = 15, q = 1)\n#' print(mat2)\n#'\n#' mat3 <- XMat(n = 15, q = 2)\n#' print(mat3)\n#'\n#' Mat1 <- DiffMat(n = 10, q = 0)\n#' Mat2 <- DiffMat(n = 15, q = 1)\n#' Mat3 <- DiffMat(n = 15, q = 2)\n#' print(Mat1%*%mat1)\n#' print(Mat2%*%mat2)\n#' print(Mat3%*%mat3)\n#' @details Noticing the correspondence between \\eqn{\\boldsymbol{D}^{(q+1)}} and \\eqn{\\boldsymbol{X}^{(q+1)}}, the result of their matrix multiplication is a combination of a zero matrix and an identity matrix. Expressed as \\eqn{\\boldsymbol{D}^{(q+1)} \\boldsymbol{X}^{(q+1)}=(\\boldsymbol{O}_{(n-q-1)\\times(q+1)},\\quad \\boldsymbol{I}_{(n-q-1)\\times(n-q-1)})}. The result is advantageous for the invertible processing of the original L0 trend filtering problem.\n#' @export\nXMat <- function(n, q){\n X <- matrix(0,n,n)\n if(q == 0){\n for(i in 1:n){\n for(j in 1:i){\n X[i,j] <- 1\n }\n }\n return(X)\n }else{\n return(apply(XMat(n, q-1),2,cumsum))\n }\n}\n\n\n\n\n\n"], ["/InverseL0TF/R/intro.R", "#' @_PACKAGE\n#'\n#' @name L0TFinv-package\n#' @title A package for L0-regularized sparse approximation\n#' @description\n#' Trend filtering is a typical method for nonparametric regression.\n#' The commonly used trend filtering models is the L1 trend filtering model \\eqn{(a)} based on the difference matrix \\eqn{\\boldsymbol{D}^{(q+1)}}, as illustrated below.\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_1}, \\quad q=0,1,2, \\ldots. \\quad (a) }\n#' L0 trend filtering \\eqn{(b)} has a advantage over other trend filtering methods, especially in the detection of change points.\n#' The expression for L0 trend filtering is as follows:\n#' \\deqn{\\min _{\\boldsymbol{\\alpha} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{\\alpha}\\|_2^2 + \\lambda\\|\\boldsymbol{D}^{(q+1)} \\boldsymbol{\\alpha}\\|_{\\ell_0}. \\quad (b) }\n#' We explore transforming the problem \\eqn{(b)} into a L0-regularized sparse format \\eqn{(c)} by introducing an artificial design matrix \\eqn{\\boldsymbol{X}^{(q+1)}} that corresponds to the difference matrix, thereby reformulating the L0 trend filtering problem into the following format.\n#' \\deqn{\\min _{\\boldsymbol{\\beta} \\in \\mathbb{R}^n} \\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2 + \\lambda \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0}. \\quad (c) }\n#' In our practical approach, we consider the maximum number of change points \\eqn{k_{\\text{max}}} as a constraint, transforming the aforementioned L0 penalty problem \\eqn{(c)} into the following L0 constraint problem.\n#' \\deqn{\\text{ minimize }\\frac{1}{2}\\|\\boldsymbol{y}-\\boldsymbol{X}^{(q+1)}\\boldsymbol{\\beta}\\|_2^2,\\quad \\text{ subject to } \\sum_{i=q+2}^n |\\boldsymbol{\\beta}_i|_{\\ell_0} \\leq k_{\\text{max}}. \\quad (d)}\n#' For such L0 constraint problems \\eqn{(d)}, we employ a splicing-based approach to design algorithms for processing.\n#' This package has the following seven main methods:\n#' \\itemize{\n#' \\item{\\strong{matrix with special structure }}{\\eqn{\\quad}Generate \\eqn{\\boldsymbol{X}^{(q+1)}} or \\eqn{\\boldsymbol{D}^{(q+1)}} matrix.}\n#' \\item{\\strong{inverse of the crossprod matrix }}{\\eqn{\\quad}Simplify the calculation of the inverse matrix of \\eqn{(\\boldsymbol{X}^{(q+1)}_A)^T \\boldsymbol{X}^{(q+1)}_A} for the cases where \\eqn{q=0} or \\eqn{q=1}, which is frequently used in splicing algorithms.}\n#' \\item{\\strong{inverse L0 trend filtering with fixed change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a given number of change points.}\n#' \\item{\\strong{inverse L0 trend filtering with optimal change points }}{\\eqn{\\quad}Fit a piecewise constant or piecewise linear estimated trend with a maximum number of change points, and select the optimal estimated trend using appropriate information criteria.}\n#' \\item{\\strong{simulated data }}{\\eqn{\\quad}Generate piecewise constant or piecewise linear data.}\n#' \\item{\\strong{print/coef}}{\\eqn{\\quad}Print a summary of the trend estimation results.}\n#' \\item{\\strong{plot }}{\\eqn{\\quad}Plot a summary of the trend estimation results.}\n#' }\n#' @details\n#' \\itemize{\n#' \\item{}{In previous studies, algorithms solving trend filtering problems \\eqn{(a)} necessitate the computation of \\eqn{((\\boldsymbol{D}^{(q+1)})^T \\boldsymbol{D}^{(q+1)})^{-1}}.\n#' When \\eqn{n} is large, just fitting the matrix into memory becomes an issue.}\n#' \\item{}{In L0 trend filtering \\eqn{(b)}, the positions of non-zero elements in the L0 norm correspond with the locations of change points.\n#' We consider two subsets: the active set \\eqn{A} for non-zero elements and the inactive set \\eqn{I} for zero elements.\n#' Despite this, computing \\eqn{((\\boldsymbol{D}^{(q+1)}_I)^T \\boldsymbol{D}^{(q+1)}_I)^{-1}} remains a task involving a substantial matrix.}\n#' \\item{}{Due to the connection between L0 constraint problems and L0 penalty problems, and considering that the sparsity of \\eqn{\\boldsymbol{\\beta}} is is more meaningful in practical applications than the selection of the hyperparameter \\eqn{\\lambda}.\n#' We focus on the constraint that reflects our aim to achieve an estimated trend with a given number of change points.\n#' So we transform the L0 penalty problem \\eqn{(c)} into the L0 constraint problem \\eqn{(d)}.}\n#' }\n#' @references\n#' Kim SJ, Koh K, Boyd SP and Gorinevsky DM. L1 Trend Filtering. Society for Industrial and Applied Mathematics (2009).\n#'\n#' Wen C, Wang X and Zhang A. L0 Trend Filtering. INFORMS Journal on Computing (2023).\nNULL\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:03:39", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(x, type = \"mse\", k = NULL, ...) {}", "code_description": "This code segment functions to: Generate visualization outputs for model evaluation metrics and trend estimations, selecting either optimal or user-specified parameters to display statistical measures versus change point quantities or comparative data fitting results."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nplot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...) {\n if (!(type %in% c(\"mse\", \"sic\", \"bic\", \"yhat\"))) {\n stop(\"The specified type is not supported\")\n }\n \n if (type != \"yhat\") {\n num <- 1:length(x[[type]])\n val <- x[[type]]\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n geom_vline(xintercept = x$k.opt, color = \"red\", linetype = \"dashed\") +\n labs(x = \"The number of change points\", y = toupper(type)) +\n theme_minimal()\n } else {\n if (!is.null(k)) {\n warning(\"k parameter is ignored for L0TFinvopt, using optimal solution\")\n }\n n <- length(x$y)\n df <- data.frame(\n num = 1:n,\n input = x$y,\n val = x$y.opt\n )\n plotObject <- ggplot(df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\", linewidth = 1) +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-04-45"}, "editdistance_info": {"edit_distance": 38.4134, "calculate_time": "2025-08-21 01:04:45", "true_code_clean": "function(x, type = \"mse\", k = NULL, ...){\n if ( !(type %in% c(\"mse\",\"sic\",\"bic\",\"yhat\")) ){\n stop(\"The specified type is not supported\")\n }\n if(type == \"mse\"){\n num = 1:(length(x$mse))\n val = x$mse\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"MSE\") +\n theme_minimal()\n }\n if(type == \"sic\"){\n num = 1:(length(x$sic))\n val = x$sic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"SIC\") +\n theme_minimal()\n }\n if(type == \"bic\"){\n num = 1:(length(x$bic))\n val = x$bic\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n labs(x = \"The number of change points\", y = \"BIC\") +\n theme_minimal()\n }\n if(type == \"yhat\"){\n n = length(x$y)\n num = 1:n\n if(is.null(k)){\n k = x$kopt\n val = x$y.all[,k]\n }else{\n if(k > ncol(x$beta.all)){\n stop(\"The number of given change points exceeds the maximum range\")\n }\n val = x$y.all[,k]\n }\n input = x$y\n df <- data.frame(num = num, input = input, val = val)\n plotObject <- ggplot(data = df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\") +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}", "predict_code_clean": "plot.L0TFinvopt <- function(x, type = \"mse\", k = NULL, ...) {\n if (!(type %in% c(\"mse\", \"sic\", \"bic\", \"yhat\"))) {\n stop(\"The specified type is not supported\")\n }\n if (type != \"yhat\") {\n num <- 1:length(x[[type]])\n val <- x[[type]]\n plotObject <- ggplot(data.frame(num, val), aes(x = num, y = val)) +\n geom_line() +\n geom_point() +\n geom_vline(xintercept = x$k.opt, color = \"red\", linetype = \"dashed\") +\n labs(x = \"The number of change points\", y = toupper(type)) +\n theme_minimal()\n } else {\n if (!is.null(k)) {\n warning(\"k parameter is ignored for L0TFinvopt, using optimal solution\")\n }\n n <- length(x$y)\n df <- data.frame(\n num = 1:n,\n input = x$y,\n val = x$y.opt\n )\n plotObject <- ggplot(df, aes(x = num)) +\n geom_point(aes(y = input), color = \"black\") +\n geom_line(aes(y = val), color = \"lightgreen\", linewidth = 1) +\n labs(x = \"Position indicators\", y = \"Value\") +\n theme_minimal()\n }\n return(plotObject)\n}"}}