diff --git a/.Rbuildignore b/.Rbuildignore new file mode 100644 index 0000000..04912b7 --- /dev/null +++ b/.Rbuildignore @@ -0,0 +1,13 @@ +^\.github$ +^\.git$ +^.*\.Rproj$ +^\.Rproj\.user$ +^LICENSE\.md$ +^README\.md$ +^CONTRIBUTING\.md$ +^CODE_OF_CONDUCT\.md$ +^cran-comments\.md$ +^CRAN-SUBMISSION$ +^.*\.Rhistory$ +^Dockerfile$ +^paper$ \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..ec0a5be --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,23 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**To Reproduce** +Please provide the minimum example to reproduce the error. + +**Session Information** +Please paste the result of `sessionInfo()`. + +**Screenshots** +If applicable, add screenshots or terminal output to help explain your problem. + +**Additional context** +Add any other context about the problem here. \ No newline at end of file diff --git a/.github/workflows/build_test_push.yml b/.github/workflows/build_test_push.yml new file mode 100644 index 0000000..adaf8c0 --- /dev/null +++ b/.github/workflows/build_test_push.yml @@ -0,0 +1,70 @@ +name: DockerHub/GHCR + +env: + IMAGE_NAME: vicus + repo-name: koki/vicus + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + workflow_dispatch: + +jobs: + build_push_test: + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Declare some variables + id: vars + shell: bash + run: | + echo "::set-output name=sha_short::$(git rev-parse --short HEAD)" + + - name: Build + run: docker build -t ${{ github.repository_owner }}/${{ env.IMAGE_NAME }} . + + - name: Tag (Latest) + run: docker tag ${{ github.repository_owner }}/${{ env.IMAGE_NAME }} ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }} + + - name: Tag (SHA) + run: docker tag ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:latest ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.sha_short }} + + - name: Push (Latest) + run: docker push ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:latest + + - name: Push (SHA) + run: docker push ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.sha_short }} + + - uses: docker/build-push-action@v1 + with: + # The two entries below need to be entered as + # github secrets. The "secret" names are "DOCKER_USERNAME" + # and "DOCKER_PASSWORD". See https://docs.github.com/en/actions/reference/encrypted-secrets#creating-encrypted-secrets-for-a-repository + # for detailed instructions. + # + # DO NOT EDIT THESE ENTRIES HERE. Doing so will + # expose your docker username and password on github. + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + # Use the environment variable on first few lines to set repo name--just centralizes changes + repository: ${{ env.repo-name }} + tag_with_ref: true + tag_with_sha: true + tags: latest + +# Ref +# https://github.com/marketplace/actions/docker-login +# https://github.com/inutano/cwl-log-generator/blob/main/.github/workflows/main.yml +# https://www.docker.com/blog/first-docker-github-action-is-here/ +# https://github.com/docker/login-action \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e9bc988 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.fuse* +*/.fuse* +*/*/.fuse* +.Rapp.history +*/.Rapp.history +*/*/.Rapp.history +.DS_Store +*/.DS_Store +*/*/.DS_Store diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2cbb4e1 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at k.t.the-answer@hotmail.co.jp. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +or answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..9b5e663 --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,23 @@ +Package: Vicus +Type: Package +Title: Exploiting Local Structures to Improve Network-Based Analysis of Biological Data +Version: 0.99.0 +Authors@R: c(person("Koki", "Tsuyuzaki", role = c("aut", "cre"), + email = "k.t.the-answer@hotmail.co.jp")) +Depends: + R (>= 3.4.0) +Imports: + methods, + utils, + RANN, + Matrix, + RSpectra +Suggests: + scatterplot3d, + knitr, + rmarkdown, + testthat +Description: Compared with the similar graph embedding method such as Laplacian Eigenmaps, Vicus can exploit more local structures of graph data. For the details of the methods, see the reference section of GitHub README.md . +License: MIT + file LICENSE +URL: https://github.com/rikenbit/Vicus +VignetteBuilder: knitr \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..26b8d06 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,7 @@ +# Base Image +FROM bioconductor/bioconductor_docker:devel + +# Install R Packages +RUN R -e "devtools::install_github('rikenbit/Vicus', \ + upgrade='always', force=TRUE, INSTALL_opts = '--install-tests');\ + tools::testInstalledPackage('Vicus')" \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ae9ba38 --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +YEAR: 2023 +COPYRIGHT HOLDER: Koki Tsuyuzaki \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..a371434 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 kokitsuyuzaki + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..e8c5cf0 --- /dev/null +++ b/NAMESPACE @@ -0,0 +1,11 @@ +importFrom(methods, as) +importFrom(utils, combn) +importFrom(RANN, nn2) +importFrom(Matrix, crossprod, tcrossprod, spMatrix) +importClassesFrom(Matrix, dgCMatrix) +importFrom(RSpectra, eigs_sym) + +export( + graphMatrix, + embedding +) \ No newline at end of file diff --git a/R/HLLE.R b/R/HLLE.R new file mode 100644 index 0000000..9192d21 --- /dev/null +++ b/R/HLLE.R @@ -0,0 +1,31 @@ +# Hessian Locally Linear Embedding +.HLLE <- function(X, K, alpha, ndim){ + # Setting + n <- nrow(X) + hs <- ndim * (ndim + 1)/2 + ii <- jj <- xx <- list() + # kNN + nnidx <- nn2(data = X, query = X, k = K+1, + treetype = "kd", "standard", eps = 0)$nn.idx + # Hessian + for(i in seq_len(n)){ + Nui <- X[nnidx[i, ], , drop = FALSE] + Nui <- sweep(Nui, 2, colMeans(Nui), "-") + tc <- svd(Nui, nu = ndim, nv = 0)$u + Xi <- cbind(1, tc, tc^2, apply(combn(seq_len(ndim), + 2), 2, function(x) tc[, x[1]] * tc[, x[2]])) + tHi <- qr.Q(qr(Xi))[, -(1:(ndim + 1)), drop = FALSE] + ii[[i]] <- rep(nnidx[i, ], hs) + jj[[i]] <- rep((i-1)*hs + (1:hs), each = ncol(nnidx)) + xx[[i]] <- as.vector(tHi) + } + if(length(ii[[1]]) != length(xx[[1]])){ + stop("K is too small. Please specify the larger value.") + } + H <- spMatrix( + i = unlist(ii, FALSE, FALSE), + j = unlist(jj, FALSE, FALSE), + x = unlist(xx, FALSE, FALSE), + nrow = n, ncol = n * hs) + as(tcrossprod(H), "generalMatrix") +} diff --git a/R/LEM.R b/R/LEM.R new file mode 100644 index 0000000..c544411 --- /dev/null +++ b/R/LEM.R @@ -0,0 +1,8 @@ +# Laplacian Eigenmaps +.LEM <- function(X, K, alpha, ndim){ + # kNN-adjacency matrix + A <- .knn_adjacency(X, K) + # Graph Laplacian matrix + D <- .spDiagMatrix(K, nrow(X)) + D - A +} diff --git a/R/Vicus-internal.R b/R/Vicus-internal.R new file mode 100644 index 0000000..f9f3e11 --- /dev/null +++ b/R/Vicus-internal.R @@ -0,0 +1,21 @@ +.inverse_rank <- function(x){ + rank(- x, ties.method = "first") +} + +.knn_adjacency <- function(X, K){ + n <- nrow(X) + nnidx <- nn2(X, k=K+1)$nn.idx + ii <- unlist(lapply(seq_len(n), function(x){ + rep(x, length=K) + })) + jj <- as.vector(t(nnidx[, -1])) + xx <- rep(1, length=n*K) + spMatrix(i=ii, j=jj, x=xx, nrow=n, ncol=n) +} + +.spDiagMatrix <- function(x, n){ + ii <- seq_len(n) + jj <- ii + xx <- rep(x, length=n) + spMatrix(i=ii, j=jj, x=xx, nrow=n, ncol=n) +} diff --git a/R/Vicus.R b/R/Vicus.R new file mode 100644 index 0000000..f1fd7dd --- /dev/null +++ b/R/Vicus.R @@ -0,0 +1,35 @@ +# Vicus +.Vicus <- function(X, K, alpha, ndim){ + # kNN-adjacency matrix + A <- .knn_adjacency(X, K) + n <- nrow(A) + ii <- rep(0, length=n*K) + jj <- ii + xx <- ii + count <- 1 + for(i in seq_len(n)){ + V_i <- c(which(A[i, ] != 0), i) + W_i <- as.matrix(A[V_i, V_i]) + colnames(W_i) <- V_i + rownames(W_i) <- V_i + # Normalized Transition Matrix + W_i <- W_i + 1e-20 + normTransMat <- W_i / rowSums(W_i) + temp <- (1 - alpha) * solve(diag(nrow(normTransMat)) - alpha * normTransMat) + beta_i <- temp[K+1, ] + for(j in seq_len(n)){ + if(j %in% V_i && i != j){ + ii[count] <- i + jj[count] <- j + index_of_j <- which(colnames(W_i) == j) + xx[count] <- as.numeric(beta_i[index_of_j] / (1 - beta_i[K + 1])) + count <- count + 1 + } + } + } + # Sparse Matrix + B <- spMatrix(i=ii, j=jj, x=xx, nrow=n, ncol=n) + # Vicus Matrix + D <- .spDiagMatrix(1, nrow(X)) + as(crossprod(D - B), "generalMatrix") +} diff --git a/R/embedding.R b/R/embedding.R new file mode 100644 index 0000000..8506b9c --- /dev/null +++ b/R/embedding.R @@ -0,0 +1,12 @@ +embedding <- function(obj){ + # Eigen Decomposition + if(obj$algorithm == "HLLE"){ + out <- eigs_sym(obj$M, k=obj$ndim+1, sigma=-1e-5) + out <- out$vectors[, order(out$values)[-1]] + }else{ + out <- eigen(obj$M) + n <- nrow(obj$M) + out <- Re(out$vectors[, seq(n-1, n-obj$ndim, by=-1)]) + } + out +} diff --git a/R/graphMatrix.R b/R/graphMatrix.R new file mode 100644 index 0000000..5358c7d --- /dev/null +++ b/R/graphMatrix.R @@ -0,0 +1,26 @@ +graphMatrix <- function(X, algorithm=c("Vicus", "LEM", "HLLE"), + K=10, alpha=0.9, ndim=2){ + # Argument Check + algorithm <- match.arg(algorithm) + .checkgraphMatrix(X, K, alpha, ndim) + M <- .flist[[algorithm]](X, K, alpha, ndim) + list(M=M, algorithm=algorithm, ndim=ndim) +} + +.checkgraphMatrix <- function(X, K, alpha, ndim){ + stopifnot(is.matrix(X)) + stopifnot(is.numeric(K)) + stopifnot(is.numeric(alpha)) + stopifnot(is.numeric(ndim)) + stopifnot(alpha > 0) + stopifnot(alpha < 1) + stopifnot(K >= 1) + stopifnot(K <= nrow(X) - 1) + stopifnot(ndim >= 1) +} + +.flist <- list( + "Vicus" = .Vicus, + "LEM" = .LEM, + "HLLE" = .HLLE +) diff --git a/README.md b/README.md index f0ec739..c4522b0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,39 @@ +[![DOI](https://zenodo.org/badge/614626969.svg)](https://zenodo.org/badge/latestdoi/614626969) +[![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/Vicus)]( +https://cran.r-project.org/package=Vicus) +[![Downloads](https://cranlogs.r-pkg.org/badges/Vicus)](https://CRAN.R-project.org/package=Vicus) +[![Total Downloads](https://cranlogs.r-pkg.org/badges/grand-total/Vicus?color=orange)](https://CRAN.R-project.org/package=Vicus) +[![:name status badge](https://rikenbit.r-universe.dev/badges/:name)](https://rikenbit.r-universe.dev) +[![:registry status badge](https://rikenbit.r-universe.dev/badges/:registry)](https://rikenbit.r-universe.dev) +[![:total status badge](https://rikenbit.r-universe.dev/badges/:total)](https://rikenbit.r-universe.dev) +[![Vicus status badge](https://rikenbit.r-universe.dev/badges/Vicus)](https://rikenbit.r-universe.dev) +![GitHub Actions](https://github.com/rikenbit/Vicus/actions/workflows/build_test_push.yml/badge.svg) + # Vicus -Vicus: Exploiting local structures to improve network-based analysis of biological data +R package for graph embedding by Vicus method + +## Installation + +====== +~~~~ +git clone https://github.com/rikenbit/Vicus/ +R CMD INSTALL Vicus +~~~~ +or type the code below in the R console window +~~~~ +library(devtools) +devtools::install_github("rikenbit/Vicus") +~~~~ + +## References +====== +- Wang B, et al., Vicus: Exploiting local structures to improve network-based analysis of biological data. PLOS Computational Biology. 13(10), e1005621, 2017 + +## Contributing + +If you have suggestions for how `Vicus` could be improved, or want to report a bug, open an issue! We'd love all and any contributions. + +For more, check out the [Contributing Guide](CONTRIBUTING.md). + +## Authors +- Koki Tsuyuzaki diff --git a/inst/NEWS b/inst/NEWS new file mode 100644 index 0000000..287a58c --- /dev/null +++ b/inst/NEWS @@ -0,0 +1,3 @@ + VERSION 0.99.0 +------------------------ + o Package released diff --git a/man/Vicus-package.Rd b/man/Vicus-package.Rd new file mode 100644 index 0000000..bac1a22 --- /dev/null +++ b/man/Vicus-package.Rd @@ -0,0 +1,30 @@ +\name{Vicus-package} +\alias{Vicus-package} +\docType{package} +\title{ +\packageTitle{Vicus} +} +\description{ +\packageDescription{Vicus} +} +\details{ + +The DESCRIPTION file: +\packageDESCRIPTION{Vicus} +\packageIndices{Vicus} +} +\author{ +\packageAuthor{Vicus} + +Maintainer: \packageMaintainer{Vicus} +} +\references{ +Wang B, et al., (2017). Vicus: Exploiting local structures to improve network-based analysis of biological data. \emph{PLOS Computational Biology}. 13(10), e1005621 + +} + +\keyword{ package } +\seealso{\code{\link{graphMatrix}},\code{\link{embedding}}} +\examples{ +ls("package:Vicus") +} \ No newline at end of file diff --git a/man/embedding.Rd b/man/embedding.Rd new file mode 100644 index 0000000..4aa7397 --- /dev/null +++ b/man/embedding.Rd @@ -0,0 +1,32 @@ +\name{embedding} +\docType{methods} +\alias{embedding} + +\title{ +Graph Embedding +} +\description{ +Lower dimensions are estimated from the object returned from graphMatrix function. +} +\usage{ +embedding(obj) +} + +\arguments{ + \item{obj}{ +Object returned from graphMatrix function. +} +} + +\value{ +A matrix (n times k) +} +\author{Koki Tsuyuzaki} + +\examples{ +X <- matrix(runif(10*20), nrow=10, ncol=20) +head(embedding(graphMatrix(X, K=2))) +} + +\keyword{methods} +\seealso{\code{\link{graphMatrix}}} \ No newline at end of file diff --git a/man/graphMatrix.Rd b/man/graphMatrix.Rd new file mode 100644 index 0000000..3faaf80 --- /dev/null +++ b/man/graphMatrix.Rd @@ -0,0 +1,47 @@ +\name{graphMatrix} +\docType{methods} +\alias{graphMatrix} + +\title{ +Graph Laplacian type matrix +} +\description{ +A symmetric matrix is returned. +} +\usage{ +graphMatrix(X, algorithm=c("Vicus", "LEM", "HLLE"), + K=10, alpha=0.9, ndim=2) +} + +\arguments{ + \item{X}{ +A numeric matrix (n times p). +} + \item{algorithm}{ +Algorithm to construct a graph matrix. Vicus matrix (Vicus), Graph Laplacian matrix (LEM), and Hessian Locally Linear Embedding matrix (HLLE) are available (Default: "Vicus"). +} + \item{K}{ +The number of neighborhoods to construct a graph matrix (Default: 10). +} + \item{alpha}{ +An optional parameter for Vicus (Default: 0.9). +} + \item{ndim}{ +The number of lower dimension to embed the graph (Default: 2). +} +} + +\value{ +M: A symmetric matrix (n times n). This matrix can be applied to embedding function. +algorithm: algorithm parameter specified by argument +ndim: ndim parameter specified by argument +} +\author{Koki Tsuyuzaki} + +\examples{ +X <- matrix(runif(10*20), nrow=10, ncol=20) +str(graphMatrix(X, K=2), 2) +} + +\keyword{methods} +\seealso{\code{\link{embedding}}} \ No newline at end of file diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..9121b73 --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,9 @@ +library("testthat") +library("Vicus") + +options(testthat.use_colours = FALSE) + +# Basic usage +test_file("testthat/test_LEM.R") +test_file("testthat/test_HLLE.R") +test_file("testthat/test_Vicus.R") diff --git a/tests/testthat/test_HLLE.R b/tests/testthat/test_HLLE.R new file mode 100644 index 0000000..befba37 --- /dev/null +++ b/tests/testthat/test_HLLE.R @@ -0,0 +1,29 @@ +X <- matrix(runif(30*20), nrow=30, ncol=20) + +# 2D +objHLLE_2D <- graphMatrix(X, algorithm="HLLE", ndim=2) + +expect_equal(length(objHLLE_2D), 3) +expect_true("dgCMatrix" %in% is(objHLLE_2D$M)) +expect_true(is.character(objHLLE_2D$algorithm)) +expect_true(is.numeric(objHLLE_2D$ndim)) + +outHLLE_2D <- embedding(objHLLE_2D) + +expect_true(is.matrix(outHLLE_2D)) +expect_equal(nrow(outHLLE_2D), nrow(X)) +expect_equal(ncol(outHLLE_2D), 2) + +# 3D +objHLLE_3D <- graphMatrix(X, algorithm="HLLE", ndim=3) + +expect_equal(length(objHLLE_3D), 3) +expect_true("dgCMatrix" %in% is(objHLLE_3D$M)) +expect_true(is.character(objHLLE_3D$algorithm)) +expect_true(is.numeric(objHLLE_3D$ndim)) + +outHLLE_3D <- embedding(objHLLE_3D) + +expect_true(is.matrix(outHLLE_3D)) +expect_equal(nrow(outHLLE_3D), nrow(X)) +expect_equal(ncol(outHLLE_3D), 3) diff --git a/tests/testthat/test_LEM.R b/tests/testthat/test_LEM.R new file mode 100644 index 0000000..7a65a92 --- /dev/null +++ b/tests/testthat/test_LEM.R @@ -0,0 +1,29 @@ +X <- matrix(runif(30*20), nrow=30, ncol=20) + +# 2D +objLEM_2D <- graphMatrix(X, algorithm="LEM", ndim=2) + +expect_equal(length(objLEM_2D), 3) +expect_true("dgCMatrix" %in% is(objLEM_2D$M)) +expect_true(is.character(objLEM_2D$algorithm)) +expect_true(is.numeric(objLEM_2D$ndim)) + +outLEM_2D <- embedding(objLEM_2D) + +expect_true(is.matrix(outLEM_2D)) +expect_equal(nrow(outLEM_2D), nrow(X)) +expect_equal(ncol(outLEM_2D), 2) + +# 3D +objLEM_3D <- graphMatrix(X, algorithm="LEM", ndim=3) + +expect_equal(length(objLEM_3D), 3) +expect_true("dgCMatrix" %in% is(objLEM_3D$M)) +expect_true(is.character(objLEM_3D$algorithm)) +expect_true(is.numeric(objLEM_3D$ndim)) + +outLEM_3D <- embedding(objLEM_3D) + +expect_true(is.matrix(outLEM_3D)) +expect_equal(nrow(outLEM_3D), nrow(X)) +expect_equal(ncol(outLEM_3D), 3) diff --git a/tests/testthat/test_Vicus.R b/tests/testthat/test_Vicus.R new file mode 100644 index 0000000..63e1dd2 --- /dev/null +++ b/tests/testthat/test_Vicus.R @@ -0,0 +1,29 @@ +X <- matrix(runif(30*20), nrow=30, ncol=20) + +# 2D +objVicus_2D <- graphMatrix(X, algorithm="Vicus", ndim=2) + +expect_equal(length(objVicus_2D), 3) +expect_true("dgCMatrix" %in% is(objVicus_2D$M)) +expect_true(is.character(objVicus_2D$algorithm)) +expect_true(is.numeric(objVicus_2D$ndim)) + +outVicus_2D <- embedding(objVicus_2D) + +expect_true(is.matrix(outVicus_2D)) +expect_equal(nrow(outVicus_2D), nrow(X)) +expect_equal(ncol(outVicus_2D), 2) + +# 3D +objVicus_3D <- graphMatrix(X, algorithm="Vicus", ndim=3) + +expect_equal(length(objVicus_3D), 3) +expect_true("dgCMatrix" %in% is(objVicus_3D$M)) +expect_true(is.character(objVicus_3D$algorithm)) +expect_true(is.numeric(objVicus_3D$ndim)) + +outVicus_3D <- embedding(objVicus_3D) + +expect_true(is.matrix(outVicus_3D)) +expect_equal(nrow(outVicus_3D), nrow(X)) +expect_equal(ncol(outVicus_3D), 3) diff --git a/vignettes/._Vicus.html b/vignettes/._Vicus.html new file mode 100644 index 0000000..9e0b9f0 Binary files /dev/null and b/vignettes/._Vicus.html differ diff --git a/vignettes/Vicus.Rmd b/vignettes/Vicus.Rmd new file mode 100644 index 0000000..f137e4e --- /dev/null +++ b/vignettes/Vicus.Rmd @@ -0,0 +1,116 @@ +--- +title: "Vicus: Exploiting local structures to improve network-based analysis of biological data" +author: +- name: Koki Tsuyuzaki + affiliation: Laboratory for Bioinformatics Research, + RIKEN Center for Biosystems Dynamics Research + email: k.t.the-answer@hotmail.co.jp +date: "`r Sys.Date()`" +bibliography: bibliography.bib +package: guidedPLS +output: rmarkdown::html_vignette +vignette: | + %\VignetteIndexEntry{Vicus: Exploiting local structures to improve network-based analysis of biological data} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +# Introduction + +In this vignette, we consider a novel graph embedding method, Vicus [@vicus]. + +Here, we use the Swiss roll data, which is a well known toy model. + +```{r data, echo=TRUE} +set.seed(1) +N <- 300 +p <- sqrt(2 + 2 * seq(-1, 1 - 2 / N, 2 / N)) +y <- 2 * runif(N, -1, 1) +X <- cbind(p * cos(2 * pi * p), y, p * sin(2 * pi * p)) +X <- scale(X, center=TRUE, scale=TRUE) * 3 +labelX <- c(rep(1:11, each = floor(N / 11)), rep(11, length=3)) +``` + +```{r data2, echo=TRUE, fig.height=4, fig.width=4} +library("scatterplot3d") + +# Color Setting +colors <- labelX +cols <- c("#9E0142", "#D53E4F", "#F46D43", "#FDAE61", + "#FEE08B", "#FFFFBF", "#E6F598", "#ABDDA4", + "#66C2A5", "#3288BD", "#5E4FA2") +for(i in seq_along(cols)){ + colors[which(colors == i)] <- cols[i] +} + +par(cex = 1.2) +scatterplot3d(X, color=colors, pch=16, main="Original Data", angle=40) +``` + +# 2D Embedding + +The `Vicus` package provides three types of graph embedding algorithms: `Vicus`, Laplacian Eigenmaps (`LEM`), and Hessian Locally Linear Embedding (`HLLE`). + +First, the `graphMatrix` function computes a matrix containing graph information for each algorithm: + +```{r graph_matrix_2d, echo=TRUE} +library("Vicus") + +objVicus <- graphMatrix(X, algorithm="Vicus", ndim=2, K=10) +objLEM <- graphMatrix(X, algorithm="LEM", ndim=2, K=10) +objHLLE <- graphMatrix(X, algorithm="HLLE", ndim=2, K=5) +str(objVicus, 2) +str(objLEM, 2) +str(objHLLE, 2) +``` + +Next, the `embedding` function performs eigenvalue decomposition and estimates the low-dimensional coordinates. + +```{r embed_2d, echo=TRUE} +outVicus <- embedding(objVicus) +outLEM <- embedding(objLEM) +outHLLE <- embedding(objHLLE) +``` + +The low dimensional coordinates show that Vicus is better able to capture the local structure of the Swiss roll data. + +```{r plot_2d, echo=TRUE, fig.height=3, fig.width=8} +layout(t(1:3)) +plot(outVicus, col=colors, pch=16, main="Vicus", cex=2) +plot(outLEM, col=colors, pch=16, main="LEM", cex=2) +plot(outHLLE, col=colors, pch=16, main="HLLE", cex=2) +``` + +# 3D Embedding + +It can also be embedded to any dimension by simply changing the value of `ndim` as follows: + +```{r graph_matrix_3d, echo=TRUE} +objVicus_3D <- graphMatrix(X, algorithm="Vicus", ndim=3) +objLEM_3D <- graphMatrix(X, algorithm="LEM", ndim=3) +objHLLE_3D <- graphMatrix(X, algorithm="HLLE", ndim=3) +``` + +The following step is the same as in 2D Embedding case above. + +```{r embed_3d, echo=TRUE} +outVicus_3D <- embedding(objVicus_3D) +outLEM_3D <- embedding(objLEM_3D) +outHLLE_3D <- embedding(objHLLE_3D) +``` + +```{r plot_3d, echo=TRUE, fig.height=7, fig.width=7} +layout(cbind(1:2, 3:4)) +scatterplot3d(X, color=colors, pch=16, main="Original Data", angle=40) +scatterplot3d(outVicus_3D, color=colors, pch=16, main="Vicus", angle=40) +scatterplot3d(outLEM_3D, color=colors, pch=16, main="LEM", angle=70) +scatterplot3d(outHLLE_3D, color=colors, pch=16, main="HLLE", angle=70) +``` + +# Session Information {.unnumbered} + +```{r sessionInfo, echo=FALSE} +sessionInfo() +``` + +# References \ No newline at end of file diff --git a/vignettes/Vicus.html b/vignettes/Vicus.html new file mode 100644 index 0000000..8b86227 --- /dev/null +++ b/vignettes/Vicus.html @@ -0,0 +1,516 @@ + + + + + + + + + + + + + + + +Vicus: Exploiting local structures to improve network-based analysis of biological data + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Vicus: Exploiting local structures to +improve network-based analysis of biological data

+

Koki Tsuyuzaki

+
+Laboratory for Bioinformatics Research, RIKEN Center for Biosystems +Dynamics Research
+
+

2023-03-23

+ + + +
+

Introduction

+

In this vignette, we consider a novel graph embedding method, Vicus +(Wang B 2017).

+

Here, we use the Swiss roll data, which is a well known toy +model.

+
set.seed(1)
+N <- 300
+p <- sqrt(2 + 2 * seq(-1, 1 - 2 / N, 2 / N))
+y <- 2 * runif(N, -1, 1)
+X <- cbind(p * cos(2 * pi * p), y, p * sin(2 * pi * p))
+X <- scale(X, center=TRUE, scale=TRUE) * 3
+labelX <- c(rep(1:11, each = floor(N / 11)), rep(11, length=3))
+
library("scatterplot3d")
+
+# Color Setting
+colors <- labelX
+cols <- c("#9E0142", "#D53E4F", "#F46D43", "#FDAE61",
+    "#FEE08B", "#FFFFBF", "#E6F598", "#ABDDA4",
+    "#66C2A5", "#3288BD", "#5E4FA2")
+for(i in seq_along(cols)){
+    colors[which(colors == i)] <- cols[i]
+}
+
+par(cex = 1.2)
+scatterplot3d(X, color=colors, pch=16, main="Original Data", angle=40)
+

+
+
+

2D Embedding

+

The Vicus package provides three types of graph +embedding algorithms: Vicus, Laplacian Eigenmaps +(LEM), and Hessian Locally Linear Embedding +(HLLE).

+

First, the graphMatrix function computes a matrix +containing graph information for each algorithm:

+
library("Vicus")
+
+objVicus <- graphMatrix(X, algorithm="Vicus", ndim=2, K=10)
+objLEM <- graphMatrix(X, algorithm="LEM", ndim=2, K=10)
+objHLLE <- graphMatrix(X, algorithm="HLLE", ndim=2, K=5)
+str(objVicus, 2)
+
## List of 3
+##  $ M        :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
+##  $ algorithm: chr "Vicus"
+##  $ ndim     : num 2
+
str(objLEM, 2)
+
## List of 3
+##  $ M        :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
+##  $ algorithm: chr "LEM"
+##  $ ndim     : num 2
+
str(objHLLE, 2)
+
## List of 3
+##  $ M        :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
+##  $ algorithm: chr "HLLE"
+##  $ ndim     : num 2
+

Next, the embedding function performs eigenvalue +decomposition and estimates the low-dimensional coordinates.

+
outVicus <- embedding(objVicus)
+outLEM <- embedding(objLEM)
+outHLLE <- embedding(objHLLE)
+

The low dimensional coordinates show that Vicus is better able to +capture the local structure of the Swiss roll data.

+
layout(t(1:3))
+plot(outVicus, col=colors, pch=16, main="Vicus", cex=2)
+plot(outLEM, col=colors, pch=16, main="LEM", cex=2)
+plot(outHLLE, col=colors, pch=16, main="HLLE", cex=2)
+

+
+
+

3D Embedding

+

It can also be embedded to any dimension by simply changing the value +of ndim as follows:

+
objVicus_3D <- graphMatrix(X, algorithm="Vicus", ndim=3)
+objLEM_3D <- graphMatrix(X, algorithm="LEM", ndim=3)
+objHLLE_3D <- graphMatrix(X, algorithm="HLLE", ndim=3)
+

The following step is the same as in 2D Embedding case above.

+
outVicus_3D <- embedding(objVicus_3D)
+outLEM_3D <- embedding(objLEM_3D)
+outHLLE_3D <- embedding(objHLLE_3D)
+
layout(cbind(1:2, 3:4))
+scatterplot3d(X, color=colors, pch=16, main="Original Data", angle=40)
+scatterplot3d(outVicus_3D, color=colors, pch=16, main="Vicus", angle=40)
+scatterplot3d(outLEM_3D, color=colors, pch=16, main="LEM", angle=70)
+scatterplot3d(outHLLE_3D, color=colors, pch=16, main="HLLE", angle=70)
+

+
+
+

Session Information

+
## R version 4.2.2 (2022-10-31)
+## Platform: x86_64-apple-darwin17.0 (64-bit)
+## Running under: macOS Catalina 10.15.7
+## 
+## Matrix products: default
+## BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
+## LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
+## 
+## locale:
+## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
+## 
+## attached base packages:
+## [1] stats     graphics  grDevices utils     datasets  methods   base     
+## 
+## other attached packages:
+## [1] Vicus_0.99.0         scatterplot3d_0.3-42
+## 
+## loaded via a namespace (and not attached):
+##  [1] Rcpp_1.0.9      rstudioapi_0.14 knitr_1.41      magrittr_2.0.3 
+##  [5] lattice_0.20-45 R6_2.5.1        rlang_1.0.6     fastmap_1.1.0  
+##  [9] stringr_1.5.0   highr_0.9       tools_4.2.2     grid_4.2.2     
+## [13] xfun_0.35       RSpectra_0.16-1 cli_3.4.1       jquerylib_0.1.4
+## [17] htmltools_0.5.4 yaml_2.3.6      digest_0.6.31   lifecycle_1.0.3
+## [21] Matrix_1.5-1    sass_0.4.4      vctrs_0.5.1     glue_1.6.2     
+## [25] cachem_1.0.6    evaluate_0.19   rmarkdown_2.19  stringi_1.7.8  
+## [29] compiler_4.2.2  bslib_0.4.2     jsonlite_1.8.4  RANN_2.6.1
+
+
+

References

+
+
+Wang B, et al. 2017. “Vicus: Exploiting Local Structures to +Improve Network-Based Analysis of Biological Data.” PLOS +Computational Biolog 13(10): e1005621. +
+
+
+ + + + + + + + + + + diff --git a/vignettes/bibliography.bib b/vignettes/bibliography.bib new file mode 100644 index 0000000..145f9df --- /dev/null +++ b/vignettes/bibliography.bib @@ -0,0 +1,7 @@ +@article{vicus, + author = {Wang B, et al.}, + journal = {PLOS Computational Biolog}, + title = {Vicus: Exploiting local structures to improve network-based analysis of biological data}, + volume = {13(10)}, + pages = {e1005621}, + year = {2017}}