From 2006e4d55a2ce4be18a0541168ed7c01d38cd431 Mon Sep 17 00:00:00 2001 From: "Joseph (Wen-Ting) Wang" Date: Wed, 17 Jan 2024 05:33:12 +0800 Subject: [PATCH] [CRAN] Prepare release v1.0.0 to CRAN (#7) * CHG: refine readme; update the description; add licence file; update the ignoring tag * CHG: refine README content * CHG: refine the r code by enhancing readbility, reformatting, and reducing redundant arguments * CHG: refine the rcpp code and description * CHG: add p parameter as mandatory; update the test cases and fix example code * CHG: refine wordings; update the manunal * FIX: correct typos * FIX: correct the bugs from CRAN result * CHG: enhance the example code * FIX: correct the codecov url * CHG: refine code based on the review comments * CHG: refine the par issue * CHG: refine example code by the CRAN review * FIX: regenerate the manual * Update README.md * CHG: update the release note --- .Rbuildignore | 4 +- DESCRIPTION | 25 +- LICENSE | 339 ++++++++++++++++++++++++ NEWS.md | 13 + R/RcppExports.R | 51 ++-- R/helper.R | 88 ++++--- R/qrglasso.R | 236 ++++++++--------- README.md | 43 ++-- man/awgl.Rd | 27 +- man/awgl_omega.Rd | 26 +- man/check_predict_parameters.Rd | 10 +- man/orthogonize_bspline.Rd | 9 +- man/plot.qrglasso.Rd | 13 +- man/plot.qrglasso.predict.Rd | 15 +- man/plot_bic_result.Rd | 10 +- man/plot_coefficient_function.Rd | 10 +- man/plot_sequentially.Rd | 8 +- man/predict.Rd | 18 +- man/qrglasso.Rd | 79 ++---- src/awgl.cpp | 425 ++++++++++++++++--------------- tests/testthat/test_qrglasso.R | 12 +- 21 files changed, 912 insertions(+), 549 deletions(-) create mode 100644 LICENSE diff --git a/.Rbuildignore b/.Rbuildignore index 246a67c..460b142 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -7,4 +7,6 @@ ^\.github$ ^codecov\.yml$ ^.*\.gcno$ -^NEWS$ \ No newline at end of file +^NEWS$ +LICENSE +\.github diff --git a/DESCRIPTION b/DESCRIPTION index dff1b80..fca53b0 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: QuantRegGLasso -Title: Adaptively Weighted Group Lasso for Semiparametic Quantile Rgression Models -Version: 0.5.0 +Title: Adaptively Weighted Group Lasso for Semiparametric Quantile Regression Models +Version: 1.0.0 Authors@R: c(person( given = "Wen-Ting", family = "Wang", @@ -12,23 +12,29 @@ Authors@R: c(person( given = "Wei-Ying", family = "Wu", email = "wuweiying1011@gmail.com", - role = "aut" - ), + role = c("aut") + ), person( given = "Toshio", family = "Honda", - email="t.honda@r.hit-u.ac.jp", - rol = c("aut")), + email = "t.honda@r.hit-u.ac.jp", + role = c("aut") + ), person( given = "Ching-Kang", family = "Ing", email="cking@stat.nthu.edu.tw", - rol = c("aut"), + role = c("aut"), comment = c(ORCID = "0000-0003-1362-8246") ) ) -Description: Address adaptively weighted group Lasso procedures of quantile regression problems. It excels in simultaneous variable selection and structure identification for varying coefficient quantile regression models, as well as additive quantile regression models featuring ultra-high dimensional covariates. (Toshio Honda, Ching-Kang Ing, Wei-Ying Wu, 2019,. ). -License: GPL-3 +Description: Implements an adaptively weighted group Lasso procedure for simultaneous variable selection and structure identification in varying + coefficient quantile regression models and additive quantile regression models with ultra-high dimensional covariates. The methodology, grounded + in a strong sparsity condition, establishes selection consistency under certain weight conditions. To address the challenge of tuning parameter + selection in practice, a BIC-type criterion named high-dimensional information criterion (HDIC) is proposed. The Lasso procedure, guided by + HDIC-determined tuning parameters, maintains selection consistency. Theoretical findings are strongly supported by simulation studies. + (Toshio Honda, Ching-Kang Ing, Wei-Ying Wu, 2019, ). +License: GPL (>= 2) LazyData: true ByteCompile: true BugReports: https://github.com/egpivo/QuantRegGLasso/issues @@ -42,7 +48,6 @@ Suggests: rmarkdown, testthat (>= 2.1.0) SystemRequirements: GNU make -VignetteBuilder: knitr Encoding: UTF-8 RoxygenNote: 7.2.3 Roxygen: list(markdown = TRUE) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ecbc059 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. \ No newline at end of file diff --git a/NEWS.md b/NEWS.md index a6bfb4c..f1a9e0f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,16 @@ +## QuantRegGLasso 1.0.0 (Release Date: 2024-01-17) +### Overview +In this release, we have deployed the package to CRAN following its standard procedures. The main features of this release include: + +- `qrglasso`: This function allows for model quantile regression by adaptively weighted group Lasso. + - `predict`: Generate estimations. + - `plot.qrglasso`: Investigate BIC performance. + - `plot.qrglasso.predict`: Visualize estimations. + +- `orthogonize_bspline`: Orthogonalize B-splines using the built-in function `splines::bs`. +--- + + ## QuantRegGLasso 0.5.0 (Release Date: 2024-01-11) ### Overview - Added a `plot.qrglasso` function for displaying BIC w.r.t. hyperparameters via `qrglasso` object. diff --git a/R/RcppExports.R b/R/RcppExports.R index 9053efd..72bcd44 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -1,37 +1,40 @@ # Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 -#' Internal function: Quantile regression with adaptively group lasso with the input omega +#' @title Internal function: Quantile Regression with Adaptively Group Lasso with `Omega` #' @keywords internal #' -#' @param Y data matrix (n x 1) -#' @param W B-splines with covariates matrix (n x pL) -#' @param omega Weights for group lasso -#' @param lambda A sequence of tuning parameters -#' @param tau A quantile of interest -#' @param qn A bound parameter for HDIC -#' @param zeta A step parameter -#' @param zetaincre An increment of each step -#' @param maxit The maximum number of iterations -#' @param tol A tolerance rate -#' @return A list of selected parameters +#' @description Internal function: Quantile regression with adaptively group Lasso with `Omega`. +#' @param Y Data matrix (\eqn{n \times 1}). +#' @param W B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows. +#' @param omega Weights for group lasso. +#' @param lambda A sequence of tuning parameters. +#' @param tau A quantile of interest. +#' @param qn A bound parameter for HDIC. +#' @param zeta A step parameter. +#' @param zetaincre An increment of each step. +#' @param maxit The maximum number of iterations. +#' @param tol A tolerance rate. +#' @return A list of selected parameters. awgl_omega <- function(Y, W, omega, lambda, tau, qn, zeta, zetaincre, maxit, tol) { .Call(`_QuantRegGLasso_awgl_omega`, Y, W, omega, lambda, tau, qn, zeta, zetaincre, maxit, tol) } -#' Internal function: Quantile regression with adaptively group lasso without input Omega +#' @title Internal function: Quantile Regression with Adaptively Group Lasso without `Omega` +#' @keywords internal #' -#' @param Y data matrix (n x 1) -#' @param W B-splines with covariates matrix (n x pL) -#' @param lambda A sequence of tuning parameters -#' @param tau A quantile of interest -#' @param L The number of groups -#' @param qn A bound parameter for HDIC -#' @param zeta A step parameter -#' @param zetaincre An increment of each step -#' @param maxit The maximum number of iterations -#' @param tol A tolerance rate -#' @return A list of selected parameters +#' @description Internal function: Quantile regression with adaptively group Lasso without `Omega`. +#' @param Y Data matrix (\eqn{n \times 1}). +#' @param W B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows. +#' @param lambda A sequence of tuning parameters. +#' @param tau A quantile of interest. +#' @param L The number of groups. +#' @param qn A bound parameter for HDIC. +#' @param zeta A step parameter. +#' @param zetaincre An increment of each step. +#' @param maxit The maximum number of iterations. +#' @param tol A tolerance rate. +#' @return A list of selected parameters. awgl <- function(Y, W, lambda, tau, L, qn, zeta, zetaincre, maxit, tol) { .Call(`_QuantRegGLasso_awgl`, Y, W, lambda, tau, L, qn, zeta, zetaincre, maxit, tol) } diff --git a/R/helper.R b/R/helper.R index 2aed68d..ca84826 100644 --- a/R/helper.R +++ b/R/helper.R @@ -1,14 +1,17 @@ -#' Orthogonalized B-splines +#' @title Orthogonalized B-splines +#' @description Generate a set of orthogonalized B-splines using the Gram-Schmidt algorithm applied to the built-in function `splines::bs()`. +#' #' @param knots Array. The knots that define the spline. #' @param boundary_knots Array. The breakpoints that define the spline. #' @param degree Integer. The degree of the piecewise polynomial. #' @param predictors Array. The predictor variables with size p. #' @param is_approx Boolean. The default is `FALSE`. #' @return A list containing: -#' \item{bsplines}{Matrix of orthogonalized B-splines with dimension (p, length(knots) + degree + 1)} -#' \item{z}{Predictors used in generation} +#' \item{\code{bsplines}}{Matrix of orthogonalized B-splines with dimensions \eqn{(p, \text{length}(knots) + \text{degree} + 1)}} +#' \item{\code{z}}{Predictors used in generation} #' @export #' @examples +#' # Example: Generate and plot the first 5 orthogonalized B-splines #' p <- 30 #' total_knots <- 10 #' degree <- 3 @@ -17,6 +20,7 @@ #' knots <- x[2:(total_knots - 1)] #' predictors <- runif(p, min = 0, max = 1) #' bsplines <- orthogonize_bspline(knots, boundaries, degree, predictors) +#' #' # Plot the first 5 B-splines #' index <- order(bsplines$z) #' original_par <- par(no.readonly = TRUE) @@ -24,7 +28,7 @@ #' for (i in 1:5) #' plot(bsplines$z[index], bsplines$bsplines[index, i], main = i, type = "l") #' par(original_par) -#' +#' @export orthogonize_bspline <- function( knots, boundary_knots, degree, predictors = NULL, is_approx = FALSE ) { @@ -83,29 +87,32 @@ orthogonize_bspline <- function( )) } - -#' Internal function: Validate new locations for a qrglasso_object object +#' @title Internal Function: Validate Parameters for Prediction with a `qrglasso` Object #' +#' @description Internal function to validate parameters for predicting with a `qrglasso` class object. +#' #' @keywords internal -#' @param qrglasso_object An `qrglasso` class object. -#' @param metric_type Character. A metric type for gamma selection. e.g., `BIC`, `BIC-log`. Default is `BIC`. -#' @param top_k Integer. A matrix of the top K estimated functions. +#' +#' @param qrglasso_object A `qrglasso` class object. +#' @param metric_type Character. Metric type for gamma selection, e.g., `BIC`, `BIC-log`. Default is `BIC`. +#' @param top_k Integer. Top K estimated functions. #' @param degree Integer. Degree of the piecewise polynomial. #' @param boundaries Array. Two boundary points. +#' #' @return `NULL`. #' check_predict_parameters <- function(qrglasso_object, metric_type, top_k, degree, boundaries) { if (!inherits(qrglasso_object, "qrglasso")) { - stop("Invalid object! Please enter a `qrglasso` object") + stop("Invalid object! Please enter a `qrglasso` object.") } if (!(metric_type %in% c("BIC", "BIC-log"))) { - stop("Only accept types: `BIC` and `BIC-log`") + stop("Only accept types: `BIC` and `BIC-log`.") } if (top_k <= 0) { - stop("Please enter a positive top k") + stop("Please enter a positive top k.") } if (degree <= 0) { - stop("Please enter a positive degree") + stop("Please enter a positive degree.") } if (length(boundaries) != 2) { stop("Please enter a size 2 boundaries.") @@ -113,20 +120,25 @@ check_predict_parameters <- function(qrglasso_object, metric_type, top_k, degree if (boundaries[1] >= boundaries[2]) { stop("Please input valid boundaries consisting of two elements in ascending order.") } - total_knots = qrglasso_object$L - degree + 1 + total_knots <- qrglasso_object$L - degree + 1 if (total_knots <= 0) { - stop("Please enter a smaller degree") + stop("Please enter a smaller degree.") } } -#' Internal function: Plot sequentially +#' @title Internal Function: Plot Sequentially +#' +#' @description Internal function to plot ggplot2 objects sequentially. +#' #' @keywords internal -#' @param objs Valid ggplot2 objects -#' @return `NULL` -#' +#' +#' @param objs List. Valid ggplot2 objects to be plotted sequentially. +#' +#' @return `NULL`. +#' plot_sequentially <- function(objs) { - originalPar <- par(no.readonly = TRUE) - on.exit(par(originalPar)) + original_par <- par(no.readonly = TRUE) + on.exit(par(original_par)) par(ask = TRUE) suppressWarnings({ for (obj in objs) { @@ -136,11 +148,17 @@ plot_sequentially <- function(objs) { par(ask = FALSE) } -#' Internal function: Plot Coefficient Function +#' @title Internal Function: Plot Coefficient Function +#' +#' @description Internal function to plot coefficient functions using ggplot2. +#' #' @keywords internal -#' @param data A dataframe contains columns ``z``, ``coefficient`` -#' @param variate A character represent the title -#' @return A ggplot object +#' +#' @param data Dataframe. A dataframe containing columns ``z``, ``coefficient``. +#' @param variate Character. A character representing the title. +#' +#' @return A ggplot object. +#' plot_coefficient_function <- function(data, variate) { default_theme <- theme_classic() + theme( @@ -148,18 +166,23 @@ plot_coefficient_function <- function(data, variate) { plot.title = element_text(hjust = 0.5) ) result <- ggplot(data, aes(x = z, y = coefficient)) + - geom_point(col="#4634eb") + + geom_point(col = "#4634eb") + ggtitle(variate) + default_theme return(result) } - -#' Internal function: Plot BIC Results w.r.t. lambda +#' @title Internal Function: Plot BIC Results w.r.t. lambda +#' +#' @description Internal function to plot BIC results with respect to lambda using ggplot2. +#' #' @keywords internal -#' @param data A dataframe contains columns ``lambda``, ``bic`` -#' @param variate A character represent the title -#' @return A ggplot object +#' +#' @param data Dataframe. A dataframe containing columns ``lambda``, ``bic``. +#' @param variate Character. A character representing the title. +#' +#' @return A ggplot object. +#' plot_bic_result <- function(data, variate) { default_theme <- theme_classic() + theme( @@ -167,7 +190,7 @@ plot_bic_result <- function(data, variate) { plot.title = element_text(hjust = 0.5) ) result <- ggplot(data, aes(x = lambda, y = bic)) + - geom_point(col="#4634eb") + + geom_point(col = "#4634eb") + geom_line() + ggtitle(variate) + xlab(expression(lambda)) + @@ -175,4 +198,3 @@ plot_bic_result <- function(data, variate) { default_theme return(result) } - diff --git a/R/qrglasso.R b/R/qrglasso.R index becd815..ef449f9 100644 --- a/R/qrglasso.R +++ b/R/qrglasso.R @@ -1,11 +1,14 @@ -#' Adaptively weighted group Lasso +#' @title Adaptively Weighted Group Lasso #' -#' @param Y A \eqn{n \times 1} data matrix -#' @param W A \eqn{n \times pL}B-spline matrix. -#' @param L The number of groups -#' @param omega A $p x 1$ weight matrix. Default value is NULL. +#' @description +#' The function `qrglasso` performs Adaptively Weighted Group Lasso for semiparametric quantile regression models. It estimates the coefficients of a quantile regression model with adaptively weighted group lasso regularization. The algorithm supports the use of B-spline basis functions to model the relationship between covariates and the response variable. Regularization is applied across different groups of covariates, and an adaptive weighting scheme is employed to enhance variable selection. +#' +#' @param Y A \eqn{n \times 1} data matrix where \eqn{n} is the sample size. +#' @param W A \eqn{n \times (p \times L)} B-spline matrix where \eqn{L} is the number of groups and \eqn{p} is the number of covariates. +#' @param p A numeric indicating the number of covariates. +#' @param omega A \eqn{p \times 1} weight matrix. Default value is NULL. #' @param tau A numeric quantile of interest. Default value is 0.5. -#' @param qn A nuneric bound parameter for HDIC. Default value is 1. +#' @param qn A numeric bound parameter for HDIC. Default value is 1. #' @param lambda A sequence of tuning parameters. Default value is NULL. #' @param maxit The maximum number of iterations. Default value is 1000. #' @param thr Threshold for convergence. Default value is \eqn{10^{-4}}. @@ -15,10 +18,14 @@ #' \item{\code{phi}}{An auxiliary estimate in the ADMM algorithm.} #' \item{\code{BIC}}{A sequence of BIC values with respect to different lambdas.} #' \item{\code{lambda}}{A sequence of tuning parameters used in the algorithm.} +#' \item{\code{L}}{The number of groups.} #' \item{\code{omega}}{A \eqn{p \times 1} weight matrix used in the algorithm.} #' @author Wen-Ting Wang -#' @references Toshio Honda, Ching-Kang Ing, Wei-Ying Wu (2019). Adaptively weighted group Lasso for semiparametric quantile regression models. \emph{Bernoulli} \bold{225} 4B. +#' @references +#' Toshio Honda, Ching-Kang Ing, Wei-Ying Wu (2019). Adaptively weighted group Lasso for semiparametric quantile regression models. \emph{Bernoulli} \bold{225} 4B. +#' #' @export +#' #' @examples #' # Example: One true non-linear covariate function #' # Define the function g1 @@ -27,10 +34,10 @@ #' } #' #' # Set parameters -#' n <- 150 -#' p <- 150 +#' n <- 100 +#' p <- 50 #' err_sd <- 0.1 ** 2 -#' tau <- 0.9 +#' tau <- 0.7 #' #' # Generate synthetic data #' set.seed(1234) @@ -48,113 +55,79 @@ #' #' # Create B-spline matrix W #' L <- total_knots + degree - 1 -#' W <- matrix(0, nrow = n, ncol = p * (L - 1)) -#' -#' for (i in 1:n) { -#' bspline_result <- orthogonize_bspline(knots, boundaries, degree, x[i, ]) -#' W[i, ] <- matrix(t(sqrt(L) * bspline_result$bsplines[, -1]), ncol = p * (L - 1), nrow = 1) -#' } +#' bspline_results <- lapply(1:n, function(i) orthogonize_bspline(knots, boundaries, degree, x[i, ])) +#' W <- matrix( +#' t(sapply(bspline_results, function(result) sqrt(L) * result$bsplines[, -1])), +#' ncol = p * (L - 1), +#' byrow = TRUE +#' ) #' #' # Perform quantile regression with group Lasso -#' result <- qrglasso(as.matrix(y), W, L - 1) -#' -#' -#' # Extract relevant information from the result -#' approx_bsplines <- orthogonize_bspline(knots, boundaries, degree) -#' bsplines <- approx_bsplines$bsplines[, -1] -#' z <- approx_bsplines$z -#' L_star <- L - 1 -#' gamma_hat <- result$gamma[, which.min(result$BIC[, 1])] -#' g1_BIC <- bsplines %*% gamma_hat[1:L_star] -#' g2_BIC <- bsplines %*% gamma_hat[(L_star + 1):(2 * L_star)] -#' -#' g10 <- bsplines %*% result$gamma[, 1][1:L_star] -#' g20 <- bsplines %*% result$gamma[, 1][(L_star + 1):(2 * L_star)] -#' -#' # Plotting -#' original_par <- par(no.readonly = TRUE) -#' par(mfrow = c(1, 2)) -#' -#' # Plot for g1(z) -#' plot(z, g1(z), type = 'l', lwd = 4, cex.lab = 2, lty = 2, cex.axis = 1.5, ylim = c(-3, 3)) -#' lines(z, g10, col = 2, lwd = 2) -#' lines(z, g1_BIC, col = 3, lwd = 2) -#' legend("topleft", c("True", expression(lambda == 0), expression(lambda[BIC])), col = c(1, 2, 3), -#' lty = c(2, 1, 1), lwd = c(3, 3, 3), horiz = TRUE, bty = "n") -#' -#' # Plot for g2(z) -#' plot(z, rep(0, length(z)), type = 'l', lwd = 4, cex.lab = 2, lty = 2, cex.axis = 1.5, -#' ylab = "g2(z)", ylim = c(-0.1, 0.1)) -#' lines(z, g20, col = 2, lwd = 2) -#' lines(z, g2_BIC, col = 3, lwd = 2) -#' legend("topleft", c("True", expression(lambda == 0), expression(lambda[BIC])), col = c(1, 2, 3, 4), -#' lty = c(2, 1, 1, 1), lwd = c(3, 3, 3, 3), horiz = TRUE, bty = "n") -#' -#' par(original_par) +#' n_lambda <- 10 +#' max_lambda <- 10 +#' lambda <- c(0, exp(seq(log(max_lambda / 1e4), log(max_lambda), length = (n_lambda - 1)))) +#' result <- qrglasso(as.matrix(y), W, p) +#' # BIC Results +#' plot(result) +#' # Prediction +#' estimate = predict(result, top_k = 1) +#' plot(estimate) #' -qrglasso <- - function(Y, - W, - L, - omega = NULL, - tau = 0.5, - qn = 1, - lambda = NULL, - maxit = 1000, - thr = 1e-04) { - if (is.null(lambda)) { - nlambda <- 51 - max.lambda <- 10 - lambda <- - c(0, exp(seq( - log(max.lambda / 1e4), log(max.lambda), length = (nlambda - 1) - ))) - } else { - nlambda <- length(lambda) - } - - zeta <- 10 - zetaincre <- 1 - - if (is.null(omega)) - result <- - awgl(Y, W, lambda, tau, L, qn, zeta, zetaincre, maxit, thr) - else - result <- - awgl_omega(Y, W, omega, lambda, tau, qn, zeta, zetaincre, maxit, thr) - - result$phi[, 1] <- result$gamma[, 1] - - obj.cv <- list( - gamma = result$gamma, - xi = result$xi, - phi = result$phi, - BIC = result$BIC, - lambda = lambda, - L = L, - omega = result$omega - ) - - class(obj.cv) <- "qrglasso" - return(obj.cv) +#' @export +qrglasso <- function(Y, + W, + p, + omega = NULL, + tau = 0.5, + qn = 1, + lambda = NULL, + maxit = 1000, + thr = 1e-04) { + if (is.null(lambda)) { + n_lambda <- 51 + max_lambda <- 10 + lambda <- c(0, exp(seq(log(max_lambda / 1e4), log(max_lambda), length = (n_lambda - 1)))) } + zeta <- 10 + zetaincre <- 1 + L_star <- dim(W)[2] / p + + if (is.null(omega)) + result <- awgl(Y, W, lambda, tau, L_star, qn, zeta, zetaincre, maxit, thr) + else + result <- awgl_omega(Y, W, omega, lambda, tau, qn, zeta, zetaincre, maxit, thr) + + result$phi[, 1] <- result$gamma[, 1] + + obj.cv <- list( + gamma = result$gamma, + xi = result$xi, + phi = result$phi, + BIC = result$BIC, + lambda = lambda, + L = L_star + 1, + omega = result$omega + ) + + class(obj.cv) <- "qrglasso" + return(obj.cv) +} - -#' @title Predict the coefficient functions +#' @title Predict Top-k Coefficient Functions #' -#' @description Predict the top-k coefficient functions +#' @description Predict the top-k coefficient functions based on a \code{qrglasso} class object. #' -#' @param qrglasso_object An \code{qrglasso} class object. -#' @param metric_type Character. A metric type for gamma selection. e.g., `BIC`, `BIC-log`. Default is `BIC`. -#' @param top_k Integer. A matrix of the top K estimated functions. Default is 5. +#' @param qrglasso_object A \code{qrglasso} class object. +#' @param metric_type Character. Metric type for gamma selection, e.g., `BIC`, `BIC-log`. Default is `BIC`. +#' @param top_k Integer. The number of top estimated functions to predict. Default is 5. #' @param degree Integer. Degree of the piecewise polynomial. Default is 2. -#' @param boundaries Array. Two boundary points. Default is c(0, 1). +#' @param boundaries Array. Two boundary points for the piecewise polynomial. Default is c(0, 1). #' @param is_approx Logical. If TRUE, the size of covariate indexes will be 1e6; otherwise, 1e4. Default is FALSE. #' @seealso \code{\link{qrglasso}} #' @return A list containing: -#' \item{coef_functions}{Matrix. Top-k coefficient function estimates with dimenstion (\eqn{m \times k}) where $m$ is size of `z`.} -#' \item{z}{Array. Index predictors used in generation} +#' \item{\code{coef_functions}}{Matrix. The estimated top-k coefficient functions with dimension (\eqn{m \times k}), where \eqn{m} is the size of \code{z}.} +#' \item{\code{z}}{Array. Index predictors used in the generation.} #' @examples #' set.seed(123) #' n <- 100 @@ -164,10 +137,11 @@ qrglasso <- #' W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) #' #' # Call qrglasso with default parameters -#' result <- qrglasso(Y = Y, W = W, L = 5) +#' result <- qrglasso(Y = Y, W = W, p = p) #' estimate <- predict(result) #' print(dim(estimate$coef_functions)) #' +#' @export predict <- function(qrglasso_object, metric_type = "BIC", top_k = 5, @@ -196,12 +170,12 @@ predict <- function(qrglasso_object, return(obj.predict) } -#' @title Display the estimated coefficient functions +#' @title Display BIC Results from `qrglasso` #' -#' @description Display the estimated coefficient functions by BIC +#' @description Visualize the HDIC BIC results corresponding to hyperparameters obtained from `qrglasso`. #' -#' @param x An object of class \code{qrglasso.predict} for the \code{plot} method -#' @param ... Not used directly +#' @param x An object of class \code{qrglasso} for the \code{plot} method. +#' @param ... Additional parameters not used directly. #' @return \code{NULL} #' @seealso \code{\link{qrglasso}} #' @@ -215,32 +189,35 @@ predict <- function(qrglasso_object, #' Y <- matrix(rnorm(n), n, 1) #' W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) #' -#' result <- qrglasso(Y = Y, W = W, L = 5) +#' # Call qrglasso with default parameters +#' result <- qrglasso(Y = Y, W = W, p = p) +#' +#' # Visualize the BIC results #' plot(result) -#' +#' +#' @export plot.qrglasso <- function(x, ...) { if (!inherits(x, "qrglasso")) { - stop("Invalid object! Please enter a `qrglasso` object") + stop("Invalid object! Please enter a `qrglasso` object.") } - originalPar <- par(no.readonly = TRUE) + original_par <- par(no.readonly = TRUE) + on.exit(par(original_par)) result <- list() variates <- c("BIC", "BIC-log") for (i in 1:2) { variate <- variates[i] - data <- data.frame(lambda = x$lambda, bic = x$BIC[,i]) + data <- data.frame(lambda = x$lambda, bic = x$BIC[, i]) result[[variate]] <- plot_bic_result(data, variate) } plot_sequentially(result) - par(originalPar) } - -#' @title Display the estimated coefficient functions +#' @title Display Predicted Coefficient Functions from `qrglasso` #' -#' @description Display the estimated coefficient functions by BIC +#' @description Visualize the predicted coefficient functions selected by BIC. #' -#' @param x An object of class \code{qrglasso.predict} for the \code{plot} method -#' @param ... Not used directly +#' @param x An object of class \code{qrglasso.predict} for the \code{plot} method. +#' @param ... Additional parameters not used directly. #' @return \code{NULL} #' @seealso \code{\link{qrglasso}} #' @@ -254,23 +231,28 @@ plot.qrglasso <- function(x, ...) { #' Y <- matrix(rnorm(n), n, 1) #' W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) #' -#' result <- qrglasso(Y = Y, W = W, L = 5) +#' # Call qrglasso with default parameters +#' result <- qrglasso(Y = Y, W = W, p = p) +#' +#' # Predict the top-k coefficient functions #' estimate <- predict(result, top_k = 2) +#' +#' # Display the predicted coefficient functions #' plot(estimate) #' +#' @export plot.qrglasso.predict <- function(x, ...) { if (!inherits(x, "qrglasso.predict")) { - stop("Invalid object! Please enter a `qrglasso.predict` object") + stop("Invalid object! Please enter a `qrglasso.predict` object.") } - originalPar <- par(no.readonly = TRUE) + original_par <- par(no.readonly = TRUE) + on.exit(par(original_par)) k <- dim(x$coef_functions)[2] result <- list() for (i in 1:k) { variate <- paste0("Coefficient function - g", i) - data <- data.frame(z = x$z, coefficient = x$coef_functions[,i]) + data <- data.frame(z = x$z, coefficient = x$coef_functions[, i]) result[[variate]] <- plot_coefficient_function(data, variate) } plot_sequentially(result) - par(originalPar) } - diff --git a/README.md b/README.md index c22dc54..bd3a004 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,50 @@ -## QuantRegGLasso Package +## QuantRegGLasso: Adaptively Weighted Group Lasso for Semiparametric Quantile Regression Models + +[![License](https://eddelbuettel.github.io/badges/GPL2+.svg)](https://www.gnu.org/licenses/gpl-2.0.html) [![R build status](https://github.com/egpivo/QuantRegGLasso/workflows/R-CMD-check/badge.svg)](https://github.com/egpivo/QuantRegGLasso/actions) -[![Code Coverage](https://codecov.io/gh/egpivo/QuantRegGLasso/branch/master/graph/badge.svg)](https://codecov.io/gh/egpivo/QuantRegGLasso) +[![Code Coverage](https://img.shields.io/codecov/c/github/egpivo/QuantRegGLasso/master.svg)](https://app.codecov.io/github/egpivo/QuantRegGLasso?branch=master) +[![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/QuantRegGLasso)](https://CRAN.R-project.org/package=QuantRegGLasso) +[![Downloads (monthly)](https://cranlogs.r-pkg.org/badges/QuantRegGLasso?color=brightgreen)](https://www.r-pkg.org/pkg/QuantRegGLasso) +[![Downloads (total)](https://cranlogs.r-pkg.org/badges/grand-total/QuantRegGLasso?color=brightgreen)](https://www.r-pkg.org/pkg/QuantRegGLasso) +[![BEJ](https://img.shields.io/badge/Bernoulli-10.3150%2FBEJ1091-brightgreen)](https://doi.org/10.3150/18-BEJ1091) + + +**QuantRegGLasso** is an R package designed for adaptively weighted group Lasso procedures in quantile regression. It excels in simultaneous variable selection and structure identification for varying coefficient quantile regression models and additive quantile regression models with ultra-high dimensional covariates. -## Description -**QuantRegGLasso** is an R package meticulously crafted to address adaptively weighted group Lasso procedures of quantile regression problems. It excels in simultaneous variable selection and structure identification for varying coefficient quantile regression models, as well as additive quantile regression models featuring ultra-high dimensional covariates. ## Installation - Install the current development version from GitHub: - ```r - remotes::install_github("egpivo/QuantRegGLasso") - ``` + ```r + remotes::install_github("egpivo/QuantRegGLasso") + ``` **Please Note:** - **Windows Users:** Ensure that you have [Rtools](https://cran.r-project.org/bin/windows/Rtools/) installed before proceeding with the installation. - **Mac Users:** You need Xcode Command Line Tools and should install the library [`gfortran`](https://github.com/fxcoudert/gfortran-for-macOS/releases). Follow these steps in the terminal: - ```bash - brew update - brew install gcc - ``` - For a detailed solution, refer to this [link](https://thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error/), or download and install the library [`gfortran`](https://github.com/fxcoudert/gfortran-for-macOS/releases) to resolve the "`ld: library not found for -lgfortran`" error. + ```bash + brew update + brew install gcc + ``` + For a detailed solution, refer to this [link](https://thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error/), or download and install the library [`gfortran`](https://github.com/fxcoudert/gfortran-for-macOS/releases) to resolve the "`ld: library not found for -lgfortran`" error. -### Author -- [Wen-Ting Wang](https://www.linkedin.com/in/wen-ting-wang-6083a17b) + +### Authors +- [Wen-Ting Wang](https://www.linkedin.com/in/wen-ting-wang-6083a17b) ([GitHub](https://github.com/egpivo)) - [Wei-Ying Wu](https://projecteuclid.org/search?author=Wei-Ying_Wu) - [Toshio Honda](https://www1.econ.hit-u.ac.jp/honda/e-honda.html) - [Ching-Kang Ing](https://www.researchgate.net/profile/Ching-Kang-Ing) ### Maintainer -[Wen-Ting Wang](https://www.linkedin.com/in/wen-ting-wang-6083a17b) +[Wen-Ting Wang](https://www.linkedin.com/in/wen-ting-wang-6083a17b) ([GitHub](https://github.com/egpivo)) ### Reference Toshio Honda, Ching-Kang Ing, Wei-Ying Wu (2019). [Adaptively weighted group Lasso for semiparametric quantile regression models](https://projecteuclid.org/journals/bernoulli/volume-25/issue-4B/Adaptively-weighted-group-Lasso-for-semiparametric-quantile-regression-models/10.3150/18-BEJ1091.full). -## License -GPL-3 +This paper introduces the adaptively weighted group Lasso procedure and its application to semiparametric quantile regression models. The methodology is grounded in a strong sparsity condition, establishing selection consistency under certain weight conditions. +## License +GPL (>= 2) diff --git a/man/awgl.Rd b/man/awgl.Rd index e1bdf6a..e361d95 100644 --- a/man/awgl.Rd +++ b/man/awgl.Rd @@ -2,34 +2,35 @@ % Please edit documentation in R/RcppExports.R \name{awgl} \alias{awgl} -\title{Internal function: Quantile regression with adaptively group lasso without input Omega} +\title{Internal function: Quantile Regression with Adaptively Group Lasso without \code{Omega}} \usage{ awgl(Y, W, lambda, tau, L, qn, zeta, zetaincre, maxit, tol) } \arguments{ -\item{Y}{data matrix (n x 1)} +\item{Y}{Data matrix (\eqn{n \times 1}).} -\item{W}{B-splines with covariates matrix (n x pL)} +\item{W}{B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows.} -\item{lambda}{A sequence of tuning parameters} +\item{lambda}{A sequence of tuning parameters.} -\item{tau}{A quantile of interest} +\item{tau}{A quantile of interest.} -\item{L}{The number of groups} +\item{L}{The number of groups.} -\item{qn}{A bound parameter for HDIC} +\item{qn}{A bound parameter for HDIC.} -\item{zeta}{A step parameter} +\item{zeta}{A step parameter.} -\item{zetaincre}{An increment of each step} +\item{zetaincre}{An increment of each step.} -\item{maxit}{The maximum number of iterations} +\item{maxit}{The maximum number of iterations.} -\item{tol}{A tolerance rate} +\item{tol}{A tolerance rate.} } \value{ -A list of selected parameters +A list of selected parameters. } \description{ -Internal function: Quantile regression with adaptively group lasso without input Omega +Internal function: Quantile regression with adaptively group Lasso without \code{Omega}. } +\keyword{internal} diff --git a/man/awgl_omega.Rd b/man/awgl_omega.Rd index c0bcedd..8029203 100644 --- a/man/awgl_omega.Rd +++ b/man/awgl_omega.Rd @@ -2,35 +2,35 @@ % Please edit documentation in R/RcppExports.R \name{awgl_omega} \alias{awgl_omega} -\title{Internal function: Quantile regression with adaptively group lasso with the input omega} +\title{Internal function: Quantile Regression with Adaptively Group Lasso with \code{Omega}} \usage{ awgl_omega(Y, W, omega, lambda, tau, qn, zeta, zetaincre, maxit, tol) } \arguments{ -\item{Y}{data matrix (n x 1)} +\item{Y}{Data matrix (\eqn{n \times 1}).} -\item{W}{B-splines with covariates matrix (n x pL)} +\item{W}{B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows.} -\item{omega}{Weights for group lasso} +\item{omega}{Weights for group lasso.} -\item{lambda}{A sequence of tuning parameters} +\item{lambda}{A sequence of tuning parameters.} -\item{tau}{A quantile of interest} +\item{tau}{A quantile of interest.} -\item{qn}{A bound parameter for HDIC} +\item{qn}{A bound parameter for HDIC.} -\item{zeta}{A step parameter} +\item{zeta}{A step parameter.} -\item{zetaincre}{An increment of each step} +\item{zetaincre}{An increment of each step.} -\item{maxit}{The maximum number of iterations} +\item{maxit}{The maximum number of iterations.} -\item{tol}{A tolerance rate} +\item{tol}{A tolerance rate.} } \value{ -A list of selected parameters +A list of selected parameters. } \description{ -Internal function: Quantile regression with adaptively group lasso with the input omega +Internal function: Quantile regression with adaptively group Lasso with \code{Omega}. } \keyword{internal} diff --git a/man/check_predict_parameters.Rd b/man/check_predict_parameters.Rd index deccf49..c2b25e6 100644 --- a/man/check_predict_parameters.Rd +++ b/man/check_predict_parameters.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/helper.R \name{check_predict_parameters} \alias{check_predict_parameters} -\title{Internal function: Validate new locations for a qrglasso_object object} +\title{Internal Function: Validate Parameters for Prediction with a \code{qrglasso} Object} \usage{ check_predict_parameters( qrglasso_object, @@ -13,11 +13,11 @@ check_predict_parameters( ) } \arguments{ -\item{qrglasso_object}{An \code{qrglasso} class object.} +\item{qrglasso_object}{A \code{qrglasso} class object.} -\item{metric_type}{Character. A metric type for gamma selection. e.g., \code{BIC}, \code{BIC-log}. Default is \code{BIC}.} +\item{metric_type}{Character. Metric type for gamma selection, e.g., \code{BIC}, \code{BIC-log}. Default is \code{BIC}.} -\item{top_k}{Integer. A matrix of the top K estimated functions.} +\item{top_k}{Integer. Top K estimated functions.} \item{degree}{Integer. Degree of the piecewise polynomial.} @@ -27,6 +27,6 @@ check_predict_parameters( \code{NULL}. } \description{ -Internal function: Validate new locations for a qrglasso_object object +Internal function to validate parameters for predicting with a \code{qrglasso} class object. } \keyword{internal} diff --git a/man/orthogonize_bspline.Rd b/man/orthogonize_bspline.Rd index d106309..4668ad5 100644 --- a/man/orthogonize_bspline.Rd +++ b/man/orthogonize_bspline.Rd @@ -25,13 +25,14 @@ orthogonize_bspline( } \value{ A list containing: -\item{bsplines}{Matrix of orthogonalized B-splines with dimension (p, length(knots) + degree + 1)} -\item{z}{Predictors used in generation} +\item{\code{bsplines}}{Matrix of orthogonalized B-splines with dimensions \eqn{(p, \text{length}(knots) + \text{degree} + 1)}} +\item{\code{z}}{Predictors used in generation} } \description{ -Orthogonalized B-splines +Generate a set of orthogonalized B-splines using the Gram-Schmidt algorithm applied to the built-in function \code{splines::bs()}. } \examples{ +# Example: Generate and plot the first 5 orthogonalized B-splines p <- 30 total_knots <- 10 degree <- 3 @@ -40,6 +41,7 @@ x <- seq(from = 0, to = 1, length.out = total_knots) knots <- x[2:(total_knots - 1)] predictors <- runif(p, min = 0, max = 1) bsplines <- orthogonize_bspline(knots, boundaries, degree, predictors) + # Plot the first 5 B-splines index <- order(bsplines$z) original_par <- par(no.readonly = TRUE) @@ -47,5 +49,4 @@ par(mfrow = c(1, 5)) for (i in 1:5) plot(bsplines$z[index], bsplines$bsplines[index, i], main = i, type = "l") par(original_par) - } diff --git a/man/plot.qrglasso.Rd b/man/plot.qrglasso.Rd index 3e58eee..8a3d44a 100644 --- a/man/plot.qrglasso.Rd +++ b/man/plot.qrglasso.Rd @@ -2,20 +2,20 @@ % Please edit documentation in R/qrglasso.R \name{plot.qrglasso} \alias{plot.qrglasso} -\title{Display the estimated coefficient functions} +\title{Display BIC Results from \code{qrglasso}} \usage{ \method{plot}{qrglasso}(x, ...) } \arguments{ -\item{x}{An object of class \code{qrglasso.predict} for the \code{plot} method} +\item{x}{An object of class \code{qrglasso} for the \code{plot} method.} -\item{...}{Not used directly} +\item{...}{Additional parameters not used directly.} } \value{ \code{NULL} } \description{ -Display the estimated coefficient functions by BIC +Visualize the HDIC BIC results corresponding to hyperparameters obtained from \code{qrglasso}. } \examples{ set.seed(123) @@ -25,7 +25,10 @@ L <- 5 Y <- matrix(rnorm(n), n, 1) W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) -result <- qrglasso(Y = Y, W = W, L = 5) +# Call qrglasso with default parameters +result <- qrglasso(Y = Y, W = W, p = p) + +# Visualize the BIC results plot(result) } diff --git a/man/plot.qrglasso.predict.Rd b/man/plot.qrglasso.predict.Rd index eacf55a..167d629 100644 --- a/man/plot.qrglasso.predict.Rd +++ b/man/plot.qrglasso.predict.Rd @@ -2,20 +2,20 @@ % Please edit documentation in R/qrglasso.R \name{plot.qrglasso.predict} \alias{plot.qrglasso.predict} -\title{Display the estimated coefficient functions} +\title{Display Predicted Coefficient Functions from \code{qrglasso}} \usage{ \method{plot}{qrglasso.predict}(x, ...) } \arguments{ -\item{x}{An object of class \code{qrglasso.predict} for the \code{plot} method} +\item{x}{An object of class \code{qrglasso.predict} for the \code{plot} method.} -\item{...}{Not used directly} +\item{...}{Additional parameters not used directly.} } \value{ \code{NULL} } \description{ -Display the estimated coefficient functions by BIC +Visualize the predicted coefficient functions selected by BIC. } \examples{ set.seed(123) @@ -25,8 +25,13 @@ L <- 5 Y <- matrix(rnorm(n), n, 1) W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) -result <- qrglasso(Y = Y, W = W, L = 5) +# Call qrglasso with default parameters +result <- qrglasso(Y = Y, W = W, p = p) + +# Predict the top-k coefficient functions estimate <- predict(result, top_k = 2) + +# Display the predicted coefficient functions plot(estimate) } diff --git a/man/plot_bic_result.Rd b/man/plot_bic_result.Rd index e893136..b936e23 100644 --- a/man/plot_bic_result.Rd +++ b/man/plot_bic_result.Rd @@ -2,19 +2,19 @@ % Please edit documentation in R/helper.R \name{plot_bic_result} \alias{plot_bic_result} -\title{Internal function: Plot BIC Results w.r.t. lambda} +\title{Internal Function: Plot BIC Results w.r.t. lambda} \usage{ plot_bic_result(data, variate) } \arguments{ -\item{data}{A dataframe contains columns \code{lambda}, \code{bic}} +\item{data}{Dataframe. A dataframe containing columns \code{lambda}, \code{bic}.} -\item{variate}{A character represent the title} +\item{variate}{Character. A character representing the title.} } \value{ -A ggplot object +A ggplot object. } \description{ -Internal function: Plot BIC Results w.r.t. lambda +Internal function to plot BIC results with respect to lambda using ggplot2. } \keyword{internal} diff --git a/man/plot_coefficient_function.Rd b/man/plot_coefficient_function.Rd index de56bb6..f238bb6 100644 --- a/man/plot_coefficient_function.Rd +++ b/man/plot_coefficient_function.Rd @@ -2,19 +2,19 @@ % Please edit documentation in R/helper.R \name{plot_coefficient_function} \alias{plot_coefficient_function} -\title{Internal function: Plot Coefficient Function} +\title{Internal Function: Plot Coefficient Function} \usage{ plot_coefficient_function(data, variate) } \arguments{ -\item{data}{A dataframe contains columns \code{z}, \code{coefficient}} +\item{data}{Dataframe. A dataframe containing columns \code{z}, \code{coefficient}.} -\item{variate}{A character represent the title} +\item{variate}{Character. A character representing the title.} } \value{ -A ggplot object +A ggplot object. } \description{ -Internal function: Plot Coefficient Function +Internal function to plot coefficient functions using ggplot2. } \keyword{internal} diff --git a/man/plot_sequentially.Rd b/man/plot_sequentially.Rd index f799ea1..dfac452 100644 --- a/man/plot_sequentially.Rd +++ b/man/plot_sequentially.Rd @@ -2,17 +2,17 @@ % Please edit documentation in R/helper.R \name{plot_sequentially} \alias{plot_sequentially} -\title{Internal function: Plot sequentially} +\title{Internal Function: Plot Sequentially} \usage{ plot_sequentially(objs) } \arguments{ -\item{objs}{Valid ggplot2 objects} +\item{objs}{List. Valid ggplot2 objects to be plotted sequentially.} } \value{ -\code{NULL} +\code{NULL}. } \description{ -Internal function: Plot sequentially +Internal function to plot ggplot2 objects sequentially. } \keyword{internal} diff --git a/man/predict.Rd b/man/predict.Rd index dc6f343..f45d292 100644 --- a/man/predict.Rd +++ b/man/predict.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/qrglasso.R \name{predict} \alias{predict} -\title{Predict the coefficient functions} +\title{Predict Top-k Coefficient Functions} \usage{ predict( qrglasso_object, @@ -14,25 +14,25 @@ predict( ) } \arguments{ -\item{qrglasso_object}{An \code{qrglasso} class object.} +\item{qrglasso_object}{A \code{qrglasso} class object.} -\item{metric_type}{Character. A metric type for gamma selection. e.g., \code{BIC}, \code{BIC-log}. Default is \code{BIC}.} +\item{metric_type}{Character. Metric type for gamma selection, e.g., \code{BIC}, \code{BIC-log}. Default is \code{BIC}.} -\item{top_k}{Integer. A matrix of the top K estimated functions. Default is 5.} +\item{top_k}{Integer. The number of top estimated functions to predict. Default is 5.} \item{degree}{Integer. Degree of the piecewise polynomial. Default is 2.} -\item{boundaries}{Array. Two boundary points. Default is c(0, 1).} +\item{boundaries}{Array. Two boundary points for the piecewise polynomial. Default is c(0, 1).} \item{is_approx}{Logical. If TRUE, the size of covariate indexes will be 1e6; otherwise, 1e4. Default is FALSE.} } \value{ A list containing: -\item{coef_functions}{Matrix. Top-k coefficient function estimates with dimenstion (\eqn{m \times k}) where $m$ is size of \code{z}.} -\item{z}{Array. Index predictors used in generation} +\item{\code{coef_functions}}{Matrix. The estimated top-k coefficient functions with dimension (\eqn{m \times k}), where \eqn{m} is the size of \code{z}.} +\item{\code{z}}{Array. Index predictors used in the generation.} } \description{ -Predict the top-k coefficient functions +Predict the top-k coefficient functions based on a \code{qrglasso} class object. } \examples{ set.seed(123) @@ -43,7 +43,7 @@ Y <- matrix(rnorm(n), n, 1) W <- matrix(rnorm(n * p * (L - 1)), n, p * (L - 1)) # Call qrglasso with default parameters -result <- qrglasso(Y = Y, W = W, L = 5) +result <- qrglasso(Y = Y, W = W, p = p) estimate <- predict(result) print(dim(estimate$coef_functions)) diff --git a/man/qrglasso.Rd b/man/qrglasso.Rd index 989e35f..6787a49 100644 --- a/man/qrglasso.Rd +++ b/man/qrglasso.Rd @@ -2,12 +2,12 @@ % Please edit documentation in R/qrglasso.R \name{qrglasso} \alias{qrglasso} -\title{Adaptively weighted group Lasso} +\title{Adaptively Weighted Group Lasso} \usage{ qrglasso( Y, W, - L, + p, omega = NULL, tau = 0.5, qn = 1, @@ -17,17 +17,17 @@ qrglasso( ) } \arguments{ -\item{Y}{A \eqn{n \times 1} data matrix} +\item{Y}{A \eqn{n \times 1} data matrix where \eqn{n} is the sample size.} -\item{W}{A \eqn{n \times pL}B-spline matrix.} +\item{W}{A \eqn{n \times (p \times L)} B-spline matrix where \eqn{L} is the number of groups and \eqn{p} is the number of covariates.} -\item{L}{The number of groups} +\item{p}{A numeric indicating the number of covariates.} -\item{omega}{A $p x 1$ weight matrix. Default value is NULL.} +\item{omega}{A \eqn{p \times 1} weight matrix. Default value is NULL.} \item{tau}{A numeric quantile of interest. Default value is 0.5.} -\item{qn}{A nuneric bound parameter for HDIC. Default value is 1.} +\item{qn}{A numeric bound parameter for HDIC. Default value is 1.} \item{lambda}{A sequence of tuning parameters. Default value is NULL.} @@ -42,10 +42,11 @@ A list with the following components: \item{\code{phi}}{An auxiliary estimate in the ADMM algorithm.} \item{\code{BIC}}{A sequence of BIC values with respect to different lambdas.} \item{\code{lambda}}{A sequence of tuning parameters used in the algorithm.} +\item{\code{L}}{The number of groups.} \item{\code{omega}}{A \eqn{p \times 1} weight matrix used in the algorithm.} } \description{ -Adaptively weighted group Lasso +The function \code{qrglasso} performs Adaptively Weighted Group Lasso for semiparametric quantile regression models. It estimates the coefficients of a quantile regression model with adaptively weighted group lasso regularization. The algorithm supports the use of B-spline basis functions to model the relationship between covariates and the response variable. Regularization is applied across different groups of covariates, and an adaptive weighting scheme is employed to enhance variable selection. } \examples{ # Example: One true non-linear covariate function @@ -55,10 +56,10 @@ g1 <- function(x) { } # Set parameters -n <- 150 -p <- 150 +n <- 100 +p <- 50 err_sd <- 0.1 ** 2 -tau <- 0.9 +tau <- 0.7 # Generate synthetic data set.seed(1234) @@ -76,49 +77,23 @@ knots <- xx[2:(total_knots - 1)] # Create B-spline matrix W L <- total_knots + degree - 1 -W <- matrix(0, nrow = n, ncol = p * (L - 1)) - -for (i in 1:n) { - bspline_result <- orthogonize_bspline(knots, boundaries, degree, x[i, ]) - W[i, ] <- matrix(t(sqrt(L) * bspline_result$bsplines[, -1]), ncol = p * (L - 1), nrow = 1) -} +bspline_results <- lapply(1:n, function(i) orthogonize_bspline(knots, boundaries, degree, x[i, ])) +W <- matrix( + t(sapply(bspline_results, function(result) sqrt(L) * result$bsplines[, -1])), + ncol = p * (L - 1), + byrow = TRUE +) # Perform quantile regression with group Lasso -result <- qrglasso(as.matrix(y), W, L - 1) - - -# Extract relevant information from the result -approx_bsplines <- orthogonize_bspline(knots, boundaries, degree) -bsplines <- approx_bsplines$bsplines[, -1] -z <- approx_bsplines$z -L_star <- L - 1 -gamma_hat <- result$gamma[, which.min(result$BIC[, 1])] -g1_BIC <- bsplines \%*\% gamma_hat[1:L_star] -g2_BIC <- bsplines \%*\% gamma_hat[(L_star + 1):(2 * L_star)] - -g10 <- bsplines \%*\% result$gamma[, 1][1:L_star] -g20 <- bsplines \%*\% result$gamma[, 1][(L_star + 1):(2 * L_star)] - -# Plotting -original_par <- par(no.readonly = TRUE) -par(mfrow = c(1, 2)) - -# Plot for g1(z) -plot(z, g1(z), type = 'l', lwd = 4, cex.lab = 2, lty = 2, cex.axis = 1.5, ylim = c(-3, 3)) -lines(z, g10, col = 2, lwd = 2) -lines(z, g1_BIC, col = 3, lwd = 2) -legend("topleft", c("True", expression(lambda == 0), expression(lambda[BIC])), col = c(1, 2, 3), - lty = c(2, 1, 1), lwd = c(3, 3, 3), horiz = TRUE, bty = "n") - -# Plot for g2(z) -plot(z, rep(0, length(z)), type = 'l', lwd = 4, cex.lab = 2, lty = 2, cex.axis = 1.5, - ylab = "g2(z)", ylim = c(-0.1, 0.1)) -lines(z, g20, col = 2, lwd = 2) -lines(z, g2_BIC, col = 3, lwd = 2) -legend("topleft", c("True", expression(lambda == 0), expression(lambda[BIC])), col = c(1, 2, 3, 4), - lty = c(2, 1, 1, 1), lwd = c(3, 3, 3, 3), horiz = TRUE, bty = "n") - -par(original_par) +n_lambda <- 10 +max_lambda <- 10 +lambda <- c(0, exp(seq(log(max_lambda / 1e4), log(max_lambda), length = (n_lambda - 1)))) +result <- qrglasso(as.matrix(y), W, p) +# BIC Results +plot(result) +# Prediction +estimate = predict(result, top_k = 1) +plot(estimate) } \references{ diff --git a/src/awgl.cpp b/src/awgl.cpp index 052d294..f8e2554 100644 --- a/src/awgl.cpp +++ b/src/awgl.cpp @@ -241,127 +241,128 @@ void qrinit(const arma::mat Y, if(iter == maxit) Rcpp::Rcout << "Not converge with error" << max(er) << "\n" << std::endl; } - -//' Internal function: Quantile regression with adaptively group lasso with the input omega +//' @title Internal function: Quantile Regression with Adaptively Group Lasso with `Omega` //' @keywords internal //' -//' @param Y data matrix (n x 1) -//' @param W B-splines with covariates matrix (n x pL) -//' @param omega Weights for group lasso -//' @param lambda A sequence of tuning parameters -//' @param tau A quantile of interest -//' @param qn A bound parameter for HDIC -//' @param zeta A step parameter -//' @param zetaincre An increment of each step -//' @param maxit The maximum number of iterations -//' @param tol A tolerance rate -//' @return A list of selected parameters +//' @description Internal function: Quantile regression with adaptively group Lasso with `Omega`. +//' @param Y Data matrix (\eqn{n \times 1}). +//' @param W B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows. +//' @param omega Weights for group lasso. +//' @param lambda A sequence of tuning parameters. +//' @param tau A quantile of interest. +//' @param qn A bound parameter for HDIC. +//' @param zeta A step parameter. +//' @param zetaincre An increment of each step. +//' @param maxit The maximum number of iterations. +//' @param tol A tolerance rate. +//' @return A list of selected parameters. // [[Rcpp::export]] -Rcpp::List awgl_omega(const arma::mat Y, - const arma::mat W, - const arma::mat omega, - const arma::vec lambda, - const double tau, - const int qn, - double zeta, - double zetaincre, - int maxit, - double tol) { - /* Quantile regression with adaptively group lasso with the input omega - * Returns - * - gamma: target estimate - * - xi, phi: auxiliary estimate in the ADMM algorithm - * - theta1, theta2: Lagrangian multipliers - * - BIC: BIC values of different lambdas - */ - int pL = W.n_cols; - int n_lambda = lambda.n_elem; - int n = Y.n_rows; - int p = omega.n_rows; - int L = (int) pL / p; - - arma::mat gamma; - arma::mat xi; - arma::mat phi; - arma::mat theta1; - arma::mat theta2; - arma::mat Winv, Wt, Winvt, gammaold, xiold, phiold, theta1old, theta2old, IpL, BIC_lambda; - gamma.zeros(pL, n_lambda); - xi.zeros(n, n_lambda); - phi.zeros(pL, n_lambda); - theta1.zeros(n , n_lambda); - theta2.zeros(pL, n_lambda); - IpL.eye(pL, pL); - BIC_lambda.zeros(n_lambda, 2); - - /* compute the gamma, xi, theta1 w.r.t lambda = 0, and compute the correponding BIC*/ - gammaold = gamma.col(0); - xiold = xi.col(0); - phiold = phi.col(0); - theta1old = theta1.col(0); - theta2old = theta2.col(0); - qrinit(Y, W, Wt,gammaold, xiold, theta1old, tau, zeta, zetaincre, maxit, tol); - BIC_lambda.row(0) = BIC(xiold, gammaold, tau, L, qn); - - /*compute the gamma, xi, phi, theta1, theta2 w.r.t lambda, and compute the correponding BIC*/ - gamma.col(0) = gammaold; - xi.col(0) = xiold; - theta1.col(0) = theta1old; - theta2.col(0) = theta2old; - - if(max(lambda) != 0) { - if(pL < n) - Winv = arma::inv_sympd(Wt * W + IpL); - else - Winv = arma::inv_sympd(Wt * W + (1 + (log(pL) / (n + 0.0))) * IpL); - - Winvt = Winv * Wt; - for(int i = 1; i < n_lambda; i++) { - gammaold = gamma.col(i - 1); - xiold = xi.col(i - 1); - phiold = phi.col(i - 1); - theta1old = theta1.col(i - 1); - theta2old = theta2.col(i - 1); - qrcore(Y, W, Wt, Winv, Winvt, omega, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); - BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); - gamma.col(i) = gammaold; - xi.col(i) = xiold; - phi.col(i) = phiold; - theta1.col(i) = theta1old; - theta2.col(i) = theta2old; - - /* If all elements of phi are zeros at some lambda, break out the loop.*/ - if(sum(abs(phi.col(i))) == 0) { - for(int j = i + 1; j < n_lambda; j++) - BIC_lambda.row(j) = BIC_lambda.row(i); - Rcpp::Rcout << "All values of gamma are zeros when lambda >" << lambda[i] << "\n" << std::endl; - break; - } - } - } - - return Rcpp::List::create(Rcpp::Named("gamma") = gamma, - Rcpp::Named("xi") = xi, - Rcpp::Named("phi") = phi, - Rcpp::Named("theta1") = theta1, - Rcpp::Named("theta2") = theta2, - Rcpp::Named("BIC") = BIC_lambda); - -} + Rcpp::List awgl_omega(const arma::mat Y, + const arma::mat W, + const arma::mat omega, + const arma::vec lambda, + const double tau, + const int qn, + double zeta, + double zetaincre, + int maxit, + double tol) { + /* Quantile regression with adaptively group lasso with the input omega + * Returns + * - gamma: target estimate + * - xi, phi: auxiliary estimate in the ADMM algorithm + * - theta1, theta2: Lagrangian multipliers + * - BIC: BIC values of different lambdas + */ + int pL = W.n_cols; + int n_lambda = lambda.n_elem; + int n = Y.n_rows; + int p = omega.n_rows; + int L = static_cast(pL / p); + + arma::mat gamma; + arma::mat xi; + arma::mat phi; + arma::mat theta1; + arma::mat theta2; + arma::mat Winv, Wt, Winvt, gammaold, xiold, phiold, theta1old, theta2old, IpL, BIC_lambda; + gamma.zeros(pL, n_lambda); + xi.zeros(n, n_lambda); + phi.zeros(pL, n_lambda); + theta1.zeros(n , n_lambda); + theta2.zeros(pL, n_lambda); + IpL.eye(pL, pL); + BIC_lambda.zeros(n_lambda, 2); + + /* compute the gamma, xi, theta1 w.r.t lambda = 0, and compute the corresponding BIC*/ + gammaold = gamma.col(0); + xiold = xi.col(0); + phiold = phi.col(0); + theta1old = theta1.col(0); + theta2old = theta2.col(0); + qrinit(Y, W, Wt, gammaold, xiold, theta1old, tau, zeta, zetaincre, maxit, tol); + BIC_lambda.row(0) = BIC(xiold, gammaold, tau, L, qn); + + /* compute the gamma, xi, phi, theta1, theta2 w.r.t lambda, and compute the corresponding BIC*/ + gamma.col(0) = gammaold; + xi.col(0) = xiold; + theta1.col(0) = theta1old; + theta2.col(0) = theta2old; + + if (max(lambda) != 0) { + if (pL < n) + Winv = arma::inv_sympd(Wt * W + IpL); + else + Winv = arma::inv_sympd(Wt * W + (1 + (log(pL) / (n + 0.0))) * IpL); + + Winvt = Winv * Wt; + for (int i = 1; i < n_lambda; i++) { + gammaold = gamma.col(i - 1); + xiold = xi.col(i - 1); + phiold = phi.col(i - 1); + theta1old = theta1.col(i - 1); + theta2old = theta2.col(i - 1); + qrcore(Y, W, Wt, Winv, Winvt, omega, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); + BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); + gamma.col(i) = gammaold; + xi.col(i) = xiold; + phi.col(i) = phiold; + theta1.col(i) = theta1old; + theta2.col(i) = theta2old; + + /* If all elements of phi are zeros at some lambda, break out the loop.*/ + if (arma::sum(arma::abs(phi.col(i))) == 0) { + for (int j = i + 1; j < n_lambda; j++) + BIC_lambda.row(j) = BIC_lambda.row(i); + Rcpp::Rcout << "All values of gamma are zeros when lambda > " << lambda[i] << "\n" << std::endl; + break; + } + } + } + + return Rcpp::List::create(Rcpp::Named("gamma") = gamma, + Rcpp::Named("xi") = xi, + Rcpp::Named("phi") = phi, + Rcpp::Named("theta1") = theta1, + Rcpp::Named("theta2") = theta2, + Rcpp::Named("BIC") = BIC_lambda); + } -//' Internal function: Quantile regression with adaptively group lasso without input Omega +//' @title Internal function: Quantile Regression with Adaptively Group Lasso without `Omega` +//' @keywords internal //' -//' @param Y data matrix (n x 1) -//' @param W B-splines with covariates matrix (n x pL) -//' @param lambda A sequence of tuning parameters -//' @param tau A quantile of interest -//' @param L The number of groups -//' @param qn A bound parameter for HDIC -//' @param zeta A step parameter -//' @param zetaincre An increment of each step -//' @param maxit The maximum number of iterations -//' @param tol A tolerance rate -//' @return A list of selected parameters +//' @description Internal function: Quantile regression with adaptively group Lasso without `Omega`. +//' @param Y Data matrix (\eqn{n \times 1}). +//' @param W B-splines with covariates matrix with \eqn{p \times L} columns and \eqn{n} rows. +//' @param lambda A sequence of tuning parameters. +//' @param tau A quantile of interest. +//' @param L The number of groups. +//' @param qn A bound parameter for HDIC. +//' @param zeta A step parameter. +//' @param zetaincre An increment of each step. +//' @param maxit The maximum number of iterations. +//' @param tol A tolerance rate. +//' @return A list of selected parameters. // [[Rcpp::export]] Rcpp::List awgl(const arma::mat Y, const arma::mat W, @@ -382,106 +383,106 @@ Rcpp::List awgl(const arma::mat Y, * - omega: estimate weights for group lasso */ - int pL = W.n_cols; - int n_lambda = lambda.n_elem; - int n = Y.n_rows; - int p = (int) pL / L; - float scad_weight = 3.7; - - arma::mat gamma, xi, phi, theta1, theta2, gammaold, xiold, phiold, theta1old, theta2old; - arma::mat Winv, Wt, Winvt, omega_fake, IpL, BIC_lambda, omega; - gamma.zeros(pL, n_lambda); - xi.zeros(n, n_lambda); - phi.zeros(pL, n_lambda); - theta1.zeros(n , n_lambda); - theta2.zeros(pL, n_lambda); - IpL.eye(pL, pL); - BIC_lambda.zeros(n_lambda, 2); - omega_fake.ones(pL, 1); - omega.zeros(p, 1); - /* compute the gamma, xi, theta1 w.r.t lambda = 0, and compute the correponding BIC*/ - gammaold = gamma.col(0); - xiold = xi.col(0); - phiold = phi.col(0); - theta1old = theta1.col(0); - theta2old = theta2.col(0); - qrinit(Y, W, Wt, gammaold, xiold, theta1old, tau, zeta, zetaincre, maxit, tol); - BIC_lambda.row(0) = BIC(xiold, gammaold, tau, L, qn); - - /*compute the gamma, xi, phi, theta1, theta2 w.r.t lambda, and compute the correponding BIC*/ - gamma.col(0) = gammaold; - xi.col(0) = xiold; - theta1.col(0) = theta1old; - theta2.col(0) = theta2old; - - if(max(lambda) != 0) { - if(pL < n) - Winv = arma::inv_sympd(Wt * W + IpL); - else - Winv = arma::inv_sympd(Wt * W + (1 + (log(pL) / (n + 0.0))) * IpL); + int pL = W.n_cols; + int n_lambda = lambda.n_elem; + int n = Y.n_rows; + int p = static_cast(pL / L); + float scad_weight = 3.7; + + arma::mat gamma, xi, phi, theta1, theta2, gammaold, xiold, phiold, theta1old, theta2old; + arma::mat Winv, Wt, Winvt, omega_fake, IpL, BIC_lambda, omega; + gamma.zeros(pL, n_lambda); + xi.zeros(n, n_lambda); + phi.zeros(pL, n_lambda); + theta1.zeros(n , n_lambda); + theta2.zeros(pL, n_lambda); + IpL.eye(pL, pL); + BIC_lambda.zeros(n_lambda, 2); + omega_fake.ones(pL, 1); + omega.zeros(p, 1); + + /* compute the gamma, xi, theta1 w.r.t lambda = 0, and compute the correponding BIC*/ + gammaold = gamma.col(0); + xiold = xi.col(0); + phiold = phi.col(0); + theta1old = theta1.col(0); + theta2old = theta2.col(0); + qrinit(Y, W, Wt, gammaold, xiold, theta1old, tau, zeta, zetaincre, maxit, tol); + BIC_lambda.row(0) = BIC(xiold, gammaold, tau, L, qn); - Winvt = Winv * Wt; + /* compute the gamma, xi, phi, theta1, theta2 w.r.t lambda, and compute the correponding BIC*/ + gamma.col(0) = gammaold; + xi.col(0) = xiold; + theta1.col(0) = theta1old; + theta2.col(0) = theta2old; - /* compute omega */ - for(int i = 1; i < n_lambda; i++) { - gammaold = gamma.col(i - 1); - xiold = xi.col(i - 1); - phiold = phi.col(i - 1); - theta1old = theta1.col(i - 1); - theta2old = theta2.col(i - 1); - qrcore(Y, W, Wt, Winv, Winvt, omega_fake, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); - BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); - gamma.col(i) = gammaold; - xi.col(i) = xiold; - phi.col(i) = phiold; - theta1.col(i) = theta1old; - theta2.col(i) = theta2old; + if (arma::max(lambda) != 0) { + if (pL < n) + Winv = arma::inv_sympd(Wt * W + IpL); + else + Winv = arma::inv_sympd(Wt * W + (1 + (std::log(pL) / static_cast(n))) * IpL); + + Winvt = Winv * Wt; - /* If all elements of phi are zeros at some lambda, break out the loop.*/ - if(sum(abs(phi.col(i))) == 0) { - for(int j = i + 1; j < n_lambda; j++) - BIC_lambda.row(j) = BIC_lambda.row(i); - break; + /* compute omega */ + for (int i = 1; i < n_lambda; i++) { + gammaold = gamma.col(i - 1); + xiold = xi.col(i - 1); + phiold = phi.col(i - 1); + theta1old = theta1.col(i - 1); + theta2old = theta2.col(i - 1); + qrcore(Y, W, Wt, Winv, Winvt, omega_fake, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); + BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); + gamma.col(i) = gammaold; + xi.col(i) = xiold; + phi.col(i) = phiold; + theta1.col(i) = theta1old; + theta2.col(i) = theta2old; + + /* If all elements of phi are zeros at some lambda, break out of the loop.*/ + if (arma::sum(arma::abs(phi.col(i))) == 0) { + for (int j = i + 1; j < n_lambda; j++) + BIC_lambda.row(j) = BIC_lambda.row(i); + break; + } } - } - uword index1; - // If .col(1), refer to BIC with log term - (BIC_lambda.col(0)).min(index1); - arma::mat weight_scad_deriv = scad_derivative(abs(gamma.col(index1)), lambda[index1], scad_weight); - omega = omega_weight(weight_scad_deriv, p, L); - - /* main procedure */ - for(int i = 1; i < n_lambda; i++) { - gammaold = gamma.col(i - 1); - xiold = xi.col(i - 1); - phiold = phi.col(i - 1); - theta1old = theta1.col(i - 1); - theta2old = theta2.col(i - 1); - qrcore(Y, W, Wt, Winv, Winvt, omega, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); - BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); - gamma.col(i) = gammaold; - xi.col(i) = xiold; - phi.col(i) = phiold; - theta1.col(i) = theta1old; - theta2.col(i) = theta2old; + uword index1; + // If .col(1), refer to BIC with log term + (BIC_lambda.col(0)).min(index1); + arma::mat weight_scad_deriv = scad_derivative(arma::abs(gamma.col(index1)), lambda[index1], scad_weight); + omega = omega_weight(weight_scad_deriv, p, L); - /* If all elements of phi are zeros at some lambda, break out the loop.*/ - if(sum(abs(phi.col(i))) == 0) { - for(int j = i+1; j < n_lambda; j++) - BIC_lambda.row(j) = BIC_lambda.row(i); + /* main procedure */ + for (int i = 1; i < n_lambda; i++) { + gammaold = gamma.col(i - 1); + xiold = xi.col(i - 1); + phiold = phi.col(i - 1); + theta1old = theta1.col(i - 1); + theta2old = theta2.col(i - 1); + qrcore(Y, W, Wt, Winv, Winvt, omega, gammaold, xiold, phiold, theta1old, theta2old, lambda[i], tau, zeta, zetaincre, maxit, tol); + BIC_lambda.row(i) = BIC(xiold, phiold, tau, L, qn); + gamma.col(i) = gammaold; + xi.col(i) = xiold; + phi.col(i) = phiold; + theta1.col(i) = theta1old; + theta2.col(i) = theta2old; - Rcpp::Rcout << "All values of gamma are zeros when lambda >" << lambda[i] << "\n" << std::endl; - break; - } + /* If all elements of phi are zeros at some lambda, break out of the loop.*/ + if (arma::sum(arma::abs(phi.col(i))) == 0) { + for (int j = i + 1; j < n_lambda; j++) + BIC_lambda.row(j) = BIC_lambda.row(i); + + Rcpp::Rcout << "All values of gamma are zeros when lambda > " << lambda[i] << "\n" << std::endl; + break; + } + } } - } - - return Rcpp::List::create(Rcpp::Named("gamma") = gamma, - Rcpp::Named("xi") = xi, - Rcpp::Named("phi") = phi, - Rcpp::Named("theta1") = theta1, - Rcpp::Named("theta2") = theta2, - Rcpp::Named("BIC") = BIC_lambda, - Rcpp::Named("omega") = omega); - -} \ No newline at end of file + + return Rcpp::List::create(Rcpp::Named("gamma") = gamma, + Rcpp::Named("xi") = xi, + Rcpp::Named("phi") = phi, + Rcpp::Named("theta1") = theta1, + Rcpp::Named("theta2") = theta2, + Rcpp::Named("BIC") = BIC_lambda, + Rcpp::Named("omega") = omega); +} diff --git a/tests/testthat/test_qrglasso.R b/tests/testthat/test_qrglasso.R index 8ed5a96..a2d0c6f 100644 --- a/tests/testthat/test_qrglasso.R +++ b/tests/testthat/test_qrglasso.R @@ -7,12 +7,14 @@ test_that("qrglasso returns expected results", { # Create sample data for testing set.seed(123) n <- 100 - pL <- 10 + p <- 2 + L <- 5 + pL <- 2 * 5 Y <- matrix(rnorm(n), n, 1) W <- matrix(rnorm(n * pL), n, pL) # Call the qrglasso function - result <- qrglasso(Y = Y, W = W, L = 2) + result <- qrglasso(Y = Y, W = W, p) # Perform assertions expect_s3_class(result, "qrglasso") @@ -33,7 +35,7 @@ test_that("qrglasso with omega", { result <- qrglasso( Y = Y, W = W, - L = L, + p = p, omega = omega, tau = 0.7, qn = 1.5, @@ -52,8 +54,8 @@ test_that("qrglasso with omega", { # Mock qrglasso class object for testing mock_qrglasso <- structure(list( - L = 5, - gamma = matrix(rnorm(400), nrow = 4), + L = 6, + gamma = matrix(rnorm(400), nrow = 5), BIC = matrix(runif(10), nrow = 5), omega = matrix(runif(120), nrow = 6) ), class = "qrglasso")