From 1da6fc204f21fcf2623dad9575b2266c368d7df1 Mon Sep 17 00:00:00 2001 From: Nuoya Wang Date: Mon, 2 Nov 2026 16:36:04 -0500 Subject: [PATCH] Add website publishing workflow and links Add website publishing workflow and links --- .Rbuildignore | 1 + .claude/settings.local.json | 26 +- .github/workflows/pkgdown.yaml | 69 +++++ CLAUDE.md | 3 +- DESCRIPTION | 3 +- NAMESPACE | 2 - NEWS.md | 4 +- R/compute_CellToCell.R | 25 +- R/compute_PseudoBulk_Connectivity.R | 205 --------------- R/create_Edgelist_PseudoBulk.R | 122 --------- R/create_Edgelist_SamplingByType.R | 1 - R/create_NICHESObject.R | 6 - R/create_NICHESObject_single.R | 4 - R/export_to_TissuePlex.R | 3 + R/extract_NICHESInputs_Seurat.R | 16 +- R/utils.R | 1 - README.md | 9 +- _pkgdown.yml | 92 ++++++- man/compute_CellToCell.Rd | 21 +- man/compute_PseudoBulk_Connectivity.Rd | 109 -------- man/create_Edgelist_PseudoBulk.Rd | 69 ----- man/create_Edgelist_SamplingByType.Rd | 1 - man/create_NICHESObject.Rd | 6 - man/export_to_TissuePlex.Rd | 4 + package management/NICHESv2_package_design.md | 15 +- .../test-compute_PseudoBulk_Connectivity.R | 191 -------------- .../test-create_Edgelist_PseudoBulk.R | 132 ---------- .../test-extract_NICHESInputs_Seurat.R | 27 +- vignettes/NICHESv2.Rmd | 41 ++- vignettes/articles/aggregation.Rmd | 161 ++++++++++++ vignettes/articles/for-reviewers.Rmd | 93 +++++++ vignettes/articles/input-formats.Rmd | 158 ++++++++++++ vignettes/articles/niches-object.Rmd | 168 +++++++++++++ vignettes/articles/nonspatial-tutorial.Rmd | 179 +++++++++++++ vignettes/articles/spatial-tutorial.Rmd | 238 ++++++++++++++++++ vignettes/articles/tissueplex-export.Rmd | 59 +++++ working-scripts-NW/score_fingerprints.R | 9 +- ..._fingerprints_after_pseudobulk_removal.txt | 17 ++ .../score_fingerprints_after_tutorials.txt | 18 ++ .../score_fingerprints_baseline.txt | 1 - ..._fingerprints_baseline_with_pseudobulk.txt | 18 ++ .../score_fingerprints_before_push.txt | 17 ++ working-scripts-NW/v1_facts_sheet.md | 39 ++- 43 files changed, 1440 insertions(+), 943 deletions(-) create mode 100644 .github/workflows/pkgdown.yaml delete mode 100644 R/compute_PseudoBulk_Connectivity.R delete mode 100644 R/create_Edgelist_PseudoBulk.R delete mode 100644 man/compute_PseudoBulk_Connectivity.Rd delete mode 100644 man/create_Edgelist_PseudoBulk.Rd delete mode 100644 tests/testthat/test-compute_PseudoBulk_Connectivity.R delete mode 100644 tests/testthat/test-create_Edgelist_PseudoBulk.R create mode 100644 vignettes/articles/aggregation.Rmd create mode 100644 vignettes/articles/for-reviewers.Rmd create mode 100644 vignettes/articles/input-formats.Rmd create mode 100644 vignettes/articles/niches-object.Rmd create mode 100644 vignettes/articles/nonspatial-tutorial.Rmd create mode 100644 vignettes/articles/spatial-tutorial.Rmd create mode 100644 vignettes/articles/tissueplex-export.Rmd create mode 100644 working-scripts-NW/score_fingerprints_after_pseudobulk_removal.txt create mode 100644 working-scripts-NW/score_fingerprints_after_tutorials.txt create mode 100644 working-scripts-NW/score_fingerprints_baseline_with_pseudobulk.txt create mode 100644 working-scripts-NW/score_fingerprints_before_push.txt diff --git a/.Rbuildignore b/.Rbuildignore index c455069..124fb4b 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -16,4 +16,5 @@ ^demo-scripts$ ^package management$ ^LICENSE\.md$ +^vignettes/articles$ diff --git a/.claude/settings.local.json b/.claude/settings.local.json index ea3216f..418d699 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -102,7 +102,31 @@ "Bash(Rscript --vanilla -e 'load\\(\"/Users/nw426/Documents/GitHub/NICHESv2-NW/data/NICHESv2_inputs.rda\"\\); print\\(NICHESv2_inputs$LRM.db[1:5,]\\); print\\(colnames\\(NICHESv2_inputs$LRM.db\\)\\); print\\(rownames\\(NICHESv2_inputs$count.mtx\\)[1:6]\\)')", "Bash(rsync -a --delete --exclude .git --exclude demo-scripts --exclude working-scripts-* --exclude omnipathr-log --exclude .claude /Users/nw426/Documents/GitHub/NICHESv2-NW/ /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/copy/NICHESv2/)", "Bash(Rscript --vanilla -e 'devtools::document\\(\"/private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/copy/NICHESv2\", quiet=TRUE\\)')", - "Bash(bash /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/verify.sh)" + "Bash(bash /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/verify.sh)", + "Bash(Rscript --vanilla -e 'for \\(p in c\\(\"stxBrain.SeuratData\",\"ifnb.SeuratData\",\"SeuratData\"\\)\\) { d <- packageDescription\\(p\\); cat\\(\"=====\",p,\"\\\\n\"\\); for \\(f in c\\(\"Version\",\"License\",\"Title\",\"Description\",\"Author\",\"Maintainer\",\"URL\",\"Repository\",\"RemoteUrl\"\\)\\) if \\(!is.null\\(d[[f]]\\)\\) cat\\(f,\":\",d[[f]],\"\\\\n\"\\); pth <- system.file\\(package=p\\); print\\(list.files\\(pth\\)\\); lic <- list.files\\(pth, pattern=\"LICEN|COPY\", ignore.case=TRUE, full.names=TRUE\\); for \\(l in lic\\) { cat\\(\"--\",basename\\(l\\),\"\\\\n\"\\); cat\\(head\\(readLines\\(l,warn=FALSE\\),6\\),sep=\"\\\\n\"\\) } }; help_txt <- function\\(p, topic\\) { db <- tools::Rd_db\\(p\\); nm <- grep\\(topic, names\\(db\\), value=TRUE\\)[1]; if \\(is.na\\(nm\\)\\) { cat\\(\"no Rd for\",topic,\"\\\\n\"\\); return\\(invisible\\(\\)\\) }; out <- capture.output\\(tools::Rd2txt\\(db[[nm]], options=list\\(underline_titles=FALSE\\)\\)\\); cat\\(out, sep=\"\\\\n\"\\) }; help_txt\\(\"stxBrain.SeuratData\",\"stxBrain\"\\); help_txt\\(\"ifnb.SeuratData\",\"ifnb\"\\)')", + "Bash(Rscript --vanilla -e 'p <- \"ifnb.SeuratData\"; db <- tools::Rd_db\\(p\\); for \\(n in names\\(db\\)\\) { o <- capture.output\\(tools::Rd2txt\\(db[[n]], options=list\\(underline_titles=FALSE\\)\\)\\); cat\\(o, sep=\"\\\\n\"\\) }; cit <- system.file\\(\"CITATION\", package=p\\); cat\\(\"--- CITATION\\\\n\"\\); cat\\(readLines\\(cit, warn=FALSE\\), sep=\"\\\\n\"\\); print\\(list.files\\(system.file\\(\"extdata\", package=p\\)\\)\\)')", + "WebFetch(domain:www.10xgenomics.com)", + "WebFetch(domain:www.ncbi.nlm.nih.gov)", + "WebFetch(domain:www.nature.com)", + "WebFetch(domain:bioconductor.org)", + "WebFetch(domain:creativecommons.org)", + "Bash(curl -s -m 25 \"https://www.10xgenomics.com/support/software/space-ranger/latest/resources/citation-guidelines\" -o /dev/null -w \"%{http_code}\\\\n\")", + "Bash(curl -s -m 25 -L \"https://raw.githubusercontent.com/satijalab/seurat-data/master/README.md\")", + "Bash(curl -s -m 25 -I \"https://seurat.nygenome.org/src/contrib/PACKAGES\")", + "WebFetch(domain:www.ebi.ac.uk)", + "Bash(git -C /Users/nw426/Documents/GitHub/NICHESv2-NW show HEAD:vignettes/spatial.Rmd)", + "Bash(grep -v \"^$\")", + "Bash(git -C /Users/nw426/Documents/GitHub/NICHESv2-NW log --oneline -n 3)", + "Bash(git -C /Users/nw426/Documents/GitHub/NICHESv2-NW show 4bf87c9:vignettes/spatial.Rmd)", + "Bash(Rscript --vanilla /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/cols.R)", + "Bash(xargs -n1 basename)", + "Bash(python3 -I - /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/site/articles)", + "Bash(D=/Users/nw426/Desktop/NICHESv2; ls -la \"$D\" | cut -c30- | head -n 40; echo ---; du -sh \"$D\" 2>/dev/null | cut -f1; find \"$D\" -type f 2>/dev/null | wc -l; find \"$D\" -type f 2>/dev/null | sed -E 's/.*\\\\.\\([A-Za-z0-9]+\\)$/\\\\1/' | tr 'A-Z' 'a-z' | sort | uniq -c | sort -rn | head -n 20; echo ---dirs; find \"$D\" -maxdepth 2 -type d 2>/dev/null | sed \"s#$D#.#\" | head -n 40)", + "Bash(Rscript --vanilla -e 'cat\\(\"R\", as.character\\(getRversion\\(\\)\\), \"\\\\nknitr\", as.character\\(packageVersion\\(\"knitr\"\\)\\), \"\\\\nxfun\", as.character\\(packageVersion\\(\"xfun\"\\)\\), \"\\\\nrmarkdown\", as.character\\(packageVersion\\(\"rmarkdown\"\\)\\), \"\\\\n\"\\); ap <- available.packages\\(repos=\"https://cloud.r-project.org\"\\); print\\(ap[c\\(\"knitr\",\"xfun\",\"rmarkdown\"\\),c\\(\"Version\",\"Depends\"\\)]\\); b <- tryCatch\\(available.packages\\(type=\"binary\", repos=\"https://cloud.r-project.org\"\\), error=function\\(e\\) NULL\\); if\\(!is.null\\(b\\)\\) print\\(b[intersect\\(c\\(\"knitr\",\"xfun\"\\),rownames\\(b\\)\\),\"Version\"]\\); x <- body\\(knitr::kable\\); f <- ls\\(asNamespace\\(\"knitr\"\\)\\); hit <- f[sapply\\(f, function\\(n\\) {g <- get\\(n, asNamespace\\(\"knitr\"\\)\\); is.function\\(g\\) && any\\(grepl\\(\"xfun::attr\\\\\\\\\\(|attr\\\\\\\\s*=\\\\\\\\s*xfun\", deparse\\(g\\)\\)\\)}\\)]; print\\(hit\\)')", + "Bash(Rscript -e 'print\\(utils::packageVersion\\(\"pkgdown\"\\)\\); print\\(pkgdown:::package_mds\\); print\\(pkgdown:::build_home_md\\)')", + "Bash(Rscript -e 'a <- available.packages\\(repos=\"https://cloud.r-project.org\"\\); print\\(a[c\\(\"pkgdown\",\"knitr\",\"Seurat\",\"SeuratObject\"\\),\"Version\"]\\); for \\(p in c\\(\"Seurat\",\"SeuratObject\",\"SeuratData\",\"rmarkdown\",\"knitr\"\\)\\) cat\\(p, as.character\\(utils::packageVersion\\(p\\)\\), \"\\\\n\"\\); print\\(unname\\(sapply\\(\"repo\", function\\(x\\) getOption\\(\"SeuratData.repo.use\"\\)\\)\\)\\)')", + "Bash(Rscript -e 'library\\(SeuratData\\); print\\(getOption\\(\"SeuratData.repo.use\"\\)\\); print\\(utils::packageDescription\\(\"SeuratData\"\\)[c\\(\"Version\",\"RemoteType\",\"RemoteRepo\",\"RemoteUsername\",\"Repository\"\\)]\\)')", + "Bash(rsync -a --delete /private/tmp/claude-234134544/-Users-nw426-Documents-GitHub-NICHESv2-NW/8e8dd3a1-059b-4622-99f2-f5ba283c1906/scratchpad/siteci/ docs/)" ] } } diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml new file mode 100644 index 0000000..9881cde --- /dev/null +++ b/.github/workflows/pkgdown.yaml @@ -0,0 +1,69 @@ +# .github/workflows/pkgdown.yaml +# +# Builds the website and publishes it to the gh-pages branch on every push to +# main. The tutorials really run here, so each build installs SeuratData and +# downloads both public test datasets. A failed build publishes nothing, and the +# live site stays as it was. +# +# To test a build without publishing it, start this workflow by hand from the +# Actions tab on any other branch. + +on: + push: + branches: [main] + workflow_dispatch: + +name: pkgdown + +jobs: + pkgdown: + runs-on: ubuntu-latest + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} # auto-generated per run + + permissions: + contents: write # lets the last step publish + + steps: + # Step 1: clone the repository onto the runner machine + - uses: actions/checkout@v4 + + # Step 2: install Pandoc (builds the pages) and R + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + + # Step 3: install this package, everything in DESCRIPTION, and the tools + # the website needs. SeuratData isn't on CRAN, so it comes from GitHub. + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: | + any::pkgdown + local::. + github::satijalab/seurat-data + + # Step 4: download the test datasets the tutorials use + - name: Install test datasets + run: SeuratData::InstallData(c("stxBrain", "ifnb")) + shell: Rscript {0} + + # Step 5: build the site + # pkgdown turns every Markdown file in the top folder into a page, so + # the project notes in CLAUDE.md are removed from this checkout first. + - name: Build site + run: | + file.remove("CLAUDE.md") + pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) + shell: Rscript {0} + + # Step 6: publish, from main only + - name: Publish to gh-pages + if: github.ref == 'refs/heads/main' + uses: JamesIves/github-pages-deploy-action@v4 + with: + clean: false + branch: gh-pages + folder: docs diff --git a/CLAUDE.md b/CLAUDE.md index 32f8a08..67190b1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,8 @@ Custom data frames are also accepted; must have `ligand` and `receptor` columns - `inst/extdata/` — `NICHESv2_example.h5ad`, a small synthetic file used by the AnnData example - `data-raw/` — scripts that build the bundled data files; excluded from package build - `tests/testthat/` — one test file per source file; `helper-testutils.R` provides shared fixtures -- `vignettes/` — one vignette, `NICHESv2.Rmd`, which runs on bundled data +- `vignettes/` — one vignette, `NICHESv2.Rmd`, which runs on bundled data; `vignettes/articles/` holds the website pages and is excluded from the package build +- `.github/workflows/` — `R-CMD-check.yaml` runs the checks; `pkgdown.yaml` builds the website and publishes it from `main`, removing this file first because pkgdown turns top-level Markdown files into pages - `demo-scripts/` — standalone R scripts demonstrating real-dataset usage (not part of the package build) - `working-scripts-MSBR/` and `working-scripts-NW/` — exploratory and prototyping scripts; not part of the package - `package management/` — design documents diff --git a/DESCRIPTION b/DESCRIPTION index 8e1e04e..7062c3e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -15,7 +15,8 @@ Description: Computes ligand-receptor (LR) signaling scores between pairs of multi-gene complex ligands and receptors. Built-in loaders are provided for the ConnectomeDB2025 (default), FANTOM5, and OmniPath LR databases. License: MIT + file LICENSE -URL: https://github.com/RaredonLab/NICHESv2 +URL: https://raredonlab.github.io/NICHESv2/, + https://github.com/RaredonLab/NICHESv2 BugReports: https://github.com/RaredonLab/NICHESv2/issues Encoding: UTF-8 Language: en-US diff --git a/NAMESPACE b/NAMESPACE index 4a2344b..3d49af0 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -15,8 +15,6 @@ export(add_neighborhoods) export(add_segmentation) export(aggregate_NICHESObject) export(compute_CellToCell) -export(compute_PseudoBulk_Connectivity) -export(create_Edgelist_PseudoBulk) export(create_Edgelist_SamplingByType) export(create_Edgelist_Spatial) export(create_NICHESObject) diff --git a/NEWS.md b/NEWS.md index 0c2c6de..79d023f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,7 +12,6 @@ First public release. methods. - `aggregate_NICHESObject()` summarizes each cell's neighborhood by LR pair and, in spatial mode, by neighboring cell type. -- `compute_PseudoBulk_Connectivity()` scores each pair of cell types. - `load_LRM_database()` provides ConnectomeDB2025 (default) and FANTOM5, both bundled for human, mouse, rat and pig, and OmniPath for human, mouse and rat. - `extract_NICHESInputs_Seurat()` and `extract_NICHESInputs_AnnData()` read @@ -39,6 +38,9 @@ First public release. - Mode `"sampled"` is now `"nonspatial"`. - `Aggregate_CellToCell_Edges()` has been removed. Use `aggregate_NICHESObject()`. +- `compute_PseudoBulk_Connectivity()` and `create_Edgelist_PseudoBulk()` have been + removed. To summarize by cell type, sum `$edge.data` using the cell types in + `$edge.meta`. - `add_cell_meta()` now replaces `$cell.meta` in full. Use `add_meta_column()` to change one column. - The default database in `load_LRM_database()` is now ConnectomeDB2025. diff --git a/R/compute_CellToCell.R b/R/compute_CellToCell.R index 44ecd3e..f02f8c8 100644 --- a/R/compute_CellToCell.R +++ b/R/compute_CellToCell.R @@ -1,7 +1,7 @@ # compute_CellToCell.R ---------------------------------------------------- # Universal cell-to-cell ligand-receptor signal scoring engine. -# Accepts any edge list produced by create_Edgelist_Spatial(), -# create_Edgelist_PseudoBulk(), or create_Edgelist_SamplingByType(). +# Accepts any edge list produced by create_Edgelist_Spatial() or +# create_Edgelist_SamplingByType(). # Supports single-gene and multi-gene complex ligands / receptors # (underscore-delimited, e.g. "COL1A1_COL1A2"). Returns a plain # 2-element list suitable for assembly into a NICHESObject via @@ -54,11 +54,9 @@ #' #' @description #' Universal scoring engine for all NICHESv2 edge modes. For each edge and each -#' valid LR pair, computes a signal score. The edge list may come from any of -#' the three edgelist constructors -- spatial, pseudobulk, or type-sampled -- -#' and the count matrix is expected to match accordingly (cell barcodes as -#' column names for spatial and nonspatial modes; cell type names for pseudobulk -#' mode). +#' valid LR pair, computes a signal score. The edge list may come from either +#' edgelist constructor -- spatial or type-sampled -- and the count matrix +#' column names must be the cell barcodes it uses. #' #' Supports \strong{multi-gene complexes}: a ligand or receptor represented as #' \code{"gene1_gene2"} is split on \code{"_"} and all component expressions @@ -99,13 +97,11 @@ #' \code{on.exit(stopCluster(cl))} so it is released even if scoring #' errors midway. #' -#' @param count.mtx Gene x cell (or gene x type for pseudobulk) -#' expression matrix (sparse \code{dgCMatrix} or dense). Row names = gene -#' symbols; column names = cell barcodes or cell type labels matching +#' @param count.mtx Gene x cell expression matrix (sparse \code{dgCMatrix} +#' or dense). Row names = gene symbols; column names = cell barcodes matching #' \code{edge.list$from} / \code{$to}. #' @param edge.list \code{data.table} from -#' \code{\link{create_Edgelist_Spatial}}, -#' \code{\link{create_Edgelist_PseudoBulk}}, or +#' \code{\link{create_Edgelist_Spatial}} or #' \code{\link{create_Edgelist_SamplingByType}}; or any \code{data.frame} #' with \code{from} and \code{to} columns whose values match #' \code{colnames(count.mtx)}. Coordinate columns @@ -152,12 +148,9 @@ #' \code{\link{create_NICHESObject}} for the wrapped pipeline that #' assembles a full \code{NICHESObject}; #' \code{\link{create_Edgelist_Spatial}}, -#' \code{\link{create_Edgelist_PseudoBulk}}, #' \code{\link{create_Edgelist_SamplingByType}} for the edge-list #' constructors; -#' \code{\link{load_LRM_database}} for the LR-database loader; -#' \code{\link{compute_PseudoBulk_Connectivity}} for type-averaged -#' connectivity in one call. +#' \code{\link{load_LRM_database}} for the LR-database loader. #' #' @examples #' \donttest{ diff --git a/R/compute_PseudoBulk_Connectivity.R b/R/compute_PseudoBulk_Connectivity.R deleted file mode 100644 index 8cd4635..0000000 --- a/R/compute_PseudoBulk_Connectivity.R +++ /dev/null @@ -1,205 +0,0 @@ -# compute_PseudoBulk_Connectivity.R --------------------------------------- -# Compute pseudobulk cell-type-to-cell-type ligand-receptor -# connectivity. Returns a lightweight data.table (not a NICHESObject) -# summarising average signal from each cell type to each other type. -# -# FUNCTIONS: -# compute_PseudoBulk_Connectivity() -- main function -# -# DEPS: data.table (>= 1.14), Matrix (>= 1.5), parallel - - -# ============================================================================== -#' Compute Pseudobulk Cell-Type Connectivity -#' -#' @description -#' Computes ligand-receptor signal scores between all ordered cell type pairs -#' using per-type mean expression profiles (pseudobulk). Covers all T^2 directed -#' type-to-type crossings including autocrine (A -> A). -#' -#' Unlike \code{create_NICHESObject()}, this function does \strong{not} build -#' a \code{NICHESObject}. It returns a compact \code{data.table} directly -#' suitable for heatmap or network visualization of type-level communication. -#' This is intentional -- the pseudobulk output is type-level rather than -#' cell-level and does not benefit from the full NICHESObject slot structure. -#' -#' @section Output schema: -#' One row per (type-pair x non-zero LRM): -#' \describe{ -#' \item{\code{SendingType}}{Sending cell type label.} -#' \item{\code{ReceivingType}}{Receiving cell type label.} -#' \item{\code{LRM}}{\code{"ligand|receptor"} string.} -#' \item{\code{ligand}}{Ligand gene or complex.} -#' \item{\code{receptor}}{Receptor gene or complex.} -#' \item{\code{score}}{Raw LR signal (product or minimum of mean expressions).} -#' \item{\code{score.norm}}{Score normalized proportionally per type-pair edge -#' (sums to 1.0 across all LRMs for a given sending-receiving pair), or equal -#' to \code{score} when \code{normalize.method = "none"}.} -#' } -#' -#' @param count.mtx Gene x cell expression matrix (sparse or dense). -#' Row names = gene symbols; column names = cell barcodes. -#' @param meta.data \code{data.frame} with row names = cell barcodes. -#' Must contain the column named by \code{cell.type.col}. -#' @param LRM.db LR database: \code{"fantom5"}, \code{"omnipath"}, or -#' a \code{data.frame} with at least \code{ligand.col} and -#' \code{receptor.col}. -#' @param cell.type.col \code{character(1)}. Column in \code{meta.data} -#' holding cell type labels. -#' @param ligand.col Column name for ligands in \code{LRM.db}. -#' Default \code{"ligand"}. -#' @param receptor.col Column name for receptors in \code{LRM.db}. -#' Default \code{"receptor"}. -#' @param method Scoring method: \code{"product"} (default) or -#' \code{"minimum"}. -#' @param normalize.method Normalization for \code{score.norm}: -#' \code{"prop"} (default, proportional per type-pair) or \code{"none"}. -#' @param n.cores CPU cores. Default 1. Socket cluster -- works on all -#' platforms. -#' @param verbose Print progress messages. Default \code{TRUE}. -#' -#' @return A \code{data.table} keyed on \code{(SendingType, ReceivingType, LRM)} -#' with columns as described above. Only non-zero score rows are included -#' (implicit sparsity). -#' -#' @seealso \code{\link{create_NICHESObject}}, -#' \code{\link{create_Edgelist_PseudoBulk}}, -#' \code{\link{compute_CellToCell}} -#' -#' @examples -#' \donttest{ -#' data(NICHESv2_inputs) -#' -#' # Type-level connectivity using the bundled inputs (3 cell types: A/B/C) -#' pb <- compute_PseudoBulk_Connectivity( -#' count.mtx = NICHESv2_inputs$count.mtx, -#' meta.data = NICHESv2_inputs$meta.data, -#' LRM.db = NICHESv2_inputs$LRM.db, -#' cell.type.col = "celltype", -#' n.cores = 1L, -#' verbose = FALSE -#' ) -#' head(pb) -#' -#' # Total signal per directed type pair -- the input to a heatmap or chord plot -#' agg <- pb[, list(total.score = sum(score)), -#' by = list(SendingType, ReceivingType)] -#' agg -#' } -#' -#' @export -compute_PseudoBulk_Connectivity <- function(count.mtx, - meta.data, - LRM.db, - cell.type.col, - ligand.col = "ligand", - receptor.col = "receptor", - method = c("product", "minimum"), - normalize.method = c("prop", "none"), - n.cores = 1L, - verbose = TRUE) { - - method <- match.arg(method) - normalize.method <- match.arg(normalize.method) - n.cores <- as.integer(n.cores) - - ## SECTION 1: Input validation ---- - - if (!is.matrix(count.mtx) && !inherits(count.mtx, "sparseMatrix")) - stop("[compute_PseudoBulk_Connectivity] 'count.mtx' must be a matrix or sparseMatrix.") - if (is.null(rownames(count.mtx)) || is.null(colnames(count.mtx))) - stop("[compute_PseudoBulk_Connectivity] 'count.mtx' must have row names (genes) and column names (cells).") - if (!is.data.frame(meta.data)) - stop("[compute_PseudoBulk_Connectivity] 'meta.data' must be a data.frame.") - if (is.null(rownames(meta.data))) - stop("[compute_PseudoBulk_Connectivity] 'meta.data' must have row names (cell barcodes).") - if (!is.character(cell.type.col) || length(cell.type.col) != 1L) - stop("[compute_PseudoBulk_Connectivity] 'cell.type.col' must be a single character string.") - if (!cell.type.col %in% colnames(meta.data)) - stop(sprintf( - "[compute_PseudoBulk_Connectivity] 'cell.type.col' ('%s') not found in 'meta.data'.", - cell.type.col - )) - - ## SECTION 2: Cell alignment ---- - - shared.cells <- intersect(rownames(meta.data), colnames(count.mtx)) - if (length(shared.cells) == 0L) - stop("[compute_PseudoBulk_Connectivity] No shared cells between 'meta.data' and 'count.mtx'.") - - if (length(shared.cells) < ncol(count.mtx) && verbose) - message(sprintf( - "[compute_PseudoBulk_Connectivity] %d cell(s) in count.mtx not in meta.data -- excluded.", - ncol(count.mtx) - length(shared.cells) - )) - if (length(shared.cells) < nrow(meta.data) && verbose) - message(sprintf( - "[compute_PseudoBulk_Connectivity] %d cell(s) in meta.data not in count.mtx -- excluded.", - nrow(meta.data) - length(shared.cells) - )) - - count.mtx <- count.mtx[, shared.cells, drop = FALSE] - meta.data <- meta.data[shared.cells, , drop = FALSE] - - ## SECTION 3: Build pseudobulk edge list and mean-expression matrix ---- - - if (verbose) message("[compute_PseudoBulk_Connectivity] Building type-pair edge list ...") - - el.raw <- create_Edgelist_PseudoBulk(meta.data = meta.data, - cell.type.col = cell.type.col) - - # Per-type mean expression: genes x cell_types dense matrix. - # Column order follows the sorted type labels in attr(el.raw, "cell.names") - # so colnames() matches the from/to values in el.raw exactly. - cell.types.ordered <- attr(el.raw, "cell.names") - - if (verbose) message("[compute_PseudoBulk_Connectivity] Computing per-type mean expression ...") - - pb.mtx <- do.call(cbind, lapply(cell.types.ordered, function(ct) { - ct.barcodes <- rownames(meta.data)[meta.data[[cell.type.col]] == ct] - Matrix::rowMeans(count.mtx[, ct.barcodes, drop = FALSE]) - })) - colnames(pb.mtx) <- cell.types.ordered - - ## SECTION 4: Score LRM pairs across all type-pair edges ---- - - if (verbose) message("[compute_PseudoBulk_Connectivity] Scoring LRM pairs ...") - - elr <- compute_CellToCell( - count.mtx = pb.mtx, - edge.list = el.raw, - LRM.db = LRM.db, - ligand.col = ligand.col, - receptor.col = receptor.col, - method = method, - n.cores = n.cores - ) - - ## SECTION 5: Assemble and normalise output data.table ---- - - result <- elr$edges[, .( - SendingType = from, - ReceivingType = to, - LRM, ligand, receptor, score - )] - - if (normalize.method == "prop") { - result[, score.norm := .prop_norm(score), by = .(SendingType, ReceivingType)] - } else { - result[, score.norm := score] - } - - setcolorder(result, c("SendingType", "ReceivingType", "LRM", - "ligand", "receptor", "score", "score.norm")) - setkeyv(result, c("SendingType", "ReceivingType", "LRM")) - - if (verbose) { - n.types <- length(cell.types.ordered) - message(sprintf( - "[compute_PseudoBulk_Connectivity] Done. %d type pairs | %d valid LRMs | %d non-zero signals.", - n.types^2, length(elr$lr.meta$LRM), nrow(result) - )) - } - - result -} diff --git a/R/create_Edgelist_PseudoBulk.R b/R/create_Edgelist_PseudoBulk.R deleted file mode 100644 index 975ee1e..0000000 --- a/R/create_Edgelist_PseudoBulk.R +++ /dev/null @@ -1,122 +0,0 @@ -# create_Edgelist_PseudoBulk.R -------------------------------------------- -# Build a type-to-type directed edge list for pseudobulk non-spatial -# cell-to-cell communication analysis. Enumerates all T^2 directed -# ordered pairs of cell types (including autocrine type -> same type). -# No sampling or randomness -- the output is fully deterministic. -# -# FUNCTIONS: -# create_Edgelist_PseudoBulk() -- main function -# -# DEPS: data.table (>= 1.14) - - -# ============================================================================== -#' Build a Pseudobulk Type-to-Type Edge List -#' -#' @description -#' Constructs a directed edge list covering all ordered cell type pairs for -#' pseudobulk non-spatial analysis. Each edge represents a directed -#' type-to-type communication channel (e.g., \code{"ATI"} -> \code{"gCap"}). -#' All T^2 directed pairs are included, encompassing both cross-type and -#' autocrine (same-type) edges. -#' -#' The output edge list is intended to be passed to \code{create_NICHESObject()} -#' with \code{mode = "pseudobulk"}, where the per-type mean expression matrix is -#' computed and paired with this edge list for scoring. Do not pass individual -#' cell barcodes as \code{count.mtx} column names when using this edge list -- -#' the column names must be cell type labels. -#' -#' @param meta.data \code{data.frame} with one row per cell. Row names must -#' be unique cell barcodes. Must contain the column specified by -#' \code{cell.type.col}. -#' @param cell.type.col \code{character(1)}. Name of the column in -#' \code{meta.data} that holds cell type labels. -#' -#' @return A \code{data.table} keyed on \code{(from, to)} with columns: -#' \describe{ -#' \item{\code{from}}{Sending cell type label (character).} -#' \item{\code{to}}{Receiving cell type label (character).} -#' } -#' Carries metadata attributes: \code{mode} (\code{"pseudobulk"}), -#' \code{param} (the \code{cell.type.col} value), \code{n.cells} (total -#' number of cells in \code{meta.data}), \code{cell.names} (sorted unique -#' cell type labels). -#' -#' @details -#' This function is a low-level primitive: it builds the pseudobulk -#' type-to-type edge list that \code{\link{compute_PseudoBulk_Connectivity}} -#' consumes internally. Most users should call -#' \code{compute_PseudoBulk_Connectivity()}, which invokes this function, -#' computes per-type mean expression, scores every type pair, and returns -#' a single \code{data.table} in one step. -#' \code{create_Edgelist_PseudoBulk()} is exposed for power users who -#' want to inspect the type-pair enumeration directly or feed the edges -#' into a custom scoring pipeline. -#' -#' Cell types are sorted alphabetically before enumeration so the output -#' order is deterministic regardless of the order they appear in -#' \code{meta.data}. -#' -#' @examples -#' meta <- data.frame( -#' cell.type = c("ATI", "ATI", "gCap", "gCap", "Macro"), -#' row.names = paste0("cell_", 1:5) -#' ) -#' el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "cell.type") -#' -#' @seealso \code{\link{create_NICHESObject}}, -#' \code{\link{create_Edgelist_SamplingByType}}, -#' \code{\link{create_Edgelist_Spatial}} -#' -#' @keywords internal -#' @export -create_Edgelist_PseudoBulk <- function(meta.data, cell.type.col) { - - ## SECTION 1: Input validation ---- - - if (!is.data.frame(meta.data)) - stop("[create_Edgelist_PseudoBulk] 'meta.data' must be a data.frame.") - if (is.null(rownames(meta.data)) || any(rownames(meta.data) == "")) - stop("[create_Edgelist_PseudoBulk] 'meta.data' must have unique, non-empty row names (cell barcodes).") - if (!is.character(cell.type.col) || length(cell.type.col) != 1L) - stop("[create_Edgelist_PseudoBulk] 'cell.type.col' must be a single character string.") - if (!cell.type.col %in% colnames(meta.data)) - stop(sprintf( - "[create_Edgelist_PseudoBulk] Column '%s' not found in 'meta.data'.", - cell.type.col - )) - - cell.types <- sort(unique(as.character(meta.data[[cell.type.col]]))) - n.types <- length(cell.types) - n.cells <- nrow(meta.data) - - if (n.types < 2L) - stop("[create_Edgelist_PseudoBulk] At least 2 distinct cell types are required.") - - ## SECTION 2: Build T^2 directed type-pair edge list ---- - # - # All ordered pairs (i, j) for i in cell.types, j in cell.types -- including - # i == j (autocrine: type communicates with itself). This covers all possible - # type-to-type signalling channels without any sampling or randomness. - - edge.dt <- data.table( - from = rep(cell.types, each = n.types), - to = rep(cell.types, times = n.types) - ) - - setkeyv(edge.dt, c("from", "to")) - - ## SECTION 3: Attach metadata attributes and report ---- - - attr(edge.dt, "mode") <- "pseudobulk" - attr(edge.dt, "param") <- cell.type.col - attr(edge.dt, "n.cells") <- n.cells - attr(edge.dt, "cell.names") <- cell.types # sorted unique type labels - - message(sprintf( - "[create_Edgelist_PseudoBulk] %d cell types | %d directed type-pair edges (including autocrine).", - n.types, nrow(edge.dt) - )) - - invisible(edge.dt) -} diff --git a/R/create_Edgelist_SamplingByType.R b/R/create_Edgelist_SamplingByType.R index c9bf70e..ef62368 100644 --- a/R/create_Edgelist_SamplingByType.R +++ b/R/create_Edgelist_SamplingByType.R @@ -86,7 +86,6 @@ #' seed = 42L, max.cells = 50L) #' #' @seealso \code{\link{create_NICHESObject}}, -#' \code{\link{create_Edgelist_PseudoBulk}}, #' \code{\link{create_Edgelist_Spatial}} #' #' @keywords internal diff --git a/R/create_NICHESObject.R b/R/create_NICHESObject.R index f255746..728753d 100644 --- a/R/create_NICHESObject.R +++ b/R/create_NICHESObject.R @@ -25,10 +25,6 @@ #' \code{cell.type.col}.} #' } #' -#' For pseudobulk (type-averaged) connectivity use -#' \code{\link{compute_PseudoBulk_Connectivity}} -- it returns a plain -#' \code{data.table}, not a \code{NICHESObject}. -#' #' @section Pipeline overview: #' Internally, \code{create_NICHESObject()} chains the following steps: #' \enumerate{ @@ -139,8 +135,6 @@ #' function; #' \code{\link{merge_NICHESObjects}} for combining objects produced #' independently; -#' \code{\link{compute_PseudoBulk_Connectivity}} for type-averaged -#' connectivity (returns a \code{data.table}, not a \code{NICHESObject}); #' \code{\link{compute_CellToCell}} for the underlying scoring engine; #' \code{\link{create_Edgelist_Spatial}}, #' \code{\link{create_Edgelist_SamplingByType}} for the edge-list diff --git a/R/create_NICHESObject_single.R b/R/create_NICHESObject_single.R index 1902514..2f7b649 100644 --- a/R/create_NICHESObject_single.R +++ b/R/create_NICHESObject_single.R @@ -11,10 +11,6 @@ # "nonspatial" - NICHES v1-style stratified random sampling of cell barcodes # within each directed type pair crossing # -# Pseudobulk analysis is handled by the separate lightweight function -# compute_PseudoBulk_Connectivity(), which returns a plain data.table -# rather than a full NICHESObject. -# # FUNCTIONS: # .create_NICHESObject_single() - internal single-partition implementation # diff --git a/R/export_to_TissuePlex.R b/R/export_to_TissuePlex.R index 0f09e0c..0388139 100644 --- a/R/export_to_TissuePlex.R +++ b/R/export_to_TissuePlex.R @@ -7,6 +7,9 @@ #' placeholder row with \code{NA} for all LRM fields. This ensures TissuePlex #' can render the full tissue graph even for edges with no scored LR pairs. #' +#' NICHESv2 stops at this file. To view it, see the +#' \href{https://raredonlab.github.io/TissuePlex/}{TissuePlex manual}. +#' #' @param object A \code{NICHESObject}. #' @param output.path Full path to the output \code{.parquet} file. #' Parent directories are created automatically. diff --git a/R/extract_NICHESInputs_Seurat.R b/R/extract_NICHESInputs_Seurat.R index 5120330..7043fad 100644 --- a/R/extract_NICHESInputs_Seurat.R +++ b/R/extract_NICHESInputs_Seurat.R @@ -108,10 +108,18 @@ extract_NICHESInputs_Seurat <- function(seurat.obj, count.mtx <- SeuratObject::GetAssayData(seurat.obj, layer = layer, assay = assay) } else { - # V4 Assay: fixed slot names; GetAssayData returns empty matrix for - # slots that were never populated (e.g. scale.data before ScaleData()). - count.mtx <- SeuratObject::GetAssayData(seurat.obj, slot = layer, - assay = assay) + # V4 Assay: fixed slot names. Read the slot directly, because the 'slot' + # argument of GetAssayData() is deprecated and SeuratObject < 5 has no + # 'layer' argument. Slots that were never populated hold an empty matrix + # (e.g. scale.data before ScaleData()). + available.slots <- c("counts", "data", "scale.data") + if (!layer %in% available.slots) { + stop( + "Slot '", layer, "' not found in assay '", assay, "' (V4 Assay).\n", + " Available slots: ", paste(available.slots, collapse = ", ") + ) + } + count.mtx <- methods::slot(assay.obj, layer) if (prod(dim(count.mtx)) == 0L) { stop( "Slot '", layer, "' in assay '", assay, "' (V4 Assay) is empty.\n", diff --git a/R/utils.R b/R/utils.R index 5129545..e6d0718 100644 --- a/R/utils.R +++ b/R/utils.R @@ -104,7 +104,6 @@ utils::globalVariables(c( # edge-table columns "edge", "from", "to", "SendingCell", "ReceivingCell", - "SendingType", "ReceivingType", # LRM / score columns "LRM", "ligand", "receptor", diff --git a/README.md b/README.md index e63c578..2c764a2 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ GitHub: ```r install.packages("remotes") -remotes::install_github("RaredonLab/NICHESv2", ref = "dev") +remotes::install_github("RaredonLab/NICHESv2", ref = "main") ``` To read the vignette locally, add `build_vignettes = TRUE`, which needs knitr, @@ -88,13 +88,14 @@ The vignette walks through the full workflow: vignette("NICHESv2") ``` +The [website](https://raredonlab.github.io/NICHESv2/) has tutorials on public +spatial and non-spatial datasets, plus a page for reviewers. + ## Features - **Two analysis modes:** `"spatial"` connects cells by k-nearest neighbors or a fixed radius, and adds autocrine self-loops. `"nonspatial"` pairs cells by random sampling within each pair of cell types. -- **Pseudobulk summaries:** `compute_PseudoBulk_Connectivity()` scores each pair - of cell types and returns a `data.table`. - **LR databases:** ConnectomeDB2025 and FANTOM5 are bundled for human, mouse, rat and pig, with no internet needed. OmniPath covers human, mouse and rat. You can also supply your own data frame, and multi-gene complexes are @@ -112,7 +113,7 @@ vignette("NICHESv2") - **Works on every platform:** parallel scoring uses socket clusters through `n.cores`. - **Interactive viewing:** `export_to_TissuePlex()` writes edges to a Parquet file - for viewing in tissue coordinates. + for viewing in [TissuePlex](https://raredonlab.github.io/TissuePlex/). ## Citation diff --git a/_pkgdown.yml b/_pkgdown.yml index d71acfb..0dad402 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -1,4 +1,94 @@ -url: ~ +url: https://raredonlab.github.io/NICHESv2/ + template: bootstrap: 5 +navbar: + structure: + left: [intro, reviewers, tutorials, guides, reference, news] + right: [search, github] + components: + reviewers: + text: For reviewers + href: articles/for-reviewers.html + tutorials: + text: Tutorials + menu: + - text: "Spatial: mouse brain" + href: articles/spatial-tutorial.html + - text: "Non-spatial: stimulated PBMCs" + href: articles/nonspatial-tutorial.html + guides: + text: Guides + menu: + - text: Input formats + href: articles/input-formats.html + - text: The NICHESObject + href: articles/niches-object.html + - text: Neighborhood aggregation + href: articles/aggregation.html + - text: Exporting to TissuePlex + href: articles/tissueplex-export.html + +articles: +- title: Reviewers + navbar: ~ + contents: + - articles/for-reviewers +- title: Tutorials + navbar: ~ + contents: + - articles/spatial-tutorial + - articles/nonspatial-tutorial +- title: Guides + navbar: ~ + contents: + - articles/input-formats + - articles/niches-object + - articles/aggregation + - articles/tissueplex-export + +reference: +- title: Build an object + contents: + - create_NICHESObject + - extract_NICHESInputs_Seurat + - extract_NICHESInputs_AnnData + - load_LRM_database + - merge_NICHESObjects +- title: Neighborhoods and aggregation + contents: + - Explore_Radius_Neighborhood + - add_neighborhoods + - extract_neighborhoods + - aggregate_NICHESObject + - add_neighborhood_edge_agg + - add_neighborhood_composition +- title: Work with an object + contents: + - "`[.NICHESObject`" + - print.NICHESObject + - summary.NICHESObject + - dim.NICHESObject + - length.NICHESObject + - is_NICHESObject + - add_meta_column + - add_cell_meta + - add_cell_rawcounts + - add_segmentation +- title: Export + contents: + - export_to_TissuePlex +- title: Lower-level steps + contents: + - compute_CellToCell + - create_Edgelist_Spatial + - create_Edgelist_SamplingByType +- title: Example data + contents: + - NICHESv2_inputs + - NICHESv2_example +- title: LR databases + contents: + - starts_with("connectomedb2025") + - starts_with("ncomms8866") diff --git a/man/compute_CellToCell.Rd b/man/compute_CellToCell.Rd index 7760390..3f2810f 100644 --- a/man/compute_CellToCell.Rd +++ b/man/compute_CellToCell.Rd @@ -15,14 +15,12 @@ compute_CellToCell( ) } \arguments{ -\item{count.mtx}{Gene x cell (or gene x type for pseudobulk) -expression matrix (sparse \code{dgCMatrix} or dense). Row names = gene -symbols; column names = cell barcodes or cell type labels matching +\item{count.mtx}{Gene x cell expression matrix (sparse \code{dgCMatrix} +or dense). Row names = gene symbols; column names = cell barcodes matching \code{edge.list$from} / \code{$to}.} \item{edge.list}{\code{data.table} from -\code{\link{create_Edgelist_Spatial}}, -\code{\link{create_Edgelist_PseudoBulk}}, or +\code{\link{create_Edgelist_Spatial}} or \code{\link{create_Edgelist_SamplingByType}}; or any \code{data.frame} with \code{from} and \code{to} columns whose values match \code{colnames(count.mtx)}. Coordinate columns @@ -73,11 +71,9 @@ Both elements are \code{data.table}s so downstream joins on } \description{ Universal scoring engine for all NICHESv2 edge modes. For each edge and each -valid LR pair, computes a signal score. The edge list may come from any of -the three edgelist constructors -- spatial, pseudobulk, or type-sampled -- -and the count matrix is expected to match accordingly (cell barcodes as -column names for spatial and nonspatial modes; cell type names for pseudobulk -mode). +valid LR pair, computes a signal score. The edge list may come from either +edgelist constructor -- spatial or type-sampled -- and the count matrix +column names must be the cell barcodes it uses. Supports \strong{multi-gene complexes}: a ligand or receptor represented as \code{"gene1_gene2"} is split on \code{"_"} and all component expressions @@ -161,10 +157,7 @@ setdiff(c("x.from", "y.from", "x.to", "y.to"), colnames(result$edges)) \code{\link{create_NICHESObject}} for the wrapped pipeline that assembles a full \code{NICHESObject}; \code{\link{create_Edgelist_Spatial}}, - \code{\link{create_Edgelist_PseudoBulk}}, \code{\link{create_Edgelist_SamplingByType}} for the edge-list constructors; - \code{\link{load_LRM_database}} for the LR-database loader; - \code{\link{compute_PseudoBulk_Connectivity}} for type-averaged - connectivity in one call. + \code{\link{load_LRM_database}} for the LR-database loader. } diff --git a/man/compute_PseudoBulk_Connectivity.Rd b/man/compute_PseudoBulk_Connectivity.Rd deleted file mode 100644 index 5626ccc..0000000 --- a/man/compute_PseudoBulk_Connectivity.Rd +++ /dev/null @@ -1,109 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/compute_PseudoBulk_Connectivity.R -\name{compute_PseudoBulk_Connectivity} -\alias{compute_PseudoBulk_Connectivity} -\title{Compute Pseudobulk Cell-Type Connectivity} -\usage{ -compute_PseudoBulk_Connectivity( - count.mtx, - meta.data, - LRM.db, - cell.type.col, - ligand.col = "ligand", - receptor.col = "receptor", - method = c("product", "minimum"), - normalize.method = c("prop", "none"), - n.cores = 1L, - verbose = TRUE -) -} -\arguments{ -\item{count.mtx}{Gene x cell expression matrix (sparse or dense). -Row names = gene symbols; column names = cell barcodes.} - -\item{meta.data}{\code{data.frame} with row names = cell barcodes. -Must contain the column named by \code{cell.type.col}.} - -\item{LRM.db}{LR database: \code{"fantom5"}, \code{"omnipath"}, or -a \code{data.frame} with at least \code{ligand.col} and -\code{receptor.col}.} - -\item{cell.type.col}{\code{character(1)}. Column in \code{meta.data} -holding cell type labels.} - -\item{ligand.col}{Column name for ligands in \code{LRM.db}. -Default \code{"ligand"}.} - -\item{receptor.col}{Column name for receptors in \code{LRM.db}. -Default \code{"receptor"}.} - -\item{method}{Scoring method: \code{"product"} (default) or -\code{"minimum"}.} - -\item{normalize.method}{Normalization for \code{score.norm}: -\code{"prop"} (default, proportional per type-pair) or \code{"none"}.} - -\item{n.cores}{CPU cores. Default 1. Socket cluster -- works on all -platforms.} - -\item{verbose}{Print progress messages. Default \code{TRUE}.} -} -\value{ -A \code{data.table} keyed on \code{(SendingType, ReceivingType, LRM)} - with columns as described above. Only non-zero score rows are included - (implicit sparsity). -} -\description{ -Computes ligand-receptor signal scores between all ordered cell type pairs -using per-type mean expression profiles (pseudobulk). Covers all T^2 directed -type-to-type crossings including autocrine (A -> A). - -Unlike \code{create_NICHESObject()}, this function does \strong{not} build -a \code{NICHESObject}. It returns a compact \code{data.table} directly -suitable for heatmap or network visualization of type-level communication. -This is intentional -- the pseudobulk output is type-level rather than -cell-level and does not benefit from the full NICHESObject slot structure. -} -\section{Output schema}{ - -One row per (type-pair x non-zero LRM): -\describe{ - \item{\code{SendingType}}{Sending cell type label.} - \item{\code{ReceivingType}}{Receiving cell type label.} - \item{\code{LRM}}{\code{"ligand|receptor"} string.} - \item{\code{ligand}}{Ligand gene or complex.} - \item{\code{receptor}}{Receptor gene or complex.} - \item{\code{score}}{Raw LR signal (product or minimum of mean expressions).} - \item{\code{score.norm}}{Score normalized proportionally per type-pair edge - (sums to 1.0 across all LRMs for a given sending-receiving pair), or equal - to \code{score} when \code{normalize.method = "none"}.} -} -} - -\examples{ -\donttest{ -data(NICHESv2_inputs) - -# Type-level connectivity using the bundled inputs (3 cell types: A/B/C) -pb <- compute_PseudoBulk_Connectivity( - count.mtx = NICHESv2_inputs$count.mtx, - meta.data = NICHESv2_inputs$meta.data, - LRM.db = NICHESv2_inputs$LRM.db, - cell.type.col = "celltype", - n.cores = 1L, - verbose = FALSE -) -head(pb) - -# Total signal per directed type pair -- the input to a heatmap or chord plot -agg <- pb[, list(total.score = sum(score)), - by = list(SendingType, ReceivingType)] -agg -} - -} -\seealso{ -\code{\link{create_NICHESObject}}, - \code{\link{create_Edgelist_PseudoBulk}}, - \code{\link{compute_CellToCell}} -} diff --git a/man/create_Edgelist_PseudoBulk.Rd b/man/create_Edgelist_PseudoBulk.Rd deleted file mode 100644 index 45eccd2..0000000 --- a/man/create_Edgelist_PseudoBulk.Rd +++ /dev/null @@ -1,69 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/create_Edgelist_PseudoBulk.R -\name{create_Edgelist_PseudoBulk} -\alias{create_Edgelist_PseudoBulk} -\title{Build a Pseudobulk Type-to-Type Edge List} -\usage{ -create_Edgelist_PseudoBulk(meta.data, cell.type.col) -} -\arguments{ -\item{meta.data}{\code{data.frame} with one row per cell. Row names must -be unique cell barcodes. Must contain the column specified by -\code{cell.type.col}.} - -\item{cell.type.col}{\code{character(1)}. Name of the column in -\code{meta.data} that holds cell type labels.} -} -\value{ -A \code{data.table} keyed on \code{(from, to)} with columns: -\describe{ - \item{\code{from}}{Sending cell type label (character).} - \item{\code{to}}{Receiving cell type label (character).} -} -Carries metadata attributes: \code{mode} (\code{"pseudobulk"}), -\code{param} (the \code{cell.type.col} value), \code{n.cells} (total -number of cells in \code{meta.data}), \code{cell.names} (sorted unique -cell type labels). -} -\description{ -Constructs a directed edge list covering all ordered cell type pairs for -pseudobulk non-spatial analysis. Each edge represents a directed -type-to-type communication channel (e.g., \code{"ATI"} -> \code{"gCap"}). -All T^2 directed pairs are included, encompassing both cross-type and -autocrine (same-type) edges. - -The output edge list is intended to be passed to \code{create_NICHESObject()} -with \code{mode = "pseudobulk"}, where the per-type mean expression matrix is -computed and paired with this edge list for scoring. Do not pass individual -cell barcodes as \code{count.mtx} column names when using this edge list -- -the column names must be cell type labels. -} -\details{ -This function is a low-level primitive: it builds the pseudobulk -type-to-type edge list that \code{\link{compute_PseudoBulk_Connectivity}} -consumes internally. Most users should call -\code{compute_PseudoBulk_Connectivity()}, which invokes this function, -computes per-type mean expression, scores every type pair, and returns -a single \code{data.table} in one step. -\code{create_Edgelist_PseudoBulk()} is exposed for power users who -want to inspect the type-pair enumeration directly or feed the edges -into a custom scoring pipeline. - -Cell types are sorted alphabetically before enumeration so the output -order is deterministic regardless of the order they appear in -\code{meta.data}. -} -\examples{ -meta <- data.frame( - cell.type = c("ATI", "ATI", "gCap", "gCap", "Macro"), - row.names = paste0("cell_", 1:5) -) -el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "cell.type") - -} -\seealso{ -\code{\link{create_NICHESObject}}, - \code{\link{create_Edgelist_SamplingByType}}, - \code{\link{create_Edgelist_Spatial}} -} -\keyword{internal} diff --git a/man/create_Edgelist_SamplingByType.Rd b/man/create_Edgelist_SamplingByType.Rd index b08c75a..e1c182f 100644 --- a/man/create_Edgelist_SamplingByType.Rd +++ b/man/create_Edgelist_SamplingByType.Rd @@ -90,7 +90,6 @@ el <- create_Edgelist_SamplingByType(meta, cell.type.col = "cell.type", } \seealso{ \code{\link{create_NICHESObject}}, - \code{\link{create_Edgelist_PseudoBulk}}, \code{\link{create_Edgelist_Spatial}} } \keyword{internal} diff --git a/man/create_NICHESObject.Rd b/man/create_NICHESObject.Rd index 28ce87a..05585cc 100644 --- a/man/create_NICHESObject.Rd +++ b/man/create_NICHESObject.Rd @@ -122,10 +122,6 @@ The primary entry point for NICHESv2. Supports two analysis modes: \item{\code{"nonspatial"}}{NICHES v1-style type-stratified sampling. Requires \code{cell.type.col}.} } - -For pseudobulk (type-averaged) connectivity use -\code{\link{compute_PseudoBulk_Connectivity}} -- it returns a plain -\code{data.table}, not a \code{NICHESObject}. } \section{Pipeline overview}{ @@ -227,8 +223,6 @@ attr(obj.split, "sample.col") # "sample" function; \code{\link{merge_NICHESObjects}} for combining objects produced independently; - \code{\link{compute_PseudoBulk_Connectivity}} for type-averaged - connectivity (returns a \code{data.table}, not a \code{NICHESObject}); \code{\link{compute_CellToCell}} for the underlying scoring engine; \code{\link{create_Edgelist_Spatial}}, \code{\link{create_Edgelist_SamplingByType}} for the edge-list diff --git a/man/export_to_TissuePlex.Rd b/man/export_to_TissuePlex.Rd index 2e17ba6..3f93d8f 100644 --- a/man/export_to_TissuePlex.Rd +++ b/man/export_to_TissuePlex.Rd @@ -44,6 +44,10 @@ edges absent from \code{$edge.data} (no active LR signal) produce a single placeholder row with \code{NA} for all LRM fields. This ensures TissuePlex can render the full tissue graph even for edges with no scored LR pairs. } +\details{ +NICHESv2 stops at this file. To view it, see the +\href{https://raredonlab.github.io/TissuePlex/}{TissuePlex manual}. +} \examples{ if (requireNamespace("arrow", quietly = TRUE)) { data(NICHESv2_example) diff --git a/package management/NICHESv2_package_design.md b/package management/NICHESv2_package_design.md index 7826c9b..d50ece8 100644 --- a/package management/NICHESv2_package_design.md +++ b/package management/NICHESv2_package_design.md @@ -147,9 +147,6 @@ load_LRM_database(db, species, ligand.col, receptor.col, verbose) create_Edgelist_Spatial(coord, k, rad, n.cores) -> data.table(from|to|weight|x.from|y.from|x.to|y.to) + autocrine self-loops -create_Edgelist_PseudoBulk(meta.data, cell.type.col) - -> data.table(from|to) with type labels; deterministic - create_Edgelist_SamplingByType(meta.data, cell.type.col, seed=42L, max.cells) -> data.table(from|to) with barcodes; attrs: mode="nonspatial" @@ -162,12 +159,6 @@ compute_CellToCell(count.mtx, edge.list, LRM.db, ligand.col, receptor.col, $lr.meta: data.table -- ligand|receptor|LRM + extras from LRM.db; keyed (ligand, receptor) -compute_PseudoBulk_Connectivity(count.mtx, meta.data, LRM.db, cell.type.col, - ligand.col, receptor.col, method, - normalize.method, n.cores, verbose) - -> plain data.table (NOT NICHESObject): - SendingType|ReceivingType|LRM|score|score.norm - -- OBJECT CONSTRUCTION -- create_NICHESObject(count.mtx, meta.data, LRM.db, mode="spatial", species="human", sample.col=NULL, @@ -379,10 +370,9 @@ Bundled data (data/): Tests (all passing): helper-testutils.R -- keep (make_grid_coord utility) test-compute_LRM_Score.R test-create_Edgelist_Spatial.R - test-create_Edgelist_PseudoBulk.R test-extract_neighborhoods.R test-create_Edgelist_SamplingByType.R test-add_neighborhoods.R test-compute_CellToCell.R - test-merge_NICHESObjects.R test-compute_PseudoBulk_Connectivity.R + test-merge_NICHESObjects.R test-Explore_Radius_Neighborhood.R test-create_NICHESObject.R test-extract_NICHESInputs_Seurat.R test-load_LRM_database.R test-extract_NICHESInputs_AnnData.R test-add_cell_meta.R @@ -613,10 +603,9 @@ R CMD check. Coverage: ~270+ test_that blocks. File structure (all in tests/testthat/): helper-testutils.R -- keep (make_grid_coord utility) test-compute_LRM_Score.R test-create_Edgelist_Spatial.R - test-create_Edgelist_PseudoBulk.R test-extract_neighborhoods.R test-create_Edgelist_SamplingByType.R test-add_neighborhoods.R test-compute_CellToCell.R - test-merge_NICHESObjects.R test-compute_PseudoBulk_Connectivity.R + test-merge_NICHESObjects.R test-Explore_Radius_Neighborhood.R test-create_NICHESObject.R test-extract_NICHESInputs_Seurat.R test-load_LRM_database.R test-extract_NICHESInputs_AnnData.R test-add_cell_meta.R diff --git a/tests/testthat/test-compute_PseudoBulk_Connectivity.R b/tests/testthat/test-compute_PseudoBulk_Connectivity.R deleted file mode 100644 index c0f2505..0000000 --- a/tests/testthat/test-compute_PseudoBulk_Connectivity.R +++ /dev/null @@ -1,191 +0,0 @@ -# ============================================================================== -# FILE: tests/testthat/test-compute_PseudoBulk_Connectivity.R -# PURPOSE: Unit tests for compute_PseudoBulk_Connectivity(). -# All inputs synthesised inline — no shared fixtures needed. -# ============================================================================== - -# ── File-level helpers ───────────────────────────────────────────────────────── - -# 15 genes x 12 cells, high density + rpois offset guarantees non-zero -# pseudobulk averages for both cell types. -make_pb_count_mtx <- function() { - set.seed(1L) - m <- Matrix::rsparsematrix(15L, 12L, density = 0.8, - rand.x = function(n) rpois(n, 5) + 1) - rownames(m) <- paste0("gene", seq_len(15L)) - colnames(m) <- paste0("cell", seq_len(12L)) - m -} - -# 12 cells split evenly across 2 types; rownames match count matrix colnames. -make_pb_meta <- function() { - data.frame( - row.names = paste0("cell", seq_len(12L)), - celltype = rep(c("TypeA", "TypeB"), each = 6L), - stringsAsFactors = FALSE - ) -} - -# 3 LRM pairs drawn from the first 6 genes; pathway column for extra-col test. -make_pb_LRM_db <- function() { - data.frame( - ligand = c("gene1", "gene3", "gene5"), - receptor = c("gene2", "gene4", "gene6"), - pathway = c("PathA", "PathB", "PathC"), - stringsAsFactors = FALSE - ) -} - -# ── Output structure ─────────────────────────────────────────────────────────── - -test_that("compute_PseudoBulk_Connectivity: returns a data.table", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - expect_s3_class(pb, "data.table") -}) - -test_that("compute_PseudoBulk_Connectivity: NOT a NICHESObject", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - expect_false(is_NICHESObject(pb)) -}) - -test_that("compute_PseudoBulk_Connectivity: has all required columns", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - expect_true(all(c("SendingType", "ReceivingType", "LRM", - "ligand", "receptor", "score", "score.norm") %in% - colnames(pb))) -}) - -test_that("compute_PseudoBulk_Connectivity: LRM column uses '|' separator", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - expect_true(all(grepl("|", pb$LRM, fixed = TRUE))) -}) - -test_that("compute_PseudoBulk_Connectivity: SendingType and ReceivingType are type labels", { - meta <- make_pb_meta() - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), meta, make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - type.labels <- unique(meta$celltype) - expect_true(all(pb$SendingType %in% type.labels)) - expect_true(all(pb$ReceivingType %in% type.labels)) -}) - -test_that("compute_PseudoBulk_Connectivity: all scores are strictly positive", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - expect_true(all(pb$score > 0)) -}) - -# ── Normalisation ────────────────────────────────────────────────────────────── - -test_that("compute_PseudoBulk_Connectivity: score.norm sums to 1 per type-pair (prop mode)", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", - normalize.method = "prop", - n.cores = 1L - ) - pair.sums <- pb[, .(s = sum(score.norm)), by = .(SendingType, ReceivingType)] - expect_true(all(abs(pair.sums$s - 1) < 1e-9)) -}) - -test_that("compute_PseudoBulk_Connectivity: score.norm equals score when normalize.method='none'", { - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", - normalize.method = "none", - n.cores = 1L - ) - expect_equal(pb$score, pb$score.norm) -}) - -# ── Determinism and method contrast ─────────────────────────────────────────── - -test_that("compute_PseudoBulk_Connectivity: output is deterministic", { - pb1 <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", verbose = FALSE, n.cores = 1L - ) - pb2 <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", verbose = FALSE, n.cores = 1L - ) - expect_equal(pb1$score, pb2$score) -}) - -test_that("compute_PseudoBulk_Connectivity: product vs minimum give different scores", { - pb.prod <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", method = "product", - verbose = FALSE, n.cores = 1L - ) - pb.min <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", method = "minimum", - verbose = FALSE, n.cores = 1L - ) - expect_false(identical(pb.prod$score, pb.min$score)) -}) - -test_that("compute_PseudoBulk_Connectivity: output contains valid type labels and is non-empty", { - meta <- make_pb_meta() - pb <- compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), meta, make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ) - type.labels <- sort(unique(meta$celltype)) - expect_gt(nrow(pb), 0L) - expect_true(all(pb$SendingType %in% type.labels)) - expect_true(all(pb$ReceivingType %in% type.labels)) - expect_gt(nrow(unique(pb[, .(SendingType, ReceivingType)])), 0L) -}) - -# ── Input validation ─────────────────────────────────────────────────────────── - -test_that("compute_PseudoBulk_Connectivity: errors when cell.type.col missing", { - expect_error( - compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "NOTACOL", n.cores = 1L - ), - regexp = "not found" - ) -}) - -test_that("compute_PseudoBulk_Connectivity: errors on non-matrix count.mtx", { - expect_error( - compute_PseudoBulk_Connectivity( - as.data.frame(as.matrix(make_pb_count_mtx())), - make_pb_meta(), make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ), - regexp = "matrix or sparseMatrix" - ) -}) - -test_that("compute_PseudoBulk_Connectivity: errors when no shared cells between matrix and meta", { - bad.meta <- make_pb_meta() - rownames(bad.meta) <- paste0("WRONG_", rownames(bad.meta)) - expect_error( - compute_PseudoBulk_Connectivity( - make_pb_count_mtx(), bad.meta, make_pb_LRM_db(), - cell.type.col = "celltype", n.cores = 1L - ), - regexp = "No shared cells" - ) -}) \ No newline at end of file diff --git a/tests/testthat/test-create_Edgelist_PseudoBulk.R b/tests/testthat/test-create_Edgelist_PseudoBulk.R deleted file mode 100644 index c6e0f2e..0000000 --- a/tests/testthat/test-create_Edgelist_PseudoBulk.R +++ /dev/null @@ -1,132 +0,0 @@ -# ============================================================================== -# FILE: tests/testthat/test-create_Edgelist_PseudoBulk.R -# PURPOSE: Unit tests for create_Edgelist_PseudoBulk(). -# All inputs synthesised inline — no shared fixtures needed. -# ============================================================================== - -# File-level helper: 15 cells across 3 types — small, deterministic, reusable. -make_pseudobulk_meta <- function() { - data.frame( - row.names = paste0("cell_", seq_len(15L)), - celltype = rep(c("TypeA", "TypeB", "TypeC"), each = 5L), - stringsAsFactors = FALSE - ) -} - -# ── Structure and schema ─────────────────────────────────────────────────────── - -test_that("create_Edgelist_PseudoBulk: returns a data.table with from and to", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_s3_class(el, "data.table") - expect_true(all(c("from", "to") %in% colnames(el))) -}) - -test_that("create_Edgelist_PseudoBulk: from/to values are type labels not barcodes", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - type.labels <- unique(meta$celltype) - all.barcodes <- rownames(meta) - - expect_true(all(el$from %in% type.labels)) - expect_true(all(el$to %in% type.labels)) - expect_false(any(el$from %in% all.barcodes)) -}) - -test_that("create_Edgelist_PseudoBulk: produces exactly T^2 edges for T types", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - n.types <- length(unique(meta$celltype)) - - expect_equal(nrow(el), n.types^2L) -}) - -test_that("create_Edgelist_PseudoBulk: all ordered type pairs are present", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - type.labels <- sort(unique(meta$celltype)) - - expected.from <- rep(type.labels, each = length(type.labels)) - expected.to <- rep(type.labels, times = length(type.labels)) - actual <- el[order(el$from, el$to), ] - - expect_equal(actual$from, sort(expected.from)) - expect_equal(actual$to, expected.to[order(expected.from)]) -}) - -test_that("create_Edgelist_PseudoBulk: autocrine edges (from == to) are included", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - autocrine <- el[el$from == el$to, ] - n.types <- length(unique(meta$celltype)) - - expect_equal(nrow(autocrine), n.types) -}) - -test_that("create_Edgelist_PseudoBulk: output is deterministic", { - meta <- make_pseudobulk_meta() - el1 <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - el2 <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_equal(el1$from, el2$from) - expect_equal(el1$to, el2$to) -}) - -# ── Attributes ──────────────────────────────────────────────────────────────── - -test_that("create_Edgelist_PseudoBulk: mode attribute is 'pseudobulk'", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_equal(attr(el, "mode"), "pseudobulk") -}) - -test_that("create_Edgelist_PseudoBulk: n.cells attribute matches nrow(meta)", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_equal(attr(el, "n.cells"), nrow(meta)) -}) - -test_that("create_Edgelist_PseudoBulk: cell.names attribute is sorted unique types", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_equal(attr(el, "cell.names"), sort(unique(meta$celltype))) -}) - -test_that("create_Edgelist_PseudoBulk: param attribute records cell.type.col", { - meta <- make_pseudobulk_meta() - el <- create_Edgelist_PseudoBulk(meta, cell.type.col = "celltype") - - expect_equal(attr(el, "param"), "celltype") -}) - -# ── Input validation ─────────────────────────────────────────────────────────── - -test_that("create_Edgelist_PseudoBulk: errors on non-data.frame input", { - expect_error( - create_Edgelist_PseudoBulk(matrix(1:4, 2L), cell.type.col = "celltype"), - regexp = "data.frame" - ) -}) - -test_that("create_Edgelist_PseudoBulk: errors when cell.type.col not in meta", { - meta <- make_pseudobulk_meta() - expect_error( - create_Edgelist_PseudoBulk(meta, cell.type.col = "NOTACOL"), - regexp = "not found" - ) -}) - -test_that("create_Edgelist_PseudoBulk: errors when fewer than 2 cell types", { - mono.meta <- data.frame( - celltype = rep("OnlyType", 5L), - row.names = paste0("cell_", 1:5) - ) - expect_error( - create_Edgelist_PseudoBulk(mono.meta, cell.type.col = "celltype"), - regexp = "2 distinct" - ) -}) \ No newline at end of file diff --git a/tests/testthat/test-extract_NICHESInputs_Seurat.R b/tests/testthat/test-extract_NICHESInputs_Seurat.R index 2a3311a..5f373a7 100644 --- a/tests/testthat/test-extract_NICHESInputs_Seurat.R +++ b/tests/testthat/test-extract_NICHESInputs_Seurat.R @@ -145,4 +145,29 @@ test_that("extract_NICHESInputs_Seurat: class-based V4/V5 dispatch produces corr expect_equal(dim(result$count.mtx), c(10L, 8L)) expect_true(assay.class %in% c("Assay", "Assay5")) -}) \ No newline at end of file +}) +test_that("extract_NICHESInputs_Seurat: V4 Assay objects extract without warnings", { + skip_if_not_installed("SeuratObject") + + set.seed(42L) + counts <- abs(Matrix::rsparsematrix(10L, 8L, density = 0.7)) + rownames(counts) <- paste0("gene", seq_len(10L)) + colnames(counts) <- paste0("cell", seq_len(8L)) + assay.v4 <- SeuratObject::CreateAssayObject(counts = counts) + seurat.obj <- SeuratObject::CreateSeuratObject(counts = assay.v4) + expect_false(inherits(seurat.obj@assays[["RNA"]], "Assay5")) + + expect_no_warning( + result <- extract_NICHESInputs_Seurat(seurat.obj, verbose = FALSE) + ) + expect_equal(as.matrix(result$count.mtx), as.matrix(counts)) + + expect_error( + extract_NICHESInputs_Seurat(seurat.obj, layer = "missing", verbose = FALSE), + "Available slots" + ) + expect_error( + extract_NICHESInputs_Seurat(seurat.obj, layer = "scale.data", verbose = FALSE), + "is empty" + ) +}) diff --git a/vignettes/NICHESv2.Rmd b/vignettes/NICHESv2.Rmd index 2400d57..588e214 100644 --- a/vignettes/NICHESv2.Rmd +++ b/vignettes/NICHESv2.Rmd @@ -8,7 +8,14 @@ vignette: > --- ```{r setup, include = FALSE} -knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) has.seurat <- requireNamespace("SeuratObject", quietly = TRUE) has.rhdf5 <- requireNamespace("rhdf5", quietly = TRUE) has.arrow <- requireNamespace("arrow", quietly = TRUE) @@ -105,7 +112,7 @@ obj$edge.data[, .(total.score = sum(score)), by = LRM][order(-total.score)][1:3] `Receiving.` prefixes, which makes it easy to filter by cell type: ```{r edge-meta} -obj$edge.meta[, .N, by = .(Sending.celltype, Receiving.celltype)][1:3] +obj$edge.meta[, .(edges = .N), by = .(Sending.celltype, Receiving.celltype)][1:3] ``` ## Aggregate by neighborhood @@ -182,20 +189,6 @@ ns <- create_NICHESObject( dim(ns) ``` -For one summary per pair of cell types, use -`compute_PseudoBulk_Connectivity()`, which returns a `data.table`: - -```{r pseudobulk} -pb <- compute_PseudoBulk_Connectivity( - count.mtx = NICHESv2_inputs$count.mtx, - meta.data = NICHESv2_inputs$meta.data, - LRM.db = NICHESv2_inputs$LRM.db, - cell.type.col = "celltype", - verbose = FALSE -) -nrow(pb) -``` - ## Using your own data ### LR databases @@ -215,9 +208,11 @@ own data frame. Multi-gene complexes are written with underscores, such as ### Seurat objects -`extract_NICHESInputs_Seurat()` works with Seurat V4 and V5 objects. It returns -`count.mtx` and `meta.data`, ready for `create_NICHESObject()`. For spatial data, -add the coordinates to `meta.data` yourself as `x` and `y` columns. +`extract_NICHESInputs_Seurat()` works with Seurat V4 and V5 objects, so you don't +need to update an older object first. It returns `count.mtx` and `meta.data`, +ready for `create_NICHESObject()`. For spatial data, add the coordinates to +`meta.data` yourself as `x` and `y` columns; `SeuratObject::GetTissueCoordinates()` +returns them. ```{r seurat, eval = has.seurat} seu <- SeuratObject::CreateSeuratObject( @@ -244,8 +239,9 @@ dim(inputs$count.mtx) ### Exporting to TissuePlex -`export_to_TissuePlex()` writes one Parquet file for interactive viewing of edges -in tissue coordinates. It needs the arrow package. +`export_to_TissuePlex()` writes one Parquet file of edges and needs the arrow +package. To view the file in tissue coordinates, see the +[TissuePlex manual](https://raredonlab.github.io/TissuePlex/). ```{r tissueplex, eval = has.arrow} out.file <- tempfile(fileext = ".parquet") @@ -258,3 +254,6 @@ unlink(out.file) See `?create_NICHESObject` for every construction option, `?add_neighborhood_edge_agg` for all 27 aggregation columns, and `?"[.NICHESObject"` for the subsetting rules. `?NICHESv2` gives an overview. + +The [website](https://raredonlab.github.io/NICHESv2/) has tutorials on public +spatial and non-spatial datasets. diff --git a/vignettes/articles/aggregation.Rmd b/vignettes/articles/aggregation.Rmd new file mode 100644 index 0000000..0b9184e --- /dev/null +++ b/vignettes/articles/aggregation.Rmd @@ -0,0 +1,161 @@ +--- +title: "Neighborhood aggregation" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Neighborhood aggregation} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) +``` + +Edges show individual cell pairs. Aggregation summarizes them for each cell's +neighborhood, which gives you per-cell values to compare across a tissue. + +```{r load} +library(NICHESv2) +library(data.table) + +data(NICHESv2_example) +obj <- aggregate_NICHESObject( + NICHESv2_example, + cell.type.col = "celltype", + verbose = FALSE +) +names(obj$aggregations) +``` + +`aggregate_NICHESObject()` runs `add_neighborhood_edge_agg()`, then +`add_neighborhood_composition()` if you pass `cell.type.col`. Each run replaces the +previous result. + +## Edge aggregation + +`$aggregations$neighborhood.edge.agg` has 27 columns, with one row for each (cell, +LRM) pair that has signal. + +```{r edge-agg} +agg <- obj$aggregations$neighborhood.edge.agg +dim(agg) +``` + +### Five categories + +Each edge in a neighborhood falls into one category relative to the focal cell: + +| Category | Meaning | +|---|---| +| `in` | A neighbor sends to the focal cell | +| `out` | The focal cell sends to a neighbor | +| `cross` | One neighbor sends to another; the focal cell isn't involved | +| `self.autocrine` | The focal cell's own self-loop | +| `other.autocrine` | A neighbor's self-loop | + +The `cross` category captures what a cell's surroundings exchange, even when the +cell itself takes no part. + +### Columns + +`{category}` below stands for each of the five categories, or `total` for all of +them together. + +| Column | Meaning | +|---|---| +| `count.{category}` | Number of edges with signal | +| `score.{category}.sum` | Total score | +| `score.{category}.mean` | Total score divided by all edges in the neighborhood, including those with no signal for this LRM | +| `score.{category}.cmean` | Total score divided by the count, or `NA` when the count is zero | +| `score.inout.ratio` | `score.in.sum` divided by `score.out.sum`, or `NA` when nothing is sent | + +Use `mean` to compare the overall signal between neighborhoods of different sizes. +Use `cmean` to see how strong the signal is on the edges that carry it. + +```{r columns} +agg[, .(cell, LRM, count.in, score.in.sum, score.in.mean, score.in.cmean)][1:3] +``` + +Edges with no signal for any LR pair still count toward the `mean` denominator, +which comes from `$neighborhood.meta$n.edges`. + +### Memory + +`chunk.size` sets how many LR pairs are processed at once, and defaults to 50. Lower +it if you run short of memory. Aggregation uses sparse matrix multiplication, so +`n.cores` has no effect on this step. + +## Neighborhood composition + +`$aggregations$neighborhood.composition` has one row per cell, with counts and +proportions of neighboring cell types. By default it counts the focal cell too; +pass `include.self = FALSE` to `add_neighborhood_composition()` to leave it out. + +```{r composition} +comp <- obj$aggregations$neighborhood.composition +head(comp[, .(cell, TypeA.neighbor.prop, TypeB.neighbor.prop, TypeC.neighbor.prop)], 3) +``` + +This table needs spatial data. In `"nonspatial"` mode it stops with an error, +because neighbor cell types would only reflect the sampling. + +## Subsets + +Aggregate the full object first, then subset. Neighborhood slots and aggregation +tables are indexed by cell, so each kept cell keeps its rows unchanged. Those values +still describe the cell's whole neighborhood, including neighbors you didn't keep. + +```{r subset} +keep <- obj$cell.meta[celltype == "TypeA", cell] +sub <- obj[keep] + +identical( + sub$aggregations$neighborhood.edge.agg$score.in.sum, + agg[cell %in% keep]$score.in.sum +) +``` + +The edge slots of a subset keep only edges between kept cells. Two things follow: + +- Summing a cell's rows in `sub$edge.data` can give less than its aggregation row. +- A TissuePlex export of the subset shows only those kept edges. + +### Recalculating on a subset + +The removed edges are gone, so a subset can't recompute full-tissue values, and +trying stops with an error: + +```{r subset-error, error = TRUE} +add_neighborhood_edge_agg(sub, verbose = FALSE) +``` + +Each kept cell already has its correct values, so you rarely need to recalculate. +To treat the subset as a separate tissue instead, rebuild its neighborhoods first. +This clears the carried-over tables, and the new values use only the kept cells: + +```{r separate} +separate <- add_neighborhoods(sub, overwrite = TRUE, verbose = FALSE) +separate <- aggregate_NICHESObject(separate, verbose = FALSE) +``` + +## Changing neighborhoods + +`add_neighborhoods(overwrite = TRUE)` can also apply another `edge.filter.mode`. It +clears existing aggregation tables, so run aggregation again afterward. + +```{r change-mode} +narrow <- add_neighborhoods( + NICHESv2_example, + edge.filter.mode = "central_cell_only", + overwrite = TRUE, + verbose = FALSE +) +narrow <- add_neighborhood_edge_agg(narrow, verbose = FALSE) +``` diff --git a/vignettes/articles/for-reviewers.Rmd b/vignettes/articles/for-reviewers.Rmd new file mode 100644 index 0000000..ea1c8a4 --- /dev/null +++ b/vignettes/articles/for-reviewers.Rmd @@ -0,0 +1,93 @@ +--- +title: "For reviewers" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{For reviewers} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +This page takes you from a clean R session to real results on public data. You +need R 4.1.0 or later, and no Python or sign-up. + +The two public datasets here let you test the software. They don't reproduce the +paper's figures, which used a separate dataset. + +## 1. Install + +```r +install.packages(c("remotes", "SeuratObject", "arrow")) +remotes::install_github("RaredonLab/NICHESv2", ref = "main") +``` + +## 2. Confirm it works + +This takes a few seconds and uses data that ship with the package. + +```r +library(NICHESv2) + +data(NICHESv2_inputs) +obj <- create_NICHESObject( + count.mtx = NICHESv2_inputs$count.mtx, + meta.data = NICHESv2_inputs$meta.data, + LRM.db = NICHESv2_inputs$LRM.db, + mode = "spatial", + k = 5L +) +dim(obj) +``` + +You should see 80 cells, 50 genes, 354 edges and 15 LRMs. + +## 3. Get the test data + +Both datasets come from +[SeuratData](https://github.com/satijalab/seurat-data). They download once, and +together take about 560 MB. SeuratData also installs the Seurat package, so this +step can take a while. NICHESv2 itself doesn't need Seurat. + +```r +remotes::install_github("satijalab/seurat-data") +SeuratData::InstallData("stxBrain") +SeuratData::InstallData("ifnb") +``` + +## 4. Run the tutorials + +| Tutorial | Data | Time with `n.cores = 2` | +|---|---|---| +| [Spatial: mouse brain](spatial-tutorial.html) | 2,696 Visium spots | About 4 minutes | +| [Non-spatial: stimulated PBMCs](nonspatial-tutorial.html) | 13,999 cells | About 1 minute, 4 GB of memory | + +Each tutorial's code runs from top to bottom, so you can copy it directly into R. +Results should match the printed output, because scoring is deterministic and +nonspatial sampling uses a fixed seed. + +For a quick check, these are the expected object sizes: + +| Tutorial | Cells | Genes | Edges | LRMs | +|---|---|---|---|---| +| Spatial | 2,696 | 31,053 | 18,500 | 3,097 | +| Non-spatial | 13,999 | 14,053 | 87,957 | 1,047 | + +The spatial tutorial stores 5,191,520 non-zero scores, and the non-spatial tutorial +stores 605,973. + +## 5. Explore further + +- [Input formats](input-formats.html) shows how to use your own data. +- [The NICHESObject](niches-object.html) explains each slot. +- [Neighborhood aggregation](aggregation.html) explains the 27 aggregation columns + and how subsets work. +- [Exporting to TissuePlex](tissueplex-export.html) links to the interactive + viewer. + +## If something goes wrong + +- **A download fails:** the data are served by the Satija Lab. Try again later. +- **A step runs out of memory:** close other programs. The non-spatial tutorial + needs about 4 GB. +- **A step feels slow:** raise `n.cores` if your computer has more cores. +- **Something else:** please open an + [issue](https://github.com/RaredonLab/NICHESv2/issues). diff --git a/vignettes/articles/input-formats.Rmd b/vignettes/articles/input-formats.Rmd new file mode 100644 index 0000000..ba27be1 --- /dev/null +++ b/vignettes/articles/input-formats.Rmd @@ -0,0 +1,158 @@ +--- +title: "Input formats" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Input formats} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) +``` + +`create_NICHESObject()` needs an expression matrix, cell metadata and an LR +database. This guide shows how to prepare each one. + +```{r load} +library(NICHESv2) +data(NICHESv2_inputs) +``` + +## Expression matrix + +`count.mtx` is a gene-by-cell matrix, sparse or dense. Row names are gene symbols +and column names are cell barcodes. + +```{r matrix} +class(NICHESv2_inputs$count.mtx) +dim(NICHESv2_inputs$count.mtx) +``` + +The values you pass set what the scores mean. Raw counts give absolute +magnitudes, and normalized expression gives relative scores. NICHESv2 uses the +matrix as it is, so this choice affects which edges score highest. + +## Cell metadata + +`meta.data` is a data frame with cell barcodes as row names, matching the matrix +columns. What else it needs depends on the mode: + +| Mode | Required columns | +|---|---| +| `"spatial"` | `x` and `y` | +| `"nonspatial"` | the column named by `cell.type.col` | + +Other columns carry through to `$cell.meta` and appear on each edge in +`$edge.meta`. + +```{r meta} +head(NICHESv2_inputs$meta.data, 3) +``` + +### Several samples + +When your data has several samples, set `sample.col` to the column that identifies +them. Each sample is processed separately and the results are merged, so no edges +cross samples. + +Barcodes must be unique across all samples, and a duplicate stops the merge with +an error. Add a prefix first if needed, such as +`paste0(sample.id, "_", barcode)`. + +## LR databases + +Pass one of three database names to `LRM.db`, or your own data frame. + +| Name | Species | Needs internet | +|---|---|---| +| `"connectomedb2025"` | human, mouse, rat, pig | No | +| `"fantom5"` | human, mouse, rat, pig | No | +| `"omnipath"` | human, mouse, rat | Yes, plus OmnipathR | + +`create_NICHESObject()` has no default database, so always set `LRM.db`. Set +`species` to match your data. To look at a database first: + +```{r database} +db <- load_LRM_database("connectomedb2025", species = "mouse", verbose = FALSE) +nrow(db) +head(db[, c("ligand", "receptor")], 3) +``` + +### Your own database + +A custom data frame needs ligand and receptor columns. If they have other names, +set `ligand.col` and `receptor.col`. Multi-gene complexes are written with +underscores, and a pair is dropped if any of its genes is missing from the matrix. + +```{r custom} +my.db <- data.frame( + L = c("Gene1", "Gene3"), + R = c("Gene2", "Gene4_Gene5") +) +obj <- create_NICHESObject( + count.mtx = NICHESv2_inputs$count.mtx, + meta.data = NICHESv2_inputs$meta.data, + LRM.db = my.db, + ligand.col = "L", + receptor.col = "R", + mode = "spatial", + k = 5L, + verbose = FALSE +) +obj$LRM.list +``` + +## Seurat objects + +`extract_NICHESInputs_Seurat()` needs the SeuratObject package and reads both V4 +and V5 objects, so you don't need to update an older object first. It returns +`count.mtx` and `meta.data`. + +```{r seurat, eval = requireNamespace("SeuratObject", quietly = TRUE)} +seu <- SeuratObject::CreateSeuratObject( + counts = NICHESv2_inputs$count.mtx, + meta.data = NICHESv2_inputs$meta.data +) +inputs <- extract_NICHESInputs_Seurat( + seu, assay = "RNA", layer = "counts", verbose = FALSE +) +dim(inputs$count.mtx) +``` + +Spatial coordinates aren't copied automatically, because Seurat keeps them with +the image. For spatial objects, add them yourself, as shown in the +[spatial tutorial](spatial-tutorial.html): + +```{r seurat-coords, eval = FALSE} +coords <- SeuratObject::GetTissueCoordinates(seurat.obj) +inputs$meta.data$x <- coords[rownames(inputs$meta.data), "x"] +inputs$meta.data$y <- coords[rownames(inputs$meta.data), "y"] +``` + +## AnnData files + +`extract_NICHESInputs_AnnData()` reads `.h5ad` files through the rhdf5 package, so +Python isn't needed. `layer = "counts"` reads the counts layer, and `obs.cols` +limits which metadata columns are kept. + +```{r anndata, eval = requireNamespace("rhdf5", quietly = TRUE)} +h5ad <- system.file("extdata", "NICHESv2_example.h5ad", package = "NICHESv2") +inputs <- extract_NICHESInputs_AnnData(h5ad, layer = "counts", verbose = FALSE) +dim(inputs$count.mtx) +colnames(inputs$meta.data) +``` + +Install rhdf5 from Bioconductor: + +```{r rhdf5, eval = FALSE} +install.packages("BiocManager") +BiocManager::install("rhdf5") +``` diff --git a/vignettes/articles/niches-object.Rmd b/vignettes/articles/niches-object.Rmd new file mode 100644 index 0000000..110d3f4 --- /dev/null +++ b/vignettes/articles/niches-object.Rmd @@ -0,0 +1,168 @@ +--- +title: "The NICHESObject" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{The NICHESObject} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) +``` + +A NICHESObject is an S3 list with 15 slots, which you read with `$`. This guide +uses `NICHESv2_example`, a small spatial object with 80 synthetic cells. + +```{r load} +library(NICHESv2) +library(data.table) + +data(NICHESv2_example) +obj <- NICHESv2_example +dim(obj) +``` + +The object is a plain list, so functions return a changed copy. Always assign the +result back: `obj <- add_meta_column(obj, ...)`. + +## Why long format + +Most cell pairs carry no signal for most LR pairs. NICHESv2 stores only non-zero +values, in keyed `data.table`s with one row per value. Memory use then follows how +much signal exists, not how many combinations are possible. + +## Cell slots + +| Slot | Contents | +|---|---| +| `$cell.list` | Cell barcodes | +| `$cell.data` | Non-zero expression, one row per (cell, gene) | +| `$cell.meta` | One row per cell | + +```{r cell} +head(obj$cell.data, 3) +``` + +In `$cell.data`, `score` is the value you supplied, and `score.norm` is its share +of that cell's total. + +## Edge slots + +An edge is one directed cell pair, with an ID of the form +`"SendingCell|ReceivingCell"`. + +| Slot | Contents | +|---|---| +| `$edge.list` | One row per edge | +| `$edge.data` | Non-zero scores, one row per (edge, LRM) | +| `$edge.meta` | One row per edge, with both cells' metadata | + +```{r edge} +head(obj$edge.data, 3) +``` + +An LRM ID has the form `"ligand|receptor"`. With the default +`normalize.method = "prop"`, `score.norm` is that LRM's share of the edge's total +score. + +`$edge.meta` adds `Sending.` and `Receiving.` versions of each metadata column, +plus `Joint.` columns for text columns: + +```{r edge-meta} +obj$edge.meta[, .(edges = .N), by = Joint.celltype][order(-edges)][1:3] +``` + +## Neighborhood slots + +These are filled in when the object is built, and all three are indexed by cell. + +| Slot | Contents | +|---|---| +| `$neighborhood.cell.list` | Each cell's neighbors | +| `$neighborhood.edge.list` | The edges in each cell's neighborhood | +| `$neighborhood.meta` | Neighbor and edge counts per cell | + +```{r neighborhood} +head(obj$neighborhood.meta, 3) +``` + +By default, a neighborhood holds every edge whose two cells are both in that +neighborhood. `add_neighborhoods(overwrite = TRUE)` changes this: + +| `edge.filter.mode` | Edges kept for a focal cell | +|---|---| +| `"both_in_neighborhood"` (default) | Both cells are the focal cell or its neighbors | +| `"any_in_neighborhood"` | At least one cell is the focal cell or a neighbor | +| `"central_cell_only"` | One cell is the focal cell | + +## Gene and LRM slots + +| Slot | Contents | +|---|---| +| `$gene.list`, `$gene.meta` | Genes and any annotations | +| `$LRM.list`, `$LRM.meta` | LR pairs and their annotations | + +```{r lrm} +head(obj$LRM.meta, 3) +``` + +## Extras + +`$aggregations` starts empty and is filled by `aggregate_NICHESObject()`. +`$segmentation` holds optional cell polygons, added with `add_segmentation()`. + +## Attributes + +Four attributes record how the object was built: + +```{r attributes} +attr(obj, "mode") +attr(obj, "sample.col") +attr(obj, "edge.filter.mode") +attr(obj, "remove.autocrine") +``` + +## Changing metadata + +To add or change one column, use `add_meta_column()` with values named by barcode: + +```{r add-column} +region <- setNames( + ifelse(obj$cell.meta$x > 0.5, "right", "left"), + obj$cell.meta$cell +) +obj <- add_meta_column(obj, "region", region, verbose = FALSE) +obj$edge.meta[, .(edges = .N), by = Sending.region] +``` + +`add_cell_meta()` replaces the whole table, so any column you leave out is lost, +including coordinates. Use it only when you mean to replace everything. + +## Subsetting + +`obj[cells]` takes a vector of barcodes. Each kept cell keeps its neighborhood +entries and aggregation rows unchanged, while the edge slots keep only edges +between kept cells. + +```{r subset} +type.a <- obj$cell.meta[celltype == "TypeA", cell] +sub <- obj[type.a] +dim(sub) +``` + +The [aggregation guide](aggregation.html) explains how to work with subsets. + +## Merging + +`merge_NICHESObjects()` combines objects from separate runs. They must share a mode +and have no barcodes in common. The merged object has no neighborhoods or +aggregations, so run `add_neighborhoods()` afterward. To process several samples +in one step, use `sample.col` in `create_NICHESObject()` instead. diff --git a/vignettes/articles/nonspatial-tutorial.Rmd b/vignettes/articles/nonspatial-tutorial.Rmd new file mode 100644 index 0000000..e8d5891 --- /dev/null +++ b/vignettes/articles/nonspatial-tutorial.Rmd @@ -0,0 +1,179 @@ +--- +title: "Non-spatial tutorial: stimulated PBMCs" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Non-spatial tutorial: stimulated PBMCs} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + fig.width = 6, fig.height = 4, fig.align = "center", + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) +``` + +This tutorial runs NICHESv2 on scRNA-seq data with no spatial coordinates: 13,999 +human PBMCs, either untreated (`CTRL`) or stimulated with interferon-beta +(`STIM`). You'll score LR signaling between sampled cell pairs and compare the +two conditions. + +Without coordinates, nothing tells us which cells really touched. NICHESv2 +therefore samples cell pairs within each pair of cell types. Treat the results +as what cell types could signal to each other, not as observed contacts. + +With `n.cores = 2`, the slowest step takes about 1 minute and needs about 4 GB of +memory. + +## Get the data + +The dataset comes from [SeuratData](https://github.com/satijalab/seurat-data), +which isn't on CRAN. Run this once; the download is about 413 MB. SeuratData also +installs the Seurat package, so the first install can take a while. + +```{r install, eval = FALSE} +install.packages(c("remotes", "SeuratObject")) +remotes::install_github("satijalab/seurat-data") +SeuratData::InstallData("ifnb") +``` + +```{r load} +library(NICHESv2) +library(data.table) +library(ggplot2) +library(SeuratObject) +library(SeuratData) + +data("ifnb") +``` + +SeuratData objects keep the Seurat version they were saved with. +`extract_NICHESInputs_Seurat()` reads both V4 and V5 objects, so you don't need +to update them first. + +## Extract the inputs + +```{r extract} +inputs <- extract_NICHESInputs_Seurat( + seurat.obj = ifnb, + assay = "RNA", + layer = "counts", + verbose = FALSE +) +dim(inputs$count.mtx) + +table(inputs$meta.data$stim) +``` + +Two metadata columns matter here: `stim` holds the condition, and +`seurat_annotations` holds 13 cell types. + +## Build the NICHESObject + +`sample.col = "stim"` builds edges separately within each condition, so a `CTRL` +cell is never paired with a `STIM` cell. Set it whenever your data has several +samples, donors or conditions. `cell.type.col` is required in this mode, and the +sampling is repeatable through `seed`, which defaults to 42. + +```{r create} +obj <- create_NICHESObject( + count.mtx = inputs$count.mtx, + meta.data = inputs$meta.data, + LRM.db = "connectomedb2025", + species = "human", + mode = "nonspatial", + sample.col = "stim", + cell.type.col = "seurat_annotations", + method = "product", + n.cores = 2L, + verbose = FALSE +) +dim(obj) +``` + +Every edge stays within one condition: + +```{r edges-by-condition} +obj$edge.meta[, .(edges = .N), by = .(Sending.stim, Receiving.stim)] +``` + +## Compare the conditions + +`$edge.meta` carries the condition and cell type of both cells on every edge, so +it joins directly onto the scores. The two conditions have different numbers of +edges, so this divides each total by that number. + +```{r compare} +edge.info <- obj$edge.meta[, .( + edge, + stim = Sending.stim, + sender = Sending.seurat_annotations, + receiver = Receiving.seurat_annotations +)] +scores <- merge(obj$edge.data[, .(edge, LRM, score)], edge.info, by = "edge") + +n.edges <- edge.info[, .(n.edges = .N), by = stim] + +by.condition <- scores[, .(total = sum(score)), by = .(LRM, stim)] +by.condition <- merge(by.condition, n.edges, by = "stim") +by.condition[, mean.per.edge := total / n.edges] + +wide <- dcast(by.condition, LRM ~ stim, value.var = "mean.per.edge", fill = 0) +wide[, fold.change := (STIM + 0.01) / (CTRL + 0.01)] +wide[STIM > 0.5][order(-fold.change)][1:5] +``` + +Interferon-induced chemokines lead this list, which is what we'd expect from this +stimulation. Comparing raw scores between conditions is a simple first look, and +it doesn't correct for differences in sequencing depth. + +## Follow one signal + +CXCL10 is a classic interferon-induced chemokine, and CXCR3 is its receptor. This +finds the cell-type pairs that carry the strongest `CXCL10|CXCR3` signal after +stimulation. + +```{r one-lrm} +cxcl10 <- scores[LRM == "CXCL10|CXCR3" & stim == "STIM"] + +pair.edges <- edge.info[stim == "STIM", .(n.edges = .N), by = .(sender, receiver)] +by.pair <- merge( + cxcl10[, .(total = sum(score)), by = .(sender, receiver)], + pair.edges, + by = c("sender", "receiver") +) +by.pair[, mean.per.edge := total / n.edges] + +ggplot(by.pair, aes(receiver, sender, fill = mean.per.edge)) + + geom_tile() + + scale_fill_viridis_c(name = "Mean score\nper edge", trans = "sqrt") + + labs(x = "Receiving cell type", y = "Sending cell type", + title = "CXCL10|CXCR3 after stimulation") + + theme_minimal(base_size = 10) + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + panel.grid = element_blank()) +``` + +Dendritic cells and monocytes are the main senders, and CD8 T and NK cells are the +main receivers. Rare cell types such as `Eryth` rest on few edges, so read their +values with care. + +## What differs from spatial mode + +- `add_neighborhood_composition()` stops in this mode, because neighbor cell types + would only reflect the sampling. +- `add_neighborhood_edge_agg()` runs, but its neighbors are sampled partners, not + physical neighbors. +- `export_to_TissuePlex()` needs coordinates, so it applies to spatial data. + +## Data source + +The data are from Kang HM, Subramaniam M, Targ S, et al. Multiplexed droplet +single-cell RNA-sequencing using natural genetic variation. *Nat Biotechnol*. +2018;36(1):89-94 (GEO: GSE96583). Cell-type labels are from the Satija Lab. diff --git a/vignettes/articles/spatial-tutorial.Rmd b/vignettes/articles/spatial-tutorial.Rmd new file mode 100644 index 0000000..4198d45 --- /dev/null +++ b/vignettes/articles/spatial-tutorial.Rmd @@ -0,0 +1,238 @@ +--- +title: "Spatial tutorial: mouse brain" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Spatial tutorial: mouse brain} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, comment = "#>", message = FALSE, + fig.width = 6, fig.height = 4.6, fig.align = "center", + render = function(x, ...) { + if (data.table::is.data.table(x) && !data.table::shouldPrint(x)) return(invisible("")) + if (is.data.frame(x)) x <- knitr::kable(x, digits = 3, format.args = list(big.mark = ",")) + knitr::knit_print(x, ...) + } +) +``` + +This tutorial runs a full spatial analysis on a public 10x Visium section of the +mouse brain: one anterior sagittal slice with 2,696 spots. You'll score LR +signaling between neighboring spots, map a signal onto the tissue, and trace it +back to the spots that sent it. + +With `n.cores = 2`, the slowest step takes about 4 minutes. + +## Get the data + +The dataset comes from [SeuratData](https://github.com/satijalab/seurat-data), +which isn't on CRAN. Run this once; the download is about 143 MB. SeuratData also +installs the Seurat package, so the first install can take a while. + +```{r install, eval = FALSE} +install.packages(c("remotes", "SeuratObject")) +remotes::install_github("satijalab/seurat-data") +SeuratData::InstallData("stxBrain") +``` + +Then load it. `stxBrain` holds four sections, and we use `anterior1`. + +```{r load} +library(NICHESv2) +library(data.table) +library(ggplot2) +library(SeuratObject) +library(SeuratData) + +data("anterior1") +``` + +SeuratData objects keep the Seurat version they were saved with. +`extract_NICHESInputs_Seurat()` reads both V4 and V5 objects, so you don't need +to update them first. + +## Extract the inputs + +```{r extract} +inputs <- extract_NICHESInputs_Seurat( + seurat.obj = anterior1, + assay = "Spatial", + layer = "counts", + verbose = FALSE +) +dim(inputs$count.mtx) +``` + +Spatial coordinates sit in the image part of the Seurat object, so add them to +the metadata as `x` and `y`. Matching by barcode keeps every spot aligned. + +```{r coords} +coords <- GetTissueCoordinates(anterior1) +inputs$meta.data$x <- coords[rownames(inputs$meta.data), "x"] +inputs$meta.data$y <- coords[rownames(inputs$meta.data), "y"] +``` + +## Choose a neighborhood + +`Explore_Radius_Neighborhood()` shows how many neighbors each radius would give, +before you build anything. + +```{r radius, fig.height = 3.6} +radius.table <- Explore_Radius_Neighborhood( + inputs$meta.data[, c("x", "y")], + r.max = 800 +) +``` + +The curve rises in steps because Visium spots sit on a hexagonal grid. The first +step is the ring of 6 touching spots. This tutorial uses `k = 6`, which gives +those immediate neighbors. Passing `rad` instead would use a fixed radius. + +This is one tissue section, so `sample.col` isn't needed. Set it when your data +has several sections, so that no edges cross between them. + +## Build the NICHESObject + +Raw counts give scores on an absolute scale. With `"connectomedb2025"` you don't +need to download anything else, and `species` must match your data. + +```{r create} +obj <- create_NICHESObject( + count.mtx = inputs$count.mtx, + meta.data = inputs$meta.data, + LRM.db = "connectomedb2025", + species = "mouse", + mode = "spatial", + k = 6L, + method = "product", + n.cores = 2L, + verbose = FALSE +) +dim(obj) +``` + +There's one row in `$edge.data` for each non-zero (edge, LR pair) score: + +```{r edge-data} +nrow(obj$edge.data) +head(obj$edge.data, 3) +``` + +## Find the strongest signals + +Summing across all edges shows which LR pairs dominate. Abundant genes rise to +the top, as they do with any magnitude-based score on raw counts. + +```{r top} +obj$edge.data[, .(total.score = sum(score), edges = .N), by = LRM][ + order(-total.score)][1:5] +``` + +## Aggregate by neighborhood + +```{r aggregate} +obj <- aggregate_NICHESObject(obj, verbose = FALSE) +agg <- obj$aggregations$neighborhood.edge.agg +``` + +This dataset has no cell-type labels, so we leave out `cell.type.col` and skip +the composition table. + +## Map a signal onto the tissue + +`Penk|Ogfr` is a useful example, because *Penk* is strongly enriched in the +striatum. `score.in.sum` adds up everything a spot receives from its neighbors +for this LR pair. + +```{r map} +one.lrm <- agg[LRM == "Penk|Ogfr", .(cell, score.in.sum)] + +plot.dt <- merge( + obj$cell.meta[, .(cell, x, y)], + one.lrm, + by = "cell", all.x = TRUE +) +plot.dt[is.na(score.in.sum), score.in.sum := 0] + +ggplot(plot.dt[order(score.in.sum)], aes(y, x, color = score.in.sum)) + + geom_point(size = 0.9) + + scale_x_continuous(NULL, labels = NULL) + + scale_y_reverse(NULL, labels = NULL) + + scale_color_viridis_c(name = "Received", trans = "sqrt") + + coord_equal() + + labs(title = "Penk|Ogfr signal received per spot") + + theme_minimal(base_size = 11) + + theme(panel.grid = element_blank()) +``` + +## Trace a signal back to its senders + +Because every edge is stored, you can see which neighbors sent the signal to the +strongest receiver. `share` is each sender's part of the total. + +```{r trace} +receiver <- one.lrm[which.max(score.in.sum), cell] + +senders <- merge( + obj$edge.data[LRM == "Penk|Ogfr", .(edge, score)], + obj$edge.list[ReceivingCell == receiver & SendingCell != receiver], + by = "edge" +) +senders[, share := score / sum(score)] +senders[order(-score), .(SendingCell, score, share)] +``` + +```{r trace-plot, fig.height = 4} +spots <- obj$cell.meta[, .(cell, x, y)] +center <- spots[cell == receiver] +nearby <- spots[abs(x - center$x) < 450 & abs(y - center$y) < 450] + +arrows <- merge(senders, spots, by.x = "SendingCell", by.y = "cell") +arrows[, `:=`(x.end = x + 0.7 * (center$x - x), + y.end = y + 0.7 * (center$y - y))] + +ggplot() + + geom_point(data = nearby, aes(y, x), color = "grey85", size = 7) + + geom_point(data = center, aes(y, x), color = "black", size = 7) + + geom_segment( + data = arrows, + aes(x = y, y = x, xend = y.end, yend = x.end, linewidth = score), + color = "#1f7a8c", + arrow = arrow(length = unit(2.5, "mm"), type = "closed") + ) + + scale_linewidth(range = c(0.4, 2), name = "Score") + + scale_x_continuous(NULL, labels = NULL) + + scale_y_reverse(NULL, labels = NULL) + + coord_equal() + + labs(title = "Who sends Penk|Ogfr to the top receiver (black)") + + theme_minimal(base_size = 11) + + theme(panel.grid = element_blank()) +``` + +All of these edges share one receiver, so the differences come only from how much +*Penk* each neighbor expresses. Two neighbors supply more than half of the signal. + +## Export the edges + +`export_to_TissuePlex()` needs the arrow package and writes one Parquet file. + +```{r export} +out.file <- file.path(tempdir(), "edges.parquet") +export_to_TissuePlex(obj, output.path = out.file, celltype.col = NULL) +round(file.size(out.file) / 1e6) +``` + +The [export guide](tissueplex-export.html) shows what to do with that file. + +```{r cleanup, include = FALSE} +unlink(out.file) +``` + +## Data source + +The data are from 10x Genomics, "Mouse Brain Serial Section 1 (Sagittal-Anterior)", +Space Ranger 1.0.0, licensed under +[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). diff --git a/vignettes/articles/tissueplex-export.Rmd b/vignettes/articles/tissueplex-export.Rmd new file mode 100644 index 0000000..79a050c --- /dev/null +++ b/vignettes/articles/tissueplex-export.Rmd @@ -0,0 +1,59 @@ +--- +title: "Exporting to TissuePlex" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Exporting to TissuePlex} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) +``` + +[TissuePlex](https://github.com/RaredonLab/TissuePlex) is an interactive viewer +that draws cell-cell communication on the tissue image. NICHESv2's part ends with +one file, `edges.parquet`, which TissuePlex reads as an edge layer. + +## Write the file + +`export_to_TissuePlex()` needs the arrow package and a spatial object. Set +`celltype.col` to your cell type column, or `NULL` if you don't have one. + +```{r export, eval = requireNamespace("arrow", quietly = TRUE)} +library(NICHESv2) + +data(NICHESv2_example) + +out.file <- file.path(tempdir(), "edges.parquet") +export_to_TissuePlex( + NICHESv2_example, + output.path = out.file, + celltype.col = "celltype" +) +``` + +Every edge in `$edge.list` is written. Edges with signal get one row per LR pair, +and edges with no signal get one placeholder row, so TissuePlex can still draw the +full tissue graph. + +If your coordinates aren't in columns named `x` and `y`, set `x.col` and `y.col`. + +```{r cleanup, include = FALSE, eval = requireNamespace("arrow", quietly = TRUE)} +unlink(out.file) +``` + +Exporting a subset writes only the edges between kept cells. + +## View it in TissuePlex + +Save the file as `edges.parquet` next to your dataset, then follow the TissuePlex +documentation from there: + +- [User manual](https://raredonlab.github.io/TissuePlex/): installation and + loading your data. +- [Worked examples](https://raredonlab.github.io/TissuePlex/vignettes.html): + full walkthroughs. + +TissuePlex needs your platform's own output files as well, such as the tissue +image. These come from your data, not from NICHESv2. diff --git a/working-scripts-NW/score_fingerprints.R b/working-scripts-NW/score_fingerprints.R index 89bb2c6..f91e0a4 100644 --- a/working-scripts-NW/score_fingerprints.R +++ b/working-scripts-NW/score_fingerprints.R @@ -83,14 +83,7 @@ i.ns <- suppressMessages(create_NICHESObject( obj_tables("ifnb", i.ns) i.ag <- suppressMessages(aggregate_NICHESObject(i.ns, verbose = FALSE)) rec("ifnb", "neighborhood.edge.agg", i.ag$aggregations$neighborhood.edge.agg) -i.pb <- suppressMessages(compute_PseudoBulk_Connectivity( - count.mtx = i$count.mtx, meta.data = i$meta.data, - LRM.db = load_LRM_database("connectomedb2025", species = "human"), - cell.type.col = "seurat_annotations", method = "product", - n.cores = 2L, verbose = FALSE -)) -rec("ifnb", "pseudobulk", i.pb) -rm(ifnb, i, i.ns, i.ag, i.pb); invisible(gc()) +rm(ifnb, i, i.ns, i.ag); invisible(gc()) ## stxBrain -------------------------------------------------------------------- data("anterior1", envir = environment()) diff --git a/working-scripts-NW/score_fingerprints_after_pseudobulk_removal.txt b/working-scripts-NW/score_fingerprints_after_pseudobulk_removal.txt new file mode 100644 index 0000000..ffe68d9 --- /dev/null +++ b/working-scripts-NW/score_fingerprints_after_pseudobulk_removal.txt @@ -0,0 +1,17 @@ +bundled edge.list 354 185318cc123b142ee53f1ffb906fe405 +bundled edge.data 190 11648813f23c292f68f7002640c6a513 +bundled cell.data 885 c8a32a2f62cbac8fca56cbdcdb344ff7 +bundled neighborhood.edge.agg 399 7942ca4b9cc7673d652c7e2c202a0983 +bundled neighborhood.composition 80 8570be24df15564250c1353d5483071c +bundled nonspatial.edge.list 230 7e725b52ac7c95b3d822781c3e591d88 +bundled nonspatial.edge.data 123 494118d98f595b1f5e11d0add2b0561e +bundled explore.radius 50 c7e9775be5068c9197fe95a94ffec41d +ifnb edge.list 87957 c12584448474811a38c04db9094c1d5d +ifnb edge.data 605973 b2a18456f9a62ad818fa272daadc463a +ifnb cell.data 9787436 66517f6a9f5844b566e5db3d77fc8597 +ifnb neighborhood.edge.agg 548303 1869970c5c93ab2965d89fce2402b073 +stxBrain explore.radius 50 94cf6d5fe20d5fda203ed2925ee7c3a6 +stxBrain edge.list 18500 8f22826cd3887d6fed85424408955c35 +stxBrain edge.data 5191520 aea90bdffab368a933a1ca1ddb5b7214 +stxBrain cell.data 15319170 a218da758486f8887dc3f802584167f8 +stxBrain neighborhood.edge.agg 2363923 21da5597a0cc5cacc8d4c19520b044dc diff --git a/working-scripts-NW/score_fingerprints_after_tutorials.txt b/working-scripts-NW/score_fingerprints_after_tutorials.txt new file mode 100644 index 0000000..23338d2 --- /dev/null +++ b/working-scripts-NW/score_fingerprints_after_tutorials.txt @@ -0,0 +1,18 @@ +bundled edge.list 354 185318cc123b142ee53f1ffb906fe405 +bundled edge.data 190 11648813f23c292f68f7002640c6a513 +bundled cell.data 885 c8a32a2f62cbac8fca56cbdcdb344ff7 +bundled neighborhood.edge.agg 399 7942ca4b9cc7673d652c7e2c202a0983 +bundled neighborhood.composition 80 8570be24df15564250c1353d5483071c +bundled nonspatial.edge.list 230 7e725b52ac7c95b3d822781c3e591d88 +bundled nonspatial.edge.data 123 494118d98f595b1f5e11d0add2b0561e +bundled explore.radius 50 c7e9775be5068c9197fe95a94ffec41d +ifnb edge.list 87957 c12584448474811a38c04db9094c1d5d +ifnb edge.data 605973 b2a18456f9a62ad818fa272daadc463a +ifnb cell.data 9787436 66517f6a9f5844b566e5db3d77fc8597 +ifnb neighborhood.edge.agg 548303 1869970c5c93ab2965d89fce2402b073 +ifnb pseudobulk 81621 a4d65265b6350c213f2d86344730fabf +stxBrain explore.radius 50 94cf6d5fe20d5fda203ed2925ee7c3a6 +stxBrain edge.list 18500 8f22826cd3887d6fed85424408955c35 +stxBrain edge.data 5191520 aea90bdffab368a933a1ca1ddb5b7214 +stxBrain cell.data 15319170 a218da758486f8887dc3f802584167f8 +stxBrain neighborhood.edge.agg 2363923 21da5597a0cc5cacc8d4c19520b044dc diff --git a/working-scripts-NW/score_fingerprints_baseline.txt b/working-scripts-NW/score_fingerprints_baseline.txt index 23338d2..ffe68d9 100644 --- a/working-scripts-NW/score_fingerprints_baseline.txt +++ b/working-scripts-NW/score_fingerprints_baseline.txt @@ -10,7 +10,6 @@ ifnb edge.list 87957 c12584448474811a38c04db9094c1d5d ifnb edge.data 605973 b2a18456f9a62ad818fa272daadc463a ifnb cell.data 9787436 66517f6a9f5844b566e5db3d77fc8597 ifnb neighborhood.edge.agg 548303 1869970c5c93ab2965d89fce2402b073 -ifnb pseudobulk 81621 a4d65265b6350c213f2d86344730fabf stxBrain explore.radius 50 94cf6d5fe20d5fda203ed2925ee7c3a6 stxBrain edge.list 18500 8f22826cd3887d6fed85424408955c35 stxBrain edge.data 5191520 aea90bdffab368a933a1ca1ddb5b7214 diff --git a/working-scripts-NW/score_fingerprints_baseline_with_pseudobulk.txt b/working-scripts-NW/score_fingerprints_baseline_with_pseudobulk.txt new file mode 100644 index 0000000..23338d2 --- /dev/null +++ b/working-scripts-NW/score_fingerprints_baseline_with_pseudobulk.txt @@ -0,0 +1,18 @@ +bundled edge.list 354 185318cc123b142ee53f1ffb906fe405 +bundled edge.data 190 11648813f23c292f68f7002640c6a513 +bundled cell.data 885 c8a32a2f62cbac8fca56cbdcdb344ff7 +bundled neighborhood.edge.agg 399 7942ca4b9cc7673d652c7e2c202a0983 +bundled neighborhood.composition 80 8570be24df15564250c1353d5483071c +bundled nonspatial.edge.list 230 7e725b52ac7c95b3d822781c3e591d88 +bundled nonspatial.edge.data 123 494118d98f595b1f5e11d0add2b0561e +bundled explore.radius 50 c7e9775be5068c9197fe95a94ffec41d +ifnb edge.list 87957 c12584448474811a38c04db9094c1d5d +ifnb edge.data 605973 b2a18456f9a62ad818fa272daadc463a +ifnb cell.data 9787436 66517f6a9f5844b566e5db3d77fc8597 +ifnb neighborhood.edge.agg 548303 1869970c5c93ab2965d89fce2402b073 +ifnb pseudobulk 81621 a4d65265b6350c213f2d86344730fabf +stxBrain explore.radius 50 94cf6d5fe20d5fda203ed2925ee7c3a6 +stxBrain edge.list 18500 8f22826cd3887d6fed85424408955c35 +stxBrain edge.data 5191520 aea90bdffab368a933a1ca1ddb5b7214 +stxBrain cell.data 15319170 a218da758486f8887dc3f802584167f8 +stxBrain neighborhood.edge.agg 2363923 21da5597a0cc5cacc8d4c19520b044dc diff --git a/working-scripts-NW/score_fingerprints_before_push.txt b/working-scripts-NW/score_fingerprints_before_push.txt new file mode 100644 index 0000000..ffe68d9 --- /dev/null +++ b/working-scripts-NW/score_fingerprints_before_push.txt @@ -0,0 +1,17 @@ +bundled edge.list 354 185318cc123b142ee53f1ffb906fe405 +bundled edge.data 190 11648813f23c292f68f7002640c6a513 +bundled cell.data 885 c8a32a2f62cbac8fca56cbdcdb344ff7 +bundled neighborhood.edge.agg 399 7942ca4b9cc7673d652c7e2c202a0983 +bundled neighborhood.composition 80 8570be24df15564250c1353d5483071c +bundled nonspatial.edge.list 230 7e725b52ac7c95b3d822781c3e591d88 +bundled nonspatial.edge.data 123 494118d98f595b1f5e11d0add2b0561e +bundled explore.radius 50 c7e9775be5068c9197fe95a94ffec41d +ifnb edge.list 87957 c12584448474811a38c04db9094c1d5d +ifnb edge.data 605973 b2a18456f9a62ad818fa272daadc463a +ifnb cell.data 9787436 66517f6a9f5844b566e5db3d77fc8597 +ifnb neighborhood.edge.agg 548303 1869970c5c93ab2965d89fce2402b073 +stxBrain explore.radius 50 94cf6d5fe20d5fda203ed2925ee7c3a6 +stxBrain edge.list 18500 8f22826cd3887d6fed85424408955c35 +stxBrain edge.data 5191520 aea90bdffab368a933a1ca1ddb5b7214 +stxBrain cell.data 15319170 a218da758486f8887dc3f802584167f8 +stxBrain neighborhood.edge.agg 2363923 21da5597a0cc5cacc8d4c19520b044dc diff --git a/working-scripts-NW/v1_facts_sheet.md b/working-scripts-NW/v1_facts_sheet.md index 4fe3660..c39d587 100644 --- a/working-scripts-NW/v1_facts_sheet.md +++ b/working-scripts-NW/v1_facts_sheet.md @@ -11,17 +11,18 @@ first. - Version 1.0.0. License MIT. R >= 4.1.0. - Authors: Nuoya Wang (maintainer), Micha Sam Brickman Raredon. - Repository: https://github.com/RaredonLab/NICHESv2 -- Install today: `remotes::install_github("RaredonLab/NICHESv2", ref = "dev")`. +- Install today: `remotes::install_github("RaredonLab/NICHESv2", ref = "main")`, + which works once dev is merged into main. Change to `install.packages("NICHESv2")` after CRAN acceptance. - Imports: data.table, Matrix, methods, RANN, dbscan, ggplot2, parallel, stats, utils. - Suggests: SeuratObject, rhdf5, OmnipathR, arrow, testthat, withr, sf, knitr, rmarkdown. -- 22 exported functions. S3 methods: `[`, `dim`, `length`, `print`, `summary`. +- 20 exported functions. S3 methods: `[`, `dim`, `length`, `print`, `summary`. ## Not known yet -- Website URL, Zenodo DOIs, paper title and citation. +- Website URL, the Zenodo code archive DOI, paper title and citation. - Do not write these into any document until they exist. ## Analysis modes @@ -32,8 +33,6 @@ first. - `mode = "nonspatial"`: type-stratified random sampling. Requires `cell.type.col`. `seed` defaults to 42. `max.cells` defaults to `NULL`. - There is no `"sampled"` mode. That name was removed. -- Pseudobulk is not a mode. `compute_PseudoBulk_Connectivity()` returns a - `data.table`, not a NICHESObject. ## Scoring @@ -122,8 +121,18 @@ Runs below used raw counts, `method = "product"`, the default database and | Aggregate | about 12 s | not run | | TissuePlex export | about 4 s | not run | -- `stxBrain` needs `assay = "Spatial"`. Spatial coordinates must be added to the - metadata by hand before `create_NICHESObject()`. +- Both datasets come from SeuratData, which isn't on CRAN. NICHESv2 hosts no + data. Install with `remotes::install_github("satijalab/seurat-data")`, then + `SeuratData::InstallData("stxBrain")` and `SeuratData::InstallData("ifnb")`. + SeuratData imports Seurat, so installing it also installs Seurat. NICHESv2 + itself only needs SeuratObject to read Seurat objects. SeuratData stays out of + `DESCRIPTION`. +- `UpdateSeuratObject()` is not needed. `extract_NICHESInputs_Seurat()` gives + identical results with or without it on both datasets (SeuratObject 5.0.2 and + 5.1.0). SeuratData objects keep their own Seurat version: `ifnb` is a V4-style + `Assay` and `anterior1` is `Assay5`. +- `stxBrain` needs `assay = "Spatial"`. Add coordinates to the metadata with + `SeuratObject::GetTissueCoordinates()`, which returns `x`, `y` and `cell`. - `stxBrain` has no cell-type labels, so composition needs labels from the user. - `ifnb` has 13 cell types with no missing labels. Conditions: CTRL 6,548 cells, STIM 7,451 cells. @@ -132,6 +141,22 @@ Runs below used raw counts, `method = "product"`, the default database and cores took 62 s, with a 421 MB object and 3.7 GB peak memory. - Never use the PPLR data. It is private. +### Licenses, checked 2026-11-02 + +- `stxBrain` anterior1 is the 10x Genomics dataset "Mouse Brain Serial Section 1 + (Sagittal-Anterior)", Space Ranger 1.0.0, under CC BY 4.0. Any copy must credit + 10x Genomics, link to the license and state what was changed. +- `ifnb` comes from Kang et al., Nat Biotechnol 2018;36(1):89-94 (GSE96583), with + cell-type labels added by the Satija Lab. The `ifnb.SeuratData` package is + labeled CC BY 4.0, but no license from the original authors was found. + +## TissuePlex + +- NICHESv2 stops at the exported `edges.parquet` file. +- Viewing is covered by the TissuePlex manual, so link to it rather than repeat + it: https://raredonlab.github.io/TissuePlex/ +- Worked examples: https://raredonlab.github.io/TissuePlex/vignettes.html + ## Wording - US spelling in all prose. Keep published titles as printed.