diff --git a/.Rbuildignore b/.Rbuildignore index a658719..03f5131 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -14,6 +14,7 @@ ^vignettes/spatial_differential_expression\.Rmd$ ^vignettes/spatial_enrichment_gradients_smi\.Rmd$ ^vignettes/troubleshooting\.Rmd$ +^vignettes/ondisk_stlists\.Rmd$ ^vignettes/img/spatial_gradients\.png$ ^vignettes/img/diagram_stenrich\.png$ ^vignettes/img/smi_dir_structure\.png$ diff --git a/.Rproj.user/49367F05/compilation-database/config.json b/.Rproj.user/49367F05/compilation-database/config.json deleted file mode 100644 index 8d71251..0000000 --- a/.Rproj.user/49367F05/compilation-database/config.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "args": [ - "-std=gnu++17", - "-I/Library/Frameworks/R.framework/Resources/include", - "-DNDEBUG", - "-I/opt/R/x86_64/include", - "-fPIC", - "-falign-functions=64", - "-I/Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/library/Rcpp/include", - "-I/Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/library/RcppEigen/include", - "-I/Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/library/RcppProgress/include", - "-DEIGEN_DONT_VECTORIZE", - "-I/Library/Developer/CommandLineTools/usr/lib/clang/17.0.0/include", - "-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1", - "-I/Library/Developer/CommandLineTools/usr/lib/clang/17/include", - "-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include", - "-I/Library/Developer/CommandLineTools/usr/include" - ], - "pch": "RcppEigen", - "is_cpp": true, - "hash": "1746237639", - "compiler": "289486678855857406", - "rversion": "4.5.0", - "dbversion": 4 -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/cpp-definition-cache b/.Rproj.user/49367F05/cpp-definition-cache deleted file mode 100644 index 0cc7ccd..0000000 --- a/.Rproj.user/49367F05/cpp-definition-cache +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "file": "/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/src/seurat_helpers.cpp", - "file_last_write": 1746237613.0, - "definitions": [ - { - "usr": "c:@F@SparseRowVar2#$@N@Eigen@S@SparseMatrix>#d#VI0#I#$@N@Rcpp@S@Vector>#VI14#@N@Rcpp@ST>1#T@PreserveStorage#", - "kind": 6, - "parent_name": "", - "name": "SparseRowVar2(Eigen::SparseMatrix, NumericVector)", - "file": "/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/src/seurat_helpers.cpp", - "line": 27, - "column": 15, - "hidden": false - }, - { - "usr": "c:@F@SparseRowVarStd#$@N@Eigen@S@SparseMatrix>#d#VI0#I#$@N@Rcpp@S@Vector>#VI14#@N@Rcpp@ST>1#T@PreserveStorage#S1_#d#", - "kind": 6, - "parent_name": "", - "name": "SparseRowVarStd(Eigen::SparseMatrix, NumericVector, NumericVector, double)", - "file": "/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/src/seurat_helpers.cpp", - "line": 47, - "column": 15, - "hidden": false - } - ], - "hidden": false - }, - { - "file": "/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/src/spatialge_helpers.cpp", - "file_last_write": 1746237613.0, - "definitions": [ - { - "usr": "c:@F@computeSubsampleSums#$@N@Rcpp@S@Matrix>#VI14#@N@Rcpp@ST>1#T@PreserveStorage#I#I#", - "kind": 6, - "parent_name": "", - "name": "computeSubsampleSums(NumericMatrix, int, int)", - "file": "/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/src/spatialge_helpers.cpp", - "line": 16, - "column": 15, - "hidden": false - } - ], - "hidden": false - } -] \ No newline at end of file diff --git a/.Rproj.user/49367F05/pcs/files-pane.pper b/.Rproj.user/49367F05/pcs/files-pane.pper deleted file mode 100644 index dd71bf8..0000000 --- a/.Rproj.user/49367F05/pcs/files-pane.pper +++ /dev/null @@ -1,9 +0,0 @@ -{ - "sortOrder": [ - { - "columnIndex": 2, - "ascending": true - } - ], - "path": "~/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/vignettes" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/pcs/source-pane.pper b/.Rproj.user/49367F05/pcs/source-pane.pper deleted file mode 100644 index a528f3b..0000000 --- a/.Rproj.user/49367F05/pcs/source-pane.pper +++ /dev/null @@ -1,3 +0,0 @@ -{ - "activeTab": -1 -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/pcs/windowlayoutstate.pper b/.Rproj.user/49367F05/pcs/windowlayoutstate.pper deleted file mode 100644 index 3c3c3ed..0000000 --- a/.Rproj.user/49367F05/pcs/windowlayoutstate.pper +++ /dev/null @@ -1,14 +0,0 @@ -{ - "left": { - "splitterpos": 246, - "topwindowstate": "HIDE", - "panelheight": 952, - "windowheight": 990 - }, - "right": { - "splitterpos": 596, - "topwindowstate": "NORMAL", - "panelheight": 952, - "windowheight": 990 - } -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/pcs/workbench-pane.pper b/.Rproj.user/49367F05/pcs/workbench-pane.pper deleted file mode 100644 index 75e70e9..0000000 --- a/.Rproj.user/49367F05/pcs/workbench-pane.pper +++ /dev/null @@ -1,5 +0,0 @@ -{ - "TabSet1": 0, - "TabSet2": 0, - "TabZoom": {} -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/rmd-outputs b/.Rproj.user/49367F05/rmd-outputs deleted file mode 100644 index 3f2ff2d..0000000 --- a/.Rproj.user/49367F05/rmd-outputs +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/.Rproj.user/49367F05/saved_source_markers b/.Rproj.user/49367F05/saved_source_markers deleted file mode 100644 index 2b1bef1..0000000 --- a/.Rproj.user/49367F05/saved_source_markers +++ /dev/null @@ -1 +0,0 @@ -{"active_set":"","sets":[]} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/1975183C b/.Rproj.user/49367F05/sources/prop/1975183C deleted file mode 100644 index 3091763..0000000 --- a/.Rproj.user/49367F05/sources/prop/1975183C +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "287,12", - "scrollLine": "286" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/3657603E b/.Rproj.user/49367F05/sources/prop/3657603E deleted file mode 100644 index 350bfff..0000000 --- a/.Rproj.user/49367F05/sources/prop/3657603E +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "129,4", - "scrollLine": "93" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/4A59D713 b/.Rproj.user/49367F05/sources/prop/4A59D713 deleted file mode 100644 index 66986e8..0000000 --- a/.Rproj.user/49367F05/sources/prop/4A59D713 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "24,60", - "scrollLine": "9" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/4B68EA1E b/.Rproj.user/49367F05/sources/prop/4B68EA1E deleted file mode 100644 index d0cf829..0000000 --- a/.Rproj.user/49367F05/sources/prop/4B68EA1E +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "28,4", - "scrollLine": "22" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/6F08B49A b/.Rproj.user/49367F05/sources/prop/6F08B49A deleted file mode 100644 index 3dcbf75..0000000 --- a/.Rproj.user/49367F05/sources/prop/6F08B49A +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "17,4", - "scrollLine": "0" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/75F04464 b/.Rproj.user/49367F05/sources/prop/75F04464 deleted file mode 100644 index e61cdff..0000000 --- a/.Rproj.user/49367F05/sources/prop/75F04464 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "33,12", - "scrollLine": "20" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/8FEB9822 b/.Rproj.user/49367F05/sources/prop/8FEB9822 deleted file mode 100644 index 08b9b84..0000000 --- a/.Rproj.user/49367F05/sources/prop/8FEB9822 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "33,4", - "scrollLine": "25" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/A1E52161 b/.Rproj.user/49367F05/sources/prop/A1E52161 deleted file mode 100644 index 1d51ce3..0000000 --- a/.Rproj.user/49367F05/sources/prop/A1E52161 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "94,18", - "scrollLine": "79" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/B9CDD1AC b/.Rproj.user/49367F05/sources/prop/B9CDD1AC deleted file mode 100644 index 51880ae..0000000 --- a/.Rproj.user/49367F05/sources/prop/B9CDD1AC +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "25,4", - "scrollLine": "24" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/DA253F8D b/.Rproj.user/49367F05/sources/prop/DA253F8D deleted file mode 100644 index 88c4d73..0000000 --- a/.Rproj.user/49367F05/sources/prop/DA253F8D +++ /dev/null @@ -1,6 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source", - "cursorPosition": "27,12", - "scrollLine": "18" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/E92354B8 b/.Rproj.user/49367F05/sources/prop/E92354B8 deleted file mode 100644 index bb27690..0000000 --- a/.Rproj.user/49367F05/sources/prop/E92354B8 +++ /dev/null @@ -1,4 +0,0 @@ -{ - "source_window_id": "", - "Source": "Source" -} \ No newline at end of file diff --git a/.Rproj.user/49367F05/sources/prop/INDEX b/.Rproj.user/49367F05/sources/prop/INDEX deleted file mode 100644 index e6d75eb..0000000 --- a/.Rproj.user/49367F05/sources/prop/INDEX +++ /dev/null @@ -1,11 +0,0 @@ -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2FSTList.R="3657603E" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2FSTclust.R="75F04464" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2FSThet.R="4B68EA1E" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2FSTplot.R="8FEB9822" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2FSTplot_interpolation.R="6F08B49A" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2Fgene_interpolation.R="B9CDD1AC" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2Fplot_counts.R="DA253F8D" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2Ftransform_data.R="4A59D713" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2FR%2Futils.R="1975183C" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2Fman%2Ftransform_data.Rd="E92354B8" -~%2FLibrary%2FCloudStorage%2FOneDrive-JohnsHopkins%2FspatialGE%2Fvignettes%2Fbasic_functions_vignette.Rmd="A1E52161" diff --git a/.Rproj.user/shared/notebooks/A3E0EAE6-basic_functions_vignette/1/s/chunks.json b/.Rproj.user/shared/notebooks/A3E0EAE6-basic_functions_vignette/1/s/chunks.json deleted file mode 100644 index 6a69836..0000000 --- a/.Rproj.user/shared/notebooks/A3E0EAE6-basic_functions_vignette/1/s/chunks.json +++ /dev/null @@ -1 +0,0 @@ -{"chunk_definitions":[],"doc_write_time":1748961339} \ No newline at end of file diff --git a/.Rproj.user/shared/notebooks/patch-chunk-names b/.Rproj.user/shared/notebooks/patch-chunk-names deleted file mode 100644 index e69de29..0000000 diff --git a/.Rproj.user/shared/notebooks/paths b/.Rproj.user/shared/notebooks/paths deleted file mode 100644 index 6dd6249..0000000 --- a/.Rproj.user/shared/notebooks/paths +++ /dev/null @@ -1,11 +0,0 @@ -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/STList.R="8FAA077C" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/STclust.R="FDFB6A6D" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/SThet.R="97589441" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/STplot.R="523FE6C8" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/STplot_interpolation.R="CF7EFCAA" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/gene_interpolation.R="518AF655" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/plot_counts.R="6711BDE4" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/transform_data.R="560847FA" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/R/utils.R="29572367" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/man/transform_data.Rd="96A36EB5" -/Users/oospina1/Library/CloudStorage/OneDrive-JohnsHopkins/spatialGE/vignettes/basic_functions_vignette.Rmd="A3E0EAE6" diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 78d7a5b..8856336 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -44,10 +44,29 @@ Rscript -e 'cat(curlGetHeaders("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/FridleyLab/spatialGE_Data/raw and regenerates `tests/golden/` (via `dev/baseline/capture_baseline.R`) in the same commit -- see the "Regression / baseline workflow" section of `dev/ARCHITECTURE.md`. -- Do not run `devtools::document()`. Installed roxygen2 is newer than - `RoxygenNote` in `DESCRIPTION`; regenerating would churn all of `man/` and - `NAMESPACE` and bury the real diff. If an `.Rd` genuinely needs to change, - hand-edit it and say so in the commit message. +- `devtools::document()` is now safe to run, and is the way to change an `.Rd`. + It previously was not: several `.Rd` files had been hand-edited beyond their + roxygen sources, so regenerating *deleted* documented behavior -- the + `@details` and `@seealso` of `STlist_to_disk`, `STlist_to_memory`, `is_backed`, + `validate_store` and `as_Seurat`. Those paragraphs now live in the roxygen + blocks, so a regeneration round-trips. Do not hand-edit an `.Rd` any more: + that is what created the divergence. + + Two things a `document()` run must not undo, both checked by CI: + + - **`importFrom(methods, .hasSlot)`.** `R/stlist_readers.R` calls it on a + Seurat image slot. The call is conditional and `SeuratObject` is only in + Suggests, so roxygen can drop the import with no other symptom. It is + declared on `color_parse()` in `R/utils.R` for that reason. + - **`S3method(base::print, sge_manifest)`.** A bare `@export` on + `print.sge_manifest` makes roxygen2 >= 8 emit `export(print.sge_manifest)` + instead, which leaves `print()` on a manifest undispatched unless the + package happens to be attached. The tag is `@exportS3Method base::print`. + + roxygen2 8 also replaced `RoxygenNote` with `Config/roxygen2/version` in + `DESCRIPTION`, and writes multi-symbol imports one per line. The second broke + the first version of the `.hasSlot` CI guard, which grepped for the + single-line form; it now asks `parseNamespaceFile()` instead. ## Failing gracefully (package-wide requirement) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 02c729a..ad44e4a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -69,3 +69,114 @@ jobs: options(spatialGE.psock = TRUE) devtools::test(stop_on_failure = TRUE) shell: Rscript {0} + + # Three of the four vignettes are in .Rbuildignore, so R CMD check never + # builds them and devtools::test() never reads them: a chunk calling an + # exported function with an argument that no longer exists can sit there + # indefinitely. This parses every vignette's code and validates argument + # names against the formals, without evaluating anything. + - name: Vignette argument check + run: Rscript dev/ci/check_vignette_args.R + + # roxygen2 8.x silently DROPS importFrom(methods,.hasSlot) when it + # regenerates NAMESPACE, even though .hasSlot is exported from methods and + # is used in R/stlist_readers.R (image handling). Regenerating docs with a + # newer roxygen therefore removes the import and breaks that path at + # runtime, with no error until a sample with images is read. Guard it. + - name: NAMESPACE import guard + # Asks R's own namespace parser instead of grepping. The previous version + # matched the literal line `importFrom(methods,.hasSlot)` that roxygen2 7 + # wrote; roxygen2 8 writes multi-symbol imports one symbol per line, so + # the grep began failing on a NAMESPACE that was in fact correct. + run: | + Rscript -e 'nd <- parseNamespaceFile("spatialGE", "..", mustExist = TRUE); + ok <- any(vapply(nd$imports, function(i) + is.list(i) && identical(i[[1]], "methods") && ".hasSlot" %in% i[[2]], + logical(1))); + if (!ok) stop("NAMESPACE no longer imports methods::.hasSlot. R/stlist_readers.R calls it on a Seurat image slot; that call is conditional, so the import can be dropped with no other symptom.")' + shell: bash + + ## The `test` job above installs Imports only, which is deliberate: the committed + ## tier must pass without any Suggests. The side effect is that anything gated by + ## skip_if_not_installed() passes *by not running*. Today that is the whole of + ## tests/testthat/test-seurat-interop.R -- i.e. as_Seurat() and Seurat v5 input, + ## the headline features added in 2.0.0 -- so this job installs the Suggests and + ## fails if those tests skip. + test-full-suggests: + runs-on: ubuntu-latest + name: full Suggests (interop must not skip) + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: '4.5.3' + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + dependencies: '"all"' + extra-packages: any::devtools, any::testthat + cache: always + + - name: Test with Suggests installed, asserting nothing skipped + run: | + res <- as.data.frame(devtools::test(reporter = "silent", stop_on_failure = FALSE)) + interop <- res[grepl("seurat-interop", res$file), , drop = FALSE] + if (nrow(interop) == 0) { + stop("test-seurat-interop.R did not run at all.") + } + if (sum(interop$skipped) > 0) { + stop("test-seurat-interop.R skipped ", sum(interop$skipped), + " test(s). SeuratObject is a Suggests and must be installed here so that", + " as_Seurat()/Seurat v5 input is actually exercised.") + } + if (sum(res$failed) > 0 || sum(res$error) > 0) { + stop("Test failures: ", sum(res$failed), " failed, ", sum(res$error), " errored.") + } + cat("interop tests run:", nrow(interop), + "| suite expectations passed:", sum(res$passed), "\n") + shell: Rscript {0} + + ## devtools::test() never looks at NAMESPACE, roxygen/usage consistency, examples, + ## or S4 registration -- so a broken @export, a stale .Rd, or an example that no + ## longer runs all pass CI today. R CMD check covers those. + ## + ## error-on is "error" rather than "warning"/"note" on purpose: the repo has not + ## been checked here before, so this job first establishes a baseline and fails on + ## hard breakage (unloadable package, failing examples). Tighten it to "warning" + ## once the existing NOTEs are cleared. + check: + runs-on: ubuntu-latest + name: R CMD check --as-cran + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: '4.5.3' + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + dependencies: '"all"' + extra-packages: any::rcmdcheck + needs: check + + - uses: r-lib/actions/check-r-package@v2 + with: + args: 'c("--as-cran", "--no-manual")' + error-on: '"error"' + upload-snapshots: true diff --git a/DESCRIPTION b/DESCRIPTION index f5bf57e..ed44281 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -28,10 +28,11 @@ Description: Visualization and analysis of spatially resolved transcriptomics da differential expression analysis using spatial mixed models. License: MIT + file LICENSE Copyright: inst/COPYRIGHT +URL: https://github.com/FridleyLab/spatialGE, https://fridleylab.github.io/spatialGE/ +BugReports: https://github.com/FridleyLab/spatialGE/issues Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.2 Imports: arrow, BiocParallel, @@ -106,3 +107,4 @@ Suggests: VignetteBuilder: knitr Config/testthat/edition: 3 +Config/roxygen2/version: 8.1.0 diff --git a/NAMESPACE b/NAMESPACE index 02a1d9b..5c0a097 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +S3method(base::print,sge_manifest) export(STclust) export(STdiff) export(STdiff_volcano) @@ -7,13 +8,17 @@ export(STenrich) export(STgradient) export(SThet) export(STlist) +export(STlist_to_disk) +export(STlist_to_memory) export(STplot) export(STplot_interpolation) +export(as_Seurat) export(compare_SThet) export(distribution_plots) export(filter_data) export(gene_interpolation) export(get_gene_meta) +export(is_backed) export(load_images) export(plot_counts) export(plot_image) @@ -24,37 +29,37 @@ export(spatial_metadata) export(summarize_STlist) export(tissue_names) export(transform_data) +export(validate_store) import(Matrix) import(ggplot2) import(ggpolypath) +importFrom(R.utils,gunzip) importFrom(Rcpp,evalCpp) importFrom(grDevices,colorRampPalette) importFrom(magrittr,"%>%") -importFrom(methods,.hasSlot) -importFrom(methods,as) -importFrom(methods,is) -importFrom(methods,new) +importFrom(methods, + .hasSlot, + as, + is, + new +) importFrom(rlang,":=") -importFrom(stats,IQR) -importFrom(stats,as.dist) -importFrom(stats,as.formula) -importFrom(stats,complete.cases) -importFrom(stats,cor.test) -importFrom(stats,cutree) -importFrom(stats,dist) -importFrom(stats,hclust) -importFrom(stats,lm) -importFrom(stats,loess) -importFrom(stats,na.omit) -importFrom(stats,p.adjust) -importFrom(stats,prcomp) -importFrom(stats,quantile) -importFrom(stats,sd) -importFrom(stats,setNames) +importFrom(stats, + IQR, + as.dist, + as.formula, + complete.cases, + cor.test, + cutree, + dist, + hclust, + lm, + loess, + na.omit, + p.adjust, + prcomp, + quantile, + sd, + setNames +) useDynLib(spatialGE, .registration=TRUE) -export(as_Seurat) -export(STlist_to_disk) -export(STlist_to_memory) -export(is_backed) -export(validate_store) -S3method(print,sge_manifest) diff --git a/NEWS.md b/NEWS.md index 8d4d78e..a99e385 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,61 @@ ## Behavior changes +* **`transform_data()` now populates `vst.variance.standardized` in + `@gene_meta`.** Previously the column was added only as a side effect of + whichever analysis ran first, so whether `get_gene_meta()` showed it depended + on call order, and `gene_interpolation()`/`STplot_interpolation()` dropped any + existing column and recomputed it. `transform_data()` now computes it for both + `method='log'` and `method='sct'`, through the same `calculate_vst()` helper + `STclust()` uses, so every caller sees one definition. Code that inspected + `colnames(get_gene_meta(x))` will see one additional column, and code that + counted on `STclust()` being what created it no longer needs to. + + Note this does not change which genes any function *selects*: `STclust()`, + `STgradient()`, `gene_interpolation()` and `STdiff()` already computed VST + themselves before ranking, so their `topgenes` choices were consistent before + this change too. (An earlier draft of this entry claimed otherwise, and also + cited a top-20 overlap between `gene_stdevs` and VST rankings of 6; measured + across the eight Visium samples of the `tnbc_bassiouni` set it is 7-13.) What + changed is where the column comes from, not what downstream functions do with + it. + +* **`transform_data()` no longer fails on a sample with very few variable + genes.** Because of the change above, `transform_data()` began fitting the + variance-mean loess that `vst.variance.standardized` requires. That fit needs + at least 4 genes with non-zero variance, and below it `stats::loess` stops + with `span is too small` -- so normalizing a very small or low-complexity + STlist aborted, where in 1.2.2 it had succeeded. The count that matters is of + *non-constant* genes, so a matrix with many genes of which only a few vary hit + it as well. Such a sample now gets a warning naming it, and is left without + the column rather than failing; `calculate_vst()` only computes when the column + is absent, so a later analysis retries instead of inheriting a wrong value. + Functions that rank genes by variability still raise an error on such a sample, + since there is no ranking to return. + +* **`dim()` on an `STlist` now obeys the base R contract.** It returns + `c(n_genes, n_spots)` as an integer vector when the object holds exactly one + sample, and `NULL` for a multi-sample object -- because there is no single gene + x spot shape to report. It previously returned a *named list* of per-sample + dimensions, which made `nrow()` and `ncol()` meaningless on an STlist and was + reported by `R CMD check` as "dim() returns class 'list'". Use + `summarize_STlist()` for a per-sample table of dimensions. Nothing inside the + package called `dim()` on an STlist. + +* **`STlist` objects are now validated at construction.** `setValidity()` rejects + a malformed object up front: a sample-keyed slot referring to a sample that is + not in `@counts`, a count matrix without gene/spot names, or an + `@spatial_meta` entry whose row count disagrees with the number of spots. These + previously surfaced much later, far from their cause. + +* **`filter_data()` reports what it did.** Every count threshold defaults to `0` + (and the `*_max*` thresholds to `NULL`), so a call supplying none of them + filtered nothing -- while looking like a successful filter. With the new + `verbose=TRUE` default it now says explicitly that nothing was filtered, or how + many samples, spots/cells and genes were removed. `filter_data()` remains + single-threaded and deliberately has no `cores` argument, unlike the analysis + functions. + * **Requesting a gene, annotation or reference domain that does not exist is now an error rather than a silent no-op.** `SThet(genes=)`, `STgradient(annot=)`, `STgradient(ref=)` and `gene_interpolation(genes=)` previously accepted a name @@ -114,6 +169,25 @@ ## New features +* **An `STlist` can now be subset by sample, and has a length.** `x[i]` returns a + new, valid `STlist` holding only the selected spatial arrays, and `length(x)` + reports how many it holds. Previously neither worked: subsetting failed with + "object of type 'S4' is not subsettable", and `length(x)` returned the number + of *slots* (7) rather than samples, so `seq_along(x)` and + `for(i in seq_len(length(x)))` silently did the wrong thing. To work with one + sample out of a multi-sample object you had to rebuild an `STlist` from the raw + files. + + Select by name (`x[tissue_names(x)[1]]`), position, negative position or logical + vector. Every sample-keyed slot is subset alongside `@counts` -- `@spatial_meta`, + `@gene_meta`, `@tr_counts`, and the per-sample level inside each + `@gene_krige` element -- so the result passes validity, and `@sample_meta` rows + are matched to their sample rather than sliced positionally. Subsetting is + deliberately one-dimensional: an `STlist` holds several arrays with independent + gene and spot sets, so there is no shared second dimension. `x[i, j]` and + `x[[i]]` raise an error saying so. An unknown sample name is also an error, + listing the available names, rather than a silent omission. + * **Parallelism on Windows.** `resolve_cores()` returned `1L` unconditionally on Windows and `sge_lapply()` forwarded only to `parallel::mclapply`, which has no `fork()` there -- so the package was entirely serial. A non-forking (PSOCK) @@ -169,6 +243,57 @@ ## Bug fixes +* `STlist` validity no longer rejects an object that has kriging results. + `setValidity()` treated `@gene_krige` as sample-keyed and compared its names to + the sample names, but that slot is keyed by **gene** first and sample second + (`x@gene_krige[[gene]][[sample]]`), so its top-level names are gene symbols. + Every object returned by `gene_interpolation()` was therefore reported invalid + -- but only when validity actually ran, and assignment through `@<-` does not + trigger it, so the function appeared to succeed and a later `validObject()` (or + any construction from that object) failed. The sample level is now checked, one + gene at a time. + +* `load_images()` no longer drops samples whose image is not the first path + match. Two defects combined: sample-to-file matching used a vectorized `&` + where it needed a scalar `&&`, and the match was positional, so with more than + one image directory or a sample whose name did not sort first the wrong file -- + or no file -- was attached. Matching is now by normalized sample name, across + every supplied directory and both extensions (`.png`/`.jpg`/`.jpeg`), with a + decoder fallback when the file extension disagrees with its actual encoding. A + sample whose image genuinely cannot be read is skipped **with a warning** rather + than silently, and if no image matches at all the error names what was searched. + +* `STplot_interpolation()` works on its documented default. With the default + `genes=NULL` it selected genes by VST but then intersected that selection with a + kriging-derived gene list; because it also required the column to be present, + the call failed on any `STlist` that had not already been through + `gene_interpolation()`. It now errors with a clear message when the object has no + kriged genes, restricts to those that do exist (warning only when the user named + genes explicitly), uses `calculate_vst()` rather than its own inline copy, and + errors clearly when a color scale has no finite values. + +* `STdiff()` explains an unusable `annot=` instead of failing inside dplyr. A + numeric metadata column -- a perfectly ordinary one, such as `total_counts` -- + reached an internal join and produced ``Can't join `x$orig_annot` with + `y$orig_annot` due to incompatible types. i `x$orig_annot` is a ``, + which names neither the function nor the argument to change. `annot` must hold + group labels, so a numeric column now raises an error naming `STdiff`, the + requirement and the fix (`as.character()`), as does a column with fewer than two + distinct groups -- which previously produced no usable comparison. + +* `transform_data(method='sct')` reports an actionable error when SCTransform + fails. On a small or low-complexity matrix `sctransform::vst()` failed with + ``missing value where TRUE/FALSE needed``, giving no indication of which sample, + how large it was, or what to change. The error now names the sample and its + dimensions (`n_genes` x spots/cells) and suggests lowering `sct_n_regr_genes` + or using `method='log'`, while still reporting the underlying message. + +* A bad `cores=` value is caught on every parallelized path. The gene-metadata + step of `transform_data()` never validated it, so `cores='abc'` coerced to `NA` + and was handed directly to the parallel lapply instead of raising an error. + Validation is now centralized (see Minor), which fixes that path and removes the + five duplicated checks elsewhere. + * `pseudobulk_samples()` no longer fails on a gene whose pseudobulk total is constant across samples. Such a gene produced an all-`NaN` column after scaling and `prcomp()` rejected it outright, so any dataset containing an all-zero gene @@ -231,6 +356,27 @@ ## Minor +* **User-facing validation errors are now raised through the shared error + catalog, so they all carry the `spatialGE exception:` signature.** About thirty + sites used a bare `stop()`, which meant an argument-validation failure looked no + different from an internal crash; and three sites wrote the `spatialGE exception:` + prefix by hand instead of using the catalog, so their wording could drift from + it. Their text is unchanged in substance but now lives in `inst/err.csv`, and + `raise_err()` gained optional `sprintf`-style interpolation so messages that embed + a gene name, sample size or threshold can be catalogued too. Code matching on the + exact wording of these messages may need updating; matching on + `spatialGE exception:` (the documented pattern) is unaffected. + +* **An unusable `cores=` value now fails the same way everywhere.** Validation of + a core count used to be each call site's job, and was done three different ways: + some sites raised `error0032`, others `error0036`, five used an uncatalogued bare + `stop()`, and `transform_data()`'s gene-metadata path did not check at all -- so + `cores='abc'` there became `NA` and was passed straight into the parallel + lapply. Resolution now happens once in `resolve_cores()`, which rejects a value + that is not one finite positive number with an error naming the fix. The + caller's coercion is preserved: `coerce='ceiling'` and `coerce='none'` still + return a non-integral value unchanged. + * The error raised when an argument that should be an `STlist` is `NULL` or of the wrong type now reads `cannot get a slot (...) from an object of type ...` rather than ``no applicable method for `@` applied to an object of class ...``, because diff --git a/R/STclust.R b/R/STclust.R index cde28b1..7b85ec6 100644 --- a/R/STclust.R +++ b/R/STclust.R @@ -89,7 +89,7 @@ STclust = function(x=NULL, samples=NULL, ws=0.025, dist_metric='euclidean', link # Do not allow weights higher than 1 if(any(ws < 0) | any(ws > 1)){ - stop('Please select a spatial weight between 0 and 1.') + raise_err(err_code='error0086') } # Check to ensure number of ks is acceptable @@ -233,11 +233,11 @@ stclust_one_sample = function(trcounts_mat, spatial_meta_df, dist_metric, ws, cl # Hierarchical clustering using range of Ks hierclusters_ls = get_hier_clusters_ks(weighted_dists=weighted_dists, ws=ws, ks=ks, linkage=linkage) } else{ - stop('Enter a valid number of k values to evaluate or \'dtc\' to apply cutreeDynamic.') + raise_err(err_code='error0087') } } else{ - stop('Currently, only spatially-informed hierarchical clustering is supported.') + raise_err(err_code='error0088') } if(verbose > 1L){ diff --git a/R/STdiff.R b/R/STdiff.R index 983fd7f..ffb18d1 100644 --- a/R/STdiff.R +++ b/R/STdiff.R @@ -84,13 +84,13 @@ STdiff = function(x=NULL, samples=NULL, annot=NULL, w=NULL, k=NULL, deepSplit=NU # Check that at least two clusters have been specified if pairwise if(pairwise & !is.null(clusters)){ if(length(clusters) < 2){ - stop('If pairwise tests requested, at least two clusters are required.') + raise_err(err_code='error0075') } } # Stop function if topgenes and sp_topgenes are not valid if((round(topgenes, 0) <= 0) | (sp_topgenes < 0 | sp_topgenes > 1)){ - stop('topgenes or sp_topgenes contain invalid values.') + raise_err(err_code='error0076') } # Define samples using names (convert indexes to names if necessary) @@ -103,13 +103,13 @@ STdiff = function(x=NULL, samples=NULL, annot=NULL, w=NULL, k=NULL, deepSplit=NU # If annot=NULL, must specify w and k if(!is.null(w) & !is.null(k)){ if(length(w) != 1 | length(k) != 1){ - stop('Please specify a single value for w and a single value for k.') + raise_err(err_code='error0077') } # Construct column name from w and k annot = paste0('stclust_spw', as.character(w)) if(k == 'dtc'){ if(is.null(deepSplit)){ - stop('If k=\"dtc\", then specify deepSplit.') + raise_err(err_code='error0078') } else if(is.logical(deepSplit)){ if(deepSplit){ annot = paste0(annot, '_dsplTrue') @@ -121,18 +121,18 @@ STdiff = function(x=NULL, samples=NULL, annot=NULL, w=NULL, k=NULL, deepSplit=NU } } else{ if(!is.numeric(k)){ - stop('Specify a valid k value.') + raise_err(err_code='error0079') } annot = paste0(annot, '_k', as.character(k)) } } else{ - stop('If no specific annotation is specified, please specify both w and k (STclust parameters).') + raise_err(err_code='error0080') } } else{ if(length(annot) == 0){ - stop('If w and k are not specified, one annotation column from @spatial_meta should be specified.') + raise_err(err_code='error0081') } else if(length(annot) > 1){ - stop('Only one annotation column from @spatial_meta can be tested at a time. ') + raise_err(err_code='error0082') } } @@ -146,12 +146,29 @@ STdiff = function(x=NULL, samples=NULL, annot=NULL, w=NULL, k=NULL, deepSplit=NU } } if(length(samples_tmp) == 0){ - stop('No samples left to test. Are the requested annotations/clusters present in at least one sample?') + raise_err(err_code='error0083') } } samples = samples_tmp rm(samples_tmp) # Clean env + # Validate the annotation's type and number of groups before anything is fit. + # STdiff treats the column as group labels and joins on it internally, so a + # numeric column (a perfectly ordinary metadata column such as total_counts) + # previously surfaced only much later, from dplyr: + # Can't join `x$orig_annot` with `y$orig_annot` due to incompatible types. + # i `x$orig_annot` is a + # which names neither STdiff nor the argument to change. + for(i in samples){ + annot_vals = x@spatial_meta[[i]][[annot]] + if(is.numeric(annot_vals)){ + raise_err(err_code='error0070', samplename=i) + } + if(length(unique(stats::na.omit(as.character(annot_vals)))) < 2){ + raise_err(err_code='error0071', samplename=i) + } + } + # Calculate standardized variance for all samples (regardless if sample is not in requested test) x = stdiff_ensure_vst(x) diff --git a/R/STdiff_prepare.R b/R/STdiff_prepare.R index 3ffb2aa..befc6d4 100644 --- a/R/STdiff_prepare.R +++ b/R/STdiff_prepare.R @@ -4,21 +4,16 @@ # stdiff_ensure_vst # Ensure vst.variance.standardized is present in gene_meta for every sample in # the STlist, computing and joining it if missing. +# +# transform_data() now populates VST itself, so this is a safety net for STlists +# whose gene_meta was replaced or built by hand. It delegates to calculate_vst() +# so there is a single definition of the statistic across STclust(), STgradient(), +# gene_interpolation() and STdiff(). # @param x an STlist. # @return the STlist with gene_meta updated. # stdiff_ensure_vst = function(x){ - for(i in 1:length(x@tr_counts)){ - # Check that vst is not already calculated - if(length(grep('vst.variance.standardized', colnames(x@gene_meta[[i]]))) == 0){ - #x@gene_meta[[i]] = Seurat::FindVariableFeatures(x@counts[[i]], verbose=F) %>% - x@gene_meta[[i]] = Seurat_FindVariableFeatures(sample_counts(x, i)) %>% - tibble::rownames_to_column(var='gene') %>% - dplyr::select('gene', 'vst.variance.standardized') %>% - dplyr::left_join(x@gene_meta[[i]], ., by='gene') - } - } - return(x) + calculate_vst(x=x, samples=names(x@tr_counts)) } diff --git a/R/SThet.R b/R/SThet.R index 724358c..e6332b4 100644 --- a/R/SThet.R +++ b/R/SThet.R @@ -83,7 +83,7 @@ SThet = function(x=NULL, genes=NULL, samples=NULL, method='moran', k=NULL, overw # Check that genes have been input if(is.null(genes)){ - stop('Please enter one or more genes to calculate statistics.') + raise_err(err_code='error0084') } # k is handed to spdep::knearneigh(), which requires k < the number of points. @@ -141,7 +141,7 @@ SThet = function(x=NULL, genes=NULL, samples=NULL, method='moran', k=NULL, overw if(!is.na(k) & k > 0){ x@misc[['sthet']][['listws']] = create_listw_from_knn(x, ks=k) } else{ - stop("If using k nearest-neighbors, please input a positive integer for k.") + raise_err(err_code='error0085') } } else{ # No listw for the default distance weighting. create_listw_from_dist() @@ -187,9 +187,6 @@ SThet = function(x=NULL, genes=NULL, samples=NULL, method='moran', k=NULL, overw gene_moran_i_notest = function(x=NULL, combo=NULL, overwrite=T, cores=NULL){ # Define cores available cores = resolve_cores(length(x@spatial_meta), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Use method to compute autocorrelation described in tutorial of https://rspatial.org/ # Loop through combinations of samples x genes @@ -233,9 +230,6 @@ gene_moran_i_notest = function(x=NULL, combo=NULL, overwrite=T, cores=NULL){ gene_geary_c_notest = function(x=NULL, combo=NULL, overwrite=T, cores=NULL){ # Define cores available cores = resolve_cores(length(x@spatial_meta), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Use method to compute autocorrelation described in tutorial of https://rspatial.org/ # Loop through combinations of samples x genes diff --git a/R/STplot_interpolation.R b/R/STplot_interpolation.R index e304c01..e50d314 100644 --- a/R/STplot_interpolation.R +++ b/R/STplot_interpolation.R @@ -6,9 +6,14 @@ #' genes and spatial samples #' #' @param x an STlist containing results from `gene_krige` for the genes selected. -#' @param genes a vector of gene names (one or several) to plot. If 'top', the 10 -#' genes with highest standard deviation from each spatial sample are plotted. -#' @param top_n an integer indicating how many top genes to perform kriging. Default is 10. +#' Kriging must have been run first with [gene_interpolation()]. +#' @param genes a vector of gene names (one or several) to plot. If `'top'` (the +#' default when `NULL`), the `top_n` genes with the highest standardized variance +#' (VST) from each spatial sample are plotted. Only genes that already have +#' kriging results can be plotted; a warning names any requested gene that was not +#' interpolated. +#' @param top_n an integer indicating how many of the most variable genes to plot +#' when `genes='top'`. Default is 10. #' @param samples a vector indicating the spatial samples to plot. If vector of numbers, #' it follows the order of `names(x@counts)`. If NULL, the function plots all samples #' @param color_pal a color scheme from `khroma` or `RColorBrewer`. @@ -63,34 +68,60 @@ STplot_interpolation = function(x=NULL, genes=NULL, top_n=10, samples=NULL, colo # Force number of top variable genes as integer top_n = as.integer(top_n) - # Test that a gene name was entered. - if (is.null(genes)) { - stop("Please, enter one or more genes to plot.") - } - # Test if no specific subject plot was requested. samples = resolve_samples(x, samples, slot='tr_counts', numeric_handling='plain', char_transform='none', post_check='none') - # If genes='top', get names of 10 genes with the highest standard deviation. - if(length(genes) == 1 && genes == 'top'){ + # The default is to plot the most variable genes, which is also what + # genes='top' requests. (Previously a NULL default stopped before this branch + # could run, so the documented no-argument call always failed.) + top_requested = is.null(genes) || (length(genes) == 1 && identical(as.character(genes), 'top')) + if (is.null(genes)) { + genes = 'top' + } + + # If genes='top', get names of the top_n most variable genes from each sample. + if(length(genes) == 1 && identical(as.character(genes), 'top')){ + # Single source of truth for VST, shared with STclust() and + # gene_interpolation(); it is idempotent and preserves the existing columns. + x = calculate_vst(x=x, samples=samples) + genes = c() for(i in samples){ - # Find tops variable genes using Seurat approach. In the past, instead of Seurat, genes with the highest stdev were used - if(any(colnames(x@gene_meta[[i]]) == 'vst.variance.standardized')){ - x@gene_meta[[i]] = x@gene_meta[[i]][, !grepl('vst.variance.standardized', colnames(x@gene_meta[[i]]))] - } - x@gene_meta[[i]] = Seurat_FindVariableFeatures(sample_counts(x, i)) %>% - tibble::rownames_to_column(var='gene') %>% - dplyr::select('gene', 'vst.variance.standardized') %>% - dplyr::left_join(x@gene_meta[[i]], ., by='gene') - - genes = append(genes, x@gene_meta[[i]][['gene']][order(x@gene_meta[[i]][['vst.variance.standardized']], decreasing=T)][1:top_n]) + gm = x@gene_meta[[i]] + genes = append(genes, gm[['gene']][order(gm[['vst.variance.standardized']], decreasing=T)][1:top_n]) } # Get unique genes from most variable. genes = unique(genes) } + # Kriging is a prerequisite: it supplies both the predicted grid and the + # tissue border below. Without it there is nothing to plot. + if(is.null(x@misc[['gene_krige']][['krige_border']])){ + raise_err(err_code='error0072') + } + kriged = genes[vapply(genes, function(g) rlang::has_name(x@gene_krige, g), logical(1))] + if(length(kriged) == 0){ + available = sort(names(x@gene_krige)) + raise_err(err_code='error0073', samplename=NULL, + if(length(available) == 0){ 'none' } else { + paste(c(utils::head(available, 5), if(length(available) > 5) '...'), + collapse=', ') + }) + } + if(length(kriged) < length(genes)){ + # Only warn when the caller named genes explicitly. When they asked for + # 'top', top_n here is independent of the top_n used at kriging time, so + # silently plotting whichever of them were interpolated is the expected + # behaviour rather than a user error. + if(!top_requested){ + warning(paste0("No kriging results for: ", + paste(setdiff(genes, kriged), collapse=', '), + ". Plotting only the genes that were interpolated."), call.=FALSE) + } + genes = kriged + } + # Store maximum and minimum expression value for plot color scaling maxvalue <- c() minvalue <- c() @@ -100,16 +131,26 @@ STplot_interpolation = function(x=NULL, genes=NULL, top_n=10, samples=NULL, colo if (rlang::has_name(x@gene_krige, gene)){ if(!is.null(x@gene_krige[[gene]][[i]][['success_or_not']])){ if(x@gene_krige[[gene]][[i]][['success_or_not']] != 'error'){ - # Find maximum expression value for each spatial array. + # Find maximum expression value for each spatial array. Drop + # non-finite predictions first: a grid that is entirely NA made + # max()/min() warn and return +/-Inf, which then propagated into the + # shared color scale for every panel. values <- x@gene_krige[[gene]][[i]][['krige_out']][['krige']] - maxvalue <- append(maxvalue, max(values, na.rm=T)) - minvalue <- append(minvalue, min(values, na.rm=T)) + values <- values[is.finite(values)] + if(length(values) > 0){ + maxvalue <- append(maxvalue, max(values)) + minvalue <- append(minvalue, min(values)) + } } } } } } # Find maximum value among selected spatial arrays. + if(length(maxvalue) == 0){ + raise_err(err_code='error0074', samplename=NULL, + paste(utils::head(genes, 5), collapse=', ')) + } maxvalue <- max(maxvalue) minvalue <- min(minvalue) diff --git a/R/classDefinitions.R b/R/classDefinitions.R index f84580f..7e31a7c 100644 --- a/R/classDefinitions.R +++ b/R/classDefinitions.R @@ -34,6 +34,9 @@ setClass(Class="STlist", #' object and other information about the object. #' #' @param object an STList object to show summary from. +#' +#' @return Invisibly returns `NULL`. Called for the side effect of printing an +#' overview: the number of spatial arrays, their dimensions and a sample count. # # setMethod("show", signature="STlist", @@ -44,12 +47,12 @@ setMethod("show", signature="STlist", counter = 1 while(counter < 11){ i = names(object@counts)[counter] - cat(paste0('\t', i, " (", ncol(object@counts[[i]]), ' ROIs|spots|cells x ', nrow(object@counts[[i]]), ' genes)\n')) + cat(paste0('\t', i, " (", sample_n_cells(object, i, 'counts'), ' ROIs|spots|cells x ', sample_n_genes(object, i, 'counts'), ' genes)\n')) counter = counter + 1 } } else{ for(i in names(object@counts)){ - cat(paste0('\t', i, " (", ncol(object@counts[[i]]), ' ROIs|spots|cells x ', nrow(object@counts[[i]]), ' genes)\n')) + cat(paste0('\t', i, " (", sample_n_cells(object, i, 'counts'), ' ROIs|spots|cells x ', sample_n_genes(object, i, 'counts'), ' genes)\n')) } } if(length(names(object@counts)) > 10){ @@ -71,6 +74,9 @@ setMethod("show", signature="STlist", #' object and other information about the object. #' #' @param object an STList object to show summary from. +#' +#' @return Invisibly returns `NULL`. Called for the side effect of printing an +#' overview: the number of spatial arrays, their dimensions and a sample count. # # setMethod("summary", signature="STlist", @@ -81,12 +87,12 @@ setMethod("summary", signature="STlist", counter = 1 while(counter < 11){ i = names(object@counts)[counter] - cat(paste0('\t', i, " (", ncol(object@counts[[i]]), ' ROIs|spots|cells x ', nrow(object@counts[[i]]), ' genes)\n')) + cat(paste0('\t', i, " (", sample_n_cells(object, i, 'counts'), ' ROIs|spots|cells x ', sample_n_genes(object, i, 'counts'), ' genes)\n')) counter = counter + 1 } } else{ for(i in names(object@counts)){ - cat(paste0('\t', i, " (", ncol(object@counts[[i]]), ' ROIs|spots|cells x ', nrow(object@counts[[i]]), ' genes)\n')) + cat(paste0('\t', i, " (", sample_n_cells(object, i, 'counts'), ' ROIs|spots|cells x ', sample_n_genes(object, i, 'counts'), ' genes)\n')) } } if(length(names(object@counts)) > 10){ @@ -101,23 +107,302 @@ setMethod("summary", signature="STlist", ) ## -#' @title dim: Prints the dimensions of count arrays within an STList object. -#' @description Returns the number of genes and spots for each array within an STList object +#' @title dim: Dimensions of the count array in an STList object. +#' @description Returns the number of genes (rows) and spots/cells (columns) +#' observed in an STList object. #' @details -#' This function takes an STList and prints the number of genes (rows) and spots (columns) of -#' each spatial array within that object. +#' An `STlist` is a container for one or more spatial arrays, and different +#' samples may have different numbers of genes. `dim()` therefore has a single +#' well-defined answer only when the object holds exactly one sample; in that +#' case it returns `c(n_genes, n_spots)` as an integer vector, like any other +#' matrix-like object. #' -#' @param x an STList object to show summary from. -# +#' For a multi-sample STlist `dim()` returns `NULL` (the base R convention for +#' "no dimensions"), because there is no single gene x spot shape to report. Use +#' [summarize_STlist()] for a per-sample table of dimensions, or [tissue_names()] +#' to iterate samples. +#' +#' Previously this method returned a *named list* of per-sample dimensions, which +#' violated the base `dim()` contract: it made [nrow()]/[ncol()] meaningless, and +#' `R CMD check` reported it as "dim() returns class 'list'". +#' +#' @param x an STList object. +#' +#' @return An integer vector `c(n_genes, n_spots)` when the object holds exactly +#' one sample; `NULL` for a multi-sample object, where there is no single gene x +#' spot shape to report. # setMethod(f="dim", signature="STlist", definition=function(x){ - dim_res = list() - for(i in seq(x@counts)){ - dim_res[[i]] = sample_dim(x, i, 'counts') + # Contract: dim() must return an integer vector, or NULL. + if(length(x@counts) != 1){ + return(NULL) } - names(dim_res) = names(x@counts) - return(dim_res) + as.integer(sample_dim(x, names(x@counts)[1], 'counts')) + } +) + + +## +# Validity checks for the STlist class. +# +# Ensures an STlist is internally consistent before it is used: that every +# sample-keyed slot refers to the same samples as @counts, that each count matrix +# has gene and spot names, and that the number of rows in @spatial_meta[[i]] +# matches the number of spots/cells (columns) in @counts[[i]]. +# +setValidity("STlist", function(object){ + counts <- object@counts + + # An empty container is allowed (e.g. mid-construction); nothing to check. + if(length(counts) == 0){ + return(TRUE) + } + + sample_names <- names(counts) + + # Every slot keyed by sample must use the same keys as @counts. + # + # @gene_krige is deliberately NOT in this list: it is keyed by GENE first and + # sample second (x@gene_krige[[gene]][[sample]]), so its top-level names are + # gene symbols. Checking it here rejected every kriged object -- but only when + # validity actually ran, and slot assignment via `@<-` does not trigger it, so + # gene_interpolation() appeared to succeed and validObject() failed afterwards. + for(slot_name in c("spatial_meta", "gene_meta", "tr_counts")){ + slot_value <- methods::slot(object, slot_name) + if(length(slot_value) == 0){ + next + } + extra <- setdiff(names(slot_value), sample_names) + if(length(extra) > 0){ + return(paste0("slot '", slot_name, "' has entries for samples not in @counts: ", + paste(extra, collapse=', '), ".")) + } + } + + # @gene_krige: check the sample level, one gene at a time. + if(length(object@gene_krige) > 0){ + for(g in names(object@gene_krige)){ + extra_samples <- setdiff(names(object@gene_krige[[g]]), sample_names) + if(length(extra_samples) > 0){ + return(paste0("@gene_krige[['", g, + "']] has entries for samples not in @counts: ", + paste(extra_samples, collapse=', '), ".")) + } + } + } + + # Per-sample consistency between the count matrix and its metadata. + # + # Only entries that actually hold a matrix are checked: unit tests build + # deliberately minimal stubs (e.g. counts = list(a = 1, b = 2)) to exercise + # name-resolution helpers in isolation, and those must stay constructible. + for(i in sample_names){ + cm <- counts[[i]] + if(!(is.matrix(cm) || inherits(cm, "Matrix"))){ + next + } + if(is.null(rownames(cm)) || is.null(colnames(cm))){ + return(paste0("the count matrix for sample '", i, + "' must have both gene (row) and spot/cell (column) names.")) + } + + sm <- object@spatial_meta[[i]] + if(is.null(sm)){ + return(paste0("no @spatial_meta entry for sample '", i, "'.")) + } + if(!is.data.frame(sm)){ + return(paste0("@spatial_meta[['", i, "']] must be a data.frame.")) + } + if(!("libname" %in% colnames(sm))){ + return(paste0("@spatial_meta[['", i, + "']] must have a 'libname' column identifying each spot/cell.")) + } + if(nrow(sm) != ncol(cm)){ + return(paste0("sample '", i, "': @spatial_meta has ", nrow(sm), + " rows but the count matrix has ", ncol(cm), " spots/cells.")) + } + } + + TRUE +}) + + +## +#' @title length: Number of spatial arrays in an STList object. +#' @description Returns the number of samples (spatial arrays) held by an +#' STList object. +#' @details +#' An `STlist` is a container for one or more spatial arrays. `length()` reports +#' how many, which makes the object usable with the usual idioms -- +#' `seq_along(x)`, `for(i in seq_len(length(x)))` -- instead of having to know +#' that the count lives in `length(x@counts)`. +#' +#' @param x an STList object. +# +#' @return A single integer: the number of spatial arrays in `x`. +# +setMethod("length", signature="STlist", + definition=function(x){ + length(x@counts) + } +) + + +## +#' @title [: Subset an STList object by sample. +#' @description Returns a new, valid STlist containing only the selected +#' spatial arrays (samples). +#' @details +#' `x[i]` selects samples, not genes or spots: an STlist holds several spatial +#' arrays and each has its own gene and spot sets, so there is no shared second +#' dimension to index. `i` may be a character vector of sample names (as returned +#' by [tissue_names()]), a numeric vector of positions, or a logical vector as +#' long as the number of samples. +#' +#' Every slot keyed by sample is subset alongside `@counts` -- `@spatial_meta`, +#' `@gene_meta`, `@tr_counts` and the per-sample entries inside each +#' `@gene_krige` element -- so the result is internally consistent and passes +#' validity. `@sample_meta` rows are matched by their `sample_name` column rather +#' than by position, so the metadata stays aligned with its sample. +#' +#' An unknown name is an error rather than a silent omission, matching the +#' package-wide rule for `samples=` arguments. +#' +#' @param x an STList object. +#' @param i sample names, positions or a logical vector selecting spatial arrays. +#' @param j not used. Subsetting is one-dimensional, so supplying `j` is an +#' error rather than a second index. +#' @param ... unused; present for compatibility with the `[` generic. +#' @param drop unused. Subsetting an STlist always returns an STlist, never a +#' bare matrix: dropping to the underlying counts would discard the metadata that +#' makes it an STlist. +# +#' @return An STlist containing only the selected spatial arrays. Subsetting to +#' zero samples is an error. +# +setMethod("[", signature(x="STlist", i="ANY", j="missing"), + definition=function(x, i, ..., drop=TRUE){ + sample_names = names(x@counts) + if(length(sample_names) == 0){ + raise_err(err_code='error0096') + } + + if(is.character(i)){ + unknown = setdiff(i, sample_names) + if(length(unknown) > 0){ + raise_err(err_code='error0095', samplename=NULL, + paste(unknown, collapse=', '), + paste(sample_names, collapse=', ')) + } + sel = match(i, sample_names) + } else if(is.logical(i)){ + # A short logical vector would silently recycle, selecting the + # wrong samples, so require an exact length. + if(length(i) != length(sample_names)){ + raise_err(err_code='error0096') + } + sel = which(i) + } else if(is.numeric(i)){ + # Base R semantics, including negative selection. An out-of-range + # positive index yields NA and is rejected rather than silently + # returning a shorter object. + sel = seq_along(sample_names)[i] + if(anyNA(sel)){ + raise_err(err_code='error0096') + } + } else { + raise_err(err_code='error0096') + } + + if(length(sel) == 0){ + raise_err(err_code='error0096') + } + + kept = sample_names[sel] + + # @sample_meta is one row per sample, but the column identifying that + # sample is not fixed: STlist() names it 'sample_name' for unnamed or + # list input, while a clinical CSV keeps its own header (the Thrane + # data uses 'sampleID'). Match on the first column -- which is what + # show()/summarize_STlist() already treat as the sample identifier -- + # and fall back to position, since STlist() builds the rows in + # @counts order. + sm = x@sample_meta + if(length(sm) > 0 && nrow(sm) == length(sample_names)){ + sm_key = as.character(sm[[1]]) + if(all(kept %in% sm_key)){ + sm = sm[match(kept, sm_key), , drop=FALSE] + } else { + sm = sm[sel, , drop=FALSE] + } + } + + new("STlist", + counts = x@counts[kept], + spatial_meta = x@spatial_meta[kept], + gene_meta = if(length(x@gene_meta) > 0) x@gene_meta[kept] else list(), + sample_meta = sm, + tr_counts = if(length(x@tr_counts) > 0) x@tr_counts[kept] else list(), + # @gene_krige is keyed by GENE first, then sample. + gene_krige = if(length(x@gene_krige) > 0){ + lapply(x@gene_krige, function(g) g[intersect(names(g), kept)]) + } else { + list() + }, + misc = x@misc) + } +) + + +## +#' @title [[: Not supported for STList objects. +#' @description Raises an informative error. Subsetting an STlist is +#' one-dimensional and returns another STlist; use `x[i]`. +#' +#' @param x an STList object. +#' @param i not used; any value raises an error. +#' @param j not used; any value raises an error. +#' @param ... not used; any value raises an error. +#' +#' @return Never returns: always raises an error naming `x[i]` as the supported +#' form. +#' +# setMethod() trims trailing ANYs from a signature, so this registers as +# '[[,STlist-method' however the signature is written -- confirmed with +# findMethods(), which reports the siglist as "STlist" for [[ and +# "STlist#ANY#ANY#ANY" for [. R CMD check derives the \alias it wants from that +# registered siglist, while roxygen2 writes the generic's full arity, so the +# short form has to be declared explicitly or the method reads as undocumented. +#' @aliases [[,STlist-method +# +setMethod("[[", signature(x="STlist"), + definition=function(x, i, ...){ + raise_err(err_code='error0096') + } +) + + +## +#' @title [: Reject two-dimensional subsetting of an STList object. +#' @description Raises an informative error. An STlist holds several spatial +#' arrays, each with its own gene and spot sets, so there is no shared second +#' dimension to index; select samples with `x[i]` and then address genes or spots +#' through that sample's slots. +#' +#' @param x an STList object. +#' @param i sample selection. Valid on its own via `x[i]`, but not together +#' with `j`. +#' @param j not used; supplying it is what makes this an error. +#' @param ... not used. +#' @param drop not used. +#' +#' @return Never returns: always raises an error naming `x[i]` as the supported +#' form. +# +setMethod("[", signature(x="STlist", i="ANY", j="ANY"), + definition=function(x, i, j, ..., drop=TRUE){ + raise_err(err_code='error0096') } ) diff --git a/R/compare_SThet.R b/R/compare_SThet.R index 4cbbaba..3fdbedd 100644 --- a/R/compare_SThet.R +++ b/R/compare_SThet.R @@ -39,7 +39,7 @@ compare_SThet = function(x=NULL, samplemeta=NULL, genes=NULL, color_by=NULL, x = assert_stlist(x, message="The input must be a STList.") if(is.null(genes)){ - stop('Please, enter one gene or more to generate plot.') + raise_err(err_code='error0092') } # Color by patient if no color_by diff --git a/R/distribution_plots.R b/R/distribution_plots.R index 32ddd50..8447727 100644 --- a/R/distribution_plots.R +++ b/R/distribution_plots.R @@ -53,7 +53,7 @@ distribution_plots = function(x=NULL, plot_meta=NULL, genes=NULL, samples=NULL, plist = gene_plots(x=x, genes=genes, samples=samples, data_type=data_type, plot_type=plot_type, color_pal=color_pal, ptsize=ptsize, ptalpha=ptalpha) } else { - stop('Specify a spot/cell meta data variable or a gene to plot.') + raise_err(err_code='error0089') } return(plist) @@ -126,13 +126,16 @@ spot_plots = function(x=NULL, plot_meta=NULL, samples=NULL, gene_plots = function(x=NULL, genes=NULL, samples=NULL, data_type='tr', plot_type='violin', color_pal='roma', ptsize=0.5, ptalpha=0.5){ - # Extract data slot + # Extract data slot. Resolved as a slot NAME rather than as the slot itself, so + # each sample's matrix is read through the accessors in the loop below: a slot + # element is an sge_manifest when the parquet backing is in use, and rownames() + # is NULL on one. if(data_type == 'tr'){ - expr_tmp = x@tr_counts + data_slot = 'tr_counts' p_title = 'Normalized expression - ' ax_title = 'Normalized expression' } else { - expr_tmp = x@counts + data_slot = 'counts' p_title = 'Raw expression - ' ax_title = 'Counts' } @@ -144,13 +147,14 @@ gene_plots = function(x=NULL, genes=NULL, samples=NULL, data_type='tr', samples_tmp = samples df_tmp = tibble::tibble() for(i in samples){ - if(!(gene %in% rownames(expr_tmp[[i]]))){ + if(!(gene %in% sample_genes(x, i, data_slot))){ message(paste0('Sample ', i, ' does not contain ', gene, '.\n')) samples_tmp = grep(paste0('^', i, '$'), samples_tmp, value=T, invert=T) } else{ + mtx_tmp = sample_slot_counts(x, i, data_slot, genes=gene) df_tmp = dplyr::bind_rows(df_tmp, - tibble::tibble(libname=colnames(expr_tmp[[i]]), - geneexpr=expr_tmp[[i]][gene, ], + tibble::tibble(libname=colnames(mtx_tmp), + geneexpr=mtx_tmp[gene, ], samplename=i)) } } @@ -214,7 +218,7 @@ cluster_gene_plots = function(x=NULL, plot_meta=NULL, genes=NULL, samples=NULL, } } if(length(samples) < 1){ - stop('All samples skipped.') + raise_err(err_code='error0090') } # Check plot type @@ -223,13 +227,16 @@ cluster_gene_plots = function(x=NULL, plot_meta=NULL, genes=NULL, samples=NULL, plot_type = 'box' } - # Extract data slot + # Extract data slot. Resolved as a slot NAME rather than as the slot itself, so + # each sample's matrix is read through the accessors in the loop below: a slot + # element is an sge_manifest when the parquet backing is in use, and rownames() + # is NULL on one. if(data_type == 'tr'){ - expr_tmp = x@tr_counts + data_slot = 'tr_counts' p_title = 'Normalized expression - ' ax_title = 'Normalized expression' } else { - expr_tmp = x@counts + data_slot = 'counts' p_title = 'Raw expression - ' ax_title = 'Counts' } @@ -241,13 +248,14 @@ cluster_gene_plots = function(x=NULL, plot_meta=NULL, genes=NULL, samples=NULL, samples_tmp = samples df_tmp = tibble::tibble() for(i in samples){ - if(!(gene %in% rownames(expr_tmp[[i]]))){ + if(!(gene %in% sample_genes(x, i, data_slot))){ message(paste0('Sample ', i, ' does not contain ', gene, '.\n')) samples_tmp = grep(paste0('^', i, '$'), samples_tmp, value=T, invert=T) } else{ + mtx_tmp = sample_slot_counts(x, i, data_slot, genes=gene) df_tmp = dplyr::bind_rows(df_tmp, - dplyr::left_join(tibble::tibble(libname=colnames(expr_tmp[[i]]), - geneexpr=expr_tmp[[i]][gene, ], + dplyr::left_join(tibble::tibble(libname=colnames(mtx_tmp), + geneexpr=mtx_tmp[gene, ], samplename=i), x@spatial_meta[[i]][, c('libname', plot_meta)], by='libname')) } diff --git a/R/filter_data.R b/R/filter_data.R index 2285ac8..a119168 100644 --- a/R/filter_data.R +++ b/R/filter_data.R @@ -16,6 +16,15 @@ #' 4. Genes matching `rm_genes_expr` #' 5. Min and max counts #' +#' Note that every count threshold defaults to `0` (and the `*_max*` thresholds +#' to `NULL`, meaning no upper bound). A call that supplies none of them, and no +#' `rm_*` argument either, therefore returns the STlist unchanged. Set at least +#' one threshold to actually filter; with `verbose=TRUE` the function says so +#' rather than returning silently. +#' +#' Filtering is sequential and single-threaded, so unlike the analysis functions +#' there is no `cores` argument. +#' #' @param x an STlist #' @param spot_minreads the minimum number of total reads for a spot to be retained #' @param spot_maxreads the maximum number of total reads for a spot to be retained @@ -35,6 +44,8 @@ #' @param rm_genes vector of gene names to remove from STlist. Removes genes in `x@counts`, `x@tr_counts`, and `x@gene_meta` #' @param rm_genes_expr a regular expression that matches genes to remove. Removes genes in `x@counts`, `x@tr_counts`, and `x@gene_meta` #' @param spot_pct_expr a expression to use with `spot_minpct` and `spot_maxpct`. By default '^MT-'. +#' @param verbose logical, if `TRUE` reports how many samples, spots/cells and +#' genes were removed (and says explicitly when nothing was filtered). #' @return an STlist containing the filtered data #' #' @examples @@ -88,11 +99,16 @@ filter_data = function(x=NULL, rm_spots=NULL, rm_genes=NULL, rm_genes_expr=NULL, - spot_pct_expr="^MT-"){ + spot_pct_expr="^MT-", + verbose=TRUE){ # Check than an STList was provided x = assert_stlist(x, message='Please, specify an STList to filter.', check_class=FALSE) + # Record the starting dimensions so the effect of this call can be reported, + # and so a no-op call is visible instead of silent. + dims_before = lapply(x@counts, dim) + # 1. Remove entire samples/tissues x = filter_stage_samples(x, rm_tissue) @@ -115,6 +131,25 @@ filter_data = function(x=NULL, spot_minpct, spot_maxpct, gene_minreads, gene_maxreads, gene_minspots, gene_maxspots, gene_minpct, gene_maxpct, spot_pct_expr) + if(verbose){ + shared = intersect(names(dims_before), names(x@counts)) + samples_rm = length(setdiff(names(dims_before), names(x@counts))) + spots_rm = sum(vapply(shared, function(s) dims_before[[s]][2] - ncol(x@counts[[s]]), numeric(1))) + genes_rm = sum(vapply(shared, function(s) dims_before[[s]][1] - nrow(x@counts[[s]]), numeric(1))) + + if(samples_rm == 0 && spots_rm == 0 && genes_rm == 0){ + # Every threshold defaults to 0 and no rm_* argument was given, so this is + # a pass-through. Say so: previously it looked like filtering had happened. + message(paste0("filter_data: nothing was filtered. All count thresholds default to 0 ", + "(and the *_max* thresholds to NULL), so this call returned the STlist ", + "unchanged. Set at least one of spot_minreads, spot_mingenes, gene_minreads ", + "or gene_minspots (and/or the matching *_max*/*_minpct*) to filter.")) + } else{ + message(sprintf("filter_data: removed %d sample(s), %d spot(s)/cell(s) and %d gene(s).", + samples_rm, spots_rm, genes_rm)) + } + } + return(x) } diff --git a/R/gene_interpolation.R b/R/gene_interpolation.R index 55d3bb5..8e4ac9f 100644 --- a/R/gene_interpolation.R +++ b/R/gene_interpolation.R @@ -85,7 +85,7 @@ gene_interpolation = function(x=NULL, genes='top', top_n=10, samples=NULL, cores # Test that a gene name was entered. if(is.null(genes)) { - stop("Please, enter one or more genes to plot.") + raise_err(err_code='error0091') } # If genes='top', get names of 10 genes with the highest standard deviation. @@ -177,9 +177,6 @@ gene_interpolation = function(x=NULL, genes='top', top_n=10, samples=NULL, cores # Define cores available cores = resolve_cores(length(unique(combo[[1]])), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Loop through combinations of samples kriging_list = sge_lapply(seq_along(1:length(as.vector(unique(combo[[1]])))), function(i_combo){ diff --git a/R/import_visium.R b/R/import_visium.R index 14f95f5..34381d3 100644 --- a/R/import_visium.R +++ b/R/import_visium.R @@ -15,6 +15,20 @@ # @return x A list with two objects: Visium counts in `dgCMatrix` sparse format and # a data frames with spot coordinates. # +# R.utils is a RUNTIME dependency of data.table::fread(), which loads it to +# decompress .gz input read straight from a path -- which is what the three +# fread() calls below do, since Cell Ranger always emits features.tsv.gz, +# barcodes.tsv.gz and matrix.mtx.gz. Because fread() loads it internally rather +# than this package calling it by name, static analysis cannot see the use, and +# R CMD check reports R.utils as a declared-but-unused Import. Naming a symbol +# here makes the dependency visible to that check and puts the reason next to +# the calls that need it; the decompression still happens inside fread(). +# +# Do NOT move R.utils to Suggests to silence the NOTE: a minimal install then +# cannot read standard 10x MEX output at all, which is the regression that +# commit 98097bc fixed. +#' @importFrom R.utils gunzip +# # import_visium = function(features_fp=NULL, barcodes_fp=NULL, counts_fp=NULL, coords_fp=NULL){ diff --git a/R/plot_spatial_expression.R b/R/plot_spatial_expression.R index 771cb4b..46487d8 100644 --- a/R/plot_spatial_expression.R +++ b/R/plot_spatial_expression.R @@ -43,11 +43,17 @@ plot_spatial_expression = function(x=NULL, genes=NULL, samples=NULL, color_pal=' char_transform='none', post_check='grep', message='The requested samples are not present in the STList spatial metadata.') - # Select appropriate slot to take counts from + # Select appropriate slot to take counts from. The slot NAME is kept alongside + # the list, because each sample's matrix is read from `x` through the accessors + # below rather than off this list: a slot element is an sge_manifest when the + # parquet backing is in use, and rownames() is NULL on one. `counts` stays the + # accumulator the rest of the function iterates over. if(data_type == 'tr'){ counts = x@tr_counts[samples] + data_slot = 'tr_counts' }else if(data_type == 'raw'){ counts = x@counts[samples] + data_slot = 'counts' # Expand sparse matrices # for(i in samples){ # counts[[i]] = expandSparse(counts[[i]]) @@ -60,7 +66,7 @@ plot_spatial_expression = function(x=NULL, genes=NULL, samples=NULL, color_pal=' # Extract genes and trasnpose expression data (to get genes in columns) # Also join coordinate data for(i in samples){ - if(any(rownames(counts[[i]]) %in% genes)){ + if(any(sample_genes(x, i, data_slot) %in% genes)){ # counts[[i]] = counts[[i]] %>% # expandSparse() %>% # tibble::rownames_to_column(var='gene') %>% @@ -72,7 +78,7 @@ plot_spatial_expression = function(x=NULL, genes=NULL, samples=NULL, color_pal=' # dplyr::left_join(x@spatial_meta[[i]] %>% # dplyr::select(libname, xpos, ypos), ., by='libname') - counts[[i]] = expandSparse(counts[[i]][rownames(counts[[i]]) %in% genes, , drop=FALSE], transpose=TRUE) %>% + counts[[i]] = expandSparse(sample_slot_counts(x, i, data_slot, genes=genes), transpose=TRUE) %>% tibble::rownames_to_column(var='libname') %>% dplyr::left_join(x@spatial_meta[[i]] %>% dplyr::select(libname, xpos, ypos), ., by='libname') diff --git a/R/seurat_helpers.R b/R/seurat_helpers.R index d1c05d5..909937b 100644 --- a/R/seurat_helpers.R +++ b/R/seurat_helpers.R @@ -72,6 +72,22 @@ Seurat_FindVariableFeatures = function(object=NULL){ hvf.info$variance.expected <- 0 hvf.info$variance.standardized <- 0 not.const <- hvf.info$variance > 0 + + # The loess below is fit across GENES, on the non-constant ones only, so it + # has a minimum data requirement that the rest of this function does not. At + # span=0.3 and loess' default degree=2 it needs 4 such genes; with 1-3 it + # stops with 'span is too small', an internal stats message naming neither + # the sample nor the cause. Note the count that matters is of non-constant + # genes, not of genes: a 100-gene matrix in which only 3 vary fails too. + # + # Returning NULL rather than raising lets calculate_vst() decide, because the + # right answer differs by caller -- transform_data() can still deliver the + # normalization a caller actually asked for, while a topgenes selection + # genuinely cannot proceed. + if(sum(not.const) < 4){ + return(NULL) + } + fit <- loess( formula = log10(x = variance) ~ log10(x = mean), data = hvf.info[not.const, ], diff --git a/R/stlist_readers.R b/R/stlist_readers.R index 8500447..81dded4 100644 --- a/R/stlist_readers.R +++ b/R/stlist_readers.R @@ -706,11 +706,17 @@ seurat_platform = function(obj){ #' spot barcodes are only unique within a sample in the general case, and a merged #' Seurat object requires globally unique cell names. #' +#' Genes not shared by every requested sample are dropped, with a message +#' reporting how many, since Seurat holds a single matrix across all cells. +#' #' @param x an STlist #' @param assay the assay name to create. Default `'Spatial'` #' @param samples the samples to include. If NULL (default), all samples #' @return a Seurat object #' +#' @seealso [STlist()] accepts a Seurat object as `rnacounts`, so the conversion +#' round-trips. +#' #' @export # as_Seurat = function(x=NULL, assay='Spatial', samples=NULL){ diff --git a/R/store_parquet.R b/R/store_parquet.R index 0f1fbff..87ef824 100644 --- a/R/store_parquet.R +++ b/R/store_parquet.R @@ -13,12 +13,19 @@ # One parquet file per sample per slot, schema (gene_idx int32, cell_idx int32, # value double), sorted by (gene_idx, cell_idx). # -# Sorting by gene gives parquet row-group min/max statistics on gene_idx, so -# filter(gene_idx %in% ...) prunes whole row groups without reading them -- which -# is the dominant access pattern in this package (STdiff, STgradient, STenrich and -# the gene plots all want ~100 genes by all spots). Physically hive-partitioning by -# gene would give finer pruning but create tens of thousands of tiny files, which -# arrow handles badly. +# Sorting by gene gives parquet row-group min/max statistics on gene_idx, which is +# what a reader would need in order to skip whole row groups for +# filter(gene_idx %in% ...) -- the dominant access pattern in this package +# (STdiff, STgradient, STenrich and the gene plots all want ~100 genes by all +# spots). Physically hive-partitioning by gene would give finer granularity but +# create tens of thousands of tiny files, which arrow handles badly. +# +# NOTE that nothing currently exploits those statistics: sge_store_materialize() +# below reads with arrow::read_parquet() and filters the resulting Table, so a +# gene-subset read still performs whole-file I/O and only the returned matrix is +# smaller. Skipping row groups would need arrow::open_dataset() (or a row-group +# selection through ParquetFileReader). So the sort key is correctness and +# future-proofing today, not a measured speedup -- do not describe it as one. # # Including cell_idx in the sort key is not cosmetic. It makes a per-gene # group_by/sum visit values in the same order Matrix::rowMeans walks a row, which @@ -66,7 +73,11 @@ new_sge_manifest = function(sample, store_id, path, generation, genes, cells, is_sge_manifest = function(x) inherits(x, 'sge_manifest') -#' @export +# Registered as an S3 method, not exported as a plain function: a bare @export +# makes roxygen2 >= 8 emit export(print.sge_manifest) instead of +# S3method(print, sge_manifest), which leaves print() on a manifest undispatched +# unless the package happens to be attached. +#' @exportS3Method base::print print.sge_manifest = function(x, ...){ cat(sprintf(' %s: %d genes x %d cells, %.0f nonzero, gen %d\n', x$sample, x$n_genes, x$n_cells, x$nnz, x$generation)) @@ -221,15 +232,23 @@ sge_store_materialize = function(m, genes = NULL, cells = NULL){ #' Matrices are stored in COO (long) form, one file per sample per slot, sorted by #' gene then cell. `STlist_to_memory()` reverses the conversion. #' -#' Note the store is a directory of files, not part of the R object. An STlist -#' saved with `saveRDS()` records paths, so moving or deleting `root` breaks it; -#' `validate_store()` reports that rather than failing obscurely later. +#' Note what this does and does not buy. It buys capacity: an STlist larger than +#' RAM can be held and read in gene-subset slices. It does not currently speed +#' anything up -- aggregate operations still materialize and compute in memory, so +#' a backed STlist is slower on those paths than an in-memory one. +#' +#' The store is a directory of files, not part of the R object. An STlist saved +#' with `saveRDS()` records paths, so moving or deleting `root` breaks it; +#' `validate_store()` reports that rather than failing obscurely later. A store +#' written under `tempdir()` is flagged as non-portable for the same reason. #' #' @param x an STlist #' @param root directory to write the store into. Created if absent #' @param overwrite logical, whether to overwrite an existing store at `root` #' @return an STlist whose count slots are on-disk backed #' +#' @seealso [STlist_to_memory()], [validate_store()], [is_backed()] +#' #' @export # STlist_to_disk = function(x = NULL, root = NULL, overwrite = FALSE){ @@ -276,9 +295,16 @@ STlist_to_disk = function(x = NULL, root = NULL, overwrite = FALSE){ ## #' @title STlist_to_memory: Bring an on-disk STlist back into memory #' @description Reverses `STlist_to_disk()`, materializing every backed matrix. +#' @details +#' The round trip is exact: COO stores the values themselves and the manifest +#' carries dimensions and dimnames, so nothing is inferred on the way back. An +#' STlist that was never backed is returned unchanged. +#' #' @param x an STlist, backed or not #' @return an STlist with in-memory count matrices #' +#' @seealso [STlist_to_disk()] +#' #' @export # STlist_to_memory = function(x = NULL){ @@ -296,8 +322,13 @@ STlist_to_memory = function(x = NULL){ ## #' @title is_backed: Is an STlist's expression data stored on disk? +#' @description Reports whether an STlist's count matrices are held in on-disk +#' parquet files rather than in memory. #' @param x an STlist #' @return logical +#' +#' @seealso [STlist_to_disk()] +#' #' @export # is_backed = function(x = NULL){ @@ -311,17 +342,25 @@ is_backed = function(x = NULL){ #' @description Verifies that a backed STlist's files exist and still match what #' its manifests record, reading parquet footers only. #' @details -#' Checks sample order against the recorded `sample_order` (fidelity rule 7), that -#' every file exists and its size/mtime fingerprint is unchanged, that dimnames -#' lengths agree with the recorded dimensions, and that `@tr_counts` genes and -#' cells are subsets of `@counts`' in the same relative order -- the invariant -#' `filter_data()` assumes. With `deep=TRUE`, also reads the data to check index -#' bounds and duplicate coordinates. +#' Checks sample order against the order recorded when the store was written, +#' that every file exists and its size/mtime fingerprint is unchanged, that +#' dimnames lengths agree with the recorded dimensions, and that `@tr_counts` +#' genes and cells are subsets of `@counts`' in the same relative order -- the +#' invariant `filter_data()` assumes. +#' +#' With `deep=TRUE`, also reads the data to check that stored coordinates are in +#' bounds and not duplicated. +#' +#' The failure this is most useful for is a store directory that has been moved +#' or deleted after the STlist was saved with `saveRDS()`, which it reports as +#' such rather than surfacing later as an error from inside an analysis. #' #' @param x a backed STlist #' @param deep logical, whether to read data pages as well as metadata #' @return invisibly TRUE, or stops with the first problem found #' +#' @seealso [STlist_to_disk()], [is_backed()] +#' #' @export # validate_store = function(x = NULL, deep = FALSE){ diff --git a/R/transform_data.R b/R/transform_data.R index 7b6b0d6..eed7107 100644 --- a/R/transform_data.R +++ b/R/transform_data.R @@ -23,7 +23,15 @@ #' @param cores integer indicating the number of cores to use during parallelization. #' If NULL, the function uses half of the available cores at a maximum. The parallelization #' uses `parallel::mclapply` and works only in Unix systems. -#' @return x an updated STlist with transformed counts. +#' @return x an updated STlist with transformed counts. `gene_meta` gains +#' `vst.variance.standardized` (Seurat's standardized variance, computed from the +#' raw counts) alongside `gene_mean` and `gene_stdevs`, so that "top variable +#' gene" selection is the same whichever function runs first. +#' +#' That column requires fitting a variance-mean trend across genes, which needs +#' at least four genes of non-zero variance. A sample with fewer is left without +#' it and warned about by name, rather than failing the transformation; functions +#' that rank genes by variability will not work on such a sample. #' #' @examples #' \donttest{ @@ -117,6 +125,15 @@ transform_data = function(x=NULL, method='log', scale_f=10000, sct_n_regr_genes= # Copy names of the list names(x@gene_meta) = names(x@counts) + # Populate the standardized variance (VST) column here, rather than leaving it + # to whichever analysis happens to run first. Previously `gene_meta` held only + # gene_mean/gene_stdevs after transform_data(), and VST appeared later -- added + # as a side effect of STclust()/gene_interpolation(). So the "top variable + # genes" a user could see (get_gene_meta) and the ones a downstream function + # would pick depended on call order. calculate_vst() is idempotent and + # left-joins onto the columns set above, so this only adds a column. + x = calculate_vst(x=x, samples=names(x@counts), cores=cores) + return(x) } @@ -144,9 +161,6 @@ log_transf = function(x=NULL, scale_f=NULL, cores=NULL){ # Detect usable cores cores = resolve_cores(length(x@counts), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Perform log-transformation on parallel if possible. # @@ -189,9 +203,6 @@ sct_transf = function(x=NULL, sct_n_regr_genes=3000, sct_min_cells=5, cores=NULL # Detect usable cores cores = resolve_cores(length(x@counts), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Payload built outside the call so the closure captures only the two scalar # parameters. See R/utils_parallel.R on what this buys. @@ -312,9 +323,18 @@ sct_transf_one_sample = function(counts_mat, sample_name, sct_n_regr_genes, sct_ libsizes = libsizes[libsizes != 0] } - # Apply SCTransform - df_tmp = sctransform::vst(df_tmp, n_genes=sct_n_regr_genes, min_cells=sct_min_cells, - return_corrected_umi=T, verbosity=0) + # Apply SCTransform. sctransform's own failure on a small or degenerate sample + # surfaces as an opaque "missing value where TRUE/FALSE needed" (after a + # "Caught simpleError. Canceling all iterations"), which names neither the + # sample nor the function, so translate it. + df_tmp = tryCatch( + sctransform::vst(df_tmp, n_genes=sct_n_regr_genes, min_cells=sct_min_cells, + return_corrected_umi=T, verbosity=0), + error = function(e){ + raise_err(err_code='error0094', samplename=NULL, + sample_name, nrow(df_tmp), ncol(df_tmp), sct_min_cells, + conditionMessage(e)) + }) # log transform the corrected UMI counts from SCTransform df_tmp = log1p(df_tmp[['umi_corrected']]) diff --git a/R/utils.R b/R/utils.R index 6d0796e..faf90b9 100644 --- a/R/utils.R +++ b/R/utils.R @@ -95,6 +95,14 @@ tissue_names = function(x){ #' @importFrom methods as is new #' @importFrom grDevices colorRampPalette # +# .hasSlot is declared here rather than beside its two uses in +# R/stlist_readers.R because roxygen2 >= 8 drops an @importFrom whose symbol it +# cannot see being called -- and those are conditional calls on a Seurat object, +# which is in Suggests. Without the import, reading a Seurat image slot fails on +# a minimal install. A CI step greps NAMESPACE for it, so a future document() +# run cannot silently remove it again. +#' @importFrom methods .hasSlot +# # color_parse = function(color_pal=NULL, n_cats=NULL){ # Get color palette and number of colors needed. @@ -138,7 +146,13 @@ color_parse = function(color_pal=NULL, n_cats=NULL){ #' can be used for plotting along with other spatialGE plots. #' #' @param x an STlist -#' @param images a string indicating a folder to load images from +#' @param images image file paths or one or more folders to load images from. +#' A named character vector (`c(sample_name = "path/to/image.png")`) maps +#' samples to files explicitly and bypasses name matching. An unnamed vector +#' is matched against the sample names in `x`; any element that is an existing +#' directory is expanded to the image files it contains. Image filenames are +#' matched to sample names by looking for `.` in the filename and, +#' failing that, a normalized prefix match (case- and separator-insensitive). #' @return an STlist with images #' #' @export @@ -152,29 +166,92 @@ load_images = function(x=NULL, images=NULL){ if(is.null(images)){ stop("Please, provide a vector with images file paths.") - } else{ - if(length(images) == 1 & dir.exists(images)){ # In case a directory was provided - images = list.files(images, full.names=T) - } } + if(!is.character(images) || length(images) == 0){ + stop("`images` must be a character vector of image file paths or folders.") + } + + # A named vector maps samples to files directly, which is the escape hatch when + # filenames do not resemble the sample names at all (e.g. Visium exports that + # name images after a GEO accession rather than the sample folder). + explicit_map = NULL + if(!is.null(names(images)) && any(nzchar(names(images)))){ + explicit_map = images[nzchar(names(images))] + } + paths = unname(images) + + # Expand any directories (one or several) into the image files they contain. + is_dir = dir.exists(paths) + if(any(is_dir)){ + from_dirs = unlist(lapply(paths[is_dir], list.files, full.names=TRUE), use.names=FALSE) + paths = c(paths[!is_dir], from_dirs) + } + + # Keep only existing files with an image extension. + keep = file.exists(paths) & grepl('\\.(png|jpg|jpeg)$', paths, ignore.case=TRUE) + if(!any(keep)){ + stop("None of the supplied paths are existing .png, .jpg or .jpeg image files.") + } + images = unique(paths[keep]) + + # Tolerant key for fallback matching: lowercase, separators removed. + norm_key = function(z) gsub('[^a-z0-9]', '', tolower(basename(z))) # Process each image. + unmatched = c() for(i in names(x@counts)){ - fp = grep(paste0(i, '\\.'), images, value=T) - if(length(fp) == 0){ - message(paste0("Image for sample ", i, " was not found.\n")) - next + fp = NULL + + # 1. Explicit sample -> file mapping. + if(!is.null(explicit_map) && i %in% names(explicit_map)){ + cand = explicit_map[[i]] + if(any(file.exists(cand))){ + fp = cand[file.exists(cand)][1] + } } - # Return warning if more than one file matches the sample name - if(length(fp) > 1){ - message(paste0("Multiple image files matched sample ", i, ". Using the first match (", fp[1], ").")) + # 2. Documented convention: the filename contains `.`. + if(is.null(fp)){ + hit = grep(paste0(i, '\\.'), images, value=TRUE) + if(length(hit) > 1){ + warning(paste0("Multiple image files matched sample ", i, + ". Using the first match (", hit[1], ")."), call.=FALSE) + } + if(length(hit) >= 1){ + fp = hit[1] + } } - if(grepl('jpg$', fp[1])){ # CosMx uses jpeg files - img_obj = jpeg::readJPEG(fp[1]) + # 3. Fallback: normalized prefix match (case- and separator-insensitive). + if(is.null(fp)){ + key = norm_key(i) + hit = images[startsWith(norm_key(images), key)] + if(length(hit) >= 1){ + fp = hit[1] + } + } + + if(is.null(fp)){ + unmatched = c(unmatched, i) + next + } + + # Pick the decoder from the extension, but fall back to the other one: image + # files are frequently mislabelled (e.g. a PNG saved as .jpg), and the + # decoder's own error does not say which file it was reading. + if(grepl('\\.jpe?g$', fp, ignore.case=TRUE)){ # CosMx uses jpeg files + img_obj = tryCatch(jpeg::readJPEG(fp), error=function(e) NULL) + if(is.null(img_obj)) img_obj = tryCatch(png::readPNG(fp), error=function(e) NULL) } else{ - img_obj = png::readPNG(fp[1]) + img_obj = tryCatch(png::readPNG(fp), error=function(e) NULL) + if(is.null(img_obj)) img_obj = tryCatch(jpeg::readJPEG(fp), error=function(e) NULL) + } + + if(is.null(img_obj)){ + warning(paste0("Could not read image file '", fp, "' for sample ", i, + " as PNG or JPEG; skipping this sample."), call.=FALSE) + unmatched = c(unmatched, i) + next } # Downsize image if too large @@ -184,6 +261,16 @@ load_images = function(x=NULL, images=NULL){ x@misc[['sp_images']][[i]] = img_obj } + + # Report unmatched samples once, with the convention to follow. + if(length(unmatched) > 0){ + warning(paste0("No image found for sample(s): ", paste(unmatched, collapse=', '), + ". Image filenames must contain '.' (for example '", + unmatched[1], ".png'), or pass a named vector mapping sample names ", + "to file paths, e.g. images=c(", unmatched[1], "='path/to/image.png')."), + call.=FALSE) + } + return(x) } @@ -219,9 +306,6 @@ create_listw_from_knn = function(x=NULL, ks=NULL){ create_listw_from_dist = function(x=NULL, cores=NULL){ # Define cores available cores = resolve_cores(length(x@spatial_meta), cores, coerce='as_integer') - if(is.na(cores)){ - stop('Could not recognize number of cores requested') - } # Create distance matrix based on the coordinates of each sampled location. listw_list = sge_lapply(seq(names(x@spatial_meta)), function(i){ @@ -358,13 +442,30 @@ get_gene_meta = function(x=NULL, sthet_only=FALSE){ ## # @title raise_err # -raise_err = function(err_code=NULL, samplename=NULL){ +raise_err = function(err_code=NULL, samplename=NULL, ...){ if(is.null(.err_db_cache$err_db)){ pkg_fp = list.files(system.file(package='spatialGE'), full.names=T, pattern='err\\.csv') .err_db_cache$err_db = suppressWarnings(utils::read.csv(pkg_fp, header=F, quote="'")) } err_db = .err_db_cache$err_db str_to_print = err_db[[2]][ err_db[[1]] == err_code ] + + # An unknown or missing code used to give character(0), and stop(character(0)) + # fails with "argument is of length zero" -- which names neither the typo'd code + # nor the function. Name it here instead. + if(length(str_to_print) != 1 || is.na(str_to_print)){ + stop(paste0('spatialGE exception: internal error - unknown error code ', + if(is.null(err_code)) '' else err_code, '.'), call.=F) + } + + # Optional sprintf() formatting. Messages that embed gene names, sample sizes or + # thresholds otherwise have to be written inline at the call site, where they + # drift from this catalog and lose the shared wording. + dots = list(...) + if(length(dots) > 0){ + str_to_print = do.call(sprintf, c(list(str_to_print), dots)) + } + if(is.null(samplename)){ stop(paste0('spatialGE exception: ', str_to_print), call.=F) } else{ @@ -391,7 +492,12 @@ calculate_vst = function(x=NULL, samples=NULL, cores=NULL){ # Find tops variable genes using Seurat approach # First check if VST hasn't been calculated. If not, calculate if(!any(colnames(x@gene_meta[[i]]) == 'vst.variance.standardized')){ - vst_tmp = Seurat_FindVariableFeatures(sample_counts(x, i)) %>% + vst_raw = Seurat_FindVariableFeatures(sample_counts(x, i)) + # Too few non-constant genes for the loess fit. Reported as NA rather + # than warned here: this runs inside a fork, where a warning() is not + # reliably delivered to the caller, so the parent loop below emits it. + if(is.null(vst_raw)) return(NA) + vst_tmp = vst_raw %>% tibble::rownames_to_column(var='gene') %>% dplyr::select('gene', 'vst.variance.standardized') %>% dplyr::left_join(x@gene_meta[[i]], ., by='gene') @@ -403,14 +509,32 @@ calculate_vst = function(x=NULL, samples=NULL, cores=NULL){ names(vst_ls) = samples for(i in samples){ - if(!is.null(vst_ls[[i]])){ + if(identical(vst_ls[[i]], NA)){ + # Leave @gene_meta without the column rather than failing: the caller + # asked for a transformation, and gene_mean/gene_stdevs are still there. + # calculate_vst() only computes when the column is absent, so whichever + # analysis next needs it will retry rather than inherit a wrong value. + warning(paste0('Sample ', i, ' has fewer than 4 genes with non-zero variance, ', + 'which is too few to fit the variance-mean trend. ', + 'Skipping vst.variance.standardized for this sample; ', + 'functions selecting genes by variability (topgenes) will not work on it.')) + } else if(!is.null(vst_ls[[i]])){ x@gene_meta[[i]] = vst_ls[[i]] } } return(x) } else{ #vst_tmp = Seurat_FindVariableFeatures(sample_counts(x, i)) %>% - vst_tmp = Seurat_FindVariableFeatures(x) %>% + vst_raw = Seurat_FindVariableFeatures(x) + # The matrix form exists to rank genes by variability for a caller's + # `topgenes`. If the trend cannot be fit there is no ranking to return, so + # this is an error rather than a skip (error when nothing matches, warn when + # only some does). The message names STgradient because that is the only + # caller of this branch; a second caller should add its own code. + if(is.null(vst_raw)){ + raise_err(err_code='error0097', samplename=NULL, nrow(x)) + } + vst_tmp = vst_raw %>% tibble::rownames_to_column(var='gene') %>% dplyr::select('gene', 'vst.variance.standardized') return(vst_tmp) diff --git a/R/utils_accessors.R b/R/utils_accessors.R index ae1e875..f96aaf0 100644 --- a/R/utils_accessors.R +++ b/R/utils_accessors.R @@ -13,9 +13,11 @@ # # When the optional parquet backing is in use (see R/store_parquet.R) a slot # element is an sge_manifest rather than a dgCMatrix, so the two matrix accessors -# materialize on demand. `genes=` is forwarded to the store so a gene-subset read -# touches only the row groups it needs; in memory it is an ordinary subset. This is -# the whole reason the accessor layer exists. +# materialize on demand. `genes=` is forwarded to the store, which builds the +# subset at its final size rather than materializing the whole matrix and masking +# it; in memory it is an ordinary subset. Note the forward saves allocation, not +# I/O -- the store reads the whole parquet file either way. This is the whole +# reason the accessor layer exists. sample_counts = function(x, sample, genes=NULL){ m = x@counts[[sample]] if(is_sge_manifest(m)) return(sge_store_materialize(m, genes=genes)) @@ -30,6 +32,16 @@ sample_tr_counts = function(x, sample, genes=NULL){ m[rownames(m) %in% genes, , drop=FALSE] } +# The materializing counterpart to sample_slot_mtx() below: resolves the slot by +# name and returns values, so a call site that already branches on the plotting +# functions' `data_type` ('tr'/'raw') does not branch a second time on which of +# the two accessors above to call. `genes=` is forwarded, so the subset is built +# at its final size rather than taken off a fully materialized matrix. +sample_slot_counts = function(x, sample, slot=c('counts', 'tr_counts'), genes=NULL){ + slot = match.arg(slot) + if(slot == 'counts') sample_counts(x, sample, genes=genes) else sample_tr_counts(x, sample, genes=genes) +} + sample_spatial_meta = function(x, sample) x@spatial_meta[[sample]] sample_gene_meta = function(x, sample) x@gene_meta[[sample]] diff --git a/R/utils_parallel.R b/R/utils_parallel.R index 1ebf810..a233633 100644 --- a/R/utils_parallel.R +++ b/R/utils_parallel.R @@ -26,12 +26,21 @@ sge_cores_override = function(){ # replacing the boilerplate that used to be duplicated at every such site: # force 1 core on Windows, auto-detect via count_cores(n) when the user did # not request a specific number, otherwise coerce whatever the user passed. +# +# Validation of an unusable `cores` value lives here too. It used to be the +# caller's job and was done inconsistently: of the 17 call sites, some raised +# error0032, others error0036, five raised an uncatalogued bare stop(), and +# transform_data()'s gene_meta path did not check at all -- so `cores='abc'` +# there became NA and was handed straight to sge_lapply(). Resolving it in one +# place makes the behavior uniform and removes six copies of the same guard. +# # @param n size of the work unit, passed to count_cores() when cores=NULL. -# @param cores user-requested cores, or NULL to auto-detect. -# @param coerce how to coerce a user-supplied cores: 'as_integer' (may -# produce NA -- the caller is responsible for checking and raising, as -# before), 'ceiling', or 'none' (used as-is, no coercion). -# @return an integer (or NA if coerce='as_integer' could not parse cores). +# @param cores user-requested cores, or NULL to auto-detect. A value that +# cannot be resolved raises error0093. +# @param coerce how to coerce a user-supplied cores: 'as_integer', 'ceiling', +# or 'none' (used as-is, no coercion). +# @return the resolved core count. The caller's coercion is preserved: a +# non-integral value survives for coerce='ceiling'/'none'. # resolve_cores = function(n, cores=NULL, coerce=c('as_integer', 'ceiling', 'none')){ coerce = match.arg(coerce) @@ -42,7 +51,7 @@ resolve_cores = function(n, cores=NULL, coerce=c('as_integer', 'ceiling', 'none' # work on the one platform where the parallel behavior differs most. override = sge_cores_override() if(!is.null(override)){ - return(override) + return(check_resolved_cores(override)) } # Windows has no fork(), so mclapply falls back to serial. It is no longer @@ -51,13 +60,44 @@ resolve_cores = function(n, cores=NULL, coerce=c('as_integer', 'ceiling', 'none' # serial on Windows regardless of what the user asked for. if(is.null(cores)){ - return(count_cores(n)) + return(check_resolved_cores(count_cores(n))) } - switch(coerce, + # suppressWarnings: as.integer('abc') warns "NAs introduced by coercion" and + # then the check below raises a catalogued error that actually explains what to + # do. Leaving the warning in place printed both. + resolved = suppressWarnings(switch(coerce, as_integer=as.integer(cores), ceiling=ceiling(cores), - none=cores) + none=cores)) + + check_resolved_cores(resolved) +} + + +## +# @title check_resolved_cores +# @description Single guard for the result of cores resolution: it must be one +# finite, positive number. Kept separate so every return path in resolve_cores() +# passes through it. +# +# Validates only -- the value is returned unchanged. coerce='ceiling' and +# 'none' deliberately preserve a non-integral value (2.5 stays 2.5), and +# as.integer() here would silently truncate it to 2, breaking the fidelity rule +# that non-mclapply consumers depend on. This is also why validation cannot live +# in sge_lapply(): it never sees these call sites. +# +# @param resolved the candidate core count. +# @return `resolved`, unchanged, if usable; otherwise raises error0093. +# +check_resolved_cores = function(resolved){ + ok = length(resolved) == 1 && !is.na(resolved) && + is.finite(suppressWarnings(as.numeric(resolved))) && + suppressWarnings(as.numeric(resolved)) >= 1 + if(!ok){ + raise_err(err_code='error0093') + } + resolved } diff --git a/README.md b/README.md index 78b1be3..2f2728f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # spatialGE - + An R package for the visualization and analysis of spatially-resolved transcriptomics data, such as those generated with 10X Visium. The **spatialGE** package features a data object @@ -27,7 +27,7 @@ this publication: https://doi.org/10.1093/bioinformatics/btac145. For details on developed methods `STenrich`, `STgradient`, and `STdiff` please refer to the spatialGE documentation.

- +

## Installation @@ -61,9 +61,17 @@ spatialGE: quantification and visualization of the tumor microenvironment hetero transcriptomics. Bioinformatics, 38:2645-2647. https://doi.org/10.1093/bioinformatics/btac145 + diff --git a/cran-comments.md b/cran-comments.md index 1950355..cc8abde 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -7,38 +7,50 @@ ## R CMD check results -0 ERRORs. The NOTEs below are expected; the reasoning for each is given so a -reviewer does not have to reconstruct it. - -### NOTE: Namespace in Imports field not imported from: 'R.utils' - -This is a false positive and the dependency is load-bearing. - -`R.utils` is a **runtime** dependency of `data.table::fread()`, which requires it -to decompress `.gz` input read directly from a path. `import_visium()` and -`import_xenium()` call `fread()` on the gzipped `features`/`barcodes`/`matrix` -files that Cell Ranger and Xenium Ranger always produce, so with `R.utils` only in -Suggests a minimal install cannot read standard 10x MEX output at all. - -Because `fread()` loads it internally rather than spatialGE calling it by name, -static analysis cannot see the use. Moving it to Suggests would silence the NOTE -and reintroduce the failure. - -### NOTE: CRAN incoming feasibility / possibly invalid URL - -`https://clustrmaps.com/site/1bwt8` in README.md is a visitor-counter badge and -currently returns an error. It predates this release. It is not a documentation -or code link and can be removed if preferred. - -The remainder of this NOTE is the maintainer line plus the incoming-feasibility -check, which could not run in the local environment because the network blocks -access to the CRAN and Bioconductor package indexes. - -### WARNING: 'qpdf' is needed for checks on size reduction of PDFs - -Environmental, not a package property: `qpdf` is not installed on the machine that -ran the check. It is present on CRAN's check machines, so this does not reproduce -there. +0 ERRORs, 0 WARNINGs, 1 NOTE. + +### NOTE: checking for future file timestamps -- unable to verify current time + +Environmental, and the only finding left. The check compares file timestamps +against an external time service, and both services R consults +(`worldclockapi.com` and `worldtimeapi.org`) were unreachable or erroring when +this check ran -- the first returned HTTP 503, the second did not respond. The +submitting network was otherwise working normally at the time, so this is an +outage of those services rather than a local block, and R has no fallback. No +file in the tarball carries a future timestamp. + +### Findings fixed rather than explained + +Earlier drafts of this file explained six other findings. All are now fixed, and +are listed here only because a reviewer comparing submissions may look for them: + +* *Undocumented S4 methods* (`[`, `[[`, `length` on `STlist`) -- now documented, + including the `@param` entries for the generics' full argument lists and an + explicit alias for `[[`, whose registered signature loses its trailing `ANY`s. +* *Namespace in Imports field not imported from: 'R.utils'* -- `R.utils` is a + **runtime** dependency of `data.table::fread()`, which loads it to decompress + the gzipped `features`/`barcodes`/`matrix` files Cell Ranger always emits. + `fread()` loads it internally rather than spatialGE calling it, so static + analysis could not see the use; it is now named in an `@importFrom` beside + those `fread()` calls. Deliberately not moved to Suggests, which would silence + the NOTE by making a minimal install unable to read standard 10x MEX output. +* *'qpdf' is needed for checks on size reduction of PDFs* -- `qpdf` installed on + the machine that runs the check. +* *checking HTML version of manual* -- the machine had Apple's 2006 build of + HTML Tidy, so R skipped HTML validation; HTML Tidy 5.8.0 is now installed. +* *Possibly invalid URL `https://clustrmaps.com/site/1bwt8`* -- a visitor-counter + badge, now commented out in README.md. +* *Possibly invalid URL `https://support.10xgenomics.com/.../what-is-space-ranger`* + -- 10x Genomics appears to have retired that host (403 to any client, + including a browser user agent, with no redirect), so the vignette now refers + to Space Ranger without linking to it. + +Four `doi.org` citations and one `satijalab.org` page were also reported as +possibly invalid at one point. That was local TLS interception, not a problem +with the links: the check reported `libcurl error code 60` together with +`(Status without verification: OK)`, i.e. it confirmed each URL resolves and +only certificate verification had failed. Pointing R's libcurl at a CA bundle +that includes the institution's root resolves it, and all five verify normally. ## Downstream dependencies diff --git a/dev/ARCHITECTURE.md b/dev/ARCHITECTURE.md index 123e5aa..761a444 100644 --- a/dev/ARCHITECTURE.md +++ b/dev/ARCHITECTURE.md @@ -87,7 +87,8 @@ changes for an STlist built the normal way. It works because all matrix reads go through `R/utils_accessors.R`: `sample_counts()`/`sample_tr_counts()` materialize a manifest on demand (and -forward `genes=` so a subset read touches only the row groups it needs), while +forward `genes=` so the subset is built at its final size instead of being +masked off a fully materialized matrix), while `sample_dim()`/`sample_genes()`/`sample_cells()` answer from the manifest with zero I/O. That split is the whole reason the accessor layer was widened before the store existed — `base::nrow()` returns `NULL` on a manifest rather than @@ -95,9 +96,16 @@ erroring, so an unrouted dim read would have silently produced `NULL`. Layout: one file per sample per slot, schema `(gene_idx int32, cell_idx int32, value double)`, **sorted by -`(gene_idx, cell_idx)`**. Sorting by gene gives row-group min/max statistics so -`filter(gene_idx %in% ...)` prunes whole row groups — the dominant access pattern -here. Including `cell_idx` makes a per-gene aggregate visit values in the order +`(gene_idx, cell_idx)`**. Sorting by gene gives row-group min/max statistics, +which is what a reader *would* need to skip whole row groups for +`filter(gene_idx %in% ...)` — the dominant access pattern here. **Nothing +exploits them yet:** `sge_store_materialize()` reads via +`arrow::read_parquet()` and filters the resulting Table, so a gene-subset read +still does whole-file I/O and only the returned matrix shrinks. Row-group +skipping would need `arrow::open_dataset()`. Treat the sort key as a +correctness and future-proofing property, not a measured speedup — and do not +repeat the pruning claim in user-facing docs. +Including `cell_idx` makes a per-gene aggregate visit values in the order `Matrix::rowMeans` walks a row, which is what would let an arrow-side aggregate agree bit-for-bit. Ordering comes free from `Matrix::t()` rather than an explicit sort: a transposed `dgCMatrix` has the original genes as its columns. diff --git a/dev/ci/check_vignette_args.R b/dev/ci/check_vignette_args.R new file mode 100644 index 0000000..5278765 --- /dev/null +++ b/dev/ci/check_vignette_args.R @@ -0,0 +1,140 @@ +#!/usr/bin/env Rscript +# +# Static argument check for the package vignettes. +# +# Three of the four vignettes are listed in .Rbuildignore, so R CMD check only +# ever builds `basic_functions_vignette.Rmd`. The other three can therefore rot +# silently: a chunk that calls an exported function with an argument name that no +# longer exists is never executed by anything in CI, and nothing parses it either. +# +# This script extracts every R chunk from each .Rmd by hand, parses the combined +# code (catching syntax errors), and walks the AST looking for calls to exported +# spatialGE functions whose named arguments are not in that function's formals. +# +# Deliberately allowed: R performs *partial* matching of named arguments, so +# `compare_SThet(gene=)` resolves to the formal `genes=` and is legal -- it runs +# without error as long as only one formal starts with "gene". Such names are not +# reported. (They are still worth avoiding in documentation, but they are not +# broken.) What this catches is a name that matches no formal at all, e.g. after +# an argument is renamed or removed. +# +# Chunk extraction scans for the fences rather than using knitr::purl(), because +# purl() *evaluates* chunk options: these vignettes use `eval=net_check` (a +# variable defined only when the network is available), and under purl() those +# chunks error out so their code never reaches the output -- which silently hides +# exactly the code this check exists to inspect. +# +# Nothing here is evaluated, so it needs no network and no data. It can run on +# every push. +# +# Usage: Rscript dev/ci/check_vignette_args.R (from the package root) +# Exits non-zero if any problem is found. +# +# Usage: Rscript dev/ci/check_vignette_args.R (from the package root) +# Exits non-zero if any problem is found. + +suppressMessages(pkgload::load_all(".", compile = FALSE, quiet = TRUE)) + +exported <- getNamespaceExports("spatialGE") +ns <- asNamespace("spatialGE") + +vignettes <- list.files("vignettes", pattern = "[.]Rmd$", full.names = TRUE) +if (length(vignettes) == 0L) { + stop("No vignettes found; run this from the package root.") +} + +problems <- character() + +record <- function(file, msg) { + problems <<- c(problems, sprintf("%s: %s", basename(file), msg)) +} + +# Resolve a call head to an exported spatialGE function name, if it is one. +head_name <- function(hd) { + if (is.name(hd)) return(as.character(hd)) + # pkg::fn / pkg:::fn + if (is.call(hd) && length(hd) == 3L && + as.character(hd[[1]]) %in% c("::", ":::") && + identical(as.character(hd[[2]]), "spatialGE")) { + return(as.character(hd[[3]])) + } + NULL +} + +# Recursively inspect an expression for calls to exported functions. +walk <- function(e, file) { + if (!is.call(e)) return(invisible(NULL)) + + nm <- head_name(e[[1]]) + if (!is.null(nm) && nzchar(nm) && nm %in% exported) { + fn <- tryCatch(get(nm, envir = ns), error = function(...) NULL) + if (is.function(fn)) { + fmls <- names(formals(fn)) + has_dots <- "..." %in% fmls + # names(e)[-1] is "" for positional arguments; only check named ones. + supplied <- names(e)[-1] + supplied <- supplied[!is.na(supplied) & nzchar(supplied)] + for (a in supplied) { + if (a %in% fmls) next + # R allows unambiguous partial matching of argument names. + if (length(fmls[startsWith(fmls, a)]) > 0L) next + if (has_dots) next + record(file, sprintf( + "%s(): no argument named '%s'. Formals are: %s", + nm, a, paste(fmls, collapse = ", "))) + } + } + } + + for (i in seq_along(e)) { + if (!is.null(e[[i]])) walk(e[[i]], file) + } + invisible(NULL) +} + +# Return the R source of every ```{r ...} chunk in an .Rmd, as one string. +extract_chunks <- function(path) { + lines <- readLines(path, warn = FALSE) + n <- length(lines) + out <- character() + i <- 1L + while (i <= n) { + if (!grepl("^\\s*```+\\s*\\{r", lines[i])) { + i <- i + 1L + next + } + # A chunk header may span lines; it ends at the first line closing with '}'. + j <- i + while (j <= n && !grepl("\\}\\s*$", lines[j])) j <- j + 1L + if (j > n) break + code_start <- j + 1L + k <- code_start + while (k <= n && !grepl("^\\s*```+\\s*$", lines[k])) k <- k + 1L + if (k > code_start) out <- c(out, lines[code_start:(k - 1L)]) + i <- k + 1L + } + paste(out, collapse = "\n") +} + +for (v in vignettes) { + code <- extract_chunks(v) + if (!nzchar(trimws(code))) next + + exprs <- tryCatch(parse(text = code), error = function(err) { + record(v, paste("contains R that does not parse:", conditionMessage(err))) + NULL + }) + if (is.null(exprs)) next + + for (e in exprs) walk(e, v) +} + +if (length(problems) > 0L) { + cat("Vignette argument check FAILED:\n\n") + cat(paste0(" - ", problems, collapse = "\n"), "\n", sep = "") + cat("\nFix the vignette (or update the check) before releasing.\n") + quit(status = 1L) +} + +cat(sprintf("Vignette argument check passed (%d vignettes, no unknown arguments).\n", + length(vignettes))) diff --git a/dev/environment/README.md b/dev/environment/README.md index 038842b..94b7f85 100644 --- a/dev/environment/README.md +++ b/dev/environment/README.md @@ -68,14 +68,55 @@ export REQUESTS_CA_BUNDLE=/path/to/combined_cacert.pem ### Concrete values observed on the Moffitt network -The intercepting root is `O=Moffitt Cancer Center, CN=ca.moffitt.goskope.com`, -so the first command above is: +**There is more than one interceptor, and which one you get depends on where you +are.** An earlier version of this section named only +`CN=ca.moffitt.goskope.com` and told you to extract that one cert. That is not +enough: it is an *intermediate*, not a root, and a different network path +intercepts with an entirely different CA. Two chains observed, both on Moffitt +networks: + +| Where | Chain presented | Trust anchor needed | +|---|---|---| +| Netskope cloud proxy | `` → `ca.moffitt.goskope.com` → `caadmin.netskope.com` | `caadmin.netskope.com` | +| On-premises | `` → `Moffitt Issuing Authority` → `Moffitt Root CA` | `Moffitt Root CA` | + +Interception is also **per host, not per network**: on the cloud-proxy path +`conda.anaconda.org` was intercepted while `github.com` was not, so R's +`download.file()` from GitHub worked while `conda search` failed. On the +on-premises path `doi.org` and `satijalab.org` are intercepted, which makes +`R CMD check --as-cran` report every DOI citation as a possibly invalid URL +(with `libcurl error code 60` and, tellingly, `(Status without verification: +OK)`). + +So do not extract one CN by name. Take every corporate cert the keychain holds, +roots and intermediates, and let the extras be harmless: ```sh -security find-certificate -a -c ca.moffitt.goskope.com -p \ - /Library/Keychains/System.keychain > corp_roots.pem +security find-certificate -a -p /Library/Keychains/System.keychain > sys.pem + +python3 - <<'EOF' > corp_roots.pem +import re, subprocess +pem = open('sys.pem').read() +for c in re.findall(r'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----', pem, re.S): + subj = subprocess.run(['openssl', 'x509', '-noout', '-subject'], + input=c, capture_output=True, text=True).stdout.lower() + if 'moffitt' in subj or 'netskope' in subj: + print(c) +EOF + +cat /etc/ssl/cert.pem corp_roots.pem > combined_cacert.pem ``` +If you prefer to do the filtering by hand, note that `security +find-certificate -c "Moffitt Root CA"` returns **nothing** even though that +cert is present -- `-c` does not match its subject. Enumerate with `-a` and +filter on the decoded subject instead. On this machine that yields 11 corporate +certs, taking the bundle from 129 to 139. + +Verify the result is a superset before replacing a working bundle, by comparing +SHA-256 fingerprints of the old and new files; losing a public root here breaks +far more than it fixes. + Note that macOS trusts this CA via the system keychain, so `/usr/bin/curl` succeeds while conda's `curl` and conda R's libcurl both fail -- "curl works, so the network is fine" is a false conclusion here. `CURL_CA_BUNDLE=/etc/ssl/cert.pem` diff --git a/dev/xver/REPORT.md b/dev/xver/REPORT.md index 382d168..e47be16 100644 --- a/dev/xver/REPORT.md +++ b/dev/xver/REPORT.md @@ -235,3 +235,121 @@ produced *false* alarms rather than false clean: 5. The 5-sample pseudobulk fixture died on the fixture's deliberate zero-variance genes before reaching the heatmap, which is why delta 9 first showed as `MISSING_EXPECTED`. + +--- + +# Re-verification at HEAD, after the Tier 1 fixes + +The sweep above is pinned to `98097bc`, which by then was **54 commits ahead of +`main` but 36 behind HEAD**. Those 36 include output-affecting work — the SThet +C++ rewrite (`e631ddb`), the sparse end-to-end log transform (`8af5346`), the +sparse row-SD (`6913444`), `filter_data()`'s de-densification (`958fbff`), +the `Seurat_FindVariableFeatures()` input fix (`a9ee265`) and the LDOUBLE +correction in `STgradient()`'s distance mean (`0998e7e`) — so the headline above +did not cover the tree that would actually ship. This section does. + +## Method + +- Compared `main` (`849c174`, v1.2.2) against **HEAD plus the Tier 1 working-tree + changes** (v2.0.0). +- Data: `melanoma_thrane`, 4 samples (293 / 383 / 256 / 248 spots x ~16k genes). +- Pipeline: `STlist` -> `filter_data()` (defaults) -> `transform_data(method='log')` + -> `SThet(genes=<5>, method=c('moran','geary'))` -> `STclust(ws=0.025, ks='dtc', + deepSplit=FALSE)` -> `STenrich(score_type='avg', reps=200)`, unrestricted and + with `annot=`+`domain=` -> `STgradient(topgenes=100)` -> + `STdiff(test_type='t_test', topgenes=50)` -> `gene_interpolation()`. +- Cluster partitions were compared as *partitions*: each spot's label keyed by + `libname`, so a relabelling cannot hide as an order difference. + +**Build note (environment, not the package).** A fresh `R CMD INSTALL` of either +version fails here: conda clang 22 and the Xcode SDK's libc++ headers disagree +(`"remove_reference not implemented!"`), and neither `R_MAKEVARS_USER` nor a +package-level `src/Makevars` resolves it cleanly. Both versions were therefore +loaded with `pkgload::load_all(compile=FALSE)` against the same compiled helpers. +That is sound **for this comparison** because `SparseRowVar2` and +`SparseRowVarStd` — the only C++ entry points main's R code calls, confirmed by +grep over `main`'s `R/`) are **byte-identical** in source between the two +versions (`git diff main HEAD -- src/seurat_helpers.cpp +src/spatialge_helpers.cpp` is empty), and v2.0.0's shared object exports them with +unchanged signatures. + +## Result: no regression + +| Artifact | Verdict | +|---|---| +| `STlist` construction (per-sample dims) | identical | +| `filter_data()` output | identical | +| Transformed counts (sum and non-zero count per sample) | **bit-identical** (`tolerance = 0`) | +| `spatial_meta`, `sample_meta` | **bit-identical** | +| Cluster partitions (per-spot labels, all 4 samples) | **exactly identical** | +| `STenrich`, unrestricted and with `annot=`+`domain=` | identical | +| `STgradient()` (4 samples) | identical | +| `STdiff(test_type='t_test')` (4 samples) | identical | +| Kriging gene names; `@misc` key sets | identical | + +Differences, all accounted for: + +| Difference | Magnitude / cause | +|---|---| +| `@gene_meta` gains `vst.variance.standardized` | **intended** (Tier 1 fix) | +| `@gene_meta` Moran's I | max abs delta **5.0e-16** | +| `@gene_meta` Geary's C | max abs delta **1.4e-14** | + +The Moran/Geary deltas are the ~2e-15 effect NEWS already documents for +`SThet()`'s default statistics; they remain below the 2.9e-14 floor this report +measured earlier. + +## Intended, user-visible deltas introduced by the Tier 1 fixes + +These are deliberate and should be listed in NEWS rather than treated as drift: + +1. **`@gene_meta$vst.variance.standardized` is now populated by + `transform_data()`**, for both `method='log'` and `method='sct'`. Before, the + column appeared only as a side effect of whichever analysis ran first + (`STclust()`, `gene_interpolation()`), so the "top variable genes" a caller + could see -- and those a downstream function would select -- depended on call + order. `gene_stdevs` and VST rank the top-20 genes differently (only 6 + overlap), so this was observable, not cosmetic. +2. **`dim()` on an `STlist` now obeys the base contract.** It returns + `c(n_genes, n_spots)` for a single-sample object and `NULL` for a multi-sample + one, instead of a named list. This removes the `R CMD check` note and makes + `nrow()`/`ncol()` well defined. Nothing in the package called it. +3. **`STlist` gained `setValidity()`**, so a malformed object (sample-key + mismatch, spot count disagreeing with `spatial_meta`, unnamed matrices) is now + rejected at construction instead of failing later. + +## Also confirmed while re-checking + +- **No exported function was removed** between 1.2.2 and HEAD: `NAMESPACE` goes + from 24 to 29 exports, all additions (`as_Seurat`, `STlist_to_disk`, + `STlist_to_memory`, `is_backed`, `validate_store`). +- The public signatures of the shared API (`STlist`, `SThet`, `filter_data`, + `transform_data`) are **unchanged** between the two versions. +- Both platform readers work on the project's own public data: Visium/TNBC (8 + samples, `dgCMatrix`, e.g. 23755 x 1949) and CosMx/SMI (6 FOV-split samples, + 980 genes x ~3.3-5.3k cells), with `platform` detected as `visium` / `cosmx` + respectively and the downstream pipeline running on both. + +## Re-check after Tier 2 and Tier 3 + +The comparison above was re-run once more, against HEAD with the full Tier 2 +(error-handling consistency, centralised cores validation, docs/packaging) and +Tier 3 (STlist subsetting/`length()`, plus the `@gene_krige` validity fix) work +applied. **The verdict table is unchanged, item for item**: + +- still identical: `STlist`, dims, `filter_data()` output, transformed-count sums + (**bit-identical**), cluster partitions, `STenrich` (with and without + annotation+domain), `STgradient`, `STdiff`; +- still differing for the same two reasons as before: `@gene_meta` gains + `vst.variance.standardized`, and Moran's I / Geary's C carry float noise + (max abs delta 5.0e-16 / 1.4e-14). + +That is the expected result, and it is worth stating why rather than just +asserting "no change": none of the Tier 2/3 edits touch a numeric path. They +change which *error* is raised and in what words, centralise an argument check, +add documentation, add S4 methods (`length`, `[`) that previously did not exist +or errored, and correct a validity predicate. The one edit with real behavior is +the `@gene_krige` fix, and it only affects whether `validObject()` accepts an +object that was already built correctly. + + diff --git a/docs/404.html b/docs/404.html index 502b4e1..b43fa00 100644 --- a/docs/404.html +++ b/docs/404.html @@ -1,17 +1,15 @@ - - + Page not found (404) • spatialGE - - - - - - + + + + + @@ -39,7 +37,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -58,6 +56,9 @@
  • Basic functionality: Visualization, domain detection, and spatial heterogeneity
  • +
  • + On-disk STlists: working with data sets larger than memory +
  • Spatially-informed differential gene expression
  • @@ -73,7 +74,14 @@ Changelog - + @@ -109,7 +117,7 @@

    Page not found (404)

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/LICENSE-text.html b/docs/LICENSE-text.html index 7f02333..92c869d 100644 --- a/docs/LICENSE-text.html +++ b/docs/LICENSE-text.html @@ -1,5 +1,5 @@ -License • spatialGELicense • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -78,7 +87,7 @@

    License

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/LICENSE.html b/docs/LICENSE.html index a05d8ca..74e7f9d 100644 --- a/docs/LICENSE.html +++ b/docs/LICENSE.html @@ -1,5 +1,5 @@ -MIT License • spatialGEMIT License • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -82,7 +91,7 @@

    MIT License

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/articles/basic_functions_vignette.html b/docs/articles/basic_functions_vignette.html index c9cf209..4be4ca7 100644 --- a/docs/articles/basic_functions_vignette.html +++ b/docs/articles/basic_functions_vignette.html @@ -1,17 +1,15 @@ - - + Basic functionality: Visualization, domain detection, and spatial heterogeneity • spatialGE - - - - - - + + + + + @@ -38,7 +36,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -57,6 +55,9 @@
  • Basic functionality: Visualization, domain detection, and spatial heterogeneity
  • +
  • + On-disk STlists: working with data sets larger than memory +
  • Spatially-informed differential gene expression
  • @@ -72,7 +73,14 @@ Changelog - + @@ -89,9 +97,9 @@

    Basic functionality: Visualization, domain detection, and spatial heterogeneity

    -

    2025-04-28

    +

    2026-10-16

    - + Source: vignettes/basic_functions_vignette.Rmd @@ -104,8 +112,8 @@

    2025-04-28

    have been designed so that any data can be analyzed as long as it contains gene expression counts per spot or cell, and the spatial coordinates of those spots or cells. Specialized data input options are -available to allow interoperability with workflows such as Space -Ranger.

    +available to allow interoperability with workflows such as Space +Ranger (available from 10X Genomics).

    This tutorial covers basic analysis possible within spatialGE. Tutorials explaining more advanced spatial analyses and other data input types can be found in the documentation site of the spatialGE GitHub @@ -129,7 +137,7 @@

    Installation#devtools::install_github("fridleylab/spatialGE")

    To use spatialGE, load the package.

    -library('spatialGE')
    +library('spatialGE')

    Spatially-resolved expression of triple negative breast cancer tumor @@ -171,20 +179,29 @@

    +

    In this tutorial, data will be deposited in a temporary directory. -However, the download path can be changed within the following code -block:

    +The data is downloaded from this link:

    +lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/tnbc_bassiouni.zip?download='
    +

    The following code block creates a temporary directory:

    +
     visium_tmp = tempdir()
     unlink(visium_tmp, recursive=TRUE)
    -dir.create(visium_tmp)
    -#> Warning in dir.create(visium_tmp):
    -#> 'C:\Users\oscar\AppData\Local\Temp\Rtmpu8rGyg' already exists
    -download.file('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/FridleyLab/spatialGE_Data/raw/refs/heads/main/tnbc_bassiouni.zip?download=', 
    -              destfile=paste0(visium_tmp, '/', 'tnbc_bassiouni.zip'), mode='wb')
    -zip_tmp = list.files(visium_tmp, pattern='tnbc_bassiouni.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=visium_tmp)
    +dir.create(visium_tmp)

    +

    The data will be downloaded to the temporary directory. The data is +compressed in a zip file, which will be unzipped into a sub-directory +called tnbc_bassiouni:

    +
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(visium_tmp, '/', 'tnbc_bassiouni.zip'), mode='wb')
    +  zip_tmp = list.files(visium_tmp, pattern='tnbc_bassiouni.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=visium_tmp)
    +  net_check <<- TRUE
    +}, error = function(e) {
    +  message("Could not download data. Are you connected to the internet?")
    +  net_check <<- FALSE
    +})

    Creating an STList (Spatial Transcriptomics List) @@ -205,17 +222,17 @@

    Creating an STList (Spa GitHub repository. The most important aspect when constructing this file is that the sample names are in the first column, and they match the names of the folders containing the data:

    -

    +

    From the temporary directory, we can use R to generate the file paths to be passed to the STlist function:

    -
    +
     visium_folders <- list.dirs(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE)

    The meta data can be accessed directly from the spatialGE package installed in the computer like so:

    -
    +
     clin_file <- list.files(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE, pattern='clinical')

    We can load the files into an STlist using this command:

    -
    +
     tnbc <- STlist(rnacounts=visium_folders, samples=clin_file, cores=2)
     #> Found Visium data
     #>  Found 8 Visium samples
    @@ -224,7 +241,7 @@ 

    Creating an STList (Spa #> Completed STlist!

    The tnbc object is an STlist that contains the count data, spot coordinates, and clinical meta data.

    -
    +
     tnbc
     #> Spatial Transcriptomics List (STlist).
     #> 8 spatial array(s):
    @@ -242,7 +259,7 @@ 

    Creating an STList (Spa

    As observed, by calling the tnbc object, information on the number of spots and genes per sample is displayed. For count statistics, the summarize_STlist function can be used:

    -
    +
     summarize_STlist(tnbc)
     #> # A tibble: 8 × 9
     #>   sample_name spotscells genes min_counts_per_spotcell mean_counts_per_spotcell
    @@ -261,10 +278,10 @@ 

    Creating an STList (Spa

    The minimum number of counts per spot is 42, which seems low. We can look at the distribution of counts and genes per spot using the distribution_plots function:

    -
    +
     cp <- distribution_plots(tnbc, plot_type='violin', plot_meta='total_counts')
     cp[['total_counts']]
    -

    +

    Now, let us remove spots with low counts by keeping only those spots with at least 5000 counts. We will also restrict the data set to spots expressing at least 1000 genes. We also will remove a few spots that @@ -273,12 +290,13 @@

    Creating an STList (Spa examined. For example, this criteria may be not enough to reduce the differences in counts, especially for sample_120d and samples_120e.

    We run this filter with the filter_data function:

    -
    +
     tnbc <- filter_data(tnbc, spot_minreads=5000, spot_mingenes=1000, spot_maxreads=150000)
    +#> filter_data: removed 0 sample(s), 812 spot(s)/cell(s) and 0 gene(s).
     
     cp2 <- distribution_plots(tnbc, plot_type='violin', plot_meta='total_counts')
     cp2[['total_counts']]
    -

    +

    Exploring variation between spatial arrays @@ -294,8 +312,10 @@

    Exploring variation between max_var_genes argument is used to specify the maximum number of genes used for computation of PCA. The genes are selected based on their standard deviation across samples.

    -
    -tnbc <- pseudobulk_samples(tnbc, max_var_genes=5000)
    +
    +tnbc <- pseudobulk_samples(tnbc, max_var_genes=5000)
    +#> Warning in pseudobulk_samples(tnbc, max_var_genes = 5000): Dropped 10856
    +#> gene(s) with zero variance across samples before the pseudobulk PCA.

    In this case, we apply the function to look for agreement between samples from the same patient: It is expected that tissue slices from the same patient are more similar among them than tissue slices from @@ -303,17 +323,17 @@

    Exploring variation between sample-level variable to the points in the PCA by including the name of the column from the sample metadata (patient_id in this example).

    -
    +
     pseudobulk_dim_plot(tnbc, plot_meta='patient_id')
    -

    +

    Users can also generate a heatmap from pseudobulk counts by calling the pseudobulk_heatmap function, which also requires prior use of the pseudobulk_samples function. The number of variable genes to show can be controlled via the hm_display_genes argument.

    -
    +
     hm_p <- pseudobulk_heatmap(tnbc, plot_meta='patient_id', hm_display_genes=30)
    -

    +

    Transformation of spatially-resolved transcriptomics data @@ -323,7 +343,7 @@

    Transformatio log-transformation to the counts, after library size normalization performed on each sample separately. Similar to Seurat, it applies a scaling factor (scale_f=10000 by default).

    -
    +
     tnbc <- transform_data(tnbc, method='log', cores=2)

    Users also can apply variance-stabilizing transformation (SCT; Hafemeister and Satija (2019)), which is another method increasingly used in single-cell and spatial transcriptomics @@ -346,7 +366,7 @@

    +
     quilts1 <- STplot(tnbc, 
                       genes=c('NDRG1', 'IGKC'), 
                       samples='sample_094c', 
    @@ -355,9 +375,9 @@ 

    -ggpubr::ggarrange(plotlist=quilts1, nrow=1, ncol=2, legend='bottom')

    -

    +
    +ggpubr::ggarrange(plotlist=quilts1, nrow=1, ncol=2, legend='bottom')
    +

    We can see that gene expression patterns of both genes are non-overlapping: IGKC is expressed in the upper right portion of the tissue, whereas NDRG1 is expressed in the right bottom @@ -381,7 +401,7 @@

    Spatial interpolation of gene expression via the fields package. We specify that kriging will be performed for two of the spatial samples (samples=c('sample_094c', 'sample_117e')):

    -
    +
     tnbc <- gene_interpolation(tnbc, 
                                genes=c('NDRG1', 'IGKC'),
                                samples=c('sample_094c', 'sample_117e'), cores=2)
    @@ -390,13 +410,13 @@ 

    Spatial interpolation of gene #> [using ordinary kriging] #> [using ordinary kriging] #> [using ordinary kriging] -#> Gene interpolation completed in 1.64 min.

    +#> Gene interpolation completed in 0.52 min.

    Generating gene expression surfaces can be time consuming. The finer resolution to which the surface is to be predicted (ngrid argument), the longer the time it takes. The execution time also depends on the number of spots/cells. The surfaces can be visualized using the STplot_interpolation() function:

    -
    +
     kriges1 <- STplot_interpolation(tnbc,
                                     genes=c('NDRG1', 'IGKC'),
                                     samples='sample_094c')
    @@ -410,11 +430,11 @@ 

    Spatial interpolation of gene

    If tissue images were uploaded to the STlist (tissue_hires_image.png.gz), it can be displayed for comparison using the plot_image function:

    -
    +
     ip = plot_image(tnbc, samples='sample_094c')
     
     ip[['image_sample_094c']]
    -

    +

    @@ -437,30 +457,30 @@

    Unsupervised spatial transcriptomic profiles will be used. After many tests, we have found that weights between 0.025 - 0.25 are enough to capture the tissue heterogeneity. By default, STclust uses dynamic tree cuts -(Langfelder, Zhang, and Horvath 2007) to -define the number of clusters. But users can also test a series of k -values (ks). For a more detailed description of the method, -please refer to the paper describing spatialGE and +(Langfelder et al. 2007) to define the +number of clusters. But users can also test a series of k values +(ks). For a more detailed description of the method, please +refer to the paper describing spatialGE and STclust (Ospina et al. 2022).

    We’ll try several weights to see it’s effect on the cluster assignments:

    -
    +
     tnbc <- STclust(tnbc, 
                     ks='dtc', 
                     ws=c(0, 0.025, 0.05, 0.2), cores=2)
     #> STclust started...
     #> Updating STlist with results...
    -#> STclust completed in 0.72 min.
    +#> STclust completed in 0.26 min.

    Results of clustering can be plotted via the STplot function:

    -
    +
     cluster_p <- STplot(tnbc, 
                         samples='sample_094c', 
                         ws=c(0, 0.025, 0.05, 0.2),
                         color_pal='highcontrast')
    -ggpubr::ggarrange(plotlist=cluster_p, nrow=2, ncol=2, legend='right')
    -

    +ggpubr::ggarrange(plotlist=cluster_p, nrow=2, ncol=2, legend='right')
    +

    We can see that from w=0 and w=0.05, we can only detect two tissue niches. At w=0.025, we gain higher resolution as one of the clusters is split and a third (‘yellow’) @@ -480,28 +500,28 @@

    As

    To explore the relationship between a clinical (sample-level) variable of interest and the level of gene expression spatial uniformity within a sample, we can use the SThet() function:

    -
    +
     tnbc <- SThet(tnbc, 
                   genes=c('NDRG1', 'IGKC'),
                   method='moran', cores=2)
     #> SThet started.
     #>  Calculating spatial weights...
    -#> SThet completed in 0.03 min.
    +#> SThet completed in 0.01 min.

    The SThet function calculates the Moran’s I statsitic (or Geary’s C) to measure the level of spatial heterogeneity in the expression of the genes ( NDRG1, IGKC). The estimates can be compared across samples using the function compare_SThet()

    -
    +
     p <- compare_SThet(tnbc, 
                        samplemeta='overall_survival_days', 
                        color_by='patient_id',
    -                   gene=c('NDRG1', 'IGKC'), 
    +                   genes=c('NDRG1', 'IGKC'), 
                        color_pal='muted',
                        ptsize=3)
     
     p
    -

    +

    The calculation of spatial statistics with SThet and and multi-sample comparison with compare_SThet provides and easy way to identify samples and genes exhibiting spatial patterns. The @@ -521,7 +541,7 @@

    As analysis/plotting that the user may want to complete. The statistics value can be accessed as a data frame using the get_gene_meta function:

    -
    +
     get_gene_meta(tnbc, sthet_only=TRUE)
     #> # A tibble: 16 × 10
     #>    sample      patient_id neoadjuvant overall_survival_days gene  gene_mean
    @@ -605,7 +625,7 @@ 

    As scSpatialSIM and spatstat packages. Also tidyverse and janitor for some data manipulation.

    -
    +
     library('rpart')
     library('spatstat')
     library('scSpatialSIM')
    @@ -618,14 +638,14 @@ 

    As simulated.

    The first step is to create a spatstat observation window:

    -
    +
     wdw <- owin(xrange=c(0, 3), yrange=c(0, 3))
     sim_visium <- CreateSimulationObject(sims=1, cell_types=1, window=wdw)

    Next, the sc.SpatialSIM is used to generate the spatial point process (positions of the spots) within the observation window. Then, assignments of spots to tissue domains are simulated and visualized:

    -
    +
     # Generate point process
     # Then, simulate tissue compartments
     set.seed(12345)
    @@ -636,7 +656,7 @@ 

    As PlotSimulation(sim_visium, which=1, what="tissue points") + scale_shape_manual(values=c(19, 1))

    -

    +

    Now, the simulated tissue domain assignments are extracted from the SpatSimObj object. Gene counts will be simulated in such a way that:

    @@ -656,12 +676,12 @@

    As “gene_2” across the entire tissue. This pattern should result in Moran’s I closer to 0 and Geary’s C closer to 1. -
    +
     # Extract tissue assignments from the `SpatSimObj` object
     # Simulate expression of 'gene_1'
     sim_visium_df <- sim_visium@`Spatial Files`[[1]] %>%
       clean_names() %>% 
    -  mutate(gene_1=case_when(tissue_assignment == 'Tissue 1' ~ 1, TRUE ~ 0.1))
    +  mutate(gene_1=case_when(tissue_assignment == 'Tissue 1' ~ 1, TRUE ~ 0.1))
     
     # Generate expression patter of "gene_2"
     for(i in 1:nrow(sim_visium_df)){
    @@ -678,7 +698,7 @@ 

    As sim_visium_df[['gene_3']] <- sample(sim_visium_df[['gene_2']])

    To visualize the simulated expression and run SThet, an STlist is created:

    -
    +
     # Extract simulated expression data
     sim_expr <- sim_visium_df %>% 
       add_column(libname=paste0('spot', seq(1:nrow(.)))) %>%
    @@ -701,14 +721,14 @@ 

    As # Plot expression ps <- STplot(simulated, genes=c('gene_1', 'gene_2', 'gene_3'), data_type='raw', color_pal='sunset', ptsize=1) -ggpubr::ggarrange(plotlist=ps, ncol=3)

    -

    +ggpubr::ggarrange(plotlist=ps, ncol=3)
    +

    As expected, simulated expression of “gene_1” is aggregated (i.e., clustered, red spots concentrated towards the center of the tissue). This result was intently obtained by setting the simulation parameters to xmin=2, xmax=3, ymin=2, ymax=3 in sc.SpatialSIM.

    -
    +
     # The `SThet` function requires normalized data
     simulated <- transform_data(simulated, cores=2)
     
    @@ -739,14 +759,12 @@ 

    As

    References

    -
    +
    -Bassiouni, Rania, Michael O. Idowu, Lee D. Gibbs, Valentina Robila, -Pamela J. Grizzard, Michelle G. Webb, Jiarong Song, Ashley Noriega, -David W. Craig, and John D. Carpten. 2023. “Spatial Transcriptomic -Analysis of a Diverse Patient Cohort Reveals a Conserved Architecture in -Triple-Negative Breast Cancer.” Cancer Research 83: -34–48. https://doi.org/10.1158/0008-5472.CAN-22-2682. +Bassiouni, Rania, Michael O. Idowu, Lee D. Gibbs, et al. 2023. +“Spatial Transcriptomic Analysis of a Diverse Patient Cohort +Reveals a Conserved Architecture in Triple-Negative Breast +Cancer.” Cancer Research 83: 34–48. https://doi.org/10.1158/0008-5472.CAN-22-2682.
    Hafemeister, Christoph, and Rahul Satija. 2019. “Normalization and @@ -760,91 +778,84 @@

    Referenceshttps://doi.org/10.1093/bioinformatics/btm563.

    -Ospina, Oscar E, Christopher M Wilson, Alex C Soupir, Anders Berglund, -Inna Smalley, Kenneth Y Tsai, and Brooke L Fridley. 2022. “spatialGE: quantification and visualization of the tumor -microenvironment heterogeneity using spatial +Ospina, Oscar E, Christopher M Wilson, Alex C Soupir, et al. 2022. +“spatialGE: quantification and visualization +of the tumor microenvironment heterogeneity using spatial transcriptomics.” Bioinformatics 38: 2645–47. https://doi.org/10.1093/bioinformatics/btac145.
    Session Info -
    +
     sessionInfo()
    -#> R version 4.4.3 (2025-02-28 ucrt)
    -#> Platform: x86_64-w64-mingw32/x64
    -#> Running under: Windows 11 x64 (build 26100)
    +#> R version 4.5.3 (2026-03-11)
    +#> Platform: aarch64-apple-darwin20.0.0
    +#> Running under: macOS Sequoia 15.8.1
     #> 
     #> Matrix products: default
    -#> 
    +#> BLAS:   /opt/anaconda3/envs/spatialge-dev/lib/libblas.3.9.0.dylib 
    +#> LAPACK: /opt/anaconda3/envs/spatialge-dev/lib/liblapack.3.9.0.dylib  LAPACK version 3.9.0
     #> 
     #> locale:
    -#> [1] LC_COLLATE=English_United States.utf8 
    -#> [2] LC_CTYPE=English_United States.utf8   
    -#> [3] LC_MONETARY=English_United States.utf8
    -#> [4] LC_NUMERIC=C                          
    -#> [5] LC_TIME=English_United States.utf8    
    +#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
     #> 
     #> time zone: America/New_York
    -#> tzcode source: internal
    +#> tzcode source: system (macOS)
     #> 
     #> attached base packages:
     #> [1] stats     graphics  grDevices utils     datasets  methods   base     
     #> 
     #> other attached packages:
    -#>  [1] janitor_2.2.1          lubridate_1.9.4        forcats_1.0.0         
    -#>  [4] stringr_1.5.1          dplyr_1.1.4            purrr_1.0.4           
    -#>  [7] readr_2.1.5            tidyr_1.3.1            tibble_3.2.1          
    -#> [10] ggplot2_3.5.1          tidyverse_2.0.0        scSpatialSIM_0.1.3.4  
    -#> [13] spatstat_3.3-2         spatstat.linnet_3.2-5  spatstat.model_3.3-5  
    -#> [16] spatstat.explore_3.4-2 nlme_3.1-167           spatstat.random_3.3-3 
    -#> [19] spatstat.geom_3.3-6    spatstat.univar_3.1-2  spatstat.data_3.1-6   
    -#> [22] rpart_4.1.24           magrittr_2.0.3         spatialGE_1.2.0       
    +#>  [1] janitor_2.2.1          lubridate_1.9.5        forcats_1.0.1         
    +#>  [4] stringr_1.6.0          dplyr_1.2.1            purrr_1.2.2           
    +#>  [7] readr_2.2.0            tidyr_1.3.2            tibble_3.3.1          
    +#> [10] ggplot2_4.0.3          tidyverse_2.0.0        scSpatialSIM_0.1.4    
    +#> [13] spatstat_3.6-2         spatstat.linnet_3.5-3  spatstat.model_3.7-2  
    +#> [16] spatstat.explore_3.8-2 nlme_3.1-171           spatstat.random_3.5-1 
    +#> [19] spatstat.geom_3.8-2    spatstat.univar_3.2-0  spatstat.data_3.1-9   
    +#> [22] rpart_4.1.27           magrittr_2.0.5         spatialGE_2.0.0       
     #> 
     #> loaded via a namespace (and not attached):
    -#>   [1] splines_4.4.3         polyclip_1.10-7       xts_0.14.1           
    -#>   [4] lifecycle_1.0.4       sf_1.0-20             rstatix_0.7.2        
    -#>   [7] pbmcapply_1.5.1       doParallel_1.0.17     lattice_0.22-6       
    -#>  [10] vroom_1.6.5           hdf5r_1.3.12          MASS_7.3-64          
    -#>  [13] backports_1.5.0       sass_0.4.9            rmarkdown_2.29       
    -#>  [16] jquerylib_0.1.4       yaml_2.3.10           sp_2.2-0             
    -#>  [19] spatstat.sparse_3.1-0 cowplot_1.1.3         DBI_1.2.3            
    -#>  [22] RColorBrewer_1.1-3    abind_1.4-8           wordspace_0.2-8      
    -#>  [25] BiocGenerics_0.52.0   tweenr_2.0.3          circlize_0.4.16      
    -#>  [28] IRanges_2.40.1        S4Vectors_0.44.0      ggrepel_0.9.6        
    -#>  [31] spatstat.utils_3.1-3  units_0.8-7           goftest_1.2-3        
    -#>  [34] pkgdown_2.1.1         svglite_2.1.3         codetools_0.2-20     
    -#>  [37] gstat_2.1-3           xml2_1.3.8            ggforce_0.4.2        
    -#>  [40] tidyselect_1.2.1      shape_1.4.6.1         farver_2.1.2         
    -#>  [43] matrixStats_1.5.0     stats4_4.4.3          dynamicTreeCut_1.63-1
    -#>  [46] jsonlite_2.0.0        GetoptLong_1.0.5      e1071_1.7-16         
    -#>  [49] Formula_1.2-5         iterators_1.0.14      systemfonts_1.2.2    
    -#>  [52] foreach_1.5.2         tools_4.4.3           ragg_1.3.3           
    -#>  [55] Rcpp_1.0.14           glue_1.8.0            gridExtra_2.3        
    -#>  [58] xfun_0.52             mgcv_1.9-1            withr_3.0.2          
    -#>  [61] fastmap_1.2.0         boot_1.3-31           spData_2.3.4         
    -#>  [64] digest_0.6.37         timechange_0.3.0      R6_2.6.1             
    -#>  [67] textshaping_1.0.0     colorspace_2.1-1      wk_0.9.4             
    -#>  [70] tensor_1.5            ggpolypath_0.3.0      utf8_1.2.4           
    -#>  [73] generics_0.1.3        intervals_0.15.5      data.table_1.17.0    
    -#>  [76] FNN_1.1.4.1           class_7.3-23          htmlwidgets_1.6.4    
    -#>  [79] spdep_1.3-10          pkgconfig_2.0.3       gtable_0.3.6         
    -#>  [82] iotools_0.3-5         ComplexHeatmap_2.22.0 htmltools_0.5.8.1    
    -#>  [85] carData_3.0-5         clue_0.3-66           scales_1.3.0         
    -#>  [88] kableExtra_1.4.0      png_0.1-8             snakecase_0.11.1     
    -#>  [91] knitr_1.50            rstudioapi_0.17.1     tzdb_0.5.0           
    -#>  [94] rjson_0.2.23          spacetime_1.3-3       curl_6.2.2           
    -#>  [97] proxy_0.4-27          cachem_1.1.0          zoo_1.8-13           
    -#> [100] GlobalOptions_0.1.2   khroma_1.16.0         KernSmooth_2.23-26   
    -#> [103] parallel_4.4.3        concaveman_1.1.0      desc_1.4.3           
    -#> [106] s2_1.1.7              pillar_1.10.2         grid_4.4.3           
    -#> [109] vctrs_0.6.5           ggpubr_0.6.0          car_3.1-3            
    -#> [112] cluster_2.1.8         evaluate_1.0.3        magick_2.8.6         
    -#> [115] cli_3.6.4             compiler_4.4.3        rlang_1.1.5          
    -#> [118] crayon_1.5.3          ggsignif_0.6.4        labeling_0.4.3       
    -#> [121] classInt_0.4-11       fs_1.6.5              stringi_1.8.7        
    -#> [124] viridisLite_0.4.2     deldir_2.0-4          munsell_0.5.1        
    -#> [127] V8_6.0.3              Matrix_1.7-2          sparsesvd_0.2-2      
    -#> [130] hms_1.1.3             bit64_4.6.0-1         broom_1.0.8          
    -#> [133] bslib_0.9.0           bit_4.6.0
    +#> [1] RColorBrewer_1.1-3 rstudioapi_0.19.0 jsonlite_2.0.0 +#> [4] shape_1.4.6.1 spatstat.utils_3.2-5 magick_2.9.1 +#> [7] farver_2.1.2 rmarkdown_2.32 GlobalOptions_0.1.4 +#> [10] fs_2.1.0 ragg_1.5.2 vctrs_0.7.3 +#> [13] rstatix_1.1.0 htmltools_0.5.9 curl_8.0.0 +#> [16] broom_1.0.13 Formula_1.2-6 sass_0.4.10 +#> [19] KernSmooth_2.23-26 bslib_0.12.0 htmlwidgets_1.6.4 +#> [22] desc_1.4.3 cachem_1.1.0 ggpolypath_0.4.0 +#> [25] lifecycle_1.0.5 iterators_1.0.14 pkgconfig_2.0.3 +#> [28] Matrix_1.7-6 R6_2.6.1 fastmap_1.2.0 +#> [31] snakecase_0.11.1 clue_0.3-68 digest_0.6.39 +#> [34] colorspace_2.1-3 S4Vectors_0.48.1 tensor_1.5.1 +#> [37] textshaping_1.0.5 ggpubr_1.0.0 labeling_0.4.3 +#> [40] timechange_0.4.0 spatstat.sparse_3.2-0 mgcv_1.9-4 +#> [43] polyclip_1.10-7 abind_1.4-8 compiler_4.5.3 +#> [46] proxy_0.4-29 bit64_4.8.6 withr_3.0.3 +#> [49] doParallel_1.0.17 S7_0.2.2 backports_1.5.1 +#> [52] carData_3.0-6 DBI_1.3.0 ggforce_0.5.0 +#> [55] R.utils_2.13.0 ggsignif_0.6.4 MASS_7.3-66 +#> [58] concaveman_1.2.0 rjson_0.2.23 classInt_0.4-11 +#> [61] tools_4.5.3 units_1.0-1 otel_0.2.0 +#> [64] goftest_1.2-3 R.oo_1.27.1 glue_1.8.1 +#> [67] grid_4.5.3 sf_1.1-2 cluster_2.1.8.3 +#> [70] generics_0.1.4 hdf5r_1.3.16 gtable_0.3.6 +#> [73] tzdb_0.5.0 R.methodsS3_1.8.2 class_7.3-23 +#> [76] hms_1.1.4 xml2_1.6.0 car_3.1-5 +#> [79] utf8_1.2.6 BiocGenerics_0.56.0 ggrepel_0.9.8 +#> [82] foreach_1.5.2 pillar_1.11.1 vroom_1.7.1 +#> [85] splines_4.5.3 circlize_0.4.18 tweenr_2.0.3 +#> [88] lattice_0.23-1 bit_4.6.0 deldir_2.0-4 +#> [91] tidyselect_1.2.1 ComplexHeatmap_2.26.1 knitr_1.52 +#> [94] gridExtra_2.3.1 V8_8.2.0 IRanges_2.44.0 +#> [97] svglite_2.2.2 stats4_4.5.3 xfun_0.60 +#> [100] matrixStats_1.5.0 stringi_1.8.9 yaml_2.3.12 +#> [103] kableExtra_1.4.1 evaluate_1.0.5 codetools_0.2-20 +#> [106] cli_3.6.6 pbmcapply_1.5.1 systemfonts_1.3.2 +#> [109] jquerylib_0.1.4 Rcpp_1.1.2 png_0.1-9 +#> [112] parallel_4.5.3 pkgdown_2.2.1 viridisLite_0.4.3 +#> [115] scales_1.4.0 e1071_1.7-17 crayon_1.5.3 +#> [118] khroma_1.17.0 GetoptLong_1.1.1 rlang_1.3.0 +#> [121] cowplot_1.2.0
    @@ -864,7 +875,7 @@

    References

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/articles/basic_functions_vignette_files/figure-html/clinplot_chunk-1.png b/docs/articles/basic_functions_vignette_files/figure-html/clinplot_chunk-1.png index 1f8a4be..6a8d997 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/clinplot_chunk-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/clinplot_chunk-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/count_dstr-1.png b/docs/articles/basic_functions_vignette_files/figure-html/count_dstr-1.png index b99b8df..ca90aa8 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/count_dstr-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/count_dstr-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/filter_chunk-1.png b/docs/articles/basic_functions_vignette_files/figure-html/filter_chunk-1.png index fd50709..52cc843 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/filter_chunk-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/filter_chunk-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/genequilt_chunk2-1.png b/docs/articles/basic_functions_vignette_files/figure-html/genequilt_chunk2-1.png index 2713737..d43e1c4 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/genequilt_chunk2-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/genequilt_chunk2-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/heatmap_chunk-1.png b/docs/articles/basic_functions_vignette_files/figure-html/heatmap_chunk-1.png index 163dae0..e6c8ccb 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/heatmap_chunk-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/heatmap_chunk-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/pca_chunk-1.png b/docs/articles/basic_functions_vignette_files/figure-html/pca_chunk-1.png index 0cc71e1..0bad1e7 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/pca_chunk-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/pca_chunk-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/plotclustspots_chunk-1.png b/docs/articles/basic_functions_vignette_files/figure-html/plotclustspots_chunk-1.png index 8dbc8d9..b541869 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/plotclustspots_chunk-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/plotclustspots_chunk-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_2-1.png b/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_2-1.png index 3898796..dcf0181 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_2-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_2-1.png differ diff --git a/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_4-1.png b/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_4-1.png index 0d2c3f9..8f58c32 100644 Binary files a/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_4-1.png and b/docs/articles/basic_functions_vignette_files/figure-html/tissue_sim_4-1.png differ diff --git a/docs/articles/index.html b/docs/articles/index.html index f7f34df..ee43a33 100644 --- a/docs/articles/index.html +++ b/docs/articles/index.html @@ -1,5 +1,5 @@ -Articles • spatialGEArticles • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0
    @@ -34,6 +34,9 @@
    +

    @@ -64,6 +73,8 @@

    All vignettes

    Basic functionality: Visualization, domain detection, and spatial heterogeneity
    +
    +
    On-disk STlists: working with data sets larger than memory
    Spatially-informed differential gene expression
    @@ -81,7 +92,7 @@

    All vignettes

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/articles/ondisk_stlists.html b/docs/articles/ondisk_stlists.html new file mode 100644 index 0000000..21a040a --- /dev/null +++ b/docs/articles/ondisk_stlists.html @@ -0,0 +1,656 @@ + + + + + + +On-disk STlists: working with data sets larger than memory • spatialGE + + + + + + + + + + + + + + + + +
    +
    + + + + +
    +
    + + + + +

    An STlist stores the gene expression counts of all samples in the +study at the same time. This is what allows functions such as +SThet and compare_SThet to compare samples, +but it also means that the memory required by an STlist grows with the +number of samples and the number of spots or cells in each one. A few +Visium samples are easily handled in a laptop. Several dozen samples, or +a CosMx experiment with hundreds of thousands of cells, may not be, and +the analysis then ends before it starts, when the object is created.

    +

    For those cases, the spatialGE +package provides the option of keeping the counts on disk instead of in +memory. The function STlist_to_disk writes the count +matrices to parquet files, +leaving in the STlist a small description of each file. The counts are +then read back as the analysis functions request them, a few genes at a +time. The function STlist_to_memory reverses the process. +The rest of the object (spot coordinates, spot-level annotations, sample +meta data, and the results of any analysis) is not affected and remains +in memory.

    +

    Note that this option is turned off by default. An STlist created in +the usual way behaves exactly as described in the other tutorials, and +none of what follows is required to use spatialGE.

    +

    It is also important to be clear about what this option provides. It +makes it possible to hold and analyze a data set that would not fit in +memory. It does not make the analysis faster. The functions still bring +counts into memory in order to compute on them, so an on-disk STlist is +somewhat slower than an in-memory one, the difference being that the +counts are not all in memory at once. Users whose data sets fit +comfortably in memory are better off leaving them there.

    +
    +

    Spatially-resolved expression of triple negative breast cancer tumor +biopsies +

    +

    To follow the same data used in the basic +functionality tutorial, we use the Visium data set from Bassiouni et al. (2023), which includes triple +negative breast cancer biopsies. Eight samples from four patients are +used here. The data is available at our spatialGE_Data +GitHub repository, and will be pulled from there during this +tutorial.

    +

    Load the spatialGE package:

    + +

    As in the other tutorials, the data will be deposited in a temporary +directory:

    +
    +lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/tnbc_bassiouni.zip?download='
    +
    +visium_tmp = tempdir()
    +unlink(visium_tmp, recursive=TRUE)
    +dir.create(visium_tmp)
    +
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(visium_tmp, '/', 'tnbc_bassiouni.zip'), mode='wb')
    +  zip_tmp = list.files(visium_tmp, pattern='tnbc_bassiouni.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=visium_tmp)
    +  net_check <<- TRUE
    +}, error = function(e) {
    +  message("Could not download data. Are you connected to the internet?")
    +  net_check <<- FALSE
    +})
    +
    +visium_folders <- list.dirs(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE)
    +clin_file <- list.files(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE, pattern='clinical')
    +
    +
    +

    Preparing the STlist before moving it to disk +

    +

    The STlist is created in the usual way, and the quality control and +normalization steps are run while the counts are still in memory:

    +
    +tnbc <- STlist(rnacounts=visium_folders, samples=clin_file, cores=2)
    +#> Found Visium data
    +#>  Found 8 Visium samples
    +#>  Data read completed
    +#> Matching gene expression and coordinate data...
    +#> Completed STlist!
    +
    +tnbc <- filter_data(tnbc, spot_minreads=5000, spot_mingenes=1000, spot_maxreads=150000)
    +#> filter_data: removed 0 sample(s), 812 spot(s)/cell(s) and 0 gene(s).
    +
    +tnbc <- transform_data(tnbc, method='log', cores=2)
    +

    The order of these steps matters. The functions +filter_data and transform_data do not simply +read the count matrices, they rewrite them: filter_data +removes spots and genes, and transform_data adds an +entirely new matrix of normalized values. Both are therefore run before +the counts are moved to disk.

    +

    In other words, an on-disk STlist is better thought of as a prepared +data set that analyses are run on, rather than as an object that is +still being assembled. If a filtering threshold has to be reconsidered +later, the object can be brought back into memory with +STlist_to_memory (shown near the end of this tutorial), +modified there, and written out again.

    +
    +
    +

    Moving the counts to disk +

    +

    The function STlist_to_disk takes the STlist and a +directory to write into. The directory is created if it does not +exist:

    +
    +store_dir <- paste0(visium_tmp, '/tnbc_store')
    +
    +tnbc_disk <- STlist_to_disk(tnbc, root=store_dir)
    +

    The result is an STlist like any other, except that its two count +slots now point at files. The function is_backed reports +which of the two forms an object is in:

    +
    +is_backed(tnbc_disk)
    +#> [1] TRUE
    +is_backed(tnbc)
    +#> [1] FALSE
    +

    Printing the object works as before, and so does +summarize_STlist. Neither of them needs to read the counts, +because the number of genes and spots per sample is recorded when the +store is written:

    +
    +tnbc_disk
    +#> Spatial Transcriptomics List (STlist).
    +#> 8 spatial array(s):
    +#>  sample_117d (1938 ROIs|spots|cells x 23755 genes)
    +#>  sample_117e (727 ROIs|spots|cells x 21662 genes)
    +#>  sample_120d (1029 ROIs|spots|cells x 21886 genes)
    +#>  sample_120e (511 ROIs|spots|cells x 20389 genes)
    +#>  sample_092a (1258 ROIs|spots|cells x 24227 genes)
    +#>  sample_092b (1314 ROIs|spots|cells x 23511 genes)
    +#>  sample_094c (1536 ROIs|spots|cells x 24581 genes)
    +#>  sample_094d (1379 ROIs|spots|cells x 24167 genes)
    +#> 
    +#> 3 variables in sample-level data:
    +#>   patient_id, neoadjuvant, overall_survival_days
    +
    +summarize_STlist(tnbc_disk)
    +#> # A tibble: 8 × 9
    +#>   sample_name spotscells genes min_counts_per_spotcell mean_counts_per_spotcell
    +#>   <chr>            <int> <int>                   <dbl>                    <dbl>
    +#> 1 sample_117d       1938 23755                    5007                   35447.
    +#> 2 sample_117e        727 21662                    5703                   35798.
    +#> 3 sample_120d       1029 21886                    5016                   17472.
    +#> 4 sample_120e        511 20389                    5003                   14633.
    +#> 5 sample_092a       1258 24227                    5018                   44201.
    +#> 6 sample_092b       1314 23511                    5025                   36283.
    +#> 7 sample_094c       1536 24581                    5457                   45746.
    +#> 8 sample_094d       1379 24167                    5193                   37460.
    +#> # ℹ 4 more variables: max_counts_per_spotcell <dbl>,
    +#> #   min_genes_per_spotcell <int>, mean_genes_per_spotcell <dbl>,
    +#> #   max_genes_per_spotcell <int>
    +
    +
    +

    What is stored on disk +

    +

    Looking at what was written is useful, since the files are ordinary +parquet and can be read with other tools if needed.

    +

    Each sample gets a sub-directory containing one file per populated +slot, so eight samples with raw and normalized counts result in sixteen +files:

    +
    +head(list.files(store_dir, recursive=TRUE), 4)
    +#> [1] "samples/0001-43ffa0e30000/counts.parquet"   
    +#> [2] "samples/0001-43ffa0e30000/tr_counts.parquet"
    +#> [3] "samples/0002-42ff9f500000/counts.parquet"   
    +#> [4] "samples/0002-42ff9f500000/tr_counts.parquet"
    +
    +length(list.files(store_dir, recursive=TRUE))
    +#> [1] 16
    +

    Note that the sub-directory names are not the sample names. Sample +names are allowed to contain characters that file paths are not, so a +position and a short hash are used instead, and the readable name is +kept inside the file description rather than in the path.

    +

    That description is what now sits in the counts slot in place of a +matrix. Printing it gives a one-line summary and the path to the +file:

    +
    +tnbc_disk@counts[['sample_094c']]
    +#> <sge_manifest> sample_094c: 24581 genes x 1536 cells, 11516088 nonzero, gen 1
    +#>   /private/var/folders/63/qj4bjln95bs911vg920503rh001s8k/T/Rtmpz9m80Y/tnbc_store/samples/0007-2ceec9e00000/counts.parquet
    +

    The slot @misc records where the store is and in which +order the samples were written:

    +
    +tnbc_disk@misc[['store']]
    +#> $root
    +#> [1] "/private/var/folders/63/qj4bjln95bs911vg920503rh001s8k/T/Rtmpz9m80Y/tnbc_store"
    +#> 
    +#> $sample_order
    +#> [1] "sample_117d" "sample_117e" "sample_120d" "sample_120e" "sample_092a"
    +#> [6] "sample_092b" "sample_094c" "sample_094d"
    +#> 
    +#> $schema_ver
    +#> [1] 1
    +#> 
    +#> $portable
    +#> [1] FALSE
    +

    The files themselves hold the counts in “long” (also called triplet, +or COO) form rather than as a rectangular matrix. Every non-zero value +is one row, giving the gene, the spot, and the value:

    +
    +head(arrow::read_parquet(tnbc_disk@counts[['sample_094c']]$path), 4)
    +#> # A tibble: 4 × 3
    +#>   gene_idx cell_idx value
    +#>      <int>    <int> <dbl>
    +#> 1        1       20     1
    +#> 2        1      184     1
    +#> 3        1      247     2
    +#> 4        1      305     1
    +

    There are two reasons for this layout. Counts from these platforms +are mostly zeros, and the long form stores only the values that are +present, which is the same reason an STlist uses sparse matrices in +memory. The rows are also sorted by gene, so that the values belonging +to one gene are together in the file rather than spread throughout +it.

    +

    Note that gene_idx and cell_idx are +positions rather than names. The gene and spot names are kept in the +file description, which is the only place they are recorded. The reason +is that a gene with a count of zero in every spot of a sample has no +rows at all in the long form, so a gene list rebuilt from the contents +of the file would be missing it. Genes like that are not unusual, and +the default settings of filter_data do not remove them.

    +
    +
    +

    How much memory is saved +

    +

    The clearest way to see the effect is to compare the size of the +count slots before and after:

    +
    +format(object.size(tnbc@counts) + object.size(tnbc@tr_counts), units='MB')
    +#> [1] "1445.9 Mb"
    +
    +format(object.size(tnbc_disk@counts) + object.size(tnbc_disk@tr_counts), units='MB')
    +#> [1] "25 Mb"
    +

    For these eight samples, the count matrices go from roughly 1.4 GB to +about 25 MB, since what is left in the object is eight short +descriptions instead of sixteen matrices. The counts themselves have of +course not disappeared. They are on disk, where the store occupies a few +hundred megabytes:

    +
    +round(sum(file.info(list.files(store_dir, recursive=TRUE, full.names=TRUE))$size) / 1024^2, 1)
    +#> [1] 346.8
    +

    The reduction applies to the count matrices only. The spot +coordinates and annotations in @spatial_meta, the per-gene +statistics in @gene_meta, and whatever is stored in +@misc all remain in memory, and in a large study these are +not negligible either. This is easier to see by comparing the size of +the whole object instead of only the count slots:

    +
    +format(object.size(tnbc), units='MB')
    +#> [1] "2184.1 Mb"
    +format(object.size(tnbc_disk), units='MB')
    +#> [1] "763.2 Mb"
    +
    +
    +

    Analyses on an on-disk STlist +

    +

    Analysis functions are called exactly as they would be on an +in-memory STlist. The counts are read from the files when each function +asks for them, and the results are the same.

    +
    +tnbc_disk <- SThet(tnbc_disk, genes=c('NDRG1', 'IGKC'), method='moran', cores=2)
    +#> SThet started.
    +#>  Calculating spatial weights...
    +#> SThet completed in 0.04 min.
    +
    +get_gene_meta(tnbc_disk, sthet_only=TRUE)
    +#> # A tibble: 16 × 10
    +#>    sample      patient_id neoadjuvant overall_survival_days gene  gene_mean
    +#>    <chr>            <dbl> <chr>                       <dbl> <chr>     <dbl>
    +#>  1 sample_117d          2 yes                          2733 IGKC      3.07 
    +#>  2 sample_117d          2 yes                          2733 NDRG1     2.13 
    +#>  3 sample_117e          2 yes                          2733 IGKC      2.54 
    +#>  4 sample_117e          2 yes                          2733 NDRG1     2.45 
    +#>  5 sample_120d          8 no                           1453 IGKC      2.98 
    +#>  6 sample_120d          8 no                           1453 NDRG1     0.672
    +#>  7 sample_120e          8 no                           1453 IGKC      2.77 
    +#>  8 sample_120e          8 no                           1453 NDRG1     1.05 
    +#>  9 sample_092a          9 no                            308 IGKC      0.371
    +#> 10 sample_092a          9 no                            308 NDRG1     1.11 
    +#> 11 sample_092b          9 no                            308 IGKC      0.105
    +#> 12 sample_092b          9 no                            308 NDRG1     1.63 
    +#> 13 sample_094c         14 yes                           718 IGKC      4.06 
    +#> 14 sample_094c         14 yes                           718 NDRG1     1.38 
    +#> 15 sample_094d         14 yes                           718 IGKC      3.23 
    +#> 16 sample_094d         14 yes                           718 NDRG1     1.25 
    +#> # ℹ 4 more variables: gene_stdevs <dbl>, vst.variance.standardized <dbl>,
    +#> #   moran_i <dbl>, geary_c <lgl>
    +

    Since this is the property the whole mechanism depends on, it is +worth verifying rather than assuming. Running the same analysis on the +in-memory object returns identical statistics:

    +
    +tnbc <- SThet(tnbc, genes=c('NDRG1', 'IGKC'), method='moran', cores=2)
    +#> SThet started.
    +#>  Calculating spatial weights...
    +#> SThet completed in 0 min.
    +
    +identical(get_gene_meta(tnbc_disk, sthet_only=TRUE)$moran_i,
    +          get_gene_meta(tnbc, sthet_only=TRUE)$moran_i)
    +#> [1] TRUE
    +

    Quilt plots of gene expression are produced in the same way as +well:

    +
    +quilts1 <- STplot(tnbc_disk,
    +                  genes=c('NDRG1', 'IGKC'),
    +                  samples='sample_094c',
    +                  color_pal='BuRd',
    +                  ptsize=0.8)
    +
    +ggpubr::ggarrange(plotlist=quilts1, nrow=1, ncol=2, legend='bottom')
    +

    +

    The distribution of expression of a gene across samples is obtained +in the same way too:

    +
    +dp <- distribution_plots(tnbc_disk, genes='NDRG1')
    +dp[['NDRG1']]
    +

    +

    And so is the spatially-informed clustering of +STclust:

    +
    +tnbc_disk <- STclust(tnbc_disk, ks='dtc', ws=c(0, 0.025), cores=2)
    +#> STclust started...
    +#> Updating STlist with results...
    +#> STclust completed in 0.27 min.
    +
    +cluster_p <- STplot(tnbc_disk, samples='sample_094c', ws=0.025, color_pal='highcontrast')
    +cluster_p[[1]]
    +

    +

    What this costs is time. Every read of a count matrix now involves +the file system, so a function that reads the counts several times pays +that cost several times. The difference is noticeable even with a data +set of this size:

    +
    +system.time(SThet(tnbc, genes='NDRG1', method='moran', cores=2))['elapsed']
    +#> SThet started.
    +#>  Calculating spatial weights...
    +#> SThet completed in 0 min.
    +#> elapsed 
    +#>   0.229
    +
    +system.time(SThet(tnbc_disk, genes='NDRG1', method='moran', cores=2))['elapsed']
    +#> SThet started.
    +#>  Calculating spatial weights...
    +#> SThet completed in 0.02 min.
    +#> elapsed 
    +#>    1.41
    +

    A difference of a few fold is typical, and it is the trade mentioned +at the beginning of this tutorial. The analysis becomes possible on data +that would not otherwise fit in memory, but it takes longer to run.

    +
    +
    +

    Checking a store, and bringing it back +

    +

    The store is a directory of files, and the STlist only holds paths to +them. The function validate_store checks that the +arrangement is still intact, reading only the file headers:

    +
    +validate_store(tnbc_disk)
    +

    Nothing is printed, which is the intended result: the function +returns TRUE invisibly when everything checks out, and +stops with a message when it does not. It confirms that every file is +where its description says it is and has not changed since it was +written, that the samples are still in the recorded order, and that the +transformed counts remain a subset of the raw counts. Passing +deep=TRUE additionally reads the data to check the stored +positions, which is slower but more thorough:

    +
    +validate_store(tnbc_disk, deep=TRUE)
    +

    It is useful to see what the function reports when something is in +fact wrong. In the following block, a path is changed to a file that +does not exist, which is what a deleted or relocated store looks like +from within the STlist:

    +
    +broken <- tnbc_disk
    +broken@counts[['sample_094c']][['path']] <- paste0(visium_tmp, '/gone.parquet')
    +
    +try(validate_store(broken))
    +#> Error : spatialGE exception: spatialGE store: A parquet file recorded in the manifest is missing. Has the store directory moved?
    +

    That is the same error any analysis would raise on the first read of +that sample, only reported up front and naming the likely cause instead +of surfacing from somewhere inside arrow.

    +

    When a store is no longer needed, or when the object has to be +reshaped again, STlist_to_memory reads every matrix +back:

    +
    +tnbc_back <- STlist_to_memory(tnbc_disk)
    +
    +is_backed(tnbc_back)
    +#> [1] FALSE
    +

    The round trip is exact rather than approximate. The long form stores +the values themselves, and the dimensions and names come from the file +description, so nothing is estimated on the way back:

    +
    +identical(tnbc_back@counts, tnbc@counts)
    +#> [1] TRUE
    +
    +
    +

    Things to keep in mind +

    +

    Because the counts are now files rather than part of the object, +there are a few consequences that are better known in advance.

    +

    The object is not self-contained. Saving an on-disk +STlist with saveRDS stores the paths, not the counts. If +that object is loaded in a session where the store has been moved or +deleted, the first function that tries to read counts will fail, and +validate_store reports the problem up front. There is +currently no way to point an existing object at a store in a new +location, so the store should be written somewhere it can remain.

    +

    A store under tempdir() will not survive the +session. The examples here write to a temporary directory, +which is appropriate for a tutorial but not for an actual analysis. The +store records whether it was written to a location that can outlive the +session:

    +
    +tnbc_disk@misc[['store']][['portable']]
    +#> [1] FALSE
    +

    The value is FALSE here because store_dir +is inside tempdir(). For an analysis that is meant to be +kept, users should provide STlist_to_disk with a directory +of their own, keeping in mind that the directory has become part of the +data.

    +

    The object has to be prepared first. As described +above, filter_data and transform_data rewrite +the count matrices, so they are run before STlist_to_disk. +The same applies to subsetting an STlist by sample with +x[i]. In those cases, the object is brought back into +memory, modified there, and written out again if the result is to be +kept.

    +

    Writing a store does not remove the original. +STlist_to_disk returns a new STlist and leaves the one it +was given untouched, which is why both tnbc and +tnbc_disk are used throughout this tutorial. That is +convenient for comparison, but keeping both of them defeats the purpose. +In practice, the in-memory object is removed once the store has been +written.

    +
    Can the parquet files be read with something other than +spatialGE? +

    Yes, and that is part of the reason for using this format. The files +are ordinary parquet with three columns, so they can be read by anything +that reads parquet (arrow in R, pyarrow or +pandas in Python, or duckdb in either +language).

    +

    The one thing to carry across is that gene_idx and +cell_idx are positions rather than names, counting from 1. +The names are held in the STlist, in the description that replaced each +matrix:

    +
    +mft <- tnbc_disk@counts[['sample_094c']]
    +
    +head(mft$genes, 3)
    +#> [1] "AL627309.1" "AL627309.5" "AP006222.2"
    +head(mft$cells, 3)
    +#> [1] "CAGCGCCAACACGATA-1" "GTGCTGCAGATAAGGA-1" "GTCGTACCTACGATTG-1"
    +

    So a value with gene_idx 1 refers to +mft$genes[1], and a cell_idx of 1 to +mft$cells[1]. Reading the files without that mapping gives +the right numbers attached to the wrong labels, which is worse than an +error, so it is worth getting right. Writing the two vectors out +alongside the data is usually enough:

    +
    +head(data.frame(gene_idx=seq_along(mft$genes), gene=mft$genes), 3)
    +#>   gene_idx       gene
    +#> 1        1 AL627309.1
    +#> 2        2 AL627309.5
    +#> 3        3 AP006222.2
    +
    +
    +
    +

    References +

    +
    +
    +Bassiouni, Rania, Michael O. Idowu, Lee D. Gibbs, et al. 2023. +“Spatial Transcriptomic Analysis of a Diverse Patient Cohort +Reveals a Conserved Architecture in Triple-Negative Breast +Cancer.” Cancer Research 83: 34–48. https://doi.org/10.1158/0008-5472.CAN-22-2682. +
    +
    +
    Session Info +
    +sessionInfo()
    +#> R version 4.5.3 (2026-03-11)
    +#> Platform: aarch64-apple-darwin20.0.0
    +#> Running under: macOS Sequoia 15.8.1
    +#> 
    +#> Matrix products: default
    +#> BLAS:   /opt/anaconda3/envs/spatialge-dev/lib/libblas.3.9.0.dylib 
    +#> LAPACK: /opt/anaconda3/envs/spatialge-dev/lib/liblapack.3.9.0.dylib  LAPACK version 3.9.0
    +#> 
    +#> locale:
    +#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
    +#> 
    +#> time zone: America/New_York
    +#> tzcode source: system (macOS)
    +#> 
    +#> attached base packages:
    +#> [1] stats     graphics  grDevices utils     datasets  methods   base     
    +#> 
    +#> other attached packages:
    +#> [1] spatialGE_2.0.0
    +#> 
    +#> loaded via a namespace (and not attached):
    +#>  [1] gtable_0.3.6       xfun_0.60          bslib_0.12.0       ggplot2_4.0.3     
    +#>  [5] htmlwidgets_1.6.4  ggpolypath_0.4.0   rstatix_1.1.0      lattice_0.23-1    
    +#>  [9] tzdb_0.5.0         vctrs_0.7.3        tools_4.5.3        generics_0.1.4    
    +#> [13] parallel_4.5.3     tibble_3.3.1       pkgconfig_2.0.3    Matrix_1.7-6      
    +#> [17] RColorBrewer_1.1-3 S7_0.2.2           desc_1.4.3         assertthat_0.2.1  
    +#> [21] lifecycle_1.0.5    stringr_1.6.0      compiler_4.5.3     farver_2.1.2      
    +#> [25] textshaping_1.0.5  ggforce_0.5.0      carData_3.0-6      htmltools_0.5.9   
    +#> [29] sass_0.4.10        yaml_2.3.12        Formula_1.2-6      pillar_1.11.1     
    +#> [33] pkgdown_2.2.1      car_3.1-5          ggpubr_1.0.0       crayon_1.5.3      
    +#> [37] jquerylib_0.1.4    tidyr_1.3.2        MASS_7.3-66        cachem_1.1.0      
    +#> [41] abind_1.4-8        tidyselect_1.2.1   digest_0.6.39      stringi_1.8.9     
    +#> [45] hdf5r_1.3.16       dplyr_1.2.1        purrr_1.2.2        labeling_0.4.3    
    +#> [49] arrow_25.0.0       polyclip_1.10-7    cowplot_1.2.0      fastmap_1.2.0     
    +#> [53] grid_4.5.3         cli_3.6.6          khroma_1.17.0      magrittr_2.0.5    
    +#> [57] utf8_1.2.6         broom_1.0.13       readr_2.2.0        withr_3.0.3       
    +#> [61] scales_1.4.0       backports_1.5.1    bit64_4.8.6        rmarkdown_2.32    
    +#> [65] bit_4.6.0          otel_0.2.0         ggsignif_0.6.4     ragg_1.5.2        
    +#> [69] png_0.1-9          hms_1.1.4          evaluate_1.0.5     knitr_1.52        
    +#> [73] rlang_1.3.0        Rcpp_1.1.2         glue_1.8.1         tweenr_2.0.3      
    +#> [77] vroom_1.7.1        jsonlite_2.0.0     R6_2.6.1           systemfonts_1.3.2 
    +#> [81] fs_2.1.0
    +
    +
    +
    + + + +
    + + + +
    + +
    +

    +

    Site built with pkgdown 2.2.1.

    +
    + +
    +
    + + + + + + + + diff --git a/docs/articles/ondisk_stlists_files/figure-html/clust_chunk-1.png b/docs/articles/ondisk_stlists_files/figure-html/clust_chunk-1.png new file mode 100644 index 0000000..a37edd5 Binary files /dev/null and b/docs/articles/ondisk_stlists_files/figure-html/clust_chunk-1.png differ diff --git a/docs/articles/ondisk_stlists_files/figure-html/dstr_chunk-1.png b/docs/articles/ondisk_stlists_files/figure-html/dstr_chunk-1.png new file mode 100644 index 0000000..154772a Binary files /dev/null and b/docs/articles/ondisk_stlists_files/figure-html/dstr_chunk-1.png differ diff --git a/docs/articles/ondisk_stlists_files/figure-html/genequilt_chunk-1.png b/docs/articles/ondisk_stlists_files/figure-html/genequilt_chunk-1.png new file mode 100644 index 0000000..d43e1c4 Binary files /dev/null and b/docs/articles/ondisk_stlists_files/figure-html/genequilt_chunk-1.png differ diff --git a/docs/articles/spatial_differential_expression.html b/docs/articles/spatial_differential_expression.html index 8e12d25..e0c3aa8 100644 --- a/docs/articles/spatial_differential_expression.html +++ b/docs/articles/spatial_differential_expression.html @@ -1,17 +1,15 @@ - - + Spatially-informed differential gene expression • spatialGE - - - - - - + + + + + @@ -38,7 +36,7 @@ spatialGE - 1.2.0 + 2.0.0
    @@ -57,6 +55,9 @@
  • Basic functionality: Visualization, domain detection, and spatial heterogeneity
  • +
  • + On-disk STlists: working with data sets larger than memory +
  • Spatially-informed differential gene expression
  • @@ -72,7 +73,14 @@ Changelog - +

    @@ -88,9 +96,9 @@

    Spatially-informed differential gene expression

    -

    2025-04-07

    +

    2026-10-15

    - + Source: vignettes/spatial_differential_expression.Rmd
    @@ -147,7 +155,7 @@

    Creating an STlist (Spa analysis with STdiff.

    Load the spatialGE package:

    -library('spatialGE')
    +library('spatialGE')

    The STlist function takes data in several formats. The reader is encouraged to see the STlist reference (see here to learn about the different options to read ST data in @@ -268,7 +276,7 @@

    A variogram of gene expressio abline(h=0.75, col='purple', lwd=3, lty=2) clip(x1=-1, x2=12.1, y1=-1, y2=2) abline(v=12, col='goldenrod1', lwd=3, lty=2)

    -

    +

    We can see that variance is higher at longer distances. Note, that this relationship is disrupted at longer spot-to-spot distances (> 15 in this case). This disruption occurs because as spot-to-spot distances @@ -334,7 +342,7 @@

    A variogram of gene expressio lines(exp_model, col=alpha('red', 0.7), lwd=3) lines(sph_model, col=alpha('blue', 0.7), lwd=3) lines(gau_model, col=alpha('orange', 0.7), lwd=3)

    -

    +

    In the case of COL1A1 for sample “ST_mel1_rep2”, all models (exponential, spherical, and gaussian) fit well the variogram. Due to computational constraints, the geoR package is not used in @@ -354,17 +362,17 @@

    Differential gene exp STdiff function can also use non-spatial mixed models to test for differentially expressed genes. In the non-spatial mixed models the the expression -y(si)y(s_i) +y(si)y(s_i) of a gene in spot/cell ii is described as:

    -

    y(si)=μ+ε(si) +

    y(si)=μ+ε(si) y(s_i) = μ + ε(s_i)

    where μμ is the average expression of the gene in the sample, and -ε(si)ε(s_i) +ε(si)ε(s_i) is the random error at spot/cell ii.

    To reduce the number of false positives in differential expression @@ -372,15 +380,15 @@

    Differential gene exp implementation of spatial mixed models with that expands the non-spatial case to include spatial covariance structures. In the spatial mixed models, the expression -y(si)y(s_i) +y(si)y(s_i) of a gene in spot/cell ii is described as:

    -

    Y(si)=μ+w(si)+ε(si) +

    Y(si)=μ+w(si)+ε(si) Y(s_i) = μ + w(s_i) + ε(s_i)

    where -w(si)w(s_i) +w(si)w(s_i) denotes the exponential spatial covariance of spot/cell ii.

    In order to detect differentially expressed genes, groups of @@ -405,7 +413,7 @@

    Detection of tissue domains wi ws=0.025, cores=2) #> STclust started... #> Updating STlist with results... -#> STclust completed in 0.03 min.

    +#> STclust completed in 0.01 min.

    Results of STclust domain detection can be plotted using the STplot function:

    @@ -416,7 +424,7 @@ 

    Detection of tissue domains wi ptsize=2, color_pal=c('#00BA38', '#EEBA38', '#619CFF', '#F8766D')) print(cluster_p[[1]])

    -

    +

    With the domains identified, the STdiff function can be used. The following command tests for differentially expressed genes on the 1000 genes with the highest variation (as defined by @@ -429,15 +437,11 @@

    Detection of tissue domains wi sp_topgenes=0.2, cores=2) # Test the 20% of the top differentially expressed genes (based on adjusted p-value) #> Testing STclust assignment (w=0.025, dtc deepSplit=False)... #> Running non-spatial mixed models... -#> Registered S3 methods overwritten by 'registry': -#> method from -#> print.registry_field proxy -#> print.registry_entry proxy -#> Completed non-spatial mixed models (3.22 min). +#> Completed non-spatial mixed models (2.13 min). #> Running spatial tests... #> -#> Completed spatial mixed models (1.39 min). -#> STdiff completed in 4.64 min.

    +#> Completed spatial mixed models (1.6 min). +#> STdiff completed in 3.79 min.

    The output of STdiff is a list, where each element is a data frame containing the test results for each sample:

    @@ -490,7 +494,7 @@ 

    Comparing res theme_bw()

     p1
    -

    +

    When comparing the -log10(p-values) from the non-spatial and spatial models, it is possible to see that the p-values from the non-spatial model tended to provide smaller, more @@ -529,8 +533,8 @@

    Comparing res test_type='wilcoxon', cores=2) #> Testing STclust assignment (w=0.025, dtc deepSplit=False)... #> Running Wilcoxon's tests... -#> Completed Wilcoxon's tests (0.46 min). -#> STdiff completed in 0.46 min.

    +#> Completed Wilcoxon's tests (0.03 min). +#> STdiff completed in 0.08 min.

    No spatial tests are executed when Wilcoxon’s Rank tests or T-tests are requested.

    @@ -565,13 +569,13 @@ 

    Visualizng STdiff results
     ggpubr::ggarrange(plotlist=vp, ncol=3, common.legend=TRUE)
    -

    +

    References

    -
    +
    Ospina, Oscar E, Alex C Soupir, Roberto Manjarres-Betancur, Guillermo Gonzalez-Calderon, Xiaoqing Yu, and Brooke L Fridley. 2024. “Differential gene expression analysis of spatial @@ -579,9 +583,9 @@

    Referenceshttps://doi.org/10.1038/s41598-024-61758-0.

    -Ospina, Oscar E, Christopher M Wilson, Alex C Soupir, Anders Berglund, -Inna Smalley, Kenneth Y Tsai, and Brooke L Fridley. 2022. “spatialGE: quantification and visualization of the tumor -microenvironment heterogeneity using spatial +Ospina, Oscar E, Christopher M Wilson, Alex C Soupir, et al. 2022. +“spatialGE: quantification and visualization +of the tumor microenvironment heterogeneity using spatial transcriptomics.” Bioinformatics 38: 2645–47. https://doi.org/10.1093/bioinformatics/btac145.
    @@ -594,58 +598,59 @@

    References
     sessionInfo()
    -#> R version 4.4.2 (2024-10-31)
    -#> Platform: aarch64-apple-darwin20
    -#> Running under: macOS Sequoia 15.3.2
    +#> R version 4.5.3 (2026-03-11)
    +#> Platform: aarch64-apple-darwin20.0.0
    +#> Running under: macOS Sequoia 15.8.1
     #> 
     #> Matrix products: default
    -#> BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
    -#> LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
    +#> BLAS:   /opt/anaconda3/envs/spatialge-dev/lib/libblas.3.9.0.dylib 
    +#> LAPACK: /opt/anaconda3/envs/spatialge-dev/lib/liblapack.3.9.0.dylib  LAPACK version 3.9.0
     #> 
     #> locale:
     #> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
     #> 
     #> time zone: America/New_York
    -#> tzcode source: internal
    +#> tzcode source: system (macOS)
     #> 
     #> attached base packages:
     #> [1] stats     graphics  grDevices utils     datasets  methods   base     
     #> 
     #> other attached packages:
    -#>  [1] ggrepel_0.9.5   lubridate_1.9.3 forcats_1.0.0   stringr_1.5.1  
    -#>  [5] dplyr_1.1.4     purrr_1.0.2     readr_2.1.5     tidyr_1.3.1    
    -#>  [9] tibble_3.2.1    ggplot2_3.5.1   tidyverse_2.0.0 spatialGE_1.2.0
    +#>  [1] ggrepel_0.9.8   lubridate_1.9.5 forcats_1.0.1   stringr_1.6.0  
    +#>  [5] dplyr_1.2.1     purrr_1.2.2     readr_2.2.0     tidyr_1.3.2    
    +#>  [9] tibble_3.3.1    ggplot2_4.0.3   tidyverse_2.0.0 spatialGE_2.0.0
     #> 
     #> loaded via a namespace (and not attached):
    -#>  [1] tidyselect_1.2.1    khroma_1.13.0       farver_2.1.2       
    -#>  [4] fastmap_1.2.0       digest_0.6.37       timechange_0.3.0   
    -#>  [7] lifecycle_1.0.4     magrittr_2.0.3      compiler_4.4.2     
    -#> [10] rlang_1.1.4         sass_0.4.9          tools_4.4.2        
    -#> [13] utf8_1.2.4          yaml_2.3.10         ggsignif_0.6.4     
    -#> [16] knitr_1.48          labeling_0.4.3      htmlwidgets_1.6.4  
    -#> [19] bit_4.0.5           sp_2.1-4            RColorBrewer_1.1-3 
    -#> [22] abind_1.4-5         registry_0.5-1      withr_3.0.1        
    -#> [25] numDeriv_2016.8-1.1 desc_1.4.3          grid_4.4.2         
    -#> [28] fansi_1.0.6         ggpubr_0.6.0        colorspace_2.1-1   
    -#> [31] scales_1.3.0        MASS_7.3-61         ggpolypath_0.3.0   
    -#> [34] cli_3.6.3           rmarkdown_2.28      crayon_1.5.3       
    -#> [37] ragg_1.3.2          generics_0.1.3      rstudioapi_0.16.0  
    -#> [40] tzdb_0.4.0          minqa_1.2.8         pbapply_1.7-2      
    -#> [43] cachem_1.1.0        proxy_0.4-27        parallel_4.4.2     
    -#> [46] vctrs_0.6.5         boot_1.3-31         Matrix_1.7-1       
    -#> [49] carData_3.0-5       jsonlite_1.8.8      slam_0.1-52        
    -#> [52] spaMM_4.5.0         car_3.1-2           hms_1.1.3          
    -#> [55] rstatix_0.7.2       bit64_4.0.5         systemfonts_1.1.0  
    -#> [58] jquerylib_0.1.4     splancs_2.01-45     glue_1.7.0         
    -#> [61] ROI_1.0-1           pkgdown_2.1.1       nloptr_2.1.1       
    -#> [64] cowplot_1.1.3       stringi_1.8.4       gtable_0.3.5       
    -#> [67] munsell_0.5.1       pillar_1.9.0        htmltools_0.5.8.1  
    -#> [70] R6_2.5.1            tcltk_4.4.2         textshaping_0.4.0  
    -#> [73] vroom_1.6.5         evaluate_0.24.0     lattice_0.22-6     
    -#> [76] highr_0.11          backports_1.5.0     broom_1.0.6        
    -#> [79] bslib_0.8.0         Rcpp_1.0.13         gridExtra_2.3      
    -#> [82] nlme_3.1-166        checkmate_2.3.2     geoR_1.9-4         
    -#> [85] xfun_0.47           fs_1.6.4            pkgconfig_2.0.3

    +#> [1] tidyselect_1.2.1 khroma_1.17.0 farver_2.1.2 +#> [4] S7_0.2.2 fastmap_1.2.0 digest_0.6.39 +#> [7] timechange_0.4.0 lifecycle_1.0.5 magrittr_2.0.5 +#> [10] compiler_4.5.3 rlang_1.3.0 sass_0.4.10 +#> [13] tools_4.5.3 utf8_1.2.6 yaml_2.3.12 +#> [16] ggsignif_0.6.4 knitr_1.52 labeling_0.4.3 +#> [19] htmlwidgets_1.6.4 bit_4.6.0 sp_2.2-3 +#> [22] RColorBrewer_1.1-3 abind_1.4-8 registry_0.5-1 +#> [25] withr_3.0.3 numDeriv_2016.8-1.1 desc_1.4.3 +#> [28] grid_4.5.3 ggpubr_1.0.0 scales_1.4.0 +#> [31] MASS_7.3-66 ggpolypath_0.4.0 cli_3.6.6 +#> [34] rmarkdown_2.32 crayon_1.5.3 ragg_1.5.2 +#> [37] reformulas_0.4.4 generics_0.1.4 otel_0.2.0 +#> [40] tzdb_0.5.0 minqa_1.2.8 pbapply_1.7-5 +#> [43] cachem_1.1.0 proxy_0.4-29 parallel_4.5.3 +#> [46] vctrs_0.7.3 boot_1.3-32 Matrix_1.7-6 +#> [49] carData_3.0-6 jsonlite_2.0.0 slam_0.1-56 +#> [52] spaMM_4.7.0 car_3.1-5 hms_1.1.4 +#> [55] rstatix_1.1.0 bit64_4.8.6 Formula_1.2-6 +#> [58] systemfonts_1.3.2 jquerylib_0.1.4 splancs_2.01-45 +#> [61] glue_1.8.1 ROI_1.0-2 pkgdown_2.2.1 +#> [64] nloptr_2.2.1 cowplot_1.2.0 stringi_1.8.9 +#> [67] gtable_0.3.6 pillar_1.11.1 htmltools_0.5.9 +#> [70] R6_2.6.1 tcltk_4.5.3 textshaping_1.0.5 +#> [73] Rdpack_2.6.6 vroom_1.7.1 evaluate_1.0.5 +#> [76] lattice_0.23-1 rbibutils_2.4.1 backports_1.5.1 +#> [79] broom_1.0.13 bslib_0.12.0 Rcpp_1.1.2 +#> [82] gridExtra_2.3.1 nlme_3.1-171 checkmate_2.3.4 +#> [85] geoR_1.9-6 xfun_0.60 fs_2.1.0 +#> [88] pkgconfig_2.0.3
    @@ -665,7 +670,7 @@

    References

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/articles/spatial_differential_expression_files/figure-html/compare_pval_p-1.png b/docs/articles/spatial_differential_expression_files/figure-html/compare_pval_p-1.png index f5b1465..cc90cc0 100644 Binary files a/docs/articles/spatial_differential_expression_files/figure-html/compare_pval_p-1.png and b/docs/articles/spatial_differential_expression_files/figure-html/compare_pval_p-1.png differ diff --git a/docs/articles/spatial_differential_expression_files/figure-html/volc_plots2-1.png b/docs/articles/spatial_differential_expression_files/figure-html/volc_plots2-1.png index b1348a2..b48f56b 100644 Binary files a/docs/articles/spatial_differential_expression_files/figure-html/volc_plots2-1.png and b/docs/articles/spatial_differential_expression_files/figure-html/volc_plots2-1.png differ diff --git a/docs/articles/spatial_enrichment_gradients_smi.html b/docs/articles/spatial_enrichment_gradients_smi.html index 3a95e0c..0408658 100644 --- a/docs/articles/spatial_enrichment_gradients_smi.html +++ b/docs/articles/spatial_enrichment_gradients_smi.html @@ -1,17 +1,15 @@ - - + Detection of gene set spatial patterns and expression gradients in CosMx-SMI • spatialGE - - - - - - + + + + + @@ -38,7 +36,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -57,6 +55,9 @@
  • Basic functionality: Visualization, domain detection, and spatial heterogeneity
  • +
  • + On-disk STlists: working with data sets larger than memory +
  • Spatially-informed differential gene expression
  • @@ -72,7 +73,14 @@ Changelog - + @@ -88,16 +96,16 @@

    Detection of gene set spatial patterns and expression gradients in CosMx-SMI

    -

    2025-04-07

    +

    2026-10-15

    - + Source: vignettes/spatial_enrichment_gradients_smi.Rmd -

    +

    The package spatialGE can be used to detect spatial patterns in gene expression at the gene and gene set level. Data from multiple spatial transcriptomics platforms can be @@ -112,18 +120,19 @@

    2025-04-07

    on a CosMx-SMI data set from Non-Small Cell Lung Cancer (NSCLC).

    How is spatialGE installed? -

    The spatialGE repository is available at GitHub and can -be installed via devtools. To install devtools -(in case it is not already installed in your R), please run the -following code:

    +

    The spatialGE repository is available at the +Comprehensive R Archive Network (CRAN) repository and can be installed +via install.packages:

    -if("devtools" %in% rownames(installed.packages()) == FALSE){
    -  install.packages("devtools")
    -}
    -

    After making sure devtools is installed, proceed to -install spatialGE:

    +# install.packages('spatialGE') +

    A development version is available at GitHub and can be installed via +devtools:

    -# devtools::install_github("fridleylab/spatialGE")
    +# if("devtools" %in% rownames(installed.packages()) == FALSE){ +# install.packages("devtools") +# } + +# devtools::install_github("fridleylab/spatialGE")

    Spatial gene set enrichment and expression gradients in non-small cell lung cancer (NSCLC) @@ -159,7 +168,7 @@

    -

    +

    The key files are shown enclosed in orange (Lung 5-1) and green (Lung 6) boxes. The “_exprMat_file.csv” file of each sample contains the gene counts. The “_metadata_file.csv” contains the cell x, y coordinates for @@ -180,7 +189,7 @@

    -library('spatialGE')

    +library('spatialGE')

    Creating an STList (Spatial Transcriptomics List) @@ -225,12 +234,16 @@

    Creating an STList (Spa
     cp <- distribution_plots(lung, plot_type='violin', plot_meta='total_counts', samples=c(1:5, 56:60))
     #> Sample NA does not contain total_counts.
    +#> 
     #> Sample NA does not contain total_counts.
    +#> 
     #> Sample NA does not contain total_counts.
    +#> 
     #> Sample NA does not contain total_counts.
    +#> 
     #> Sample NA does not contain total_counts.
     cp[['total_counts']]
    -

    +

    Cells with zero counts, can be removed using the filter_data function. The function can also be used to remove all counts from specific genes. This option is useful in this @@ -239,7 +252,8 @@

    Creating an STList (Spa those genes will be removed. Negative probes in CosMx-SMI begin with the token “NegPrb”:

    -lung <- filter_data(lung, spot_minreads=20, rm_genes_expr='^NegPrb')
    +lung <- filter_data(lung, spot_minreads=20, rm_genes_expr='^NegPrb') +#> filter_data: removed 0 sample(s), 171 spot(s)/cell(s) and 120 gene(s).

    Transformation of spatially-resolved transcriptomics data @@ -268,7 +282,7 @@

    Detecting gene se

    The algorithm in STenrich is depicted in the following diagram:

    -

    +

    The STenrich function is a modification of the method proposed by Hunter et al. (2021). The steps in this modified version are as follows: First, Euclidean @@ -373,26 +387,26 @@

    Detecting gene se seed=12345, cores=2) #> Running STenrich... #> Calculating average gene set expression... -#> STenrich completed in 0.41 min.

    +#> STenrich completed in 0.38 min.

    The result of the function is a list of data frames, with one data frame per samples (FOV in this case). For example, this is the data frame for the first FOV in the STlist:

     head(stenrich_df$Lung5_Rep1_fov_1)
     #>          sample_name                         gene_set size_test size_gene_set
    -#> 15 Lung5_Rep1_fov_11 HALLMARK_IL6_JAK_STAT3_SIGNALING        58           103
    -#> 27 Lung5_Rep1_fov_11       HALLMARK_KRAS_SIGNALING_UP        55           220
    -#> 57 Lung5_Rep1_fov_11 HALLMARK_TNFA_SIGNALING_VIA_NFKB        76           228
    -#> 9  Lung5_Rep1_fov_11     HALLMARK_IL2_STAT5_SIGNALING        58           216
    -#> 21 Lung5_Rep1_fov_11       HALLMARK_KRAS_SIGNALING_DN        20           220
    -#> 33 Lung5_Rep1_fov_11        HALLMARK_MTORC1_SIGNALING        13           211
    +#> 15 Lung5_Rep1_fov_11 HALLMARK_IL6_JAK_STAT3_SIGNALING        58            90
    +#> 27 Lung5_Rep1_fov_11       HALLMARK_KRAS_SIGNALING_UP        55           201
    +#> 57 Lung5_Rep1_fov_11 HALLMARK_TNFA_SIGNALING_VIA_NFKB        75           200
    +#> 9  Lung5_Rep1_fov_11     HALLMARK_IL2_STAT5_SIGNALING        58           200
    +#> 21 Lung5_Rep1_fov_11       HALLMARK_KRAS_SIGNALING_DN        20           200
    +#> 33 Lung5_Rep1_fov_11        HALLMARK_MTORC1_SIGNALING        13           200
     #>    prop_size_test p_value adj_p_value
    -#> 15          0.563   0.000      0.0000
    -#> 27          0.250   0.004      0.0200
    -#> 57          0.333   0.009      0.0300
    -#> 9           0.269   0.213      0.5325
    -#> 21          0.091   0.295      0.5900
    -#> 33          0.062   1.000      1.0000
    +#> 15 0.644 0.000 0.00000000 +#> 27 0.274 0.007 0.02333333 +#> 57 0.375 0.007 0.02333333 +#> 9 0.290 0.207 0.51750000 +#> 21 0.100 0.298 0.59600000 +#> 33 0.065 1.000 1.00000000

    Each row represents a test for the null hypothesis of no spatial aggregation in the expression of the set in the “gene_set” column. The column “size_test” is the number of genes of a gene set that were @@ -425,7 +439,7 @@

    Detecting gene se xlab(NULL) + theme(axis.text.x=element_text(angle=70, vjust=1, hjust=1)) + facet_wrap(~slide) -

    +

    The “NOTCH signaling” pathway showed spatial patterns less frequently in the slide “Lung5_Rep1” compared to “Lung6”. With the function STplot, the average gene set expression for this pathway @@ -441,13 +455,13 @@

    Detecting gene se filter(str_detect(sample_name, "Lung5_Rep1")) %>% slice_head(n=3) #> sample_name gene_set size_test size_gene_set -#> 1 Lung5_Rep1_fov_11 HALLMARK_NOTCH_SIGNALING 13 34 -#> 2 Lung5_Rep1_fov_2 HALLMARK_NOTCH_SIGNALING 13 34 -#> 3 Lung5_Rep1_fov_6 HALLMARK_NOTCH_SIGNALING 13 34 +#> 1 Lung5_Rep1_fov_11 HALLMARK_NOTCH_SIGNALING 13 32 +#> 2 Lung5_Rep1_fov_6 HALLMARK_NOTCH_SIGNALING 13 32 +#> 3 Lung5_Rep1_fov_2 HALLMARK_NOTCH_SIGNALING 13 32 #> prop_size_test p_value adj_p_value prop_gene_set -#> 1 0.382 0.989 1.000 0.3823529 -#> 2 0.382 0.981 0.981 0.3823529 -#> 3 0.382 0.858 0.977 0.3823529 +#> 1 0.406 0.988 1.000 0.40625 +#> 2 0.406 0.865 0.984 0.40625 +#> 3 0.406 0.977 0.977 0.40625
     bind_rows(stenrich_df) %>%
       mutate(prop_gene_set=size_test/size_gene_set) %>%
    @@ -457,13 +471,13 @@ 

    Detecting gene se filter(str_detect(sample_name, "Lung6")) %>% slice_head(n=3) #> sample_name gene_set size_test size_gene_set prop_size_test -#> 1 Lung6_fov_4 HALLMARK_NOTCH_SIGNALING 13 34 0.382 -#> 2 Lung6_fov_6 HALLMARK_NOTCH_SIGNALING 13 34 0.382 -#> 3 Lung6_fov_7 HALLMARK_NOTCH_SIGNALING 13 34 0.382 +#> 1 Lung6_fov_4 HALLMARK_NOTCH_SIGNALING 13 32 0.406 +#> 2 Lung6_fov_6 HALLMARK_NOTCH_SIGNALING 13 32 0.406 +#> 3 Lung6_fov_7 HALLMARK_NOTCH_SIGNALING 13 32 0.406 #> p_value adj_p_value prop_gene_set -#> 1 0.000 0.000000000 0.3823529 -#> 2 0.000 0.000000000 0.3823529 -#> 3 0.001 0.001666667 0.3823529

    +#> 1 0 0 0.40625 +#> 2 0 0 0.40625 +#> 3 0 0 0.40625

    Plots can be generated like so:

     qp <- STplot(lung, genes=gene_sets[names(gene_sets) == 'HALLMARK_NOTCH_SIGNALING'], 
    @@ -472,7 +486,7 @@ 

    Detecting gene se color_pal='YlOrBr') ggpubr::ggarrange(plotlist=qp, ncol=3, nrow=2, common.legend=TRUE)

    -

    +

    Although expression of the NOTCH signaling pathway is higher overall in “Lung6”, the expression is not uniform, but rather is arranged in patterns within each FOV. Conversely, cells in FOVs of “Lung5_Rep1” that @@ -518,18 +532,20 @@

    Detecting gene se
     img_fp = paste0(nsclc_tmp, '/nanostring_nsclc/Lung5_Rep1-Flat_files_and_images/CellComposite')
     lung <- load_images(lung, images=img_fp)
    -#> Image for sample Lung6_fov_4 was not found.
    -#> Image for sample Lung6_fov_6 was not found.
    -#> Image for sample Lung6_fov_7 was not found.
    +#> Warning: No image found for sample(s): Lung6_fov_4, Lung6_fov_6, Lung6_fov_7. +#> Image filenames must contain '<sample_name>.' (for example 'Lung6_fov_4.png'), +#> or pass a named vector mapping sample names to file paths, e.g. +#> images=c(Lung6_fov_4='path/to/image.png').

    The images for slide “Lung6” were not found, which are in the corresponsing folder. The load_images function is ran again to add images from “Lung6”:

     img_fp = paste0(nsclc_tmp, '/nanostring_nsclc/Lung6-Flat_files_and_images/CellComposite')
     lung <- load_images(lung, images=img_fp)
    -#> Image for sample Lung5_Rep1_fov_2 was not found.
    -#> Image for sample Lung5_Rep1_fov_6 was not found.
    -#> Image for sample Lung5_Rep1_fov_11 was not found.
    +#> Warning: No image found for sample(s): Lung5_Rep1_fov_2, Lung5_Rep1_fov_6, +#> Lung5_Rep1_fov_11. Image filenames must contain '<sample_name>.' (for example +#> 'Lung5_Rep1_fov_2.png'), or pass a named vector mapping sample names to file +#> paths, e.g. images=c(Lung5_Rep1_fov_2='path/to/image.png').

    The function plot_image is used to generate the ggplot objects containing the images:

    @@ -553,7 +569,7 @@ 

    Detecting gene se dom_p$Lung6_fov_7_stclust_spw0.02_dsplFalse, ti$image_Lung6_fov_7, ncol=4, nrow=3)

    -

    +

     
     # If no tissue images are available:
    @@ -564,8 +580,8 @@ 

    Detecting gene se deg <- STdiff(lung, w=0.02, k='dtc', deepSplit=FALSE, test_type='wilcoxon', cores=2) #> Testing STclust assignment (w=0.02, dtc deepSplit=False)... #> Running Wilcoxon's tests... -#> Completed Wilcoxon's tests (5.77 min). -#> STdiff completed in 5.77 min.

    +#> Completed Wilcoxon's tests (0.96 min). +#> STdiff completed in 1.82 min.

    Then, the top 3 DE genes per cluster in the samples showing NOTCH signaling spatial patterns are identified:

    @@ -609,7 +625,7 @@ 

    Identifc function. The following diagram depicts the STgradient algorithm:

    -

    +

    In STgradient, the spatial coordinates are used to calculate Euclidean distances of each cell to each of the other cells. The reference domain is the domain from which the distances will be @@ -663,7 +679,7 @@

    Identifc samples=c('Lung6_fov_4', 'Lung6_fov_6', 'Lung6_fov_7'), distsumm='min', robust=TRUE, cores=2) -#> STgradient completed in 0.1 min.

    +#> STgradient completed in 0.12 min.

    Here are the first few rows of the STgradient result for sample “Lung6_fov_4”:

    @@ -711,7 +727,7 @@ 

    Identifc
     qp2 <- STplot(lung, genes=c('KRT6A', 'HLA-B'), samples='Lung6_fov_4', color_pal='YlOrBr')
     ggpubr::ggarrange(plotlist=qp2, common.legend=TRUE)
    -

    +

    Here are the results for genes within the NOTCH signaling pathway:

    @@ -735,7 +751,7 @@ 

    Identifc

    References

    -
    +
    Hafemeister, Christoph, and Rahul Satija. 2019. “Normalization and Variance Stabilization of Single-Cell RNA-Seq Data Using Regularized @@ -752,59 +768,59 @@

    References
     sessionInfo()
    -#> R version 4.4.2 (2024-10-31)
    -#> Platform: aarch64-apple-darwin20
    -#> Running under: macOS Sequoia 15.3.2
    +#> R version 4.5.3 (2026-03-11)
    +#> Platform: aarch64-apple-darwin20.0.0
    +#> Running under: macOS Sequoia 15.8.1
     #> 
     #> Matrix products: default
    -#> BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
    -#> LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
    +#> BLAS:   /opt/anaconda3/envs/spatialge-dev/lib/libblas.3.9.0.dylib 
    +#> LAPACK: /opt/anaconda3/envs/spatialge-dev/lib/liblapack.3.9.0.dylib  LAPACK version 3.9.0
     #> 
     #> locale:
     #> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
     #> 
     #> time zone: America/New_York
    -#> tzcode source: internal
    +#> tzcode source: system (macOS)
     #> 
     #> attached base packages:
     #> [1] stats     graphics  grDevices utils     datasets  methods   base     
     #> 
     #> other attached packages:
    -#>  [1] lubridate_1.9.3 forcats_1.0.0   stringr_1.5.1   dplyr_1.1.4    
    -#>  [5] purrr_1.0.2     readr_2.1.5     tidyr_1.3.1     tibble_3.2.1   
    -#>  [9] ggplot2_3.5.1   tidyverse_2.0.0 msigdbr_7.5.1   spatialGE_1.2.0
    +#>  [1] lubridate_1.9.5 forcats_1.0.1   stringr_1.6.0   dplyr_1.2.1    
    +#>  [5] purrr_1.2.2     readr_2.2.0     tidyr_1.3.2     tibble_3.3.1   
    +#>  [9] ggplot2_4.0.3   tidyverse_2.0.0 msigdbr_26.1.1  spatialGE_2.0.0
     #> 
     #> loaded via a namespace (and not attached):
    -#>  [1] tidyselect_1.2.1      EBImage_4.46.0        khroma_1.13.0        
    -#>  [4] farver_2.1.2          bitops_1.0-8          RCurl_1.98-1.16      
    -#>  [7] fastmap_1.2.0         tweenr_2.0.3          digest_0.6.37        
    -#> [10] timechange_0.3.0      lifecycle_1.0.4       magrittr_2.0.3       
    -#> [13] compiler_4.4.2        rlang_1.1.4           sass_0.4.9           
    -#> [16] tools_4.4.2           utf8_1.2.4            yaml_2.3.10          
    -#> [19] knitr_1.48            ggsignif_0.6.4        S4Arrays_1.4.1       
    -#> [22] labeling_0.4.3        htmlwidgets_1.6.4     DelayedArray_0.30.1  
    -#> [25] abind_1.4-5           babelgene_22.9        withr_3.0.1          
    -#> [28] BiocGenerics_0.50.0   desc_1.4.3            grid_4.4.2           
    -#> [31] polyclip_1.10-7       stats4_4.4.2          fansi_1.0.6          
    -#> [34] ggpubr_0.6.0          colorspace_2.1-1      scales_1.3.0         
    -#> [37] MASS_7.3-61           ggpolypath_0.3.0      cli_3.6.3            
    -#> [40] rmarkdown_2.28        crayon_1.5.3          ragg_1.3.2           
    -#> [43] generics_0.1.3        rstudioapi_0.16.0     tzdb_0.4.0           
    -#> [46] cachem_1.1.0          ggforce_0.4.2         zlibbioc_1.50.0      
    -#> [49] parallel_4.4.2        tiff_0.1-12           XVector_0.44.0       
    -#> [52] matrixStats_1.3.0     vctrs_0.6.5           Matrix_1.7-1         
    -#> [55] carData_3.0-5         jsonlite_1.8.8        car_3.1-2            
    -#> [58] fftwtools_0.9-11      IRanges_2.38.1        hms_1.1.3            
    -#> [61] S4Vectors_0.42.1      rstatix_0.7.2         jpeg_0.1-10          
    -#> [64] systemfonts_1.1.0     locfit_1.5-9.10       jquerylib_0.1.4      
    -#> [67] glue_1.7.0            pkgdown_2.1.1         cowplot_1.1.3        
    -#> [70] stringi_1.8.4         gtable_0.3.5          munsell_0.5.1        
    -#> [73] pillar_1.9.0          htmltools_0.5.8.1     R6_2.5.1             
    -#> [76] textshaping_0.4.0     evaluate_0.24.0       lattice_0.22-6       
    -#> [79] highr_0.11            backports_1.5.0       png_0.1-8            
    -#> [82] broom_1.0.6           bslib_0.8.0           Rcpp_1.0.13          
    -#> [85] gridExtra_2.3         SparseArray_1.4.8     xfun_0.47            
    -#> [88] fs_1.6.4              MatrixGenerics_1.16.0 pkgconfig_2.0.3

    +#> [1] tidyselect_1.2.1 EBImage_4.52.0 khroma_1.17.0 +#> [4] farver_2.1.2 bitops_1.1-0 S7_0.2.2 +#> [7] RCurl_1.98-1.20 fastmap_1.2.0 tweenr_2.0.3 +#> [10] digest_0.6.39 timechange_0.4.0 lifecycle_1.0.5 +#> [13] magrittr_2.0.5 compiler_4.5.3 rlang_1.3.0 +#> [16] sass_0.4.10 tools_4.5.3 utf8_1.2.6 +#> [19] yaml_2.3.12 knitr_1.52 ggsignif_0.6.4 +#> [22] S4Arrays_1.10.1 labeling_0.4.3 htmlwidgets_1.6.4 +#> [25] curl_8.0.0 DelayedArray_0.36.1 RColorBrewer_1.1-3 +#> [28] abind_1.4-8 withr_3.0.3 BiocGenerics_0.56.0 +#> [31] desc_1.4.3 grid_4.5.3 polyclip_1.10-7 +#> [34] stats4_4.5.3 ggpubr_1.0.0 scales_1.4.0 +#> [37] MASS_7.3-66 ggpolypath_0.4.0 cli_3.6.6 +#> [40] rmarkdown_2.32 ragg_1.5.2 generics_0.1.4 +#> [43] otel_0.2.0 tzdb_0.5.0 cachem_1.1.0 +#> [46] ggforce_0.5.0 assertthat_0.2.1 parallel_4.5.3 +#> [49] tiff_0.1-12 XVector_0.50.0 matrixStats_1.5.0 +#> [52] vctrs_0.7.3 Matrix_1.7-6 carData_3.0-6 +#> [55] jsonlite_2.0.0 car_3.1-5 fftwtools_0.9-11 +#> [58] IRanges_2.44.0 hms_1.1.4 S4Vectors_0.48.1 +#> [61] rstatix_1.1.0 Formula_1.2-6 jpeg_0.1-11 +#> [64] systemfonts_1.3.2 locfit_1.5-9.12 jquerylib_0.1.4 +#> [67] glue_1.8.1 pkgdown_2.2.1 cowplot_1.2.0 +#> [70] stringi_1.8.9 gtable_0.3.6 pillar_1.11.1 +#> [73] htmltools_0.5.9 R6_2.6.1 textshaping_1.0.5 +#> [76] evaluate_1.0.5 lattice_0.23-1 png_0.1-9 +#> [79] backports_1.5.1 broom_1.0.13 bslib_0.12.0 +#> [82] Rcpp_1.1.2 gridExtra_2.3.1 SparseArray_1.10.10 +#> [85] xfun_0.60 fs_2.1.0 MatrixGenerics_1.22.0 +#> [88] pkgconfig_2.0.3

    @@ -824,7 +840,7 @@

    References

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/count_dstr-1.png b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/count_dstr-1.png index 7df04b3..d566382 100644 Binary files a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/count_dstr-1.png and b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/count_dstr-1.png differ diff --git a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/notch_plots-1.png b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/notch_plots-1.png index fe2cc9a..cddf226 100644 Binary files a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/notch_plots-1.png and b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/notch_plots-1.png differ diff --git a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/plot_domains-1.png b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/plot_domains-1.png index 71119b6..48bbcc0 100644 Binary files a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/plot_domains-1.png and b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/plot_domains-1.png differ diff --git a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/stg_plots-1.png b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/stg_plots-1.png index 5ce278f..6ec946c 100644 Binary files a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/stg_plots-1.png and b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/stg_plots-1.png differ diff --git a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/unnamed-chunk-1-1.png b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/unnamed-chunk-1-1.png index 08a2815..468f949 100644 Binary files a/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/unnamed-chunk-1-1.png and b/docs/articles/spatial_enrichment_gradients_smi_files/figure-html/unnamed-chunk-1-1.png differ diff --git a/docs/articles/troubleshooting.html b/docs/articles/troubleshooting.html index 14e90f3..5f248a2 100644 --- a/docs/articles/troubleshooting.html +++ b/docs/articles/troubleshooting.html @@ -1,17 +1,15 @@ - - + Troubleshooting • spatialGE - - - - - - + + + + + @@ -38,7 +36,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -57,6 +55,9 @@
  • Basic functionality: Visualization, domain detection, and spatial heterogeneity
  • +
  • + On-disk STlists: working with data sets larger than memory +
  • Spatially-informed differential gene expression
  • @@ -72,7 +73,14 @@ Changelog - + @@ -87,9 +95,9 @@ @@ -106,7 +114,7 @@

    2025-04-07

    A workaround is to set options(timeout) to a large number:

    options(timeout=9999999) # To avoid R closing connection with GitHub
    -devtools::install_github("fridleylab/spatialGE")
    +devtools::install_github("fridleylab/spatialGE")
    The gene_interpolation function outputs an error: Error in solve.default(qr.R(qr.VT)). What can be done about it? @@ -152,7 +160,7 @@

    2025-04-07

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/authors.html b/docs/authors.html index 3cfe20b..097248a 100644 --- a/docs/authors.html +++ b/docs/authors.html @@ -1,5 +1,5 @@ -Authors and Citation • spatialGEAuthors and Citation • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -73,24 +82,29 @@

    Authors and Citation

    Brooke Fridley. Author.

    +
  • +

    Satija Lab. Copyright holder. +
    Copyright holder of code fragments from Seurat function FindVariableFeatures

    +
  • Citation

    - + Source: DESCRIPTION
    -

    Ospina O, Soupir A, Fridley B (2025). +

    Ospina O, Soupir A, Fridley B (2026). spatialGE: Visualization and Analysis of Spatial Heterogeneity in Spatially-Resolved Gene Expression. -R package version 1.2.0. +R package version 2.0.0, https://github.com/FridleyLab/spatialGE.

    @Manual{,
       title = {spatialGE: Visualization and Analysis of Spatial Heterogeneity in Spatially-Resolved Gene Expression},
       author = {Oscar Ospina and Alex Soupir and Brooke Fridley},
    -  year = {2025},
    -  note = {R package version 1.2.0},
    +  year = {2026},
    +  note = {R package version 2.0.0},
    +  url = {https://github.com/FridleyLab/spatialGE},
     }
    @@ -104,7 +118,7 @@

    Citation

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/index.html b/docs/index.html index 6194a51..3bf24bc 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,24 +1,22 @@ - - + Visualization and Analysis of Spatial Heterogeneity in Spatially-Resolved Gene Expression • spatialGE - - - - - - + + + + + - + @@ -89,7 +97,7 @@
    -

    +

    An R package for the visualization and analysis of spatially-resolved transcriptomics data, such as those generated with 10X Visium. The spatialGE package features a data object (STlist: Spatial Transctiptomics List) to store data and results from multiple tissue sections, as well as associated analytical methods for:

    • Visualization: STplot, gene_interpolation, STplot_interpolation to explore gene expression in spatial context.
    • @@ -101,13 +109,13 @@

    The methods in the initial spatialGE release, technical details, and their utility are presented in this publication: https://doi.org/10.1093/bioinformatics/btac145. For details on the recently developed methods STenrich, STgradient, and STdiff please refer to the spatialGE documentation.

    -

    +

    Installation

    The spatialGE repository is available at GitHub and can be installed via devtools.

    options(timeout=9999999) # To avoid R closing connection with GitHub
    -devtools::install_github("fridleylab/spatialGE")
    +devtools::install_github("fridleylab/spatialGE")

    How to use spatialGE @@ -126,15 +134,34 @@

    How to citehttps://doi.org/10.1093/bioinformatics/btac145

    +

    @@ -57,11 +66,91 @@
    - + +
    +

    Behavior changes

    +
    • +

      transform_data() now populates vst.variance.standardized in @gene_meta. Previously the column was added only as a side effect of whichever analysis ran first, so whether get_gene_meta() showed it depended on call order, and gene_interpolation()/STplot_interpolation() dropped any existing column and recomputed it. transform_data() now computes it for both method='log' and method='sct', through the same calculate_vst() helper STclust() uses, so every caller sees one definition. Code that inspected colnames(get_gene_meta(x)) will see one additional column, and code that counted on STclust() being what created it no longer needs to.

      +

      Note this does not change which genes any function selects: STclust(), STgradient(), gene_interpolation() and STdiff() already computed VST themselves before ranking, so their topgenes choices were consistent before this change too. (An earlier draft of this entry claimed otherwise, and also cited a top-20 overlap between gene_stdevs and VST rankings of 6; measured across the eight Visium samples of the tnbc_bassiouni set it is 7-13.) What changed is where the column comes from, not what downstream functions do with it.

      +
    • +
    • transform_data() no longer fails on a sample with very few variable genes. Because of the change above, transform_data() began fitting the variance-mean loess that vst.variance.standardized requires. That fit needs at least 4 genes with non-zero variance, and below it stats::loess stops with span is too small – so normalizing a very small or low-complexity STlist aborted, where in 1.2.2 it had succeeded. The count that matters is of non-constant genes, so a matrix with many genes of which only a few vary hit it as well. Such a sample now gets a warning naming it, and is left without the column rather than failing; calculate_vst() only computes when the column is absent, so a later analysis retries instead of inheriting a wrong value. Functions that rank genes by variability still raise an error on such a sample, since there is no ranking to return.

    • +
    • dim() on an STlist now obeys the base R contract. It returns c(n_genes, n_spots) as an integer vector when the object holds exactly one sample, and NULL for a multi-sample object – because there is no single gene x spot shape to report. It previously returned a named list of per-sample dimensions, which made nrow() and ncol() meaningless on an STlist and was reported by R CMD check as “dim() returns class ‘list’”. Use summarize_STlist() for a per-sample table of dimensions. Nothing inside the package called dim() on an STlist.

    • +
    • STlist objects are now validated at construction. setValidity() rejects a malformed object up front: a sample-keyed slot referring to a sample that is not in @counts, a count matrix without gene/spot names, or an @spatial_meta entry whose row count disagrees with the number of spots. These previously surfaced much later, far from their cause.

    • +
    • filter_data() reports what it did. Every count threshold defaults to 0 (and the *_max* thresholds to NULL), so a call supplying none of them filtered nothing – while looking like a successful filter. With the new verbose=TRUE default it now says explicitly that nothing was filtered, or how many samples, spots/cells and genes were removed. filter_data() remains single-threaded and deliberately has no cores argument, unlike the analysis functions.

    • +
    • Requesting a gene, annotation or reference domain that does not exist is now an error rather than a silent no-op. SThet(genes=), STgradient(annot=), STgradient(ref=) and gene_interpolation(genes=) previously accepted a name matching nothing and returned without complaint, so a typo looked like a run that legitimately found nothing. The rule is now: error when nothing matches, and message naming what was dropped when only some does. Code that relied on the no-op will now stop; that reliance was almost certainly accidental.

    • +
    • STenrich() now requires annot and domain together. Domain-restricted mode was guarded by !is.null(annot) & !is.null(domain), so supplying one without the other skipped the entire block: the unrestricted analysis ran and returned results a caller would reasonably read as domain-restricted, with nothing downstream able to detect the discrepancy. Supplying one alone is now an error. If you have results from 1.2.x produced by passing annot without domain, they are not domain-restricted and are worth regenerating.

    • +
    • SThet()’s default (k=NULL) statistics moved by ~2e-15. The distance-weighted complete graph is no longer materialized as a listw; Moran’s I and Geary’s C are computed directly from the coordinates in C++. Szero is bit-identical, and the residual difference is summation order inside the weighted dot product – four orders of magnitude below the ~2e-2 spot-order sensitivity already documented for SThet(k=). The reason for the change is capacity: the old listw needed 1.2 GB for a single 4,096-spot sample and about 181 GB extrapolated to 50,000 cells, i.e. it could not run on Xenium or CosMx data at all. It now completes in ~39 s using ~100 KB. @misc$sthet$listws is no longer populated on this path; SThet(k=) still builds a real spdep object.

    • +
    • gene_stdevs in @gene_meta moved by ~1e-16. Per-gene standard deviations are computed without densifying the matrix, which changes the summation order. Nothing downstream consumes gene_stdevs – topgenes selection uses vst.variance.standardized – and cluster assignments, all vst.* columns and @tr_counts were verified bit-identical.

    • +
    • A Seurat object’s platform is no longer assumed to be Visium. STlist() hardcoded @misc$platform = 'visium' for any Seurat input; it is now inferred from the image class. This matters because platform selects STgradient()’s default nb_dist_thr and branches in plot_image() and STplot_interpolation(), so importing an imaging-based (Xenium/CosMx) Seurat object previously produced results computed with Visium-appropriate distance thresholds.

    • +
    • pseudobulk_heatmap() displays a different set of genes, because it was selecting the wrong ones. The heatmap keeps the hm_display_genes most variable genes, ranked by coefficient of variation, but the CV was computed upside down as mean/sd instead of sd/mean. Sorting that decreasing put the highest mean/sd first – that is, the lowest true CV – so the plot showed the most uniformly-expressed genes rather than the most variable ones, the exact opposite of the intent. Any heatmap produced by 1.2.x is showing the wrong gene set and is worth regenerating.

    • +
    • cores= is now honored by STlist() and transform_data(). Both accepted the argument and then ignored it, so they always ran at the auto-detected core count no matter what was passed. Passing cores= now actually changes the number of forked workers. Two consequences: wall-clock times for these two functions will differ from 1.2.x for any explicit cores=, and because forked children re-seed their own RNG, transform_data(method='sct') is only reproducible at cores=1 once a sample exceeds sctransform::vst’s internal sampling threshold. Pass cores=1 where exact SCT reproducibility matters.

    • +
    • +

      Spot/cell ordering within an STlist is now deterministic. process_lists() contained a coordinate sort that silently had no effect, so through 1.2.2 spots simply retained whatever order they appeared in in the input files – meaning two files describing the same tissue with rows in a different order produced differently-ordered STlists. The sort now applies, so ordering depends on the coordinates themselves rather than on input file layout.

      +

      Note what it sorts by: the third column of the coordinate data, whichever that is, not xpos specifically. With the usual libname, ypos, xpos column order that means xpos, and because the sort is stable the result reads as xpos then ypos. Supply the coordinate columns in a different order and the sort key changes with them.

      +

      No function signatures, arguments, or return types changed. Counts, transformed counts, and the vst.* gene-level statistics are bit-identical once matched by name. What changes for them is order: the column order of @counts/@tr_counts, the row order of @spatial_meta, and therefore the row order of results built from them. Code that addresses spots by libname is unaffected; code that indexes them positionally, or that depends on how ties break in an adj_p_value-sorted result, may need updating.

      +

      Four results are not merely reordered, because they depend on spot order by construction rather than by layout. All four behaved this way in 1.2.x too – there, the order came from your input file, so the same tissue supplied with rows in a different order gave different numbers. Ordering is now determined by the coordinates, which removes that file-layout dependence, but the underlying sensitivity remains and is worth knowing about:

      +
      • +STenrich() p-values. The permutation null is drawn over spot positions, so a fixed seed selects a different random subset when the spots are in a different order. The observed statistic is unaffected; only the null, and therefore p_value/adj_p_value, move.
      • +
      • +SThet(k = ) Moran’s I. With k given, neighbours come from a k-nearest neighbour graph, and on a regular grid the k-th distance is tied between several spots; the tie is broken by position. On our test data Moran’s I moves by up to 0.02 – large enough to matter. SThet() without k uses a distance-based weight list and is unaffected (agreement to ~1e-15).
      • +
      • +STgradient(distsumm = 'avg') Spearman correlations. Averaging each spot’s distances to the reference domain produces exact ties on a regular grid, and a change in summation order of ~1e-16 is enough to flip one, which flips a rank. Correlations move by up to 0.004. distsumm = 'min' does not create the same ties.
      • +
      • +plot_counts() density curves, which plot a seeded random distrib_subset of spots selected by position. Cosmetic, but the curve is not identical. The point jitter in distribution_plots(plot_type = 'violin') behaves the same way.
      • +

      If you need a value that does not depend on spot order at all, prefer SThet() without k and STgradient(distsumm = 'min'), and raise reps in STenrich() so the permutation estimate is less sensitive to which subset is drawn.

      +
    • +
    +
    +

    New features

    +
    • +

      An STlist can now be subset by sample, and has a length. x[i] returns a new, valid STlist holding only the selected spatial arrays, and length(x) reports how many it holds. Previously neither worked: subsetting failed with “object of type ‘S4’ is not subsettable”, and length(x) returned the number of slots (7) rather than samples, so seq_along(x) and for(i in seq_len(length(x))) silently did the wrong thing. To work with one sample out of a multi-sample object you had to rebuild an STlist from the raw files.

      +

      Select by name (x[tissue_names(x)[1]]), position, negative position or logical vector. Every sample-keyed slot is subset alongside @counts – @spatial_meta, @gene_meta, @tr_counts, and the per-sample level inside each @gene_krige element – so the result passes validity, and @sample_meta rows are matched to their sample rather than sliced positionally. Subsetting is deliberately one-dimensional: an STlist holds several arrays with independent gene and spot sets, so there is no shared second dimension. x[i, j] and x[[i]] raise an error saying so. An unknown sample name is also an error, listing the available names, rather than a silent omission.

      +
    • +
    • Parallelism on Windows. resolve_cores() returned 1L unconditionally on Windows and sge_lapply() forwarded only to parallel::mclapply, which has no fork() there – so the package was entirely serial. A non-forking (PSOCK) backend is now used on Windows, and can be forced anywhere with options(spatialGE.psock=TRUE). mclapply remains the default where fork() exists. The spatialGE.cores/SPATIALGE_CORES override is also now consulted before any platform decision; it was previously ignored on Windows.

    • +
    • Seurat v5 support, and conversion in both directions. Seurat input was v4 only: v5 stores counts in an Assay5’s layers, so the old access returned NULL, and v5’s VisiumV2/FOV images carry no @coordinates frame. Both are handled now, the assay defaults to DefaultAssay() rather than a hardcoded 'Spatial', and the import is sparse-to-sparse instead of densifying every gene by every cell across all slices up front. as_Seurat() is new and provides the reverse conversion.

    • +
    • Optional on-disk storage. STlist_to_disk(x, root) moves count matrices into per-sample parquet files so data larger than memory can be held and read in gene-subset slices; STlist_to_memory() reverses it, exactly. Opt-in and off by default – an STlist built the normal way is unchanged. is_backed() and validate_store() support it. Note this buys capacity, not speed: aggregates still compute in memory, so a backed STlist is currently slower on those paths.

    • +
    • Large-data performance. Several operations no longer densify sparse matrices. Measured on a 200-gene x 50,000-cell synthetic sample: filter_data() 27x faster, per-gene standard deviations 42x, and log transformation 33x (bit-identical output).

    • +
    • STgradient()’s distance step no longer materializes the n x n distance matrix. stgradient_dists_one_sample() built as.matrix(stats::dist(coords)) – 934 MB allocated at 4,096 spots and about 20 GB at 50,000 cells, so the function could not run on Xenium or CosMx data at all. The distances are now computed in C++ in O(n) memory. Output is bit-identical for both distsumm='min' and distsumm='avg' (the latter reproduces R’s two-pass corrected mean()), so no results change; measured 1.6x faster and about 3,100x less allocation at 4,096 spots, and 50,000 cells now completes instead of failing to allocate.

    • +
    • STdiff()’s t_test and wilcoxon paths are 17-27x faster. stdiff_mean_test() re-filtered and re-selected the whole expression frame once per gene x cluster combination; the two groups depend only on the annotation, so the split is now computed with base indexing and the gene column is pulled directly. Output is unchanged – the same t.test/wilcox.test calls on the same vectors. The default mm path is not affected.

    • +
    • Set the environment variable SPATIALGE_CORES, or the option spatialGE.cores, to force every parallelized call site to run serially and in-process without editing any code. Intended for profiling (profvis cannot see inside parallel::mclapply’s forks) and for debugging a worker that fails only under forking. The option takes precedence over the environment variable. This is a development aid and is deliberately not part of the documented API.

    • +
    +
    +

    Bug fixes

    +
    • STlist validity no longer rejects an object that has kriging results. setValidity() treated @gene_krige as sample-keyed and compared its names to the sample names, but that slot is keyed by gene first and sample second (x@gene_krige[[gene]][[sample]]), so its top-level names are gene symbols. Every object returned by gene_interpolation() was therefore reported invalid – but only when validity actually ran, and assignment through @<- does not trigger it, so the function appeared to succeed and a later validObject() (or any construction from that object) failed. The sample level is now checked, one gene at a time.

    • +
    • load_images() no longer drops samples whose image is not the first path match. Two defects combined: sample-to-file matching used a vectorized & where it needed a scalar &&, and the match was positional, so with more than one image directory or a sample whose name did not sort first the wrong file – or no file – was attached. Matching is now by normalized sample name, across every supplied directory and both extensions (.png/.jpg/.jpeg), with a decoder fallback when the file extension disagrees with its actual encoding. A sample whose image genuinely cannot be read is skipped with a warning rather than silently, and if no image matches at all the error names what was searched.

    • +
    • STplot_interpolation() works on its documented default. With the default genes=NULL it selected genes by VST but then intersected that selection with a kriging-derived gene list; because it also required the column to be present, the call failed on any STlist that had not already been through gene_interpolation(). It now errors with a clear message when the object has no kriged genes, restricts to those that do exist (warning only when the user named genes explicitly), uses calculate_vst() rather than its own inline copy, and errors clearly when a color scale has no finite values.

    • +
    • STdiff() explains an unusable annot= instead of failing inside dplyr. A numeric metadata column – a perfectly ordinary one, such as total_counts – reached an internal join and produced Can't join `x$orig_annot` with `y$orig_annot` due to incompatible types. i `x$orig_annot` is a <double>, which names neither the function nor the argument to change. annot must hold group labels, so a numeric column now raises an error naming STdiff, the requirement and the fix (as.character()), as does a column with fewer than two distinct groups – which previously produced no usable comparison.

    • +
    • transform_data(method='sct') reports an actionable error when SCTransform fails. On a small or low-complexity matrix sctransform::vst() failed with missing value where TRUE/FALSE needed, giving no indication of which sample, how large it was, or what to change. The error now names the sample and its dimensions (n_genes x spots/cells) and suggests lowering sct_n_regr_genes or using method='log', while still reporting the underlying message.

    • +
    • A bad cores= value is caught on every parallelized path. The gene-metadata step of transform_data() never validated it, so cores='abc' coerced to NA and was handed directly to the parallel lapply instead of raising an error. Validation is now centralized (see Minor), which fixes that path and removes the five duplicated checks elsewhere.

    • +
    • pseudobulk_samples() no longer fails on a gene whose pseudobulk total is constant across samples. Such a gene produced an all-NaN column after scaling and prcomp() rejected it outright, so any dataset containing an all-zero gene – routine after a permissive filter_data() – could not be analysed. Those genes are now dropped with a warning.

    • +
    • SThet() no longer fails when @spatial_meta has been row-subset with base [. Both spatial-weight builders fed the frame to tibble::column_to_rownames(), which rejects non-contiguous row names, so the call died with an error naming neither SThet nor the cause. This is the same defect that made STenrich()’s domain= path unreachable through 1.2.2, in two call sites that fix did not cover.

    • +
    • STenrich() no longer crashes on a gene set with exactly one gene present. Subsetting dropped the matrix to a dimensionless vector, which DelayedMatrixStats::colMeans2() rejects – even though min_genes=1 explicitly permits single-gene sets.

    • +
    • Seurat_FindVariableFeatures() no longer fails on any input that is not already a dgCMatrix. It called as.sparse(), which is SeuratObject::as.sparse() and was never imported, so the call had been unresolvable since the code was vendored – masked because every caller happened to pass a dgCMatrix, and because the name was listed in utils::globalVariables(), suppressing the check NOTE that would have caught it.

    • +
    • STlist() accepts a Seurat object with samples=NULL. The sample-name parsing tested an argument derived from samples before reaching the Seurat branch, so the normal way to call it raised “argument is of length zero”.

    • +
    • filter_data() can now produce a sample with exactly one surviving spot. The dense intermediate collapsed to a vector at one column, which then broke row-name handling.

    • +
    • transform_data(), SThet(), STenrich() and gene_interpolation() report invalid input as spatialGE errors naming the function and argument, instead of surfacing internal failures such as object 'tr_results' not found or attempt to select less than one element in get1index.

    • +
    • STenrich(annot=, domain=) now works. Domain-restricted gene set testing was announced in 1.2.1 but never functioned: restricting to a domain subsets the spatial metadata rows, which leaves stray row names that tibble::column_to_rownames() rejects, so the call always failed with ​`.data` must be a data frame without row names. Every domain-restricted call in 1.2.1 and 1.2.2 errored out. The unrestricted and score_type='gsva' paths were unaffected.

    • +
    • All 14 documented function examples now run. A doubled roxygen comment marker (#' #' zip_tmp = ...) commented out the assignment that the following unzip() call depended on, so every example failed with object 'zip_tmp' not found. Each example’s tryCatch reported this as “Could not run example. Are you connected to the internet?”, misattributing a code defect to the network, while R CMD check still reported checking examples ... OK.

    • +
    • STgradient() no longer leaks state between genes. pval_warn was only assigned inside a branch that requires more than one spot in the fitted range, so a gene that fell below that threshold left the previous gene’s value in place. Affects the pval_comment column only.

    • +
    • .github/ is no longer shipped inside the package tarball (added to .Rbuildignore).

    • +
    +
    +

    Minor

    +
    • User-facing validation errors are now raised through the shared error catalog, so they all carry the spatialGE exception: signature. About thirty sites used a bare stop(), which meant an argument-validation failure looked no different from an internal crash; and three sites wrote the spatialGE exception: prefix by hand instead of using the catalog, so their wording could drift from it. Their text is unchanged in substance but now lives in inst/err.csv, and raise_err() gained optional sprintf-style interpolation so messages that embed a gene name, sample size or threshold can be catalogued too. Code matching on the exact wording of these messages may need updating; matching on spatialGE exception: (the documented pattern) is unaffected.

    • +
    • An unusable cores= value now fails the same way everywhere. Validation of a core count used to be each call site’s job, and was done three different ways: some sites raised error0032, others error0036, five used an uncatalogued bare stop(), and transform_data()’s gene-metadata path did not check at all – so cores='abc' there became NA and was passed straight into the parallel lapply. Resolution now happens once in resolve_cores(), which rejects a value that is not one finite positive number with an error naming the fix. The caller’s coercion is preserved: coerce='ceiling' and coerce='none' still return a non-integral value unchanged.

    • +
    • The error raised when an argument that should be an STlist is NULL or of the wrong type now reads cannot get a slot (...) from an object of type ... rather than no applicable method for `@` applied to an object of class ..., because the shared argument-resolution helper reads slots via methods::slot(). Both messages are raw R errors and neither is informative; nothing is caught or handled differently.

    • +
    • STdiff() no longer emits dplyr’s “Detected an unexpected many-to-many relationship” warning under dplyr 1.1 and later. The gene x annotation table it builds is deliberately many-to-many – every gene of a sample combines with every annotation of that sample – but it was declared with the deprecated multiple='all', which newer dplyr checks separately from relationship= and therefore ignores. The join now declares relationship='many-to-many'. The joined rows, and every result built from them, are unchanged.

    • +
    +
    +
    + +
    +
    +
    • Added C++ code to speed up STenrich computations (Thank you, Dr. Soupir!).
    • The STenrich function can now calculate gene set enrichment scores (via GSVA) in addition to gene set average expression.
    • The STenrich function can now test for gene set “hot-spots” within an specific tissue domain (annot and domain arguments).
    • @@ -73,7 +162,7 @@
    - +
    • Functions STenrich, STgradient, and STdiff available.
    • Added C++ code for Seurat’s implementation of FindVariableFeatures
    • @@ -96,7 +185,7 @@
    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/pkgdown.yml b/docs/pkgdown.yml index 6a56f04..0ede135 100644 --- a/docs/pkgdown.yml +++ b/docs/pkgdown.yml @@ -1,9 +1,10 @@ -pandoc: 3.6.3 -pkgdown: 2.1.1 +pandoc: 3.9.0.2 +pkgdown: 2.2.1 pkgdown_sha: ~ articles: basic_functions_vignette: basic_functions_vignette.html + ondisk_stlists: ondisk_stlists.html spatial_differential_expression: spatial_differential_expression.html spatial_enrichment_gradients_smi: spatial_enrichment_gradients_smi.html troubleshooting: troubleshooting.html -last_built: 2025-04-08T02:33Z +last_built: 2026-10-15T19:55Z diff --git a/docs/reference/STclust.html b/docs/reference/STclust.html index 5aa2789..2ad4ded 100644 --- a/docs/reference/STclust.html +++ b/docs/reference/STclust.html @@ -1,5 +1,5 @@ -STclust: Detect clusters of spots/cells — STclust • spatialGESTclust: Detect clusters of spots/cells — STclust • spatialGE + @@ -58,7 +67,7 @@
    @@ -76,8 +85,9 @@

    STclust: Detect clusters of spots/cells

    linkage = "ward.D2", ks = "dtc", topgenes = 2000, - deepSplit = F, - cores = NULL + deepSplit = FALSE, + cores = NULL, + verbose = TRUE )
    @@ -116,7 +126,7 @@

    Arguments

    topgenes

    the number of genes with highest spot-to-spot expression variation. The -variance is calculated via Seurat::FindVariableFeatures.

    +variance is calculated via Seurat::FindVariableFeatures.

    deepSplit
    @@ -127,6 +137,10 @@

    Arguments

    cores

    an integer indicating the number of cores to use in parallelization (Unix only)

    + +
    verbose
    +

    either logical or an integer (0, 1, or 2) to increase verbosity

    +

    Value

    @@ -136,7 +150,7 @@

    Value

    Details

    The function takes an STlist and calculates euclidean distances between cells or spots based on the x,y spatial locations, and the expression of the top variable genes -(Seurat::FindVariableFeatures). The resulting distances are weighted by +(Seurat::FindVariableFeatures). The resulting distances are weighted by applying 1-ws to the gene expression distances and ws to the spatial distances. Hierarchical clustering is performed on the sum of the weighted distance matrices. The STclust method allows for identification of tissue niches/domains that are @@ -145,41 +159,47 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                         full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,3)], spotcoords=coord_files[c(1,3)], samples=clin_file)
    -#> Warning: Sample ST_mel2_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  melanoma <- STclust(melanoma, ws=c(0, 0.025))
    +  STplot(melanoma, ws=0.025, samples='ST_mel1_rep2', ptsize=1)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma, method='log')
    -melanoma <- STclust(melanoma, ws=c(0, 0.025))
     #> STclust started...
     #> Updating STlist with results...
    -#> STclust completed in 0.02 min.
    -STplot(melanoma, ws=0.025, samples='ST_mel1_rep2', ptsize=1)
    +#> STclust completed in 0.01 min.
     #> $ST_mel1_rep2_stclust_spw0.025_dsplFalse
     
     #> 
    +# }
     
     
    @@ -195,7 +215,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STdiff.html b/docs/reference/STdiff.html index 4816e65..fa60918 100644 --- a/docs/reference/STdiff.html +++ b/docs/reference/STdiff.html @@ -1,5 +1,5 @@ -STdiff: Differential gene expression analysis for spatial transcriptomics data — STdiff • spatialGESTdiff: Differential gene expression analysis for spatial transcriptomics data — STdiff • spatialGE + @@ -58,7 +67,7 @@
    @@ -81,7 +90,7 @@

    STdiff: Differential gene expression analysis for spatial transcriptomics da test_type = "mm", sp_topgenes = 0.2, clusters = NULL, - pairwise = F, + pairwise = FALSE, verbose = 1L, cores = NULL )

    @@ -156,9 +165,7 @@

    Arguments

    verbose
    -

    output progress indicators. If verbose=0, no text is shown in console. -Other values are 1 and 2 indicating increasing level of verbosity. Default is -verbose=1

    +

    either logical or an integer (0, 1, or 2) to increase verbosity

    cores
    @@ -199,7 +206,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STdiff_volcano.html b/docs/reference/STdiff_volcano.html index 958f4d7..aa7092d 100644 --- a/docs/reference/STdiff_volcano.html +++ b/docs/reference/STdiff_volcano.html @@ -1,5 +1,5 @@ -STdiff_volcano: Generates volcano plots from STdiff results — STdiff_volcano • spatialGESTdiff_volcano: Generates volcano plots from STdiff results — STdiff_volcano • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -122,7 +131,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STenrich.html b/docs/reference/STenrich.html index c6b918f..69d31a0 100644 --- a/docs/reference/STenrich.html +++ b/docs/reference/STenrich.html @@ -1,5 +1,5 @@ -STenrich — STenrich • spatialGESTenrich — STenrich • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -79,7 +88,8 @@

    STenrich

    min_genes = 5, pval_adj_method = "BH", seed = 12345, - cores = NULL + cores = NULL, + verbose = TRUE )
    @@ -148,6 +158,10 @@

    Arguments

    the number of cores used during parallelization. If NULL (default), the number of cores is defined automatically

    + +
    verbose
    +

    either logical or an integer (0, 1, or 2) to increase verbosity

    +

    Value

    @@ -177,7 +191,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STgradient.html b/docs/reference/STgradient.html index 91ac824..286bbbf 100644 --- a/docs/reference/STgradient.html +++ b/docs/reference/STgradient.html @@ -1,5 +1,5 @@ -STgradient: Tests of gene expression spatial gradients — STgradient • spatialGESTgradient: Tests of gene expression spatial gradients — STgradient • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -73,14 +82,15 @@

    STgradient: Tests of gene expression spatial gradients

    annot = NULL, ref = NULL, exclude = NULL, - out_rm = F, + out_rm = FALSE, limit = NULL, distsumm = "min", min_nb = 3, - robust = T, + robust = TRUE, nb_dist_thr = NULL, - log_dist = F, - cores = NULL + log_dist = FALSE, + cores = NULL, + verbose = TRUE )
    @@ -161,6 +171,10 @@

    Arguments

    the number of cores used during parallelization. If NULL (default), the number of cores is defined automatically

    + +
    verbose
    +

    logical, whether to print text to console

    +

    Value

    @@ -188,7 +202,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/SThet.html b/docs/reference/SThet.html index 85e7b9a..4df131b 100644 --- a/docs/reference/SThet.html +++ b/docs/reference/SThet.html @@ -1,5 +1,5 @@ -SThet: Computes global spatial autocorrelation statistics on gene expression — SThet • spatialGESThet: Computes global spatial autocorrelation statistics on gene expression — SThet • spatialGE + @@ -58,7 +67,7 @@
    @@ -74,8 +83,9 @@

    SThet: Computes global spatial autocorrelation statistics on gene expression samples = NULL, method = "moran", k = NULL, - overwrite = T, - cores = NULL + overwrite = TRUE, + cores = NULL, + verbose = TRUE )

    @@ -115,7 +125,11 @@

    Arguments

    cores

    integer indicating the number of cores to use during parallelization. If NULL, the function uses half of the available cores at a maximum. The parallelization -uses parallel::mclapply and works only in Unix systems.

    +uses parallel::mclapply and works only in Unix systems

    + + +
    verbose
    +

    logical, whether to print text to console

    @@ -133,49 +147,58 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  melanoma <- SThet(melanoma, genes=c('MLANA', 'TP53'), method='moran')
    +  get_gene_meta(melanoma, sthet_only=TRUE)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma, method='log')
    -melanoma <- SThet(melanoma, genes=c('MLANA', 'TP53'), method='moran')
     #> SThet started.
     #> 	Calculating spatial weights...
    -#> SThet completed in 0.02 min.
    -get_gene_meta(melanoma, sthet_only=TRUE)
    -#> # A tibble: 4 × 15
    +#> SThet completed in 0 min.
    +#> # A tibble: 8 × 16
     #>   sample     patient slice gender BRAF_status NRAS_status CDKN2A_status survival
     #>   <chr>        <dbl> <chr> <chr>  <chr>       <chr>       <chr>         <chr>   
     #> 1 ST_mel1_r…       1 B     Male   mut         wt          hd            10_plus…
     #> 2 ST_mel1_r…       1 B     Male   mut         wt          hd            10_plus…
     #> 3 ST_mel2_r…       2 A     Female wt          wt          hd            401_days
     #> 4 ST_mel2_r…       2 A     Female wt          wt          hd            401_days
    -#> # ℹ 7 more variables: survival_months <dbl>, RIN <dbl>, gene <chr>,
    -#> #   gene_mean <dbl>, gene_stdevs <dbl>, moran_i <dbl>, geary_c <lgl>
    +#> 5 ST_mel3_r…       3 A     Male   mut         wt          wt            208_days
    +#> 6 ST_mel3_r…       3 A     Male   mut         wt          wt            208_days
    +#> 7 ST_mel4_r…       4 B     Male   mut         wt          wt            305_days
    +#> 8 ST_mel4_r…       4 B     Male   mut         wt          wt            305_days
    +#> # ℹ 8 more variables: survival_months <dbl>, RIN <dbl>, gene <chr>,
    +#> #   gene_mean <dbl>, gene_stdevs <dbl>, vst.variance.standardized <dbl>,
    +#> #   moran_i <dbl>, geary_c <lgl>
    +# }
     
     
    @@ -191,7 +214,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STlist-class.html b/docs/reference/STlist-class.html index dcf6a69..0ba83f5 100644 --- a/docs/reference/STlist-class.html +++ b/docs/reference/STlist-class.html @@ -1,5 +1,5 @@ -Definition of an STlist object class. — STlist-class • spatialGEDefinition of an STlist object class. — STlist-class • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -112,7 +121,7 @@

    Slots

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STlist.html b/docs/reference/STlist.html index 5f7ab39..ad8ad63 100644 --- a/docs/reference/STlist.html +++ b/docs/reference/STlist.html @@ -1,5 +1,5 @@ -STlist: Creation of STlist objects for spatial transcriptomics analysis — STlist • spatialGESTlist: Creation of STlist objects for spatial transcriptomics analysis — STlist • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -66,7 +75,13 @@

    STlist: Creation of STlist objects for spatial transcriptomics analysis

    -
    STlist(rnacounts = NULL, spotcoords = NULL, samples = NULL, cores = NULL)
    +
    STlist(
    +  rnacounts = NULL,
    +  spotcoords = NULL,
    +  samples = NULL,
    +  cores = NULL,
    +  verbose = TRUE
    +)
    @@ -98,7 +113,7 @@

    Arguments

    the "fov" and "cell_ID" columns. The STlist function will separate data from each FOV, since analysis in spatialGE is conducted at the FOV level. Requires samples and spotcoords.

    -
  • Seurat object (V4). A Seurat V4 object produced via Seurat::Load10X_Spatial. +

  • Seurat object (V4). A Seurat V4 object produced via Seurat::Load10X_Spatial. Multiple samples are allowed as long as they are stored as "slices" in the Seurat object. Does not require samples as sample names are taken from names(seurat_obj@images)

  • A named list of data frames with raw gene counts (one data frame per spatial @@ -138,7 +153,11 @@

    Arguments

    cores

    integer indicating the number of cores to use during parallelization. If NULL, the function uses half of the available cores at a maximum. The parallelization -uses parallel::mclapply and works only in Unix systems.

    +uses parallel::mclapply and works only in Unix systems

    + + +
    verbose
    +

    logical, whether to print text to console

  • @@ -165,7 +184,7 @@

    Details

  • CosMx-SMI outputs. Two files are required to process SMI outputs: The exprMat and metadata files. Both files must contain the "fov" and "cell_ID" columns. In addition, the metadata files must contain the "CenterX_local_px" and "CenterY_local_px" columns.

  • -
  • Seurat object (V4). A Seurat V4 object produced via Seurat::Load10X_Spatial.

  • +
  • Seurat object (V4). A Seurat V4 object produced via Seurat::Load10X_Spatial.

  • Optionally, the user can input a path to a file containing a table of sample-level metadata (e.g., clinical outcomes, tissue type, age). This sample metadata file should contain sample IDs in the first column partially matching the file names of @@ -178,42 +197,48 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,3)],
    -                   spotcoords=coord_files[c(1,3)],
    -                   samples=clin_file) # Only first three samples
    -#> Warning: Sample ST_mel2_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma
     #> Spatial Transcriptomics List (STlist).
    -#> 2 spatial array(s):
    +#> 4 spatial array(s):
     #> 	ST_mel1_rep2 (293 ROIs|spots|cells x 16148 genes)
    +#> 	ST_mel2_rep1 (383 ROIs|spots|cells x 16831 genes)
     #> 	ST_mel3_rep1 (256 ROIs|spots|cells x 15653 genes)
    +#> 	ST_mel4_rep2 (248 ROIs|spots|cells x 15991 genes)
     #> 
     #> 9 variables in sample-level data:
     #> 	 patient, slice, gender, BRAF_status, NRAS_status, CDKN2A_status, survival, survival_months, RIN 
    +# }
     
     
    @@ -229,7 +254,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STlist_to_disk.html b/docs/reference/STlist_to_disk.html new file mode 100644 index 0000000..7332392 --- /dev/null +++ b/docs/reference/STlist_to_disk.html @@ -0,0 +1,149 @@ + +STlist_to_disk: Move an STlist's count matrices to on-disk parquet — STlist_to_disk • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Converts an in-memory STlist into one backed by parquet files, so +data larger than memory can be held and read in slices.

    +
    + +
    +
    STlist_to_disk(x = NULL, root = NULL, overwrite = FALSE)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STlist

    + + +
    root
    +

    directory to write the store into. Created if absent

    + + +
    overwrite
    +

    logical, whether to overwrite an existing store at root

    + +
    +
    +

    Value

    +

    an STlist whose count slots are on-disk backed

    +
    +
    +

    Details

    +

    Opt-in and reversible. @counts and @tr_counts elements are replaced by +manifests describing per-sample parquet files; every other slot is untouched. +All package functions continue to work, because slot reads go through internal +accessors that materialize on demand – so this trades memory for I/O rather +than changing results.

    +

    Matrices are stored in COO (long) form, one file per sample per slot, sorted by +gene then cell. STlist_to_memory() reverses the conversion.

    +

    Note what this does and does not buy. It buys capacity: an STlist larger than +RAM can be held and read in gene-subset slices. It does not currently speed +anything up – aggregate operations still materialize and compute in memory, so +a backed STlist is slower on those paths than an in-memory one.

    +

    The store is a directory of files, not part of the R object. An STlist saved +with saveRDS() records paths, so moving or deleting root breaks it; +validate_store() reports that rather than failing obscurely later. A store +written under tempdir() is flagged as non-portable for the same reason.

    +
    + + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/STlist_to_memory.html b/docs/reference/STlist_to_memory.html new file mode 100644 index 0000000..eaf9aa4 --- /dev/null +++ b/docs/reference/STlist_to_memory.html @@ -0,0 +1,127 @@ + +STlist_to_memory: Bring an on-disk STlist back into memory — STlist_to_memory • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Reverses STlist_to_disk(), materializing every backed matrix.

    +
    + +
    +
    STlist_to_memory(x = NULL)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STlist, backed or not

    + +
    +
    +

    Value

    +

    an STlist with in-memory count matrices

    +
    +
    +

    Details

    +

    The round trip is exact: COO stores the values themselves and the manifest +carries dimensions and dimnames, so nothing is inferred on the way back. An +STlist that was never backed is returned unchanged.

    +
    +
    +

    See also

    + +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/STplot.html b/docs/reference/STplot.html index 06d466d..8fcb8cd 100644 --- a/docs/reference/STplot.html +++ b/docs/reference/STplot.html @@ -1,5 +1,5 @@ -STplot: Plots of gene expression, cluster memberships, and metadata in spatial context — STplot • spatialGESTplot: Plots of gene expression, cluster memberships, and metadata in spatial context — STplot • spatialGE + @@ -59,7 +68,7 @@
    @@ -155,39 +164,43 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  STplot(melanoma, gene='MLANA', samples='ST_mel1_rep2', ptsize=1)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma)
    -STplot(melanoma, gene='MLANA', samples='ST_mel1_rep2', ptsize=1)
     #> $MLANA_ST_mel1_rep2
     
     #> 
    +# }
     
     
    @@ -203,7 +216,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/STplot_interpolation.html b/docs/reference/STplot_interpolation.html index f886df0..6437a7c 100644 --- a/docs/reference/STplot_interpolation.html +++ b/docs/reference/STplot_interpolation.html @@ -1,5 +1,5 @@ -STplot_interpolation: Visualize gene expression surfaces — STplot_interpolation • spatialGESTplot_interpolation: Visualize gene expression surfaces — STplot_interpolation • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -80,16 +89,21 @@

    Arguments

    x
    -

    an STlist containing results from gene_krige for the genes selected.

    +

    an STlist containing results from gene_krige for the genes selected. +Kriging must have been run first with gene_interpolation().

    genes
    -

    a vector of gene names (one or several) to plot. If 'top', the 10 -genes with highest standard deviation from each spatial sample are plotted.

    +

    a vector of gene names (one or several) to plot. If 'top' (the +default when NULL), the top_n genes with the highest standardized variance +(VST) from each spatial sample are plotted. Only genes that already have +kriging results can be plotted; a warning names any requested gene that was not +interpolated.

    top_n
    -

    an integer indicating how many top genes to perform kriging. Default is 10.

    +

    an integer indicating how many of the most variable genes to plot +when genes='top'. Default is 10.

    samples
    @@ -113,44 +127,48 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  melanoma <- gene_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
    +  kp = STplot_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
    +  ggpubr::ggarrange(plotlist=kp)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma)
    -melanoma <- gene_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
     #> Gene interpolation started.
     #> Warning: No convergence after 200 iterations: try different initial values?
     #> [using ordinary kriging]
     #> [using ordinary kriging]
    -#> Gene interpolation completed in 0.01 min.
    -kp = STplot_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
    -ggpubr::ggarrange(plotlist=kp)
    +#> Gene interpolation completed in 0 min.
     
    +# }
     
     
    @@ -166,7 +184,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/as_Seurat.html b/docs/reference/as_Seurat.html new file mode 100644 index 0000000..2752cbb --- /dev/null +++ b/docs/reference/as_Seurat.html @@ -0,0 +1,145 @@ + +as_Seurat: Convert an STlist to a Seurat object — as_Seurat • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Converts an STlist into a Seurat (v5) object, one image/slice per +sample, so spatialGE results can be taken into Seurat-based workflows.

    +
    + +
    +
    as_Seurat(x = NULL, assay = "Spatial", samples = NULL)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STlist

    + + +
    assay
    +

    the assay name to create. Default 'Spatial'

    + + +
    samples
    +

    the samples to include. If NULL (default), all samples

    + +
    +
    +

    Value

    +

    a Seurat object

    +
    +
    +

    Details

    +

    Each sample in the STlist becomes one FOV in the returned object, named after +the sample. Raw counts go to the counts layer and, when transform_data() +has been run, transformed counts go to the data layer. Spot-level columns +from @spatial_meta – including STclust cluster assignments – are carried +into @meta.data, prefixed by sample where a merge would otherwise collide.

    +

    Cell names are prefixed with the sample name (<sample>_<libname>) because +spot barcodes are only unique within a sample in the general case, and a merged +Seurat object requires globally unique cell names.

    +

    Genes not shared by every requested sample are dropped, with a message +reporting how many, since Seurat holds a single matrix across all cells.

    +
    +
    +

    See also

    +

    STlist() accepts a Seurat object as rnacounts, so the conversion +round-trips.

    +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/compare_SThet.html b/docs/reference/compare_SThet.html index f29332e..89fc694 100644 --- a/docs/reference/compare_SThet.html +++ b/docs/reference/compare_SThet.html @@ -1,5 +1,5 @@ -compare_SThet: Compares spatial autocorrelation statistics across samples — compare_SThet • spatialGEcompare_SThet: Compares spatial autocorrelation statistics across samples — compare_SThet • spatialGE + @@ -58,7 +67,7 @@
    @@ -73,7 +82,7 @@

    compare_SThet: Compares spatial autocorrelation statistics across samples samplemeta = NULL, genes = NULL, color_by = NULL, - categorical = T, + categorical = TRUE, color_pal = "muted", ptsize = 1 )

    @@ -140,7 +149,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/dim-STlist-method.html b/docs/reference/dim-STlist-method.html index ab8fee2..db6b1ff 100644 --- a/docs/reference/dim-STlist-method.html +++ b/docs/reference/dim-STlist-method.html @@ -1,5 +1,6 @@ -dim: Prints the dimensions of count arrays within an STList object. — dim,STlist-method • spatialGEdim: Dimensions of the count array in an STList object. — dim,STlist-method • spatialGE @@ -17,7 +18,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +35,9 @@ + @@ -56,13 +66,14 @@
    -

    Returns the number of genes and spots for each array within an STList object

    +

    Returns the number of genes (rows) and spots/cells (columns) +observed in an STList object.

    @@ -75,13 +86,29 @@

    Arguments

    x
    -

    an STList object to show summary from.

    +

    an STList object.

    +
    +

    Value

    +

    An integer vector c(n_genes, n_spots) when the object holds exactly +one sample; NULL for a multi-sample object, where there is no single gene x +spot shape to report.

    +

    Details

    -

    This function takes an STList and prints the number of genes (rows) and spots (columns) of -each spatial array within that object.

    +

    An STlist is a container for one or more spatial arrays, and different +samples may have different numbers of genes. dim() therefore has a single +well-defined answer only when the object holds exactly one sample; in that +case it returns c(n_genes, n_spots) as an integer vector, like any other +matrix-like object.

    +

    For a multi-sample STlist dim() returns NULL (the base R convention for +"no dimensions"), because there is no single gene x spot shape to report. Use +summarize_STlist() for a per-sample table of dimensions, or tissue_names() +to iterate samples.

    +

    Previously this method returned a named list of per-sample dimensions, which +violated the base dim() contract: it made nrow()/ncol() meaningless, and +R CMD check reported it as "dim() returns class 'list'".

    @@ -96,7 +123,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/distribution_plots.html b/docs/reference/distribution_plots.html index 9f3d9bc..9ff7ab5 100644 --- a/docs/reference/distribution_plots.html +++ b/docs/reference/distribution_plots.html @@ -1,5 +1,5 @@ -per_unit_counts: Generates distribution plots of spot/cell meta data or gene expression — distribution_plots • spatialGEper_unit_counts: Generates distribution plots of spot/cell meta data or gene expression — distribution_plots • spatialGE + @@ -58,7 +67,7 @@
    @@ -127,6 +136,10 @@

    Arguments

    the transparency of points (violin/box plot) or curves (density plots)

    +
    +

    Value

    +

    a list containing ggplot2 objects

    +

    Details

    The function allows to visualize the distribution of spot/cell total @@ -147,7 +160,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/vignettes/img/logo.png b/docs/reference/figures/logo.png similarity index 100% rename from vignettes/img/logo.png rename to docs/reference/figures/logo.png diff --git a/docs/spatialGE_workflow_v3.png b/docs/reference/figures/spatialGE_workflow_v3.png similarity index 100% rename from docs/spatialGE_workflow_v3.png rename to docs/reference/figures/spatialGE_workflow_v3.png diff --git a/docs/reference/filter_data.html b/docs/reference/filter_data.html index 7685f5d..28e93aa 100644 --- a/docs/reference/filter_data.html +++ b/docs/reference/filter_data.html @@ -1,5 +1,5 @@ -filter_data: Filters cells/spots, genes, or samples — filter_data • spatialGEfilter_data: Filters cells/spots, genes, or samples — filter_data • spatialGE + @@ -58,7 +67,7 @@
    @@ -87,7 +96,8 @@

    filter_data: Filters cells/spots, genes, or samples

    rm_spots = NULL, rm_genes = NULL, rm_genes_expr = NULL, - spot_pct_expr = "^MT-" + spot_pct_expr = "^MT-", + verbose = TRUE )
    @@ -170,6 +180,11 @@

    Arguments

    spot_pct_expr

    a expression to use with spot_minpct and spot_maxpct. By default '^MT-'.

    + +
    verbose
    +

    logical, if TRUE reports how many samples, spots/cells and +genes were removed (and says explicitly when nothing was filtered).

    +

    Value

    @@ -188,39 +203,51 @@

    Details

  • Genes (rm_genes)

  • Genes matching rm_genes_expr

  • Min and max counts

  • -
    +

    Note that every count threshold defaults to 0 (and the *_max* thresholds +to NULL, meaning no upper bound). A call that supplies none of them, and no +rm_* argument either, therefore returns the STlist unchanged. Set at least +one threshold to actually filter; with verbose=TRUE the function says so +rather than returning silently.

    +

    Filtering is sequential and single-threaded, so unlike the analysis functions +there is no cores argument.

    +

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                       full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- filter_data(melanoma, spot_minreads=2000)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- filter_data(melanoma, spot_minreads=2000)
    +#> filter_data: removed 0 sample(s), 183 spot(s)/cell(s) and 0 gene(s).
    +# }
     
     
    @@ -236,7 +263,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/gene_interpolation.html b/docs/reference/gene_interpolation.html index ff28958..70b3856 100644 --- a/docs/reference/gene_interpolation.html +++ b/docs/reference/gene_interpolation.html @@ -1,5 +1,5 @@ -gene_interpolation: Spatial interpolation of gene expression — gene_interpolation • spatialGEgene_interpolation: Spatial interpolation of gene expression — gene_interpolation • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -71,7 +80,8 @@

    gene_interpolation: Spatial interpolation of gene expression

    genes = "top", top_n = 10, samples = NULL, - cores = NULL + cores = NULL, + verbose = TRUE )
    @@ -104,6 +114,10 @@

    Arguments

    If NULL, the function uses half of the available cores at a maximum. The parallelization uses parallel::mclapply and works only in Unix systems.

    + +
    verbose
    +

    either logical or an integer (0, 1, or 2) to increase verbosity.

    +

    Value

    @@ -120,46 +134,54 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                         full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  melanoma <- gene_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
    +  kp = STplot_interpolation(melanoma, genes=c('MLANA', 'COL1A1'))
    +  ggpubr::ggarrange(plotlist=kp)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma)
    -melanoma <- gene_interpolation(melanoma, genes=c('MLANA', 'COL1A1'), samples='ST_mel1_rep2')
     #> Gene interpolation started.
     #> Warning: No convergence after 200 iterations: try different initial values?
     #> [using ordinary kriging]
     #> [using ordinary kriging]
     #> Gene interpolation completed in 0 min.
    -kp = STplot_interpolation(melanoma, genes=c('MLANA', 'COL1A1'))
    -#> Kriging for subject MLANA in sample ST_mel2_rep1 is not present in STlist
    -#> Kriging for subject COL1A1 in sample ST_mel2_rep1 is not present in STlist
    -ggpubr::ggarrange(plotlist=kp)
    +#> Kriging for subject MLANA in sample ST_mel2_rep1 is not present in STlist
    +#> Kriging for subject COL1A1 in sample ST_mel2_rep1 is not present in STlist
    +#> Kriging for subject MLANA in sample ST_mel3_rep1 is not present in STlist
    +#> Kriging for subject COL1A1 in sample ST_mel3_rep1 is not present in STlist
    +#> Kriging for subject MLANA in sample ST_mel4_rep2 is not present in STlist
    +#> Kriging for subject COL1A1 in sample ST_mel4_rep2 is not present in STlist
     
    +# }
     
     
    @@ -175,7 +197,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/get_gene_meta.html b/docs/reference/get_gene_meta.html index d493578..663a8cf 100644 --- a/docs/reference/get_gene_meta.html +++ b/docs/reference/get_gene_meta.html @@ -1,5 +1,5 @@ -get_gene_meta: Extract gene-level metadata and statistics — get_gene_meta • spatialGEget_gene_meta: Extract gene-level metadata and statistics — get_gene_meta • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -66,7 +75,7 @@

    get_gene_meta: Extract gene-level metadata and statistics

    -
    get_gene_meta(x = NULL, sthet_only = F)
    +
    get_gene_meta(x = NULL, sthet_only = FALSE)
    @@ -95,49 +104,58 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +  melanoma <- SThet(melanoma, genes=c('MLANA', 'TP53'), method='moran')
    +  get_gene_meta(melanoma, sthet_only=TRUE)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma, method='log')
    -melanoma <- SThet(melanoma, genes=c('MLANA', 'TP53'), method='moran')
     #> SThet started.
     #> 	Calculating spatial weights...
    -#> SThet completed in 0.01 min.
    -get_gene_meta(melanoma, sthet_only=TRUE)
    -#> # A tibble: 4 × 15
    +#> SThet completed in 0 min.
    +#> # A tibble: 8 × 16
     #>   sample     patient slice gender BRAF_status NRAS_status CDKN2A_status survival
     #>   <chr>        <dbl> <chr> <chr>  <chr>       <chr>       <chr>         <chr>   
     #> 1 ST_mel1_r…       1 B     Male   mut         wt          hd            10_plus…
     #> 2 ST_mel1_r…       1 B     Male   mut         wt          hd            10_plus…
     #> 3 ST_mel2_r…       2 A     Female wt          wt          hd            401_days
     #> 4 ST_mel2_r…       2 A     Female wt          wt          hd            401_days
    -#> # ℹ 7 more variables: survival_months <dbl>, RIN <dbl>, gene <chr>,
    -#> #   gene_mean <dbl>, gene_stdevs <dbl>, moran_i <dbl>, geary_c <lgl>
    +#> 5 ST_mel3_r…       3 A     Male   mut         wt          wt            208_days
    +#> 6 ST_mel3_r…       3 A     Male   mut         wt          wt            208_days
    +#> 7 ST_mel4_r…       4 B     Male   mut         wt          wt            305_days
    +#> 8 ST_mel4_r…       4 B     Male   mut         wt          wt            305_days
    +#> # ℹ 8 more variables: survival_months <dbl>, RIN <dbl>, gene <chr>,
    +#> #   gene_mean <dbl>, gene_stdevs <dbl>, vst.variance.standardized <dbl>,
    +#> #   moran_i <dbl>, geary_c <lgl>
    +# }
     
     
    @@ -153,7 +171,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/index.html b/docs/reference/index.html index b3f1a1f..9388df7 100644 --- a/docs/reference/index.html +++ b/docs/reference/index.html @@ -1,5 +1,5 @@ -Package index • spatialGEPackage index • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -95,6 +104,14 @@

    All functions STlist()

    STlist: Creation of STlist objects for spatial transcriptomics analysis

    + +

    STlist_to_disk()

    + +

    STlist_to_disk: Move an STlist's count matrices to on-disk parquet

    + +

    STlist_to_memory()

    + +

    STlist_to_memory: Bring an on-disk STlist back into memory

    STplot()

    @@ -103,6 +120,10 @@

    All functions STplot_interpolation()

    STplot_interpolation: Visualize gene expression surfaces

    + +

    as_Seurat()

    + +

    as_Seurat: Convert an STlist to a Seurat object

    compare_SThet()

    @@ -110,7 +131,7 @@

    All functions

    dim(<STlist>)

    -

    dim: Prints the dimensions of count arrays within an STList object.

    +

    dim: Dimensions of the count array in an STList object.

    distribution_plots()

    @@ -127,6 +148,14 @@

    All functions get_gene_meta()

    get_gene_meta: Extract gene-level metadata and statistics

    + +

    is_backed()

    + +

    is_backed: Is an STlist's expression data stored on disk?

    + +

    length(<STlist>)

    + +

    length: Number of spatial arrays in an STList object.

    load_images()

    @@ -159,6 +188,18 @@

    All functions spatial_metadata()

    spatial_metadata: Prints the names of the available spot/cell annotations

    + +

    `[`(<STlist>,<ANY>,<ANY>,<ANY>)

    + +

    [: Reject two-dimensional subsetting of an STList object.

    + +

    `[`(<STlist>,<ANY>,<missing>,<ANY>)

    + +

    [: Subset an STList object by sample.

    + +

    `[[`(<STlist>,<ANY>,<ANY>)

    + +

    [[: Not supported for STList objects.

    summarize_STlist()

    @@ -175,6 +216,10 @@

    All functions transform_data()

    transform_data: Transformation of spatial transcriptomics data

    + +

    validate_store()

    + +

    validate_store: Check an on-disk STlist against its manifests

    diff --git a/docs/reference/is_backed.html b/docs/reference/is_backed.html new file mode 100644 index 0000000..afe4b78 --- /dev/null +++ b/docs/reference/is_backed.html @@ -0,0 +1,123 @@ + +is_backed: Is an STlist's expression data stored on disk? — is_backed • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Reports whether an STlist's count matrices are held in on-disk +parquet files rather than in memory.

    +
    + +
    +
    is_backed(x = NULL)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STlist

    + +
    +
    +

    Value

    +

    logical

    +
    +
    +

    See also

    + +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/length-STlist-method.html b/docs/reference/length-STlist-method.html new file mode 100644 index 0000000..b81af4b --- /dev/null +++ b/docs/reference/length-STlist-method.html @@ -0,0 +1,127 @@ + +length: Number of spatial arrays in an STList object. — length,STlist-method • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Returns the number of samples (spatial arrays) held by an +STList object.

    +
    + +
    +
    # S4 method for class 'STlist'
    +length(x)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STList object.

    + +
    +
    +

    Value

    +

    A single integer: the number of spatial arrays in x.

    +
    +
    +

    Details

    +

    An STlist is a container for one or more spatial arrays. length() reports +how many, which makes the object usable with the usual idioms – +seq_along(x), for(i in seq_len(length(x))) – instead of having to know +that the count lives in length(x@counts).

    +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/load_images.html b/docs/reference/load_images.html index 49e332b..3dd3fea 100644 --- a/docs/reference/load_images.html +++ b/docs/reference/load_images.html @@ -1,5 +1,5 @@ -load_images: Place tissue images within STlist — load_images • spatialGEload_images: Place tissue images within STlist — load_images • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -78,7 +87,13 @@

    Arguments

    images
    -

    a string indicating a folder to load images from

    +

    image file paths or one or more folders to load images from. +A named character vector (c(sample_name = "path/to/image.png")) maps +samples to files explicitly and bypasses name matching. An unnamed vector +is matched against the sample names in x; any element that is an existing +directory is expanded to the image files it contains. Image filenames are +matched to sample names by looking for <sample_name>. in the filename and, +failing that, a normalized prefix match (case- and separator-insensitive).

    @@ -104,7 +119,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/plot_counts-1.png b/docs/reference/plot_counts-1.png index bd0584f..c7482aa 100644 Binary files a/docs/reference/plot_counts-1.png and b/docs/reference/plot_counts-1.png differ diff --git a/docs/reference/plot_counts.html b/docs/reference/plot_counts.html index d13b739..d05b549 100644 --- a/docs/reference/plot_counts.html +++ b/docs/reference/plot_counts.html @@ -1,5 +1,5 @@ -plot_counts: Generates plots for the distribution of counts — plot_counts • spatialGEplot_counts: Generates plots for the distribution of counts — plot_counts • spatialGE + @@ -58,7 +67,7 @@
    @@ -136,37 +145,41 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  cp <- plot_counts(melanoma, data_type='raw', plot_type=c('violin', 'box'))
    +  ggpubr::ggarrange(plotlist=cp)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -cp <- plot_counts(melanoma, data_type='raw', plot_type=c('violin', 'box'))
    -ggpubr::ggarrange(plotlist=cp)
     
    +# }
     
     
    @@ -182,7 +195,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/plot_image.html b/docs/reference/plot_image.html index ad99097..5a0fd53 100644 --- a/docs/reference/plot_image.html +++ b/docs/reference/plot_image.html @@ -1,5 +1,5 @@ -plot_image: Generate a ggplot object of the tissue image — plot_image • spatialGEplot_image: Generate a ggplot object of the tissue image — plot_image • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -106,7 +115,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/pseudobulk_dim_plot-1.png b/docs/reference/pseudobulk_dim_plot-1.png index 2e8b2b6..b1bcacb 100644 Binary files a/docs/reference/pseudobulk_dim_plot-1.png and b/docs/reference/pseudobulk_dim_plot-1.png differ diff --git a/docs/reference/pseudobulk_dim_plot.html b/docs/reference/pseudobulk_dim_plot.html index 1e51baf..d126c9e 100644 --- a/docs/reference/pseudobulk_dim_plot.html +++ b/docs/reference/pseudobulk_dim_plot.html @@ -1,5 +1,5 @@ -pseudobulk_dim_plot: Plot PCA of pseudobulk samples — pseudobulk_dim_plot • spatialGEpseudobulk_dim_plot: Plot PCA of pseudobulk samples — pseudobulk_dim_plot • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -127,35 +136,42 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files,
    -                   spotcoords=coord_files,
    -                   samples=clin_file, cores=2)
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- pseudobulk_samples(melanoma)
    +  pseudobulk_dim_plot(melanoma, plot_meta='patient')
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- pseudobulk_samples(melanoma)
    -pseudobulk_dim_plot(melanoma, plot_meta='patient')
    +#> Warning: Dropped 6245 gene(s) with zero variance across samples before the pseudobulk PCA.
     
    +# }
     
     
    @@ -171,7 +187,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/pseudobulk_heatmap-1.png b/docs/reference/pseudobulk_heatmap-1.png index 63fd837..aab9c30 100644 Binary files a/docs/reference/pseudobulk_heatmap-1.png and b/docs/reference/pseudobulk_heatmap-1.png differ diff --git a/docs/reference/pseudobulk_heatmap.html b/docs/reference/pseudobulk_heatmap.html index 02b2925..0dfaeb8 100644 --- a/docs/reference/pseudobulk_heatmap.html +++ b/docs/reference/pseudobulk_heatmap.html @@ -1,5 +1,5 @@ -pseudobulk_heatmap: Heatmap of pseudobulk samples — pseudobulk_heatmap • spatialGEpseudobulk_heatmap: Heatmap of pseudobulk samples — pseudobulk_heatmap • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -113,35 +122,42 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files,
    -                   spotcoords=coord_files,
    -                   samples=clin_file, cores=2)
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- pseudobulk_samples(melanoma)
    +  hm <- pseudobulk_heatmap(melanoma, plot_meta='BRAF_status', hm_display_genes=30)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- pseudobulk_samples(melanoma)
    -hm <- pseudobulk_heatmap(melanoma, plot_meta='BRAF_status', hm_display_genes=30)
    +#> Warning: Dropped 6245 gene(s) with zero variance across samples before the pseudobulk PCA.
     
    +# }
     
     
    @@ -157,7 +173,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/pseudobulk_samples-1.png b/docs/reference/pseudobulk_samples-1.png index fd7f663..f48c7ba 100644 Binary files a/docs/reference/pseudobulk_samples-1.png and b/docs/reference/pseudobulk_samples-1.png differ diff --git a/docs/reference/pseudobulk_samples.html b/docs/reference/pseudobulk_samples.html index 78229a0..ceaf4c1 100644 --- a/docs/reference/pseudobulk_samples.html +++ b/docs/reference/pseudobulk_samples.html @@ -1,5 +1,5 @@ -pseudobulk_samples: Aggregates counts into "pseudo bulk" samples — pseudobulk_samples • spatialGEpseudobulk_samples: Aggregates counts into "pseudo bulk" samples — pseudobulk_samples • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -66,7 +75,7 @@

    pseudobulk_samples: Aggregates counts into "pseudo bulk" samples

    -
    pseudobulk_samples(x = NULL, max_var_genes = 5000, calc_umap = F)
    +
    pseudobulk_samples(x = NULL, max_var_genes = 5000, calc_umap = FALSE)
    @@ -100,35 +109,42 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files,
    -                   spotcoords=coord_files,
    -                   samples=clin_file, cores=2)
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- pseudobulk_samples(melanoma)
    +  pseudobulk_dim_plot(melanoma)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- pseudobulk_samples(melanoma)
    -pseudobulk_dim_plot(melanoma)
    +#> Warning: Dropped 6245 gene(s) with zero variance across samples before the pseudobulk PCA.
     
    +# }
     
     
    @@ -144,7 +160,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/show-STlist-method.html b/docs/reference/show-STlist-method.html index ebe32d7..1c5fb9f 100644 --- a/docs/reference/show-STlist-method.html +++ b/docs/reference/show-STlist-method.html @@ -1,5 +1,5 @@ -show: Prints overview of STList oject. — show,STlist-method • spatialGEshow: Prints overview of STList oject. — show,STlist-method • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -78,6 +87,11 @@

    Arguments

    an STList object to show summary from.

    +
    +

    Value

    +

    Invisibly returns NULL. Called for the side effect of printing an +overview: the number of spatial arrays, their dimensions and a sample count.

    +

    Details

    This function takes an STList and prints a the number of spatial arrays in that @@ -96,7 +110,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/spatial_metadata.html b/docs/reference/spatial_metadata.html index f139774..47a488d 100644 --- a/docs/reference/spatial_metadata.html +++ b/docs/reference/spatial_metadata.html @@ -1,6 +1,5 @@ -spatial_metadata: Prints the names of the available spot/cell annotations — spatial_metadata • spatialGEspatial_metadata: Prints the names of the available spot/cell annotations — spatial_metadata • spatialGE @@ -18,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -35,6 +34,9 @@ + @@ -58,13 +66,12 @@
    -

    returns a character vector with the names of the annotations in the -x@spatial_meta slot.

    +

    returns the names of the annotations in the x@spatial_meta slot.

    @@ -79,6 +86,10 @@

    Arguments

    an STList object

    +
    +

    Value

    +

    a list of character vectors containing the column names of x@spatial_meta

    +
    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/sub-STlist-ANY-ANY-ANY-method.html b/docs/reference/sub-STlist-ANY-ANY-ANY-method.html new file mode 100644 index 0000000..c1b3aaa --- /dev/null +++ b/docs/reference/sub-STlist-ANY-ANY-ANY-method.html @@ -0,0 +1,142 @@ + +[: Reject two-dimensional subsetting of an STList object. — [,STlist,ANY,ANY,ANY-method • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Raises an informative error. An STlist holds several spatial +arrays, each with its own gene and spot sets, so there is no shared second +dimension to index; select samples with x[i] and then address genes or spots +through that sample's slots.

    +
    + +
    +
    # S4 method for class 'STlist,ANY,ANY,ANY'
    +x[i, j, ..., drop = TRUE]
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STList object.

    + + +
    i
    +

    sample selection. Valid on its own via x[i], but not together +with j.

    + + +
    j
    +

    not used; supplying it is what makes this an error.

    + + +
    ...
    +

    not used.

    + + +
    drop
    +

    not used.

    + +
    +
    +

    Value

    +

    Never returns: always raises an error naming x[i] as the supported +form.

    +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/sub-STlist-ANY-missing-ANY-method.html b/docs/reference/sub-STlist-ANY-missing-ANY-method.html new file mode 100644 index 0000000..de60c4f --- /dev/null +++ b/docs/reference/sub-STlist-ANY-missing-ANY-method.html @@ -0,0 +1,155 @@ + +[: Subset an STList object by sample. — [,STlist,ANY,missing,ANY-method • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Returns a new, valid STlist containing only the selected +spatial arrays (samples).

    +
    + +
    +
    # S4 method for class 'STlist,ANY,missing,ANY'
    +x[i, j, ..., drop = TRUE]
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STList object.

    + + +
    i
    +

    sample names, positions or a logical vector selecting spatial arrays.

    + + +
    j
    +

    not used. Subsetting is one-dimensional, so supplying j is an +error rather than a second index.

    + + +
    ...
    +

    unused; present for compatibility with the [ generic.

    + + +
    drop
    +

    unused. Subsetting an STlist always returns an STlist, never a +bare matrix: dropping to the underlying counts would discard the metadata that +makes it an STlist.

    + +
    +
    +

    Value

    +

    An STlist containing only the selected spatial arrays. Subsetting to +zero samples is an error.

    +
    +
    +

    Details

    +

    x[i] selects samples, not genes or spots: an STlist holds several spatial +arrays and each has its own gene and spot sets, so there is no shared second +dimension to index. i may be a character vector of sample names (as returned +by tissue_names()), a numeric vector of positions, or a logical vector as +long as the number of samples.

    +

    Every slot keyed by sample is subset alongside @counts – @spatial_meta, +@gene_meta, @tr_counts and the per-sample entries inside each +@gene_krige element – so the result is internally consistent and passes +validity. @sample_meta rows are matched by their sample_name column rather +than by position, so the metadata stays aligned with its sample.

    +

    An unknown name is an error rather than a silent omission, matching the +package-wide rule for samples= arguments.

    +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/sub-sub-STlist-ANY-ANY-method.html b/docs/reference/sub-sub-STlist-ANY-ANY-method.html new file mode 100644 index 0000000..4302ee8 --- /dev/null +++ b/docs/reference/sub-sub-STlist-ANY-ANY-method.html @@ -0,0 +1,133 @@ + +[[: Not supported for STList objects. — [[,STlist,ANY,ANY-method • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Raises an informative error. Subsetting an STlist is +one-dimensional and returns another STlist; use x[i].

    +
    + +
    +
    # S4 method for class 'STlist,ANY,ANY'
    +x[[i, j, ...]]
    +
    + +
    +

    Arguments

    + + +
    x
    +

    an STList object.

    + + +
    i
    +

    not used; any value raises an error.

    + + +
    j
    +

    not used; any value raises an error.

    + + +
    ...
    +

    not used; any value raises an error.

    + +
    +
    +

    Value

    +

    Never returns: always raises an error naming x[i] as the supported +form.

    +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/reference/summarize_STlist.html b/docs/reference/summarize_STlist.html index 0ae87e6..b1dee7b 100644 --- a/docs/reference/summarize_STlist.html +++ b/docs/reference/summarize_STlist.html @@ -1,5 +1,5 @@ -summarize_STlist: Generates a data frame with summary statistics — summarize_STlist • spatialGEsummarize_STlist: Generates a data frame with summary statistics — summarize_STlist • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -89,43 +98,49 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                         full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file) # Only first two samples
    +  summarize_STlist(melanoma)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?.")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -summarize_STlist(melanoma)
    -#> # A tibble: 2 × 9
    +#> # A tibble: 4 × 9
     #>   sample_name  spotscells genes min_counts_per_spotcell mean_counts_per_spotcell
     #>   <chr>             <int> <int>                   <dbl>                    <dbl>
     #> 1 ST_mel1_rep2        293 16148                       6                    6056.
     #> 2 ST_mel2_rep1        383 16831                       9                    3649.
    +#> 3 ST_mel3_rep1        256 15653                     291                    4366.
    +#> 4 ST_mel4_rep2        248 15991                    3315                    9665.
     #> # ℹ 4 more variables: max_counts_per_spotcell <dbl>,
     #> #   min_genes_per_spotcell <int>, mean_genes_per_spotcell <dbl>,
     #> #   max_genes_per_spotcell <int>
    +# }
     
     
    @@ -141,7 +156,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/summary-STlist-method.html b/docs/reference/summary-STlist-method.html index 07230e2..249aa58 100644 --- a/docs/reference/summary-STlist-method.html +++ b/docs/reference/summary-STlist-method.html @@ -1,5 +1,5 @@ -summary: Prints overview of STList oject. — summary,STlist-method • spatialGEsummary: Prints overview of STList oject. — summary,STlist-method • spatialGE @@ -17,7 +17,7 @@ spatialGE - 1.2.0 + 2.0.0 @@ -34,6 +34,9 @@ + @@ -57,7 +66,7 @@
    @@ -78,6 +87,11 @@

    Arguments

    an STList object to show summary from.

    +
    +

    Value

    +

    Invisibly returns NULL. Called for the side effect of printing an +overview: the number of spatial arrays, their dimensions and a sample count.

    +

    Details

    This function takes an STList and prints a the number of spatial arrays in that @@ -96,7 +110,7 @@

    Details

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/tissue_names.html b/docs/reference/tissue_names.html index 23c6fb3..253c5b7 100644 --- a/docs/reference/tissue_names.html +++ b/docs/reference/tissue_names.html @@ -1,5 +1,5 @@ -tissue_names: Prints the names of the tissue samples in the STlist — tissue_names • spatialGEtissue_names: Prints the names of the tissue samples in the STlist — tissue_names • spatialGE + @@ -58,7 +67,7 @@
    @@ -79,6 +88,10 @@

    Arguments

    an STList object

    +
    +

    Value

    +

    a character vector with the sample names in the STlist object

    +
    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/transform_data.html b/docs/reference/transform_data.html index f256561..5b90dd9 100644 --- a/docs/reference/transform_data.html +++ b/docs/reference/transform_data.html @@ -1,5 +1,5 @@ -transform_data: Transformation of spatial transcriptomics data — transform_data • spatialGEtransform_data: Transformation of spatial transcriptomics data — transform_data • spatialGE + @@ -58,7 +67,7 @@
    @@ -114,7 +123,14 @@

    Arguments

    Value

    -

    x an updated STlist with transformed counts.

    +

    x an updated STlist with transformed counts. gene_meta gains +vst.variance.standardized (Seurat's standardized variance, computed from the +raw counts) alongside gene_mean and gene_stdevs, so that "top variable +gene" selection is the same whichever function runs first.

    +

    That column requires fitting a variance-mean trend across genes, which needs +at least four genes of non-zero variance. A sample with fewer is left without +it and warned about by name, rather than failing the transformation; functions +that rank genes by variability will not work on such a sample.

    Details

    @@ -129,35 +145,39 @@

    Details

    Examples

    -
    
    +    
    # \donttest{
     # Using included melanoma example (Thrane et al.)
     # Download example data set from spatialGE_Data
     thrane_tmp = tempdir()
     unlink(thrane_tmp, recursive=TRUE)
     dir.create(thrane_tmp)
     lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download='
    -download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    -zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    -unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    -# Generate the file paths to be passed to the STlist function
    -count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='counts')
    -coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                          full.names=TRUE, pattern='mapping')
    -clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    -                        full.names=TRUE, pattern='clinical')
    -# Create STlist
    -library('spatialGE')
    -melanoma <- STlist(rnacounts=count_files[c(1,2)],
    -                   spotcoords=coord_files[c(1,2)],
    -                   samples=clin_file) # Only first two samples
    -#> Warning: Sample ST_mel3_rep1 was not found among the count/coordinate files.
    -#> Warning: Sample ST_mel4_rep2 was not found among the count/coordinate files.
    +tryCatch({ # In case data is not available from network
    +  download.file(lk, destfile=paste0(thrane_tmp, '/', 'melanoma_thrane.zip'), mode='wb')
    +  zip_tmp = list.files(thrane_tmp, pattern='melanoma_thrane.zip$', full.names=TRUE)
    +  unzip(zipfile=zip_tmp, exdir=thrane_tmp)
    +  # Generate the file paths to be passed to the STlist function
    +  count_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='counts')
    +  coord_files <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                            full.names=TRUE, pattern='mapping')
    +  clin_file <- list.files(paste0(thrane_tmp, '/melanoma_thrane'),
    +                          full.names=TRUE, pattern='clinical')
    +  # Create STlist
    +  library('spatialGE')
    +  melanoma <- STlist(rnacounts=count_files,
    +                     spotcoords=coord_files,
    +                     samples=clin_file)
    +  melanoma <- transform_data(melanoma)
    +}, error = function(e) {
    +  message("Could not run example. Are you connected to the internet?")
    +  return(NULL)
    +})
     #> Found matrix data
     #> Matching gene expression and coordinate data...
     #> Converting counts to sparse matrices
     #> Completed STlist!
    -melanoma <- transform_data(melanoma, method='log')
    +# }
     
     
    @@ -173,7 +193,7 @@

    Examples

    -

    Site built with pkgdown 2.1.1.

    +

    Site built with pkgdown 2.2.1.

    diff --git a/docs/reference/validate_store.html b/docs/reference/validate_store.html new file mode 100644 index 0000000..2a200eb --- /dev/null +++ b/docs/reference/validate_store.html @@ -0,0 +1,140 @@ + +validate_store: Check an on-disk STlist against its manifests — validate_store • spatialGE + + +
    +
    + + + +
    +
    + + +
    +

    Verifies that a backed STlist's files exist and still match what +its manifests record, reading parquet footers only.

    +
    + +
    +
    validate_store(x = NULL, deep = FALSE)
    +
    + +
    +

    Arguments

    + + +
    x
    +

    a backed STlist

    + + +
    deep
    +

    logical, whether to read data pages as well as metadata

    + +
    +
    +

    Value

    +

    invisibly TRUE, or stops with the first problem found

    +
    +
    +

    Details

    +

    Checks sample order against the order recorded when the store was written, +that every file exists and its size/mtime fingerprint is unchanged, that +dimnames lengths agree with the recorded dimensions, and that @tr_counts +genes and cells are subsets of @counts' in the same relative order – the +invariant filter_data() assumes.

    +

    With deep=TRUE, also reads the data to check that stored coordinates are in +bounds and not duplicated.

    +

    The failure this is most useful for is a store directory that has been moved +or deleted after the STlist was saved with saveRDS(), which it reports as +such rather than surfacing later as an error from inside an analysis.

    +
    +
    +

    See also

    + +
    + +
    + +
    + + +
    + +
    +

    Site built with pkgdown 2.2.1.

    +
    + +
    + + + + + + + + diff --git a/docs/sitemap.xml b/docs/sitemap.xml index 1c8e09d..5048c96 100644 --- a/docs/sitemap.xml +++ b/docs/sitemap.xml @@ -4,6 +4,7 @@ /LICENSE.html /articles/basic_functions_vignette.html /articles/index.html +/articles/ondisk_stlists.html /articles/spatial_differential_expression.html /articles/spatial_enrichment_gradients_smi.html /articles/troubleshooting.html @@ -19,8 +20,11 @@ /reference/SThet_invdist_test.html /reference/STlist-class.html /reference/STlist.html +/reference/STlist_to_disk.html +/reference/STlist_to_memory.html /reference/STplot.html /reference/STplot_interpolation.html +/reference/as_Seurat.html /reference/compare_SThet.html /reference/dim-STlist-method.html /reference/distribution_plots.html @@ -28,6 +32,7 @@ /reference/gene_interpolation.html /reference/get_gene_meta.html /reference/index.html +/reference/is_backed.html /reference/load_images.html /reference/old_SThet.html /reference/plot_counts.html @@ -42,5 +47,6 @@ /reference/summary-STlist-method.html /reference/tissue_names.html /reference/transform_data.html +/reference/validate_store.html diff --git a/inst/err.csv b/inst/err.csv index 0d530f8..949d123 100644 --- a/inst/err.csv +++ b/inst/err.csv @@ -59,3 +59,31 @@ error0066,'validate_store: Recorded dimensions do not match the recorded gene/ce error0067,'validate_store: Duplicate gene names are not supported by the on-disk store.' error0068,'validate_store: Stored coordinates are out of bounds or duplicated.' error0069,'validate_store: Transformed counts are not a same-order subset of raw counts.' +error0070,'STdiff: The annotation column must contain group labels (character or factor), not numbers. Convert it with as.character() first.' +error0071,'STdiff: The annotation column must contain at least two distinct groups to test.' +error0072,'STplot_interpolation: no kriging results were found in this STlist. Run gene_interpolation() first.' +error0073,'STplot_interpolation: none of the requested genes were interpolated. Run gene_interpolation() first; already-interpolated genes include: %s.' +error0074,'STplot_interpolation: the kriging results for the requested genes (%s) contain no finite predicted values, so there is nothing to plot. Re-run gene_interpolation() on them.' +error0075,'STdiff: at least two clusters are required for pairwise tests.' +error0076,'STdiff: topgenes and sp_topgenes must be positive integers, or a proportion between 0 and 1.' +error0077,'STdiff: specify single values for w and k.' +error0078,'STdiff: if k="dtc", then deepSplit must also be specified.' +error0079,'STdiff: specify a valid k value (a positive integer or "dtc").' +error0080,'STdiff: if no annotation is specified, both w and k (the STclust parameters) are required.' +error0081,'STdiff: specify one annotation column from @spatial_meta when w and k are not given.' +error0082,'STdiff: only one annotation column from @spatial_meta can be tested at a time.' +error0083,'STdiff: no samples are left to test. Check that the requested annotation or clusters exist in at least one sample.' +error0084,'SThet: enter one or more genes to calculate statistics for.' +error0085,'SThet: k must be a positive integer when using nearest-neighbor weights.' +error0086,'STclust: select a spatial weight (w) between 0 and 1.' +error0087,'STclust: enter valid k values to evaluate, or "dtc" for cutreeDynamic.' +error0088,'STclust: only spatially-informed hierarchical clustering is currently supported.' +error0089,'distribution_plots: specify either a spot/cell metadata variable or a gene to plot.' +error0090,'distribution_plots: all requested samples were skipped, so there is nothing to plot.' +error0091,'gene_interpolation: enter one or more genes to interpolate.' +error0092,'compare_SThet: enter one or more genes to plot.' +error0093,'resolve_cores: could not recognize the requested number of cores. Use a positive integer, or set options(spatialGE.cores=) / SPATIALGE_CORES.' +error0094,'transform_data(method="sct"): SCTransform failed for sample %s (%d genes x %d spots/cells, min_cells=%d). Lower sct_n_regr_genes, or use method="log". Underlying error: %s' +error0095,'STlist subsetting (x[i]): unknown sample name(s): %s. Available samples: %s.' +error0096,'STlist subsetting (x[i]): i must select samples by name, position or logical vector. Subsetting is one-dimensional: an STlist holds several spatial arrays, each with its own genes and spots.' +error0097,'STgradient: only %d gene(s) in this distance range have non-zero variance, which is too few to rank genes by variability (at least 4 are needed). Provide genes explicitly instead of relying on topgenes, or widen the distance range.' diff --git a/man/STlist_to_disk.Rd b/man/STlist_to_disk.Rd index b8e3018..bc3a553 100644 --- a/man/STlist_to_disk.Rd +++ b/man/STlist_to_disk.Rd @@ -21,26 +21,25 @@ Converts an in-memory STlist into one backed by parquet files, so data larger than memory can be held and read in slices. } \details{ -Opt-in and reversible. \code{@counts} and \code{@tr_counts} elements are replaced -by manifests describing per-sample parquet files; every other slot is untouched. +Opt-in and reversible. \verb{@counts} and \verb{@tr_counts} elements are replaced by +manifests describing per-sample parquet files; every other slot is untouched. All package functions continue to work, because slot reads go through internal -accessors that materialize on demand -- so this trades memory for I/O rather than -changing results. +accessors that materialize on demand -- so this trades memory for I/O rather +than changing results. Matrices are stored in COO (long) form, one file per sample per slot, sorted by gene then cell. \code{STlist_to_memory()} reverses the conversion. -Note what this does and does not buy. It buys capacity: an STlist larger than RAM -can be held and read in gene-subset slices. It does not currently speed anything -up -- aggregate operations still materialize and compute in memory, so a backed -STlist is slower on those paths than an in-memory one. +Note what this does and does not buy. It buys capacity: an STlist larger than +RAM can be held and read in gene-subset slices. It does not currently speed +anything up -- aggregate operations still materialize and compute in memory, so +a backed STlist is slower on those paths than an in-memory one. -The store is a directory of files, not part of the R object. An STlist saved with -\code{saveRDS()} records paths, so moving or deleting \code{root} breaks it; +The store is a directory of files, not part of the R object. An STlist saved +with \code{saveRDS()} records paths, so moving or deleting \code{root} breaks it; \code{validate_store()} reports that rather than failing obscurely later. A store written under \code{tempdir()} is flagged as non-portable for the same reason. } \seealso{ -\code{\link{STlist_to_memory}}, \code{\link{validate_store}}, -\code{\link{is_backed}} +\code{\link[=STlist_to_memory]{STlist_to_memory()}}, \code{\link[=validate_store]{validate_store()}}, \code{\link[=is_backed]{is_backed()}} } diff --git a/man/STlist_to_memory.Rd b/man/STlist_to_memory.Rd index 7581ba4..db8802c 100644 --- a/man/STlist_to_memory.Rd +++ b/man/STlist_to_memory.Rd @@ -16,10 +16,10 @@ an STlist with in-memory count matrices Reverses \code{STlist_to_disk()}, materializing every backed matrix. } \details{ -The round trip is exact: COO stores the values themselves and the manifest carries -dimensions and dimnames, so nothing is inferred on the way back. An STlist that -was never backed is returned unchanged. +The round trip is exact: COO stores the values themselves and the manifest +carries dimensions and dimnames, so nothing is inferred on the way back. An +STlist that was never backed is returned unchanged. } \seealso{ -\code{\link{STlist_to_disk}} +\code{\link[=STlist_to_disk]{STlist_to_disk()}} } diff --git a/man/STplot_interpolation.Rd b/man/STplot_interpolation.Rd index f257b65..d73ba53 100644 --- a/man/STplot_interpolation.Rd +++ b/man/STplot_interpolation.Rd @@ -13,12 +13,17 @@ STplot_interpolation( ) } \arguments{ -\item{x}{an STlist containing results from \code{gene_krige} for the genes selected.} +\item{x}{an STlist containing results from \code{gene_krige} for the genes selected. +Kriging must have been run first with \code{\link[=gene_interpolation]{gene_interpolation()}}.} -\item{genes}{a vector of gene names (one or several) to plot. If 'top', the 10 -genes with highest standard deviation from each spatial sample are plotted.} +\item{genes}{a vector of gene names (one or several) to plot. If \code{'top'} (the +default when \code{NULL}), the \code{top_n} genes with the highest standardized variance +(VST) from each spatial sample are plotted. Only genes that already have +kriging results can be plotted; a warning names any requested gene that was not +interpolated.} -\item{top_n}{an integer indicating how many top genes to perform kriging. Default is 10.} +\item{top_n}{an integer indicating how many of the most variable genes to plot +when \code{genes='top'}. Default is 10.} \item{samples}{a vector indicating the spatial samples to plot. If vector of numbers, it follows the order of \code{names(x@counts)}. If NULL, the function plots all samples} diff --git a/man/as_Seurat.Rd b/man/as_Seurat.Rd index f0f5894..24fb13e 100644 --- a/man/as_Seurat.Rd +++ b/man/as_Seurat.Rd @@ -22,19 +22,19 @@ sample, so spatialGE results can be taken into Seurat-based workflows. } \details{ Each sample in the STlist becomes one FOV in the returned object, named after -the sample. Raw counts go to the \code{counts} layer and, when -\code{transform_data()} has been run, transformed counts go to the \code{data} -layer. Spot-level columns from \code{@spatial_meta} -- including \code{STclust} -cluster assignments -- are carried into \code{@meta.data}. +the sample. Raw counts go to the \code{counts} layer and, when \code{transform_data()} +has been run, transformed counts go to the \code{data} layer. Spot-level columns +from \verb{@spatial_meta} -- including \code{STclust} cluster assignments -- are carried +into \verb{@meta.data}, prefixed by sample where a merge would otherwise collide. -Cell names are prefixed with the sample name (\code{_}) because +Cell names are prefixed with the sample name (\verb{_}) because spot barcodes are only unique within a sample in the general case, and a merged Seurat object requires globally unique cell names. -Genes not shared by every requested sample are dropped, with a message reporting -how many, since Seurat holds a single matrix across all cells. +Genes not shared by every requested sample are dropped, with a message +reporting how many, since Seurat holds a single matrix across all cells. } \seealso{ -\code{\link{STlist}} accepts a Seurat object as \code{rnacounts}, so the -conversion round-trips. +\code{\link[=STlist]{STlist()}} accepts a Seurat object as \code{rnacounts}, so the conversion +round-trips. } diff --git a/man/dim-STlist-method.Rd b/man/dim-STlist-method.Rd index 069604f..595afd7 100644 --- a/man/dim-STlist-method.Rd +++ b/man/dim-STlist-method.Rd @@ -2,17 +2,35 @@ % Please edit documentation in R/classDefinitions.R \name{dim,STlist-method} \alias{dim,STlist-method} -\title{dim: Prints the dimensions of count arrays within an STList object.} +\title{dim: Dimensions of the count array in an STList object.} \usage{ \S4method{dim}{STlist}(x) } \arguments{ -\item{x}{an STList object to show summary from.} +\item{x}{an STList object.} +} +\value{ +An integer vector \code{c(n_genes, n_spots)} when the object holds exactly +one sample; \code{NULL} for a multi-sample object, where there is no single gene x +spot shape to report. } \description{ -Returns the number of genes and spots for each array within an STList object +Returns the number of genes (rows) and spots/cells (columns) +observed in an STList object. } \details{ -This function takes an STList and prints the number of genes (rows) and spots (columns) of -each spatial array within that object. +An \code{STlist} is a container for one or more spatial arrays, and different +samples may have different numbers of genes. \code{dim()} therefore has a single +well-defined answer only when the object holds exactly one sample; in that +case it returns \code{c(n_genes, n_spots)} as an integer vector, like any other +matrix-like object. + +For a multi-sample STlist \code{dim()} returns \code{NULL} (the base R convention for +"no dimensions"), because there is no single gene x spot shape to report. Use +\code{\link[=summarize_STlist]{summarize_STlist()}} for a per-sample table of dimensions, or \code{\link[=tissue_names]{tissue_names()}} +to iterate samples. + +Previously this method returned a \emph{named list} of per-sample dimensions, which +violated the base \code{dim()} contract: it made \code{\link[=nrow]{nrow()}}/\code{\link[=ncol]{ncol()}} meaningless, and +\verb{R CMD check} reported it as "dim() returns class 'list'". } diff --git a/man/figures/logo.png b/man/figures/logo.png new file mode 100644 index 0000000..1fd6d95 Binary files /dev/null and b/man/figures/logo.png differ diff --git a/vignettes/img/spatialGE_workflow_v3.png b/man/figures/spatialGE_workflow_v3.png similarity index 100% rename from vignettes/img/spatialGE_workflow_v3.png rename to man/figures/spatialGE_workflow_v3.png diff --git a/man/filter_data.Rd b/man/filter_data.Rd index 3ddf243..e34d8a5 100644 --- a/man/filter_data.Rd +++ b/man/filter_data.Rd @@ -23,7 +23,8 @@ filter_data( rm_spots = NULL, rm_genes = NULL, rm_genes_expr = NULL, - spot_pct_expr = "^MT-" + spot_pct_expr = "^MT-", + verbose = TRUE ) } \arguments{ @@ -64,6 +65,9 @@ filter_data( \item{rm_genes_expr}{a regular expression that matches genes to remove. Removes genes in \code{x@counts}, \code{x@tr_counts}, and \code{x@gene_meta}} \item{spot_pct_expr}{a expression to use with \code{spot_minpct} and \code{spot_maxpct}. By default '^MT-'.} + +\item{verbose}{logical, if \code{TRUE} reports how many samples, spots/cells and +genes were removed (and says explicitly when nothing was filtered).} } \value{ an STlist containing the filtered data @@ -87,6 +91,15 @@ filters in the following order: \item Genes matching \code{rm_genes_expr} \item Min and max counts } + +Note that every count threshold defaults to \code{0} (and the \verb{*_max*} thresholds +to \code{NULL}, meaning no upper bound). A call that supplies none of them, and no +\verb{rm_*} argument either, therefore returns the STlist unchanged. Set at least +one threshold to actually filter; with \code{verbose=TRUE} the function says so +rather than returning silently. + +Filtering is sequential and single-threaded, so unlike the analysis functions +there is no \code{cores} argument. } \examples{ \donttest{ diff --git a/man/is_backed.Rd b/man/is_backed.Rd index 1857943..04e8f77 100644 --- a/man/is_backed.Rd +++ b/man/is_backed.Rd @@ -17,5 +17,5 @@ Reports whether an STlist's count matrices are held in on-disk parquet files rather than in memory. } \seealso{ -\code{\link{STlist_to_disk}} +\code{\link[=STlist_to_disk]{STlist_to_disk()}} } diff --git a/man/length-STlist-method.Rd b/man/length-STlist-method.Rd new file mode 100644 index 0000000..08436a1 --- /dev/null +++ b/man/length-STlist-method.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/classDefinitions.R +\name{length,STlist-method} +\alias{length,STlist-method} +\title{length: Number of spatial arrays in an STList object.} +\usage{ +\S4method{length}{STlist}(x) +} +\arguments{ +\item{x}{an STList object.} +} +\value{ +A single integer: the number of spatial arrays in \code{x}. +} +\description{ +Returns the number of samples (spatial arrays) held by an +STList object. +} +\details{ +An \code{STlist} is a container for one or more spatial arrays. \code{length()} reports +how many, which makes the object usable with the usual idioms -- +\code{seq_along(x)}, \verb{for(i in seq_len(length(x)))} -- instead of having to know +that the count lives in \code{length(x@counts)}. +} diff --git a/man/load_images.Rd b/man/load_images.Rd index f2ef9c7..c7acfc6 100644 --- a/man/load_images.Rd +++ b/man/load_images.Rd @@ -9,7 +9,13 @@ load_images(x = NULL, images = NULL) \arguments{ \item{x}{an STlist} -\item{images}{a string indicating a folder to load images from} +\item{images}{image file paths or one or more folders to load images from. +A named character vector (\code{c(sample_name = "path/to/image.png")}) maps +samples to files explicitly and bypasses name matching. An unnamed vector +is matched against the sample names in \code{x}; any element that is an existing +directory is expanded to the image files it contains. Image filenames are +matched to sample names by looking for \verb{.} in the filename and, +failing that, a normalized prefix match (case- and separator-insensitive).} } \value{ an STlist with images diff --git a/man/show-STlist-method.Rd b/man/show-STlist-method.Rd index 107f4a5..41c6235 100644 --- a/man/show-STlist-method.Rd +++ b/man/show-STlist-method.Rd @@ -9,6 +9,10 @@ \arguments{ \item{object}{an STList object to show summary from.} } +\value{ +Invisibly returns \code{NULL}. Called for the side effect of printing an +overview: the number of spatial arrays, their dimensions and a sample count. +} \description{ Prints overview/summary of STList oject. } diff --git a/man/sub-STlist-ANY-ANY-ANY-method.Rd b/man/sub-STlist-ANY-ANY-ANY-method.Rd new file mode 100644 index 0000000..4fca588 --- /dev/null +++ b/man/sub-STlist-ANY-ANY-ANY-method.Rd @@ -0,0 +1,30 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/classDefinitions.R +\name{[,STlist,ANY,ANY,ANY-method} +\alias{[,STlist,ANY,ANY,ANY-method} +\title{[: Reject two-dimensional subsetting of an STList object.} +\usage{ +\S4method{[}{STlist,ANY,ANY,ANY}(x, i, j, ..., drop = TRUE) +} +\arguments{ +\item{x}{an STList object.} + +\item{i}{sample selection. Valid on its own via \code{x[i]}, but not together +with \code{j}.} + +\item{j}{not used; supplying it is what makes this an error.} + +\item{...}{not used.} + +\item{drop}{not used.} +} +\value{ +Never returns: always raises an error naming \code{x[i]} as the supported +form. +} +\description{ +Raises an informative error. An STlist holds several spatial +arrays, each with its own gene and spot sets, so there is no shared second +dimension to index; select samples with \code{x[i]} and then address genes or spots +through that sample's slots. +} diff --git a/man/sub-STlist-ANY-missing-ANY-method.Rd b/man/sub-STlist-ANY-missing-ANY-method.Rd new file mode 100644 index 0000000..f89a07a --- /dev/null +++ b/man/sub-STlist-ANY-missing-ANY-method.Rd @@ -0,0 +1,46 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/classDefinitions.R +\name{[,STlist,ANY,missing,ANY-method} +\alias{[,STlist,ANY,missing,ANY-method} +\title{[: Subset an STList object by sample.} +\usage{ +\S4method{[}{STlist,ANY,missing,ANY}(x, i, j, ..., drop = TRUE) +} +\arguments{ +\item{x}{an STList object.} + +\item{i}{sample names, positions or a logical vector selecting spatial arrays.} + +\item{j}{not used. Subsetting is one-dimensional, so supplying \code{j} is an +error rather than a second index.} + +\item{...}{unused; present for compatibility with the \code{[} generic.} + +\item{drop}{unused. Subsetting an STlist always returns an STlist, never a +bare matrix: dropping to the underlying counts would discard the metadata that +makes it an STlist.} +} +\value{ +An STlist containing only the selected spatial arrays. Subsetting to +zero samples is an error. +} +\description{ +Returns a new, valid STlist containing only the selected +spatial arrays (samples). +} +\details{ +\code{x[i]} selects samples, not genes or spots: an STlist holds several spatial +arrays and each has its own gene and spot sets, so there is no shared second +dimension to index. \code{i} may be a character vector of sample names (as returned +by \code{\link[=tissue_names]{tissue_names()}}), a numeric vector of positions, or a logical vector as +long as the number of samples. + +Every slot keyed by sample is subset alongside \verb{@counts} -- \verb{@spatial_meta}, +\verb{@gene_meta}, \verb{@tr_counts} and the per-sample entries inside each +\verb{@gene_krige} element -- so the result is internally consistent and passes +validity. \verb{@sample_meta} rows are matched by their \code{sample_name} column rather +than by position, so the metadata stays aligned with its sample. + +An unknown name is an error rather than a silent omission, matching the +package-wide rule for \verb{samples=} arguments. +} diff --git a/man/sub-sub-STlist-ANY-ANY-method.Rd b/man/sub-sub-STlist-ANY-ANY-method.Rd new file mode 100644 index 0000000..e2b2e21 --- /dev/null +++ b/man/sub-sub-STlist-ANY-ANY-method.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/classDefinitions.R +\name{[[,STlist,ANY,ANY-method} +\alias{[[,STlist,ANY,ANY-method} +\alias{[[,STlist-method} +\title{[[: Not supported for STList objects.} +\usage{ +\S4method{[[}{STlist,ANY,ANY}(x, i, j, ...) +} +\arguments{ +\item{x}{an STList object.} + +\item{i}{not used; any value raises an error.} + +\item{j}{not used; any value raises an error.} + +\item{...}{not used; any value raises an error.} +} +\value{ +Never returns: always raises an error naming \code{x[i]} as the supported +form. +} +\description{ +Raises an informative error. Subsetting an STlist is +one-dimensional and returns another STlist; use \code{x[i]}. +} diff --git a/man/summary-STlist-method.Rd b/man/summary-STlist-method.Rd index c3bc821..059b424 100644 --- a/man/summary-STlist-method.Rd +++ b/man/summary-STlist-method.Rd @@ -9,6 +9,10 @@ \arguments{ \item{object}{an STList object to show summary from.} } +\value{ +Invisibly returns \code{NULL}. Called for the side effect of printing an +overview: the number of spatial arrays, their dimensions and a sample count. +} \description{ Prints overview/summary of STList oject. } diff --git a/man/transform_data.Rd b/man/transform_data.Rd index 6f06e78..b8bd386 100644 --- a/man/transform_data.Rd +++ b/man/transform_data.Rd @@ -33,7 +33,15 @@ If NULL, the function uses half of the available cores at a maximum. The paralle uses \code{parallel::mclapply} and works only in Unix systems.} } \value{ -x an updated STlist with transformed counts. +x an updated STlist with transformed counts. \code{gene_meta} gains +\code{vst.variance.standardized} (Seurat's standardized variance, computed from the +raw counts) alongside \code{gene_mean} and \code{gene_stdevs}, so that "top variable +gene" selection is the same whichever function runs first. + +That column requires fitting a variance-mean trend across genes, which needs +at least four genes of non-zero variance. A sample with fewer is left without +it and warned about by name, rather than failing the transformation; functions +that rank genes by variability will not work on such a sample. } \description{ Applies data transformation methods to spatial transcriptomics diff --git a/man/validate_store.Rd b/man/validate_store.Rd index 160bb07..5eced68 100644 --- a/man/validate_store.Rd +++ b/man/validate_store.Rd @@ -15,23 +15,23 @@ validate_store(x = NULL, deep = FALSE) invisibly TRUE, or stops with the first problem found } \description{ -Verifies that a backed STlist's files exist and still match what its -manifests record, reading parquet footers only. +Verifies that a backed STlist's files exist and still match what +its manifests record, reading parquet footers only. } \details{ -Checks sample order against the order recorded when the store was written, that -every file exists and its size/mtime fingerprint is unchanged, that dimnames -lengths agree with the recorded dimensions, and that \code{@tr_counts} genes and -cells are subsets of \code{@counts}' in the same relative order -- the invariant -\code{filter_data()} assumes. +Checks sample order against the order recorded when the store was written, +that every file exists and its size/mtime fingerprint is unchanged, that +dimnames lengths agree with the recorded dimensions, and that \verb{@tr_counts} +genes and cells are subsets of \verb{@counts}' in the same relative order -- the +invariant \code{filter_data()} assumes. -With \code{deep=TRUE}, also reads the data to check that stored coordinates are -in bounds and not duplicated. +With \code{deep=TRUE}, also reads the data to check that stored coordinates are in +bounds and not duplicated. -The failure this is most useful for is a store directory that has been moved or -deleted after the STlist was saved with \code{saveRDS()}, which it reports as +The failure this is most useful for is a store directory that has been moved +or deleted after the STlist was saved with \code{saveRDS()}, which it reports as such rather than surfacing later as an error from inside an analysis. } \seealso{ -\code{\link{STlist_to_disk}} +\code{\link[=STlist_to_disk]{STlist_to_disk()}}, \code{\link[=is_backed]{is_backed()}} } diff --git a/plans/golden-finding-boot.md b/plans/golden-finding-boot.md new file mode 100644 index 0000000..88e05ae --- /dev/null +++ b/plans/golden-finding-boot.md @@ -0,0 +1,350 @@ +# A pkgdown-only vignette for on-disk STlists + +## Context + +`STlist_to_disk()` / `STlist_to_memory()` / `is_backed()` / `validate_store()` +shipped in 2.0.0 with one `NEWS.md` paragraph, no `@examples` on any of the four +reference pages, and no tutorial. It is the one feature in the package a user +cannot discover by reading `?`-help, because the thing that needs explaining is +a *workflow* (build in memory, move to disk, analyze, come back) rather than any +single argument. So: a new article on the pkgdown site, `.Rbuildignore`d like +three of the four existing vignettes, so it reaches readers without adding a +network-dependent vignette to the CRAN tarball. + +Writing it surfaced three defects that have to be fixed first, or the article +would be a tour of workarounds. All three are reads of `@counts`/`@tr_counts` +that bypass `R/utils_accessors.R`, and `base::nrow()`/`rownames()` return `NULL` +on an `sge_manifest` rather than erroring — so each fails by *silently* reporting +nothing, which `.claude/CLAUDE.md` calls out as worse than an error: + +| Call | On a backed STlist today | +|---|---| +| `x` / `print(x)` / `summary(x)` | prints `sample_117d ( ROIs\|spots\|cells x genes)` — blank dimensions, no warning | +| `STplot(x, genes='NDRG1')` | warns "None of the requested genes are available" per sample, then stops with "Data was not found in the specified slot of this STList." | +| `distribution_plots(x, genes='NDRG1')` | messages "does not contain NDRG1" for every sample, returns plots that only fail when printed | + +`STlist_to_disk()`'s own roxygen claims "All package functions continue to work, +because slot reads go through internal accessors." These three are why that is +currently false. Printing the object is also the first thing both existing +tutorials do after building one (`tnbc`, `melanoma`), so the vignette cannot +avoid it. + +Scope confirmed with the user: fix those three, then write the article, then a +full `pkgdown::build_site()`. + +## 0. Check the existing work in first + +`R/classDefinitions.R` (+279) and `R/distribution_plots.R` (+4) — two of the +four files to edit — already carry uncommitted changes, so my commits cannot +cleanly separate from them. They belong to one coherent body of finished refactor +work already written up in `NEWS.md` (+126): 28 modified files (the `dim()` +base-contract rework, `stop()` → `raise_err()` conversions with 27 new +`inst/err.csv` codes, `STplot_interpolation`/`filter_data`/`transform_data`/ +`utils_parallel` changes, hand-edited `man/`, a 107-line `.github/workflows/test.yml` +expansion) plus 7 new `tests/testthat/` files and `dev/ci/`. + +So: one checkpoint commit of exactly that, before anything else. I will survey +the diff and **show the proposed message for approval before committing** — it +is not my work to characterize unprompted. + +Excluded from it: `docs/` (the full rebuild in step 8 overwrites the partial +`build_reference()` sitting there, and the complete site lands in commit 6) and +`plans/golden-finding-boot.md` (this file). + +## 1. Add the materializing slot accessor + +`R/utils_accessors.R`, after `sample_tr_counts()` (line 31). Both plotting fixes +branch on `data_type` (`'tr'`/`'raw'`), which is a different vocabulary from the +accessors' `slot=` (`'counts'`/`'tr_counts'`); `sample_slot_mtx()` already does +that dispatch but returns the raw element, so it only serves the structural +accessors. The materializing counterpart, with `genes=` forwarded: + +```r +sample_slot_counts = function(x, sample, slot=c('counts', 'tr_counts'), genes=NULL){ + slot = match.arg(slot) + if(slot == 'counts') sample_counts(x, sample, genes=genes) else sample_tr_counts(x, sample, genes=genes) +} +``` + +Not exported, so no `NAMESPACE`/`man/` churn and no `devtools::document()`. +Name is unused in `R/`, `tests/` and `NAMESPACE`. + +## 2. `show()` / `summary()` — report real dimensions + +`R/classDefinitions.R` lines **50, 55, 90, 95** (four byte-identical lines, two +in `show`, two in `summary`, one per `>= 11`-samples branch). Substitute only +the two reads: + +```r +# before +cat(paste0('\t', i, " (", ncol(object@counts[[i]]), ' ROIs|spots|cells x ', nrow(object@counts[[i]]), ' genes)\n')) +# after +cat(paste0('\t', i, " (", sample_n_cells(object, i, 'counts'), ' ROIs|spots|cells x ', sample_n_genes(object, i, 'counts'), ' genes)\n')) +``` + +Already the idiom in this file — the `dim()` method is +`as.integer(sample_dim(x, names(x@counts)[1], 'counts'))`. + +## 3. `plot_spatial_expression()` — read the gene slice through the accessors + +`R/plot_spatial_expression.R`. Keep `counts` as the accumulator (lines 79-89 +depend on it: sample-dropping, the per-sample `warning()`, the +`rlang::is_empty(counts)` stop). Only carry the slot *name* alongside it and +read from `x`: + +- lines 47-50: add `data_slot = 'tr_counts'` / `data_slot = 'counts'` to the two + existing branches +- line 63: `if(any(rownames(counts[[i]]) %in% genes)){` → + `if(any(sample_genes(x, i, data_slot) %in% genes)){` +- line 75: `expandSparse(counts[[i]][rownames(counts[[i]]) %in% genes, , drop=FALSE], transpose=TRUE)` → + `expandSparse(sample_slot_counts(x, i, data_slot, genes=genes), transpose=TRUE)` + +`plot_spatial_geneset.R:52` is the reference implementation that already does +this correctly, and is why `STplot(genes=list(...))` works on a backed object +while `STplot(genes='GENE')` does not. + +## 4. `distribution_plots()` — same change in both helpers + +`R/distribution_plots.R`, in `gene_plots()` (≈129-156) and +`cluster_gene_plots()` (≈226-254). Replace `expr_tmp = x@tr_counts` / +`expr_tmp = x@counts` with `data_slot = 'tr_counts'` / `data_slot = 'counts'` +(leaving the `p_title`/`ax_title` assignments alone), then in each loop: + +- `if(!(gene %in% rownames(expr_tmp[[i]])))` → `if(!(gene %in% sample_genes(x, i, data_slot)))` +- add `mtx_tmp = sample_slot_counts(x, i, data_slot, genes=gene)` in the `else` + branch and read `colnames(mtx_tmp)` / `mtx_tmp[gene, ]` in place of + `colnames(expr_tmp[[i]])` / `expr_tmp[[i]][gene, ]` + +`mtx_tmp` is this repo's existing name for a materialized one-sample matrix +(`summarize_STlist.R:53`, `filter_data_stages.R:147`, `STenrich.R:170`). +`expr_tmp` then has no remaining uses in either helper. + +### Why steps 2-4 are output-neutral in memory + +For a non-manifest element, each accessor reduces **by substitution** to the +expression it replaces: `sample_n_cells(x, i, 'counts')` → `base::ncol(x@counts[[i]])`, +`sample_genes(x, i, 'tr_counts')` → `base::rownames(x@tr_counts[[i]])`, and +`sample_tr_counts(x, i, genes=g)` → `m[rownames(m) %in% g, , drop=FALSE]` — +literally the same logical-mask expression already at both call sites, so +fidelity rule 9's matrix-row order is preserved by construction (it drives +`qp_list` key order downstream, so it is not cosmetic). Absent sample names, +`NA_character_` from an out-of-range numeric index, and an empty `@tr_counts` +all reduce to `NULL` through `[[` exactly as through a list slice, so the +"genuinely absent" branches are untouched. + +**One behavior does move**, and it should be stated in the commit message: a +duplicated `samples=` (e.g. `STplot(x, genes='NDRG1', samples=c('a','a'))`, +never de-duplicated) currently has iteration 2 read the data.frame iteration 1 +wrote back into `counts`, producing a false "None of the requested genes are +available" warning and, for a single sample, a false stop. Reading from `x` +fixes that. Not golden-covered (`bl_pipeline()` passes `samples=NULL`) and no +test exercises it. + +Golden surfaces: `show`/`summary` are not in `bl_pipeline()` at all; +`STplot(st5, genes=c("Gene1","GradGene1"), data_type="tr")` and +`distribution_plots(st5, genes=c("Gene1","GradGene1"), data_type="tr")` are, and +both take the all-genes-present path. **So no commit here regenerates +`tests/golden/`.** The golden gate is run as proof — a diff there means the fix +is wrong, not that the baseline needs recapturing. + +## 5. Tests + +`tests/testthat/test-store_parquet.R`, whose premise is already parity — one +block per fix, using the file's existing `store_fixture()` / `backed_fixture(st, name)`: + +- `show()`/`summary()`: `expect_identical(capture.output(methods::show(bk)), capture.output(methods::show(st)))`, + plus one literal assertion that the real numbers appear (the current output is + blanks, so an identity check alone would pass against another blank). +- `STplot(genes=)`: compare `names()` and per-panel rendered data both ways, for + `data_type='tr'` and `'raw'`; keep assertions that an absent gene still warns + per sample and then stops. +- `distribution_plots(genes=)`: same, plus the `plot_meta=` + `genes=` path + through `cluster_gene_plots()` on an `STclust`ed fixture, and that an absent + gene still messages. + +Plots are compared through a local helper that `set.seed()`s and then +`ggplot2::ggplot_build()`s, because `ggforce::geom_sina` (the +`plot_type='violin'` default) draws fresh jitter inside the build — +`dev/baseline/compare_baseline.R:94-98` handles it the same way. + +`test-graceful-errors.R` gets one test for the *silent* half of the rule (a +present gene must never be reported absent on a backed object). **Its `leaked` +vector is not touched** — none of these three surfaces as an internal error +string, and the backed failures that do leak internals are `transform_data()` +and `filter_data(verbose=TRUE)`, which stay documented-as-ordering below. + +## 6. Correct the row-group pruning claim + +`R/store_parquet.R:16-18`, `R/utils_accessors.R:16-17` and the store section of +`dev/ARCHITECTURE.md` all say a `genes=` read "touches only the row groups it +needs". `sge_store_materialize()` calls `arrow::read_parquet(m$path, as_data_frame=FALSE)` +and *then* `dplyr::filter()`s in Acero, so the whole file is read — pruning +would need `open_dataset()`. The saving is one full-size `dgCMatrix` allocation, +not I/O. Comment-only commit, fixed before the vignette because the article's +performance wording depends on getting this right, and because +`dev/ARCHITECTURE.md`'s own rule is to trust the code and fix the doc. + +## 7. The vignette + +New `vignettes/ondisk_stlists.Rmd`; add `^vignettes/ondisk_stlists\.Rmd$` to +`.Rbuildignore`. Sorts second in the auto-discovered articles index (after +`basic_functions_vignette`), which is the right slot for a follow-on topic. + +House conventions to match exactly, from the existing four: + +- YAML: the same five fields in the same order — `title`, ``date: '`r format(Sys.Date())`'``, + `output: rmarkdown::html_vignette`, `bibliography: vignette_references.bib`, + and the `vignette:` block with `%\VignetteIndexEntry{spatialge_tutorial_ondisk}`. + No `description:` field — none of the four has one. +- First chunk `vig_settings` with `include=F`, `knitr::opts_chunk$set(collapse=TRUE, comment="#>", fig.width=8, fig.height=5)` + and `options(rmarkdown.html_vignette.check_title=F)`. +- The `tryCatch` + `net_check <<- TRUE/FALSE` download guard from + `basic_functions_vignette.Rmd:91-99` with `eval=net_check` on every + downstream chunk. **Required** — the other two tutorials download with no + guard, and a full `build_site()` aborts if a download fails. +- Code style: `<-` for objects, `=` with no surrounding spaces for arguments, + single-quoted strings, `cores=2`, `warning=F`/`message=F` chunk options, + snake_case chunk names. +- Prose style: "we"/"users", prose before each chunk ending in a colon, prose + after interpreting the result, `***`spatialGE`***` at first mention, gene + names italicized, `
    **...**` for asides, closing + `## References` + `
    ` and a Session Info `
    `. + +Data: `tnbc_bassiouni`, the same eight Visium samples as +`basic_functions_vignette.Rmd`, so the article reads as a continuation and the +`object.size()` numbers are worth quoting. `@bassiouni_2023` is already in +`vignette_references.bib`. + +Outline: + +1. What problem this solves — an STlist holds every sample's counts in memory at + once; the store trades that for I/O. States up front that it buys capacity, + not speed. +2. Building the STlist, then `filter_data()` and `transform_data()` — with the + ordering stated as the deliberate workflow it is, since both rewrite the + matrices and must run before the move. +3. `STlist_to_disk()`, `is_backed()`, printing the object, `summarize_STlist()`. +4. What is actually on disk: `list.files()`, the `print.sge_manifest` one-liner, + `arrow::read_parquet()` of one file showing the `(gene_idx, cell_idx, value)` + triplets, and why COO sorted by gene. +5. Memory, measured in the document with `object.size()` rather than quoting the + fixture's 888 KB → 72 KB. +6. Analysis: `SThet()`, `STclust()`, `STplot()` for a gene and for clusters, + `distribution_plots()` — with an explicit equality check against the + in-memory result, and one honest timing comparison. +7. `validate_store()`, `validate_store(deep=TRUE)`, and `STlist_to_memory()` + with an `identical()` round-trip check. +8. What to keep in mind — the store is a directory of files, not part of the R + object, so `saveRDS()` records paths (`@misc$store$portable`, `FALSE` under + `tempdir()`); transform and filter before moving; come back to memory before + subsetting with `x[i]`, which leaves `@misc$store$sample_order` stale and + makes `validate_store()` raise. + +No `NEWS.md` entry — `NEWS.md` has never mentioned a vignette. + +## 8. Rebuild the site + +```sh +export CURL_CA_BUNDLE=/Users/4471592/.ssl/combined_cacert.pem +export SSL_CERT_FILE=/Users/4471592/.ssl/combined_cacert.pem +Rscript -e 'cat(curlGetHeaders("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/FridleyLab/spatialGE_Data/raw/refs/heads/main/melanoma_thrane.zip?download=")[1])' # expect HTTP/2 302 +Rscript -e 'pkgdown::build_site()' +``` + +The CA-bundle export is mandatory on this network (`dev/environment/README.md`) +— conda R's libcurl does not trust the intercepting root, and without it every +`download.file()` fails with libcurl error 60 while `/usr/bin/curl` succeeds. +Verified working above. + +The committed site is stale (shows 1.2.0, built with pkgdown 2.1.1; 2.2.1 is +installed), so a full build churns all ~117 tracked HTML files and re-runs the +two unguarded tutorials. Expect 30-90 minutes. If an article fails, I report it +rather than committing a half-written `docs/`. + +## 9. Commits + +One per numbered step, staging only the paths that step touches — never +`git add -A`, given the dirty tree. No AI/tool mentions anywhere. + +| # | Contents | Baseline regen | +|---|---|---| +| 0 | step 0 — the pre-existing work, message approved first | no | +| 1 | step 1 + step 2 + their test block | no | +| 2 | step 3 + its test block | no (commit body records the duplicated-`samples=` change) | +| 3 | step 4 + its test block + the `test-graceful-errors.R` test | no | +| 4 | step 6 — comments and `dev/ARCHITECTURE.md` | no | +| 5 | step 7 — `vignettes/ondisk_stlists.Rmd` + `.Rbuildignore` | no | +| 6 | step 8 — the rebuilt `docs/` | no | + +Step 1 is one commit because committing `sample_slot_counts()` alone would add +an unused function. + +## Verification + +Per fix commit: + +```sh +Rscript -e 'devtools::load_all(); testthat::test_local()' +``` + +Before the vignette, and again at the end: + +```sh +SPATIALGE_GOLDEN=true Rscript -e 'devtools::load_all(); testthat::test_local()' # expect zero diffs +Rscript dev/ci/check_vignette_args.R # statically checks the new .Rmd +``` + +`check_vignette_args.R` parses every `vignettes/*.Rmd` on every push and +validates named arguments against formals without evaluating anything, so the +new article is covered by CI from the moment it lands. + +End-to-end, the thing the article actually claims — run before writing it, so +the prose describes observed behavior rather than intended behavior: + +```r +devtools::load_all() +st <- STlist(rnacounts=visium_folders, samples=clin_file, cores=2) +st <- filter_data(st, spot_minreads=5000, spot_mingenes=1000, spot_maxreads=150000) +st <- transform_data(st, method='log', cores=2) +bk <- STlist_to_disk(st, file.path(tempdir(), 'tnbc_store'), overwrite=TRUE) + +bk # real dimensions, not blanks +identical(summarize_STlist(bk), summarize_STlist(st)) +validate_store(bk, deep=TRUE) +STplot(bk, genes='NDRG1', samples='sample_094c') # errors today +distribution_plots(bk, genes='NDRG1') # silently empty today +identical(STlist_to_memory(bk)@counts, st@counts) +``` + +Then render the article alone before committing to a full site build: + +```sh +Rscript -e 'pkgdown::build_article("ondisk_stlists")' +``` + +## Found but out of scope + +Not touching these; listing them because they came out of the same read and are +each worth their own decision: + +- **Duplicate gene names silently truncate a backed gene-subset read.** + `sge_store_materialize()` resolves rows with `match()`, which keeps only the + first position per name, while the in-memory mask keeps every duplicate row. + `STlist_to_disk()` records `gene_dup` but does not refuse; only + `validate_store()` raises (`error0067`). Reachable on real 10x data — + duplicated symbols in `features.tsv` are routine, and + `filter_data_stages.R` records that duplicates now pass through silently. The + fix is to raise `error0067` at write time. +- **`distribution_plots(genes=)` matching nothing returns broken plots** rather + than raising `error0090`; the ggplot2 internal `object 'samplename' not found` + only appears at print time. Reachable in memory today, not specific to the + store. +- **`plot_spatial_expression()` has no `assert_transformed()`** while + `plot_spatial_geneset()` does, so the two `STplot` paths give different + messages on an untransformed STlist. +- **`setValidity()` skips a backed STlist** — its guard requires a matrix, so a + manifest bypasses the gene/spot-name and `spatial_meta`-row-count checks that + `x[i]` would otherwise catch. +- **`@misc$store` has no branch in `bl_compare_stlist()`**, so adding a backed + step to `bl_pipeline()` would trip the `misc_uncompared_keys` guard. It embeds + tempdir paths and mtimes, so it needs a normalizer rather than a comparison. diff --git a/tests/testthat/test-STplot_interpolation.R b/tests/testthat/test-STplot_interpolation.R new file mode 100644 index 0000000..6b4a678 --- /dev/null +++ b/tests/testthat/test-STplot_interpolation.R @@ -0,0 +1,97 @@ +## +# STplot_interpolation(): the default (no-argument) call, and its kriging +# prerequisite. +# +# Regression coverage for a defect that made the documented default unusable: +# `stop("Please, enter one or more genes to plot.")` ran *before* the branch that +# resolves `genes='top'`, so calling the function without `genes` -- exactly what +# ?STplot_interpolation shows, and what its own @param documents as "If 'top'" +# -- always failed. The gitignored golden tier only ever called it with explicit +# gene names, so nothing caught it. +# +# The synthetic fixtures make these offline and deterministic. + +.sti_fixture <- function() { + set.seed(20260115) + fx <- fixture_write_list_dfs(fixture_base_data()) + st <- STlist(rnacounts = fx$rnacounts, spotcoords = fx$spotcoords, + cores = 1, verbose = FALSE) + st <- suppressWarnings(filter_data(st, gene_minreads = 0, spot_minreads = 0)) + transform_data(st, method = "log", cores = 1) +} + +.sti_kriged <- function(top_n = 3) { + st <- .sti_fixture() + ## Kriging on the small fixture emits variogram-fit warnings; this file tests + ## STplot_interpolation(), not gene_interpolation(). + suppressWarnings( + suppressMessages(gene_interpolation(st, genes = "top", top_n = top_n, + cores = 1, verbose = FALSE)) + ) +} + +testthat::test_that("STplot_interpolation() errors clearly before kriging has run", { + st <- .sti_fixture() + + ## Used to fail later on an empty color scale, or produce +/-Inf. + testthat::expect_error( + STplot_interpolation(st), + "spatialGE exception.*STplot_interpolation.*gene_interpolation" + ) +}) + +testthat::test_that("STplot_interpolation() works with no `genes` argument", { + ## The headline regression: this call used to always error. + st <- .sti_kriged() + + plots <- STplot_interpolation(st) + + testthat::expect_true(length(plots) > 0) + testthat::expect_s3_class(plots[[1]], "ggplot") +}) + +testthat::test_that("genes=NULL and genes='top' select the same plots", { + st <- .sti_kriged() + + default_plots <- STplot_interpolation(st, top_n = 3) + top_plots <- STplot_interpolation(st, genes = "top", top_n = 3) + + testthat::expect_equal(length(default_plots), length(top_plots)) +}) + +testthat::test_that("STplot_interpolation() still accepts explicit gene names", { + st <- .sti_kriged() + genes <- utils::head(names(st@gene_krige), 2) + + plots <- STplot_interpolation(st, genes = genes) + + testthat::expect_true(length(plots) > 0) +}) + +testthat::test_that("STplot_interpolation() warns and plots the rest when a named gene was not kriged", { + st <- .sti_kriged() + present <- utils::head(names(st@gene_krige), 1) + + testthat::expect_warning( + plots <- STplot_interpolation(st, genes = c(present, "NoSuchKrigedGene")), + "No kriging results for: NoSuchKrigedGene" + ) + testthat::expect_true(length(plots) > 0) +}) + +testthat::test_that("STplot_interpolation() errors clearly when no named gene was kriged", { + st <- .sti_kriged() + + testthat::expect_error( + STplot_interpolation(st, genes = "NoSuchKrigedGene"), + "spatialGE exception.*STplot_interpolation.*gene_interpolation" + ) +}) + +testthat::test_that("a default 'top' request does not warn about genes that were never kriged", { + ## top_n here is independent of the top_n used at kriging time, so asking for + ## more genes than were interpolated is expected rather than a user error. + st <- .sti_kriged(top_n = 2) + + testthat::expect_no_warning(STplot_interpolation(st, top_n = 50)) +}) diff --git a/tests/testthat/test-error-catalog.R b/tests/testthat/test-error-catalog.R new file mode 100644 index 0000000..687b92c --- /dev/null +++ b/tests/testthat/test-error-catalog.R @@ -0,0 +1,117 @@ +## +# Error-catalog consistency. +# +# Every user-facing validation error in the package is supposed to be raised +# through raise_err(), so that it (a) carries the same "spatialGE exception:" +# signature a caller can pattern-match on, and (b) has its wording stored in +# inst/err.csv rather than inline at the call site. That was not true before: +# ~30 sites used a bare stop(), five of them for the identical condition +# ("Could not recognize number of cores requested"), and three sites hardcoded a +# "spatialGE exception:" string by hand instead of using the catalog. +# +# These tests cover the shared machinery and pin a representative error from each +# family, so a new bare stop() in one of them is caught. + +.ec_fixture <- function(transformed = TRUE) { + set.seed(20260115) + fx <- fixture_write_list_dfs(fixture_base_data()) + st <- suppressWarnings(suppressMessages( + STlist(rnacounts = fx$rnacounts, spotcoords = fx$spotcoords, + cores = 1, verbose = FALSE) + )) + if (transformed) { + st <- suppressWarnings(suppressMessages( + transform_data(st, method = "log", cores = 1) + )) + } + st +} + +# The error a call raises, or NA if it does not raise. +.err_of <- function(expr) { + tryCatch({ expr; NA_character_ }, error = function(e) conditionMessage(e)) +} + +testthat::test_that("every code in err.csv is unique and resolvable", { + db <- suppressWarnings(utils::read.csv( + system.file("err.csv", package = "spatialGE"), + header = FALSE, quote = "'")) + + testthat::expect_gt(nrow(db), 50) + ## Duplicate codes would make raise_err() return a length-2 vector, which the + ## guard turns into an "unknown error code" report -- so catch them here. + testthat::expect_identical(anyDuplicated(db[[1]]), 0L) + testthat::expect_false(any(is.na(db[[2]]))) + ## read.csv(quote = "'") means an apostrophe inside a message would terminate + ## the field early and silently corrupt that entry. + testthat::expect_false(any(grepl("'", db[[2]], fixed = TRUE))) +}) + +testthat::test_that("raise_err() names an unknown code instead of failing obscurely", { + ## Previously the lookup returned character(0) and stop(character(0)) failed + ## with "argument is of length zero", naming neither the code nor the cause. + msg <- .err_of(raise_err(err_code = "error9999")) + testthat::expect_match(msg, "unknown error code error9999") + + msg_null <- .err_of(raise_err()) + testthat::expect_match(msg_null, "unknown error code ") +}) + +testthat::test_that("raise_err() interpolates formatted messages", { + msg <- .err_of(raise_err(err_code = "error0073", samplename = NULL, + "GeneA, GeneB")) + testthat::expect_match(msg, "spatialGE exception") + testthat::expect_match(msg, "GeneA, GeneB") + + ## samplename is appended after the formatted text. + msg2 <- .err_of(raise_err(err_code = "error0070", samplename = "alpha")) + testthat::expect_match(msg2, "Sample: alpha\\.") +}) + +testthat::test_that("user-facing validation errors carry the spatialGE signature", { + st <- .ec_fixture() + + ## One representative site from each family that used a bare stop() before. + sites <- list( + "SThet(genes=NULL)" = function() SThet(st, genes = NULL), + "STdiff(pairwise bad)" = function() STdiff(st, annot = NULL), + "STclust(w out of range)" = function() STclust(st, ws = 5), + "gene_interpolation(NULL)" = function() gene_interpolation(st, genes = NULL) + ) + + for (nm in names(sites)) { + msg <- .err_of(sites[[nm]]()) + testthat::expect_false(is.na(msg), label = paste(nm, "did not error")) + testthat::expect_match(msg, "^spatialGE exception:", label = nm) + } +}) + +testthat::test_that("resolve_cores() rejects an unusable core count in one place", { + ## Previously the caller checked, and did so inconsistently: some sites raised + ## error0032/error0036, five used a bare stop(), and transform_data()'s + ## gene_meta path did not check at all, passing NA straight to sge_lapply(). + for (bad in list("abc", NA, 0, -1)) { + msg <- .err_of(resolve_cores(10, bad)) + testthat::expect_match(msg, "spatialGE exception") + testthat::expect_match(msg, "number of cores") + } + + ## Valid requests must still resolve. + testthat::expect_equal(resolve_cores(10, cores = 2), 2L) +}) + +testthat::test_that("resolve_cores() preserves the caller's coercion", { + ## Fidelity rule: coerce='ceiling' and 'none' deliberately keep a non-integral + ## value, because consumers that are not mclapply depend on it surviving. The + ## centralised guard must validate without coercing. + testthat::expect_identical(resolve_cores(10, cores = 2.5, coerce = "ceiling"), 3) + testthat::expect_identical(resolve_cores(10, cores = 2.5, coerce = "none"), 2.5) +}) + +testthat::test_that("a bad cores= value fails cleanly at a call site, not as NA", { + st <- .ec_fixture(transformed = FALSE) + + ## transform_data()'s gene_meta path was the unguarded one. + msg <- .err_of(transform_data(st, method = "log", cores = "abc")) + testthat::expect_match(msg, "^spatialGE exception:.*number of cores") +}) diff --git a/tests/testthat/test-filter_data.R b/tests/testthat/test-filter_data.R index 5dc7553..fd823b3 100644 --- a/tests/testthat/test-filter_data.R +++ b/tests/testthat/test-filter_data.R @@ -23,3 +23,50 @@ testthat::test_that("filter_stage_genes_expr removes matching genes from gene_me testthat::expect_equal(nrow(st_filtered@gene_meta[[s]]), nrow(st@gene_meta[[s]]) - 1) } }) + + +## +# filter_data() reporting. +# +# Every count threshold defaults to 0 (and the *_max* thresholds to NULL), so a +# call that supplies none of them filters nothing -- which previously looked like +# a successful filter. verbose=TRUE now says so explicitly, and otherwise reports +# what was removed. + +.fd_fixture <- function() { + f <- fixtures$list_dfs + suppressWarnings(suppressMessages( + STlist(rnacounts = f$rnacounts, spotcoords = f$spotcoords, + cores = 1, verbose = FALSE) + )) +} + +testthat::test_that("filter_data() says so when a call filters nothing", { + st <- .fd_fixture() + + testthat::expect_message( + out <- filter_data(st, verbose = TRUE), + "nothing was filtered" + ) + ## And it really is a pass-through. + testthat::expect_equal(lapply(out@counts, dim), lapply(st@counts, dim)) +}) + +testthat::test_that("filter_data() reports how much it removed", { + st <- .fd_fixture() + ## A threshold high enough to drop at least one spot from the fixture. + cutoff <- stats::quantile(Matrix::colSums(st@counts[[1]]), 0.9) + + testthat::expect_message( + out <- filter_data(st, spot_minreads = cutoff, verbose = TRUE), + "removed .* sample\\(s\\), .* spot\\(s\\)/cell\\(s\\) and .* gene\\(s\\)" + ) + testthat::expect_lt(ncol(out@counts[[1]]), ncol(st@counts[[1]])) +}) + +testthat::test_that("filter_data(verbose=FALSE) is silent", { + st <- .fd_fixture() + + testthat::expect_silent(suppressWarnings(filter_data(st, verbose = FALSE))) +}) + diff --git a/tests/testthat/test-graceful-errors.R b/tests/testthat/test-graceful-errors.R index 06f8fee..57527cd 100644 --- a/tests/testthat/test-graceful-errors.R +++ b/tests/testthat/test-graceful-errors.R @@ -173,6 +173,28 @@ testthat::test_that("STenrich requires annot and domain together", { cores = 1, verbose = FALSE)) }) +testthat::test_that("the on-disk backing never reports a present gene as absent", { + ## The other half of the rule: silently accepting bad state, or silently + ## answering nothing, is worse than an error because the caller believes it + ## worked. All three defects this pins were that half rather than the error + ## half -- show()/summary() printed blank dimensions, distribution_plots() + ## messaged every gene as absent and then returned plots that failed only when + ## printed, and STplot() stopped with "Data was not found in the specified + ## slot" about data that was right there. + ## + ## A manifest answers rownames()/nrow() with NULL rather than erroring, so any + ## read that leaves the accessors in R/utils_accessors.R fails this way by + ## default. That is why this is a class guard and not three separate tests. + st <- ge_fixture() + bk <- STlist_to_disk(st, file.path(tempdir(), paste0("sge-ge-", as.integer(runif(1, 1, 1e6)))), + overwrite = TRUE) + + testthat::expect_no_warning(STplot(bk, genes = "Gene1")) + testthat::expect_no_message(distribution_plots(bk, genes = "Gene1")) + testthat::expect_false(any(grepl("( ROIs|spots|cells x genes)", + capture.output(methods::show(bk)), fixed = TRUE))) +}) + testthat::test_that("no user-facing failure leaks an internal variable name", { st <- ge_fixture() stu <- ge_fixture(transformed = FALSE) @@ -199,3 +221,53 @@ testthat::test_that("no user-facing failure leaks an internal variable name", { testthat::expect_match(msg, "spatialGE exception") } }) + +testthat::test_that("STdiff rejects a numeric annotation with an actionable message", { + ## `annot` is documented as "a column name ... containing the groups/clusters + ## to test", but a perfectly ordinary numeric metadata column (total_counts, + ## survival_months) used to surface only much later, from dplyr: + ## Can't join `x$orig_annot` with `y$orig_annot` due to incompatible types. + ## i `x$orig_annot` is a + ## which names neither STdiff nor the argument to change. + st <- ge_fixture() + acol <- "num_annot" + for (s in names(st@spatial_meta)) { + st@spatial_meta[[s]][[acol]] <- seq_len(nrow(st@spatial_meta[[s]])) + } + + testthat::expect_error( + STdiff(st, annot = acol, topgenes = 5, test_type = "t_test", + cores = 1, verbose = FALSE), + "spatialGE exception.*STdiff.*character or factor" + ) +}) + +testthat::test_that("STdiff rejects an annotation with a single group", { + st <- ge_fixture() + acol <- "one_group" + for (s in names(st@spatial_meta)) { + st@spatial_meta[[s]][[acol]] <- "only" + } + + testthat::expect_error( + STdiff(st, annot = acol, topgenes = 5, test_type = "t_test", + cores = 1, verbose = FALSE), + "spatialGE exception.*STdiff.*at least two distinct groups" + ) +}) + +testthat::test_that("STdiff still accepts a character annotation", { + ## The guard above must not reject the normal case. + st <- ge_fixture() + acol <- "char_annot" + for (s in names(st@spatial_meta)) { + st@spatial_meta[[s]][[acol]] <- rep(c("a", "b"), length.out = nrow(st@spatial_meta[[s]])) + } + + res <- suppressWarnings( + STdiff(st, annot = acol, topgenes = 5, test_type = "t_test", + cores = 1, verbose = FALSE) + ) + + testthat::expect_true(is.list(res)) +}) diff --git a/tests/testthat/test-load_images.R b/tests/testthat/test-load_images.R new file mode 100644 index 0000000..133c1aa --- /dev/null +++ b/tests/testthat/test-load_images.R @@ -0,0 +1,119 @@ +## +# load_images(): image-to-sample wiring. +# +# Regression coverage for the previously-untested paths. `load_images()` had no +# committed test references at all -- the only exercise was in the gitignored, +# CI-not-run golden tier, which passed a *single directory* whose files were +# named exactly `.png`. That combination hid two defects: +# +# 1. `if(length(images) == 1 & dir.exists(images))` used the vectorized `&`, +# so passing more than one path -- which is what the function's own error +# message tells users to do -- failed with "the condition has length > 1". +# 2. Image decoding was chosen from the file extension only, so a mislabelled +# image produced an opaque decoder error naming no file. +# +# These tests use the synthetic fixtures, so they are offline and deterministic. + +.img_test_stlist <- function() { + f <- fixtures$list_dfs + STlist(rnacounts = f$rnacounts, spotcoords = f$spotcoords, cores = 1) +} + +.img_test_samples <- function() fixtures$base$samples + +## Writes one small PNG per sample into `dir`, named `.png`. +.img_test_write <- function(dir, samples = .img_test_samples(), ext = "png") { + dir.create(dir, showWarnings = FALSE, recursive = TRUE) + for (s in samples) fixture_write_image(file.path(dir, paste0(s, ".", ext))) + dir +} + +testthat::test_that("load_images() accepts a single directory", { + st <- .img_test_stlist() + d <- .img_test_write(file.path(tempdir(), "li-dir")) + + out <- load_images(st, images = d) + + testthat::expect_s4_class(out, "STlist") + testthat::expect_setequal(names(out@misc$sp_images), .img_test_samples()) +}) + +testthat::test_that("load_images() accepts a vector of file paths", { + ## Regression: this used to fail with "the condition has length > 1". + st <- .img_test_stlist() + d <- .img_test_write(file.path(tempdir(), "li-vec")) + paths <- file.path(d, paste0(.img_test_samples(), ".png")) + + testthat::expect_length(paths, length(.img_test_samples())) + out <- load_images(st, images = paths) + + testthat::expect_setequal(names(out@misc$sp_images), .img_test_samples()) +}) + +testthat::test_that("load_images() accepts several directories in one call", { + ## The SMI vignette needs images from two per-slide folders; previously that + ## required one call per folder. + st <- .img_test_stlist() + samples <- .img_test_samples() + d1 <- .img_test_write(file.path(tempdir(), "li-multi-1"), samples[1]) + d2 <- .img_test_write(file.path(tempdir(), "li-multi-2"), samples[-1]) + + out <- load_images(st, images = c(d1, d2)) + + testthat::expect_setequal(names(out@misc$sp_images), samples) +}) + +testthat::test_that("load_images() warns, naming the sample, when no image matches", { + ## e.g. Visium exports that name images after a GEO accession rather than the + ## sample folder: "GSM6433585_092A_tissue_hires_image.png" vs "sample_092a". + st <- .img_test_stlist() + d <- file.path(tempdir(), "li-unmatched") + dir.create(d, showWarnings = FALSE, recursive = TRUE) + fixture_write_image(file.path(d, "GSM0000000_notasample_tissue_hires_image.png")) + + testthat::expect_warning( + out <- load_images(st, images = d), + "No image found for sample" + ) + testthat::expect_length(out@misc$sp_images, 0) +}) + +testthat::test_that("load_images() honours an explicit sample -> file mapping", { + ## The escape hatch for filenames that do not resemble the sample names. + st <- .img_test_stlist() + samples <- .img_test_samples() + d <- file.path(tempdir(), "li-named") + dir.create(d, showWarnings = FALSE, recursive = TRUE) + files <- file.path(d, paste0("GSM000", seq_along(samples), "_image.png")) + for (fp in files) fixture_write_image(fp) + + mapping <- stats::setNames(files, samples) + out <- load_images(st, images = mapping) + + testthat::expect_setequal(names(out@misc$sp_images), samples) +}) + +testthat::test_that("load_images() loads an image whose extension is wrong", { + ## Decoding falls back to the other codec instead of trusting the extension. + st <- .img_test_stlist() + d <- .img_test_write(file.path(tempdir(), "li-mislabelled"), ext = "jpg") + + out <- testthat::expect_silent(load_images(st, images = d)) + + testthat::expect_setequal(names(out@misc$sp_images), .img_test_samples()) +}) + +testthat::test_that("load_images() errors clearly when given no usable image", { + st <- .img_test_stlist() + + testthat::expect_error( + load_images(st, images = file.path(tempdir(), "li-does-not-exist.png")), + "existing .png, .jpg or .jpeg" + ) +}) + +testthat::test_that("load_images() still requires an `images` argument", { + st <- .img_test_stlist() + + testthat::expect_error(load_images(st), "provide a vector with images file paths") +}) diff --git a/tests/testthat/test-stlist_subset.R b/tests/testthat/test-stlist_subset.R new file mode 100644 index 0000000..be19bd7 --- /dev/null +++ b/tests/testthat/test-stlist_subset.R @@ -0,0 +1,164 @@ +## +# STlist subsetting and length. +# +# Before this, an STlist could not be subset at all: `st[1]` failed with +# "object of type 'S4' is not subsettable", so there was no way to pull one +# sample out of a multi-sample object and carry on working with it -- the only +# route was to rebuild an STlist from the raw files. `length()` did not exist +# either, so seq_along()/seq_len(length(x)) idioms silently used length 0. +# +# Subsetting has to keep four sample-keyed slots in step with @counts +# (@spatial_meta, @gene_meta, @tr_counts and the per-sample level of +# @gene_krige) plus align @sample_meta rows. Getting that wrong is exactly the +# kind of thing setValidity() now catches, so every result here is also checked +# with validObject(). + +.ss_fixture <- function(transformed = FALSE) { + set.seed(20260115) + fx <- fixture_write_list_dfs(fixture_base_data()) + st <- suppressWarnings(suppressMessages( + STlist(rnacounts = fx$rnacounts, spotcoords = fx$spotcoords, + cores = 1, verbose = FALSE) + )) + if (transformed) { + st <- suppressWarnings(suppressMessages( + transform_data(st, method = "log", cores = 1) + )) + } + st +} + +testthat::test_that("length() reports the number of spatial arrays", { + st <- .ss_fixture() + + testthat::expect_identical(length(st), length(names(st@counts))) + ## The idiom this enables. + testthat::expect_length(seq_len(length(st)), length(names(st@counts))) +}) + +testthat::test_that("x[i] subsets samples by name, position and logical", { + st <- .ss_fixture() + sn <- names(st@counts) + testthat::expect_gt(length(sn), 1) + + by_name <- st[sn[2]] + testthat::expect_s4_class(by_name, "STlist") + testthat::expect_identical(names(by_name@counts), sn[2]) + testthat::expect_true(validObject(by_name)) + + ## A single-sample result is now genuinely matrix-like. + testthat::expect_identical(dim(by_name), c(nrow(st@counts[[sn[2]]]), ncol(st@counts[[sn[2]]]))) + + testthat::expect_identical(names(st[c(sn[3], sn[1])]@counts), c(sn[3], sn[1])) + testthat::expect_identical(names(st[seq_len(2)]@counts), sn[seq_len(2)]) + testthat::expect_identical(names(st[-1]@counts), sn[-1]) + + logical_i <- rep(FALSE, length(sn)); logical_i[2] <- TRUE + testthat::expect_identical(names(st[logical_i]@counts), sn[2]) +}) + +testthat::test_that("subsetting keeps every sample-keyed slot in step", { + st <- .ss_fixture(transformed = TRUE) + sn <- names(st@counts) + + sub <- st[c(sn[3], sn[1])] + + testthat::expect_true(validObject(sub)) + for (slot_name in c("counts", "spatial_meta", "gene_meta", "tr_counts")) { + testthat::expect_identical(names(methods::slot(sub, slot_name)), c(sn[3], sn[1]), + label = paste0("@", slot_name)) + } + ## Values must be untouched, not merely renamed. + testthat::expect_equal(sub@tr_counts[[1]], st@tr_counts[[sn[3]]], tolerance = 0) + testthat::expect_identical(nrow(sub@gene_meta[[1]]), nrow(st@gene_meta[[sn[3]]])) +}) + +testthat::test_that("subsetting aligns @sample_meta with the selected samples", { + st <- .ss_fixture() + sn <- names(st@counts) + + ## The identifying column is not fixed: STlist() uses 'sample_name' for list + ## input, while a clinical CSV keeps its own header (the Thrane data uses + ## 'sampleID'). Match on the first column, which is what show() treats as the + ## sample identifier. + testthat::expect_identical(nrow(st@sample_meta), length(sn)) + + sub <- st[c(sn[3], sn[1])] + + testthat::expect_identical(nrow(sub@sample_meta), 2L) + testthat::expect_identical(as.character(sub@sample_meta[[1]]), c(sn[3], sn[1])) +}) + +testthat::test_that("an unknown sample name is an error that lists the alternatives", { + st <- .ss_fixture() + sn <- names(st@counts) + + testthat::expect_error( + st["NoSuchSample"], + "spatialGE exception.*unknown sample name" + ) + ## And it names what is available, rather than just refusing. + msg <- tryCatch(st["NoSuchSample"], error = function(e) conditionMessage(e)) + testthat::expect_match(msg, sn[1], fixed = TRUE) +}) + +testthat::test_that("invalid selections are rejected rather than silently recycled", { + st <- .ss_fixture() + + ## A short logical vector would recycle and select the wrong samples. + testthat::expect_error(st[c(TRUE, FALSE)], "spatialGE exception") + ## Out of range must not silently return a shorter object. + testthat::expect_error(st[99], "spatialGE exception") + ## Selecting nothing is not a useful STlist. + testthat::expect_error(st[rep(FALSE, length(st))], "spatialGE exception") + ## An unsupported index type. + testthat::expect_error(st[list(1)], "spatialGE exception") +}) + +testthat::test_that("two-dimensional subsetting explains why it is unsupported", { + st <- .ss_fixture() + + ## An STlist holds several arrays with independent gene/spot sets, so there is + ## no shared second dimension. Say that instead of failing generically. + testthat::expect_error(st[1, 1], "one-dimensional") + ## [[ is not a sample accessor either. + testthat::expect_error(st[[1]], "spatialGE exception") +}) + +testthat::test_that("validObject() accepts an object with kriging results", { + ## Regression: setValidity() originally listed @gene_krige among the + ## sample-keyed slots and compared its names to the sample names. But + ## @gene_krige is keyed by GENE first (x@gene_krige[[gene]][[sample]]), so + ## every kriged object was reported invalid. It went unnoticed because slot + ## assignment via `@<-` does not run validity, so gene_interpolation() + ## succeeded and only a later validObject() (or new()) failed. + st <- .ss_fixture(transformed = TRUE) + sn <- names(st@counts) + + st@gene_krige <- list( + GeneA = stats::setNames(lapply(sn, function(s) list(success_or_not = "ok")), sn) + ) + + testthat::expect_true(validObject(st)) +}) + +testthat::test_that("subsetting filters kriging results to the kept samples", { + st <- .ss_fixture(transformed = TRUE) + sn <- names(st@counts) + + st@gene_krige <- list( + GeneA = stats::setNames(lapply(sn, function(s) list(krige_out = s)), sn), + GeneB = stats::setNames(lapply(sn, function(s) list(krige_out = s)), sn) + ) + + sub <- st[sn[1]] + + testthat::expect_true(validObject(sub)) + ## Genes survive (kriging is per gene) ... + testthat::expect_setequal(names(sub@gene_krige), c("GeneA", "GeneB")) + ## ... but only the kept sample remains within each. + for (g in names(sub@gene_krige)) { + testthat::expect_identical(names(sub@gene_krige[[g]]), sn[1]) + } + testthat::expect_identical(sub@gene_krige$GeneA[[sn[1]]]$krige_out, sn[1]) +}) diff --git a/tests/testthat/test-stlist_validity.R b/tests/testthat/test-stlist_validity.R new file mode 100644 index 0000000..96fc692 --- /dev/null +++ b/tests/testthat/test-stlist_validity.R @@ -0,0 +1,106 @@ +## +# STlist class contract: dim() and validity. +# +# `dim()` used to return a *named list* of per-sample dimensions, which violates +# the base R contract (dim() must return an integer vector or NULL). It made +# nrow()/ncol() meaningless on an STlist and was reported by R CMD check as +# "dim() returns class 'list'". Nothing in the package or its tests called it, so +# nothing caught it. +# +# The class also had no setValidity(), so a malformed STlist could be constructed +# freely and failed later, far from the cause. + +.sv_fixture <- function() { + set.seed(20260115) + fx <- fixture_write_list_dfs(fixture_base_data()) + suppressWarnings(suppressMessages( + STlist(rnacounts = fx$rnacounts, spotcoords = fx$spotcoords, + cores = 1, verbose = FALSE) + )) +} + +testthat::test_that("dim() returns an integer vector for a single-sample STlist", { + st <- .sv_fixture() + one <- new("STlist", + counts = st@counts[1], + spatial_meta = st@spatial_meta[1], + gene_meta = list(), + sample_meta = st@sample_meta, + tr_counts = list(), + gene_krige = list(), + misc = st@misc) + + d <- dim(one) + + testthat::expect_type(d, "integer") + testthat::expect_length(d, 2) + testthat::expect_identical(d, c(nrow(st@counts[[1]]), ncol(st@counts[[1]]))) +}) + +testthat::test_that("dim() returns NULL (not a list) for a multi-sample STlist", { + ## Regression: this used to be a named list, e.g. list(alpha = c(G, n), ...). + st <- .sv_fixture() + testthat::expect_gt(length(st@counts), 1) + + d <- dim(st) + + testthat::expect_null(d) + ## The base contract, stated directly: nrow()/ncol() must not return a list. + testthat::expect_false(is.list(nrow(st))) + testthat::expect_null(nrow(st)) +}) + +testthat::test_that("a normally-built STlist is valid", { + st <- .sv_fixture() + + testthat::expect_true(validObject(st)) +}) + +testthat::test_that("an STlist stays valid through transform_data()", { + ## Zero-count spots are dropped from both @counts and @spatial_meta, so the + ## two must remain in step. + st <- .sv_fixture() + suppressWarnings(suppressMessages( + st <- transform_data(st, method = "log", cores = 1) + )) + + testthat::expect_true(validObject(st)) +}) + +testthat::test_that("setValidity rejects a spatial_meta/counts size mismatch", { + st <- .sv_fixture() + s <- names(st@counts)[1] + st@spatial_meta[[s]] <- st@spatial_meta[[s]][-1, , drop = FALSE] + + testthat::expect_error(validObject(st), "rows but the count matrix has") +}) + +testthat::test_that("setValidity rejects a sample-keyed slot for an unknown sample", { + st <- .sv_fixture() + st@gene_meta <- list(ghost = data.frame(gene = "x")) + + testthat::expect_error(validObject(st), "samples not in @counts") +}) + +testthat::test_that("setValidity rejects a count matrix without spot names", { + st <- .sv_fixture() + colnames(st@counts[[1]]) <- NULL + + testthat::expect_error(validObject(st), "spot/cell \\(column\\) names") +}) + +testthat::test_that("setValidity rejects a spatial_meta that is not a data.frame", { + st <- .sv_fixture() + s <- names(st@counts)[1] + st@spatial_meta[[s]] <- as.matrix(st@spatial_meta[[s]]) + + testthat::expect_error(validObject(st), "must be a data.frame") +}) + +testthat::test_that("setValidity rejects spatial_meta without libname", { + st <- .sv_fixture() + s <- names(st@counts)[1] + st@spatial_meta[[s]][["libname"]] <- NULL + + testthat::expect_error(validObject(st), "libname") +}) diff --git a/tests/testthat/test-store_parquet.R b/tests/testthat/test-store_parquet.R index e6c4a94..3bc8c1e 100644 --- a/tests/testthat/test-store_parquet.R +++ b/tests/testthat/test-store_parquet.R @@ -21,6 +21,17 @@ backed_fixture <- function(st, name = "store"){ STlist_to_disk(st, root, overwrite = TRUE) } +## Compare what a plot RENDERS, not the object graph -- environments and ggplot +## internals are noisy and non-substantive. Some geoms (ggforce::geom_sina, the +## plot_type='violin' default) draw fresh jitter inside ggplot_build() itself +## rather than when the object is constructed, so two independently built plots +## differ even when the upstream data is identical. Re-seeding before each build +## is how dev/baseline/compare_baseline.R handles the same problem. +built_data <- function(p){ + set.seed(20260115) + lapply(ggplot2::ggplot_build(p)$data, as.data.frame) +} + testthat::test_that("STlist_to_disk writes one file per sample per populated slot", { st <- store_fixture() bk <- backed_fixture(st) @@ -131,6 +142,105 @@ testthat::test_that("analyses give identical results backed and in memory", { testthat::expect_identical(summarize_STlist(bk), summarize_STlist(st)) }) +testthat::test_that("show() and summary() report real dimensions when backed", { + st <- store_fixture() + bk <- backed_fixture(st) + + ## Printing the object is the first thing anyone does with it, and this was the + ## silent-wrong-answer case rather than an error: nrow()/ncol() return NULL on a + ## manifest and paste0() renders a zero-length argument as "", so an unrouted + ## dim read printed "alpha ( ROIs|spots|cells x genes)" with no warning at all. + testthat::expect_identical(capture.output(methods::show(bk)), + capture.output(methods::show(st))) + testthat::expect_identical(capture.output(summary(bk)), + capture.output(summary(st))) + + ## ...and the numbers are the real ones, which an identity check alone would not + ## catch -- two blank renderings are also identical to each other. + expected <- sprintf("\talpha (%d ROIs|spots|cells x %d genes)", + ncol(st@counts[["alpha"]]), nrow(st@counts[["alpha"]])) + testthat::expect_true(any(capture.output(methods::show(bk)) == expected)) +}) + +testthat::test_that("STplot(genes=) works on a backed STlist and matches in memory", { + st <- store_fixture() + bk <- backed_fixture(st) + genes <- c("Gene1", "GradGene1") + + ## plot_spatial_expression() took a list slice of the slot and then tested + ## rownames() on it, which is NULL on a manifest -- so every sample fell to the + ## "none of the requested genes are available" branch and the function died + ## naming the slot rather than the real cause. The gene-SET path + ## (plot_spatial_geneset) already read through the accessors, so the two STplot + ## entry points disagreed about the same object. + a <- STplot(st, genes = genes, data_type = "tr") + b <- STplot(bk, genes = genes, data_type = "tr") + + ## Panel keys are built in MATRIX gene order, not in the order the caller asked + ## for (fidelity rule 9), so this also pins that the accessor's two gene-subset + ## mechanisms -- a logical mask in memory, sorted match() positions on disk -- + ## agree on order and not merely on content. + testthat::expect_identical(names(b), names(a)) + for(nm in names(a)){ + testthat::expect_identical(built_data(b[[nm]]), built_data(a[[nm]]), + label = paste("STplot panel", nm)) + } + + ## The raw slot takes the other branch of the data_type switch. + ra <- STplot(st, genes = genes, data_type = "raw") + rb <- STplot(bk, genes = genes, data_type = "raw") + testthat::expect_identical(names(rb), names(ra)) + testthat::expect_identical(built_data(rb[[1]]), built_data(ra[[1]])) + + ## A gene that really is absent must still drop the sample, warn once per + ## sample, and then stop. That branch is what made the bug look like an + ## ordinary "gene not found", so it has to keep behaving identically. + testthat::expect_error(suppressWarnings(STplot(bk, genes = "NoSuchGene")), + "Data was not found in the specified slot") + w <- testthat::capture_warnings(try(STplot(bk, genes = "NoSuchGene"), silent = TRUE)) + testthat::expect_length(w, length(tissue_names(bk))) + testthat::expect_true(all(grepl("None of the requested genes are available for sample", w))) +}) + +testthat::test_that("distribution_plots(genes=) works on a backed STlist and matches in memory", { + st <- store_fixture() + bk <- backed_fixture(st) + genes <- c("Gene1", "GradGene1") + + ## gene_plots() read the whole slot and tested rownames(expr_tmp[[i]]), so on a + ## backed object EVERY gene was reported absent in EVERY sample. Quieter than + ## the STplot case and worse for it: the function returned normally, having + ## messaged its way to an empty df_tmp, and the plots it handed back failed only + ## when something tried to print them. + a <- distribution_plots(st, genes = genes, data_type = "tr") + b <- testthat::expect_no_message(distribution_plots(bk, genes = genes, data_type = "tr")) + + testthat::expect_identical(names(b), names(a)) + for(nm in names(a)){ + testthat::expect_identical(built_data(b[[nm]]), built_data(a[[nm]]), + label = paste("distribution_plots panel", nm)) + } + + ## The raw slot takes the other branch of the data_type switch. + testthat::expect_identical( + built_data(distribution_plots(bk, genes = "Gene1", data_type = "raw")[["Gene1"]]), + built_data(distribution_plots(st, genes = "Gene1", data_type = "raw")[["Gene1"]])) + + ## plot_meta= together with genes= routes through cluster_gene_plots() instead, + ## which carried its own copy of the same unrouted read. + sc <- STclust(st, ws = 0.025, ks = "dtc", deepSplit = FALSE, topgenes = 100, + cores = 1, verbose = FALSE) + sb <- backed_fixture(sc, "clust") + col <- "stclust_spw0.025_dsplFalse" + testthat::expect_identical( + built_data(distribution_plots(sb, plot_meta = col, genes = "Gene1", plot_type = "box")[["Gene1"]]), + built_data(distribution_plots(sc, plot_meta = col, genes = "Gene1", plot_type = "box")[["Gene1"]])) + + ## A gene that genuinely is absent must still message and skip the sample. + testthat::expect_message(distribution_plots(bk, genes = "NoSuchGene"), + "does not contain NoSuchGene") +}) + testthat::test_that("validate_store detects a missing or altered file", { st <- store_fixture() bk <- backed_fixture(st) diff --git a/tests/testthat/test-vst_selection.R b/tests/testthat/test-vst_selection.R new file mode 100644 index 0000000..0e2503e --- /dev/null +++ b/tests/testthat/test-vst_selection.R @@ -0,0 +1,202 @@ +## +# VST (standardized variance) availability and stability. +# +# `gene_meta` used to hold only gene_mean/gene_stdevs after transform_data(); +# `vst.variance.standardized` appeared later, as a side effect of whichever +# analysis ran first (STclust(), gene_interpolation()). transform_data() now +# populates VST itself, so get_gene_meta() shows it regardless of call order. +# +# Two corrections to an earlier version of this comment, both measured: the +# gene_stdevs-vs-VST top-20 overlap is 7-13 across the eight tnbc_bassiouni +# samples (8-11 on this fixture), not 6/20; and the set of genes a function +# *selects* never depended on call order, because STclust(), STgradient(), +# gene_interpolation() and STdiff() each computed VST themselves before ranking. +# What the change fixed is where the column comes from, not what is done with it. +# +# The synthetic fixtures make these offline and deterministic. + +.vst_fixture_raw <- function() { + set.seed(20260115) + fx <- fixture_write_list_dfs(fixture_base_data()) + st <- STlist(rnacounts = fx$rnacounts, spotcoords = fx$spotcoords, + cores = 1, verbose = FALSE) + suppressWarnings(suppressMessages( + filter_data(st, gene_minreads = 0, spot_minreads = 0, verbose = FALSE) + )) +} + +.vst_fixture <- function(method = "log") { + suppressWarnings(suppressMessages( + transform_data(.vst_fixture_raw(), method = method, cores = 1) + )) +} + +.vst_top <- function(x, n = 20) { + gm <- x@gene_meta[[1]] + gm[["gene"]][order(gm[["vst.variance.standardized"]], decreasing = TRUE)][seq_len(n)] +} + +## An STlist with `nvar` varying genes plus `nconst` constant ones, on a 10x10 +## grid. Deliberately tiny: the variance-mean loess cannot be fit below 4 +## non-constant genes. +.vst_tiny_fixture <- function(nvar, nconst = 0) { + set.seed(20260115) + xy <- expand.grid(x = 1:10, y = 1:10) + libs <- paste0("spot", seq_len(nrow(xy))) + rows <- list() + for (i in seq_len(nvar)) rows[[length(rows) + 1L]] <- stats::rpois(nrow(xy), 5 + i) + for (i in seq_len(nconst)) rows[[length(rows) + 1L]] <- rep(3, nrow(xy)) + mtx <- do.call(rbind, rows) + expr <- data.frame(genename = paste0("gene_", seq_len(nrow(mtx))), mtx) + colnames(expr) <- c("genename", libs) + coords <- data.frame(libname = libs, y = xy$y, x = xy$x) + STlist(rnacounts = list(tiny = expr), spotcoords = list(tiny = coords), + cores = 1, verbose = FALSE) +} + +testthat::test_that("transform_data() populates VST for the log method", { + st <- .vst_fixture("log") + + testthat::expect_true( + all(vapply(st@gene_meta, function(g) "vst.variance.standardized" %in% colnames(g), logical(1))) + ) +}) + +testthat::test_that("transform_data() populates VST for the sct method, or fails actionably", { + ## SCTransform computes its own variance statistics, but they were never + ## carried into gene_meta -- so VST had to come from a later analysis. + ## + ## sctransform cannot fit the small synthetic fixture (200 genes x ~120 spots), + ## so this asserts whichever of the two documented outcomes occurs. The + ## populated-VST branch is exercised on real data by dev/xver and the golden + ## tier; what matters here is that a failure is never opaque. + st <- .vst_fixture_raw() + + res <- tryCatch( + suppressWarnings(transform_data(st, method = "sct", cores = 1)), + error = function(e) e + ) + + if (inherits(res, "error")) { + testthat::expect_match(conditionMessage(res), + "spatialGE exception.*sct.*SCTransform") + testthat::expect_match(conditionMessage(res), "sct_n_regr_genes|method='log'") + } else { + testthat::expect_true( + all(vapply(res@gene_meta, + function(g) "vst.variance.standardized" %in% colnames(g), logical(1))) + ) + } +}) + +testthat::test_that("VST is visible through get_gene_meta() without running an analysis", { + st <- .vst_fixture("log") + + testthat::expect_true("vst.variance.standardized" %in% colnames(get_gene_meta(st))) +}) + +testthat::test_that("the mean/stdev columns survive the VST join", { + ## calculate_vst() left-joins onto gene_meta; it must not replace the columns + ## transform_data() just computed. + st <- .vst_fixture("log") + + for (gm in st@gene_meta) { + testthat::expect_true(all(c("gene", "gene_mean", "gene_stdevs", + "vst.variance.standardized") %in% colnames(gm))) + } +}) + +testthat::test_that("STclust() does not change the VST column or the top-gene ranking", { + ## The regression this guards: previously STclust() was what *created* VST, so + ## the genes selected before vs after it could differ. + st <- .vst_fixture("log") + before_cols <- lapply(st@gene_meta, function(g) g[["vst.variance.standardized"]]) + before_top <- .vst_top(st) + + st2 <- suppressWarnings(STclust(st, ws = 0.025, ks = "dtc", deepSplit = FALSE, + cores = 1, verbose = FALSE)) + + testthat::expect_equal(lapply(st2@gene_meta, function(g) g[["vst.variance.standardized"]]), + before_cols) + testthat::expect_identical(.vst_top(st2), before_top) +}) + +testthat::test_that("STdiff() runs on an STlist straight from transform_data()", { + ## No preceding STclust(); VST must already be there. + st <- .vst_fixture("log") + acol <- "test_annot" + st@spatial_meta[[1]][[acol]] <- rep(c("a", "b"), length.out = nrow(st@spatial_meta[[1]])) + + res <- suppressWarnings(STdiff(st, annot = acol, topgenes = 5, + test_type = "t_test", cores = 1, verbose = FALSE)) + + testthat::expect_true(is.list(res)) +}) + +testthat::test_that("stdiff_ensure_vst() is idempotent and delegates to calculate_vst()", { + st <- .vst_fixture("log") + once <- stdiff_ensure_vst(st) + twice <- stdiff_ensure_vst(once) + + testthat::expect_equal(once@gene_meta, twice@gene_meta) +}) + +testthat::test_that("transform_data() warns and skips VST when too few genes vary", { + ## Populating VST here means transform_data() now fits a loess ACROSS GENES, + ## which has a minimum data requirement the rest of the function does not: at + ## span=0.3 it needs 4 non-constant genes, and below that stats::loess stops + ## with 'span is too small'. That made transform_data() fail on an STlist it + ## handled in 1.2.2. The simulated 3-gene example in + ## basic_functions_vignette.Rmd is exactly this case, which is how it was + ## found -- the vignette could no longer be built. + st <- .vst_tiny_fixture(nvar = 3) + + w <- testthat::capture_warnings(st <- transform_data(st, cores = 1)) + testthat::expect_true(any(grepl("non-zero variance", w))) + testthat::expect_true(any(grepl("tiny", w))) # names the sample + + ## The transformation itself, which is what the caller asked for, succeeded. + testthat::expect_false(rlang::is_empty(st@tr_counts)) + testthat::expect_identical(dim(st@tr_counts[["tiny"]]), dim(st@counts[["tiny"]])) + testthat::expect_true(all(c("gene_mean", "gene_stdevs") %in% colnames(st@gene_meta[["tiny"]]))) + + ## ...and the column that could not be fit is absent rather than zero-filled. + ## calculate_vst() only computes when it is missing, so a later analysis + ## retries instead of inheriting a meaningless value. + testthat::expect_false("vst.variance.standardized" %in% colnames(st@gene_meta[["tiny"]])) + + ## SThet() does not use VST, so the vignette's actual goal still works. + st <- SThet(st, genes = paste0("gene_", 1:3), method = "moran", cores = 1, verbose = FALSE) + testthat::expect_true("moran_i" %in% colnames(get_gene_meta(st, sthet_only = TRUE))) +}) + +testthat::test_that("it is the non-constant gene count that gates the VST fit", { + ## A guard on nrow() would have missed this: the loess is fit on the + ## non-constant genes only, so a matrix with plenty of genes of which just + ## three vary fails in exactly the same way. + st <- .vst_tiny_fixture(nvar = 3, nconst = 97) + testthat::expect_identical(nrow(st@counts[["tiny"]]), 100L) + + w <- testthat::capture_warnings(st <- transform_data(st, cores = 1)) + testthat::expect_true(any(grepl("non-zero variance", w))) + testthat::expect_false("vst.variance.standardized" %in% colnames(st@gene_meta[["tiny"]])) + + ## One more varying gene is enough to fit it. + ok <- suppressWarnings(transform_data(.vst_tiny_fixture(nvar = 4), cores = 1)) + testthat::expect_true("vst.variance.standardized" %in% colnames(ok@gene_meta[["tiny"]])) +}) + +testthat::test_that("calculate_vst() on a matrix errors when the trend cannot be fit", { + ## The matrix form exists to rank genes for a caller's topgenes, so there is no + ## useful degraded answer: error when nothing matches, warn when only some does. + st <- .vst_tiny_fixture(nvar = 3) + + testthat::expect_error(calculate_vst(x = st@counts[["tiny"]]), + "spatialGE exception.*too few to rank genes by variability") + + ## And it still works on a matrix that can be fit, returning the gene/statistic + ## frame STgradient ranks (a plain data.frame, not a tibble). + fit <- calculate_vst(x = .vst_tiny_fixture(nvar = 6)@counts[["tiny"]]) + testthat::expect_identical(colnames(fit), c("gene", "vst.variance.standardized")) + testthat::expect_identical(nrow(fit), 6L) +}) diff --git a/vignettes/basic_functions_vignette.Rmd b/vignettes/basic_functions_vignette.Rmd index 026deaf..1563447 100644 --- a/vignettes/basic_functions_vignette.Rmd +++ b/vignettes/basic_functions_vignette.Rmd @@ -18,7 +18,7 @@ knitr::opts_chunk$set( options(rmarkdown.html_vignette.check_title=F) ``` -The package ***`spatialGE`*** provides a collection of tools for the visualization of gene expression from spatially-resolved transcriptomic experiments. The data input methods have been designed so that any data can be analyzed as long as it contains gene expression counts per spot or cell, and the spatial coordinates of those spots or cells. Specialized data input options are available to allow interoperability with workflows such as [*Space Ranger*](https://support.10xgenomics.com/spatial-gene-expression/software/pipelines/latest/what-is-space-ranger). +The package ***`spatialGE`*** provides a collection of tools for the visualization of gene expression from spatially-resolved transcriptomic experiments. The data input methods have been designed so that any data can be analyzed as long as it contains gene expression counts per spot or cell, and the spatial coordinates of those spots or cells. Specialized data input options are available to allow interoperability with workflows such as *Space Ranger* (available from 10X Genomics). This tutorial covers basic analysis possible within spatialGE. Tutorials explaining more advanced spatial analyses and other data input types can be found in the documentation site of the [spatialGE GitHub repository](https://fridleylab.github.io/spatialGE/). A point-and-click, user-friendly interface is also available at https://spatialge.moffitt.org. @@ -282,7 +282,7 @@ The `SThet` function calculates the Moran's I statsitic (or Geary's C) to measur p <- compare_SThet(tnbc, samplemeta='overall_survival_days', color_by='patient_id', - gene=c('NDRG1', 'IGKC'), + genes=c('NDRG1', 'IGKC'), color_pal='muted', ptsize=3) diff --git a/vignettes/ondisk_stlists.Rmd b/vignettes/ondisk_stlists.Rmd new file mode 100644 index 0000000..00bef2d --- /dev/null +++ b/vignettes/ondisk_stlists.Rmd @@ -0,0 +1,321 @@ +--- +title: "On-disk STlists: working with data sets larger than memory" +date: '`r format(Sys.Date())`' +output: rmarkdown::html_vignette +bibliography: vignette_references.bib +vignette: > + %\VignetteIndexEntry{spatialge_tutorial_ondisk} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r vig_settings, include=F} +knitr::opts_chunk$set( + collapse=TRUE, + comment="#>", + fig.width=8, fig.height=5 +) +options(rmarkdown.html_vignette.check_title=F) +``` + +An STlist stores the gene expression counts of all samples in the study at the same time. This is what allows functions such as `SThet` and `compare_SThet` to compare samples, but it also means that the memory required by an STlist grows with the number of samples and the number of spots or cells in each one. A few Visium samples are easily handled in a laptop. Several dozen samples, or a CosMx experiment with hundreds of thousands of cells, may not be, and the analysis then ends before it starts, when the object is created. + +For those cases, the ***`spatialGE`*** package provides the option of keeping the counts on disk instead of in memory. The function `STlist_to_disk` writes the count matrices to [parquet](https://parquet.apache.org) files, leaving in the STlist a small description of each file. The counts are then read back as the analysis functions request them, a few genes at a time. The function `STlist_to_memory` reverses the process. The rest of the object (spot coordinates, spot-level annotations, sample meta data, and the results of any analysis) is not affected and remains in memory. + +Note that this option is turned off by default. An STlist created in the usual way behaves exactly as described in the other tutorials, and none of what follows is required to use `spatialGE`. + +It is also important to be clear about what this option provides. It makes it possible to hold and analyze a data set that would not fit in memory. It does not make the analysis faster. The functions still bring counts into memory in order to compute on them, so an on-disk STlist is somewhat slower than an in-memory one, the difference being that the counts are not all in memory at once. Users whose data sets fit comfortably in memory are better off leaving them there. + +## Spatially-resolved expression of triple negative breast cancer tumor biopsies + +To follow the same data used in the [basic functionality tutorial](https://fridleylab.github.io/spatialGE/articles/basic_functions_vignette.html), we use the Visium data set from @bassiouni_2023, which includes triple negative breast cancer biopsies. Eight samples from four patients are used here. The data is available at our [spatialGE_Data GitHub repository](https://github.com/FridleyLab/spatialGE_Data), and will be pulled from there during this tutorial. + +Load the `spatialGE` package: + +```{r load_spatialge, message=F} +library('spatialGE') +``` + +As in the other tutorials, the data will be deposited in a temporary directory: + +```{r data_download1} +lk='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/FridleyLab/spatialGE_Data/raw/refs/heads/main/tnbc_bassiouni.zip?download=' +``` + +```{r temp_dir} +visium_tmp = tempdir() +unlink(visium_tmp, recursive=TRUE) +dir.create(visium_tmp) +``` + +```{r data_download2} +tryCatch({ # In case data is not available from network + download.file(lk, destfile=paste0(visium_tmp, '/', 'tnbc_bassiouni.zip'), mode='wb') + zip_tmp = list.files(visium_tmp, pattern='tnbc_bassiouni.zip$', full.names=TRUE) + unzip(zipfile=zip_tmp, exdir=visium_tmp) + net_check <<- TRUE +}, error = function(e) { + message("Could not download data. Are you connected to the internet?") + net_check <<- FALSE +}) +``` + +```{r data_fpaths, eval=net_check} +visium_folders <- list.dirs(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE) +clin_file <- list.files(paste0(visium_tmp, '/tnbc_bassiouni'), full.names=TRUE, recursive=FALSE, pattern='clinical') +``` + +## Preparing the STlist before moving it to disk + +The STlist is created in the usual way, and the quality control and normalization steps are run while the counts are still in memory: + +```{r create_stlist, warning=F, eval=net_check} +tnbc <- STlist(rnacounts=visium_folders, samples=clin_file, cores=2) + +tnbc <- filter_data(tnbc, spot_minreads=5000, spot_mingenes=1000, spot_maxreads=150000) + +tnbc <- transform_data(tnbc, method='log', cores=2) +``` + +The order of these steps matters. The functions `filter_data` and `transform_data` do not simply read the count matrices, they rewrite them: `filter_data` removes spots and genes, and `transform_data` adds an entirely new matrix of normalized values. Both are therefore run before the counts are moved to disk. + +In other words, an on-disk STlist is better thought of as a prepared data set that analyses are run on, rather than as an object that is still being assembled. If a filtering threshold has to be reconsidered later, the object can be brought back into memory with `STlist_to_memory` (shown near the end of this tutorial), modified there, and written out again. + +## Moving the counts to disk + +The function `STlist_to_disk` takes the STlist and a directory to write into. The directory is created if it does not exist: + +```{r to_disk, eval=net_check} +store_dir <- paste0(visium_tmp, '/tnbc_store') + +tnbc_disk <- STlist_to_disk(tnbc, root=store_dir) +``` + +The result is an STlist like any other, except that its two count slots now point at files. The function `is_backed` reports which of the two forms an object is in: + +```{r is_backed_chunk, eval=net_check} +is_backed(tnbc_disk) +is_backed(tnbc) +``` + +Printing the object works as before, and so does `summarize_STlist`. Neither of them needs to read the counts, because the number of genes and spots per sample is recorded when the store is written: + +```{r call_stlist, eval=net_check} +tnbc_disk +``` + +```{r count_stats, eval=net_check} +summarize_STlist(tnbc_disk) +``` + +## What is stored on disk + +Looking at what was written is useful, since the files are ordinary parquet and can be read with other tools if needed. + +Each sample gets a sub-directory containing one file per populated slot, so eight samples with raw and normalized counts result in sixteen files: + +```{r store_files, eval=net_check} +head(list.files(store_dir, recursive=TRUE), 4) + +length(list.files(store_dir, recursive=TRUE)) +``` + +Note that the sub-directory names are not the sample names. Sample names are allowed to contain characters that file paths are not, so a position and a short hash are used instead, and the readable name is kept inside the file description rather than in the path. + +That description is what now sits in the counts slot in place of a matrix. Printing it gives a one-line summary and the path to the file: + +```{r manifest_print, eval=net_check} +tnbc_disk@counts[['sample_094c']] +``` + +The slot `@misc` records where the store is and in which order the samples were written: + +```{r store_misc, eval=net_check} +tnbc_disk@misc[['store']] +``` + +The files themselves hold the counts in "long" (also called triplet, or COO) form rather than as a rectangular matrix. Every non-zero value is one row, giving the gene, the spot, and the value: + +```{r read_parquet, eval=net_check} +head(arrow::read_parquet(tnbc_disk@counts[['sample_094c']]$path), 4) +``` + +There are two reasons for this layout. Counts from these platforms are mostly zeros, and the long form stores only the values that are present, which is the same reason an STlist uses sparse matrices in memory. The rows are also sorted by gene, so that the values belonging to one gene are together in the file rather than spread throughout it. + +Note that `gene_idx` and `cell_idx` are positions rather than names. The gene and spot names are kept in the file description, which is the only place they are recorded. The reason is that a gene with a count of zero in every spot of a sample has no rows at all in the long form, so a gene list rebuilt from the contents of the file would be missing it. Genes like that are not unusual, and the default settings of `filter_data` do not remove them. + +## How much memory is saved + +The clearest way to see the effect is to compare the size of the count slots before and after: + +```{r mem_before, eval=net_check} +format(object.size(tnbc@counts) + object.size(tnbc@tr_counts), units='MB') +``` + +```{r mem_after, eval=net_check} +format(object.size(tnbc_disk@counts) + object.size(tnbc_disk@tr_counts), units='MB') +``` + +For these eight samples, the count matrices go from roughly 1.4 GB to about 25 MB, since what is left in the object is eight short descriptions instead of sixteen matrices. The counts themselves have of course not disappeared. They are on disk, where the store occupies a few hundred megabytes: + +```{r store_size, eval=net_check} +round(sum(file.info(list.files(store_dir, recursive=TRUE, full.names=TRUE))$size) / 1024^2, 1) +``` + +The reduction applies to the count matrices only. The spot coordinates and annotations in `@spatial_meta`, the per-gene statistics in `@gene_meta`, and whatever is stored in `@misc` all remain in memory, and in a large study these are not negligible either. This is easier to see by comparing the size of the whole object instead of only the count slots: + +```{r mem_whole, eval=net_check} +format(object.size(tnbc), units='MB') +format(object.size(tnbc_disk), units='MB') +``` + +## Analyses on an on-disk STlist + +Analysis functions are called exactly as they would be on an in-memory STlist. The counts are read from the files when each function asks for them, and the results are the same. + +```{r sthet_chunk, eval=net_check} +tnbc_disk <- SThet(tnbc_disk, genes=c('NDRG1', 'IGKC'), method='moran', cores=2) + +get_gene_meta(tnbc_disk, sthet_only=TRUE) +``` + +Since this is the property the whole mechanism depends on, it is worth verifying rather than assuming. Running the same analysis on the in-memory object returns identical statistics: + +```{r sthet_compare, eval=net_check} +tnbc <- SThet(tnbc, genes=c('NDRG1', 'IGKC'), method='moran', cores=2) + +identical(get_gene_meta(tnbc_disk, sthet_only=TRUE)$moran_i, + get_gene_meta(tnbc, sthet_only=TRUE)$moran_i) +``` + +Quilt plots of gene expression are produced in the same way as well: + +```{r genequilt_chunk, fig.align='center', eval=net_check} +quilts1 <- STplot(tnbc_disk, + genes=c('NDRG1', 'IGKC'), + samples='sample_094c', + color_pal='BuRd', + ptsize=0.8) + +ggpubr::ggarrange(plotlist=quilts1, nrow=1, ncol=2, legend='bottom') +``` + +The distribution of expression of a gene across samples is obtained in the same way too: + +```{r dstr_chunk, fig.align='center', eval=net_check} +dp <- distribution_plots(tnbc_disk, genes='NDRG1') +dp[['NDRG1']] +``` + +And so is the spatially-informed clustering of `STclust`: + +```{r clust_chunk, warning=F, message=F, eval=net_check} +tnbc_disk <- STclust(tnbc_disk, ks='dtc', ws=c(0, 0.025), cores=2) + +cluster_p <- STplot(tnbc_disk, samples='sample_094c', ws=0.025, color_pal='highcontrast') +cluster_p[[1]] +``` + +What this costs is time. Every read of a count matrix now involves the file system, so a function that reads the counts several times pays that cost several times. The difference is noticeable even with a data set of this size: + +```{r timing_chunk, eval=net_check} +system.time(SThet(tnbc, genes='NDRG1', method='moran', cores=2))['elapsed'] + +system.time(SThet(tnbc_disk, genes='NDRG1', method='moran', cores=2))['elapsed'] +``` + +A difference of a few fold is typical, and it is the trade mentioned at the beginning of this tutorial. The analysis becomes possible on data that would not otherwise fit in memory, but it takes longer to run. + +## Checking a store, and bringing it back + +The store is a directory of files, and the STlist only holds paths to them. The function `validate_store` checks that the arrangement is still intact, reading only the file headers: + +```{r validate_chunk, eval=net_check} +validate_store(tnbc_disk) +``` + +Nothing is printed, which is the intended result: the function returns `TRUE` invisibly when everything checks out, and stops with a message when it does not. It confirms that every file is where its description says it is and has not changed since it was written, that the samples are still in the recorded order, and that the transformed counts remain a subset of the raw counts. Passing `deep=TRUE` additionally reads the data to check the stored positions, which is slower but more thorough: + +```{r validate_deep, eval=net_check} +validate_store(tnbc_disk, deep=TRUE) +``` + +It is useful to see what the function reports when something is in fact wrong. In the following block, a path is changed to a file that does not exist, which is what a deleted or relocated store looks like from within the STlist: + +```{r validate_broken, eval=net_check} +broken <- tnbc_disk +broken@counts[['sample_094c']][['path']] <- paste0(visium_tmp, '/gone.parquet') + +try(validate_store(broken)) +``` + +That is the same error any analysis would raise on the first read of that sample, only reported up front and naming the likely cause instead of surfacing from somewhere inside `arrow`. + +When a store is no longer needed, or when the object has to be reshaped again, `STlist_to_memory` reads every matrix back: + +```{r to_memory, eval=net_check} +tnbc_back <- STlist_to_memory(tnbc_disk) + +is_backed(tnbc_back) +``` + +The round trip is exact rather than approximate. The long form stores the values themselves, and the dimensions and names come from the file description, so nothing is estimated on the way back: + +```{r round_trip, eval=net_check} +identical(tnbc_back@counts, tnbc@counts) +``` + +## Things to keep in mind + +Because the counts are now files rather than part of the object, there are a few consequences that are better known in advance. + +**The object is not self-contained.** Saving an on-disk STlist with `saveRDS` stores the paths, not the counts. If that object is loaded in a session where the store has been moved or deleted, the first function that tries to read counts will fail, and `validate_store` reports the problem up front. There is currently no way to point an existing object at a store in a new location, so the store should be written somewhere it can remain. + +**A store under `tempdir()` will not survive the session.** The examples here write to a temporary directory, which is appropriate for a tutorial but not for an actual analysis. The store records whether it was written to a location that can outlive the session: + +```{r portable_chunk, eval=net_check} +tnbc_disk@misc[['store']][['portable']] +``` + +The value is `FALSE` here because `store_dir` is inside `tempdir()`. For an analysis that is meant to be kept, users should provide `STlist_to_disk` with a directory of their own, keeping in mind that the directory has become part of the data. + +**The object has to be prepared first.** As described above, `filter_data` and `transform_data` rewrite the count matrices, so they are run before `STlist_to_disk`. The same applies to subsetting an STlist by sample with `x[i]`. In those cases, the object is brought back into memory, modified there, and written out again if the result is to be kept. + +**Writing a store does not remove the original.** `STlist_to_disk` returns a new STlist and leaves the one it was given untouched, which is why both `tnbc` and `tnbc_disk` are used throughout this tutorial. That is convenient for comparison, but keeping both of them defeats the purpose. In practice, the in-memory object is removed once the store has been written. + +
    + +**Can the parquet files be read with something other than `spatialGE`?** + +Yes, and that is part of the reason for using this format. The files are ordinary parquet with three columns, so they can be read by anything that reads parquet (`arrow` in R, `pyarrow` or `pandas` in Python, or `duckdb` in either language). + +The one thing to carry across is that `gene_idx` and `cell_idx` are positions rather than names, counting from 1. The names are held in the STlist, in the description that replaced each matrix: + +```{r external_read, eval=net_check} +mft <- tnbc_disk@counts[['sample_094c']] + +head(mft$genes, 3) +head(mft$cells, 3) +``` + +So a value with `gene_idx` 1 refers to `mft$genes[1]`, and a `cell_idx` of 1 to `mft$cells[1]`. Reading the files without that mapping gives the right numbers attached to the wrong labels, which is worse than an error, so it is worth getting right. Writing the two vectors out alongside the data is usually enough: + +```{r external_write, eval=net_check} +head(data.frame(gene_idx=seq_along(mft$genes), gene=mft$genes), 3) +``` + +
    + +## References + +
    + +
    + +**Session Info** + +```{r} +sessionInfo() +``` + +