diff --git a/docs/articles/abserr-celltype-1.png b/docs/articles/abserr-celltype-1.png index 084970e..a01aedf 100644 Binary files a/docs/articles/abserr-celltype-1.png and b/docs/articles/abserr-celltype-1.png differ diff --git a/docs/articles/abserr-celltype-sep-1.png b/docs/articles/abserr-celltype-sep-1.png index d7b0f54..251fb9c 100644 Binary files a/docs/articles/abserr-celltype-sep-1.png and b/docs/articles/abserr-celltype-sep-1.png differ diff --git a/docs/articles/clustering-1.png b/docs/articles/clustering-1.png index ef76bc6..4b0f59e 100644 Binary files a/docs/articles/clustering-1.png and b/docs/articles/clustering-1.png differ diff --git a/docs/articles/corr-pred-1.png b/docs/articles/corr-pred-1.png index 087ebd6..f10e446 100644 Binary files a/docs/articles/corr-pred-1.png and b/docs/articles/corr-pred-1.png differ diff --git a/docs/articles/negative-grad-1.png b/docs/articles/negative-grad-1.png index d692c75..67686c5 100644 Binary files a/docs/articles/negative-grad-1.png and b/docs/articles/negative-grad-1.png differ diff --git a/docs/articles/positive-grad-1.png b/docs/articles/positive-grad-1.png index 4a7c242..8c2f223 100644 Binary files a/docs/articles/positive-grad-1.png and b/docs/articles/positive-grad-1.png differ diff --git a/docs/articles/pred-spatial-1.png b/docs/articles/pred-spatial-1.png index 03f4acf..95bc9ba 100644 Binary files a/docs/articles/pred-spatial-1.png and b/docs/articles/pred-spatial-1.png differ diff --git a/docs/articles/pred-spatial-sep-1.png b/docs/articles/pred-spatial-sep-1.png index 81164d4..b9254f8 100644 Binary files a/docs/articles/pred-spatial-sep-1.png and b/docs/articles/pred-spatial-sep-1.png differ diff --git a/docs/articles/pred-spatial-sep-2.png b/docs/articles/pred-spatial-sep-2.png index 587c75b..30e980e 100644 Binary files a/docs/articles/pred-spatial-sep-2.png and b/docs/articles/pred-spatial-sep-2.png differ diff --git a/docs/articles/pred-spatial-sep-3.png b/docs/articles/pred-spatial-sep-3.png index deaf1c1..d1fd6d4 100644 Binary files a/docs/articles/pred-spatial-sep-3.png and b/docs/articles/pred-spatial-sep-3.png differ diff --git a/docs/articles/pred-spatial-sep-extrinsic-1.png b/docs/articles/pred-spatial-sep-extrinsic-1.png index bc089b7..7017111 100644 Binary files a/docs/articles/pred-spatial-sep-extrinsic-1.png and b/docs/articles/pred-spatial-sep-extrinsic-1.png differ diff --git a/docs/articles/pred-spatial-sep-extrinsic-2.png b/docs/articles/pred-spatial-sep-extrinsic-2.png index 96a276c..a9948e5 100644 Binary files a/docs/articles/pred-spatial-sep-extrinsic-2.png and b/docs/articles/pred-spatial-sep-extrinsic-2.png differ diff --git a/docs/articles/pred-spatial-sep-extrinsic-3.png b/docs/articles/pred-spatial-sep-extrinsic-3.png index 5757e08..9da2933 100644 Binary files a/docs/articles/pred-spatial-sep-extrinsic-3.png and b/docs/articles/pred-spatial-sep-extrinsic-3.png differ diff --git a/docs/articles/realModelExample-hq.html b/docs/articles/realModelExample-hq.html index e577f9a..6fdfa03 100644 --- a/docs/articles/realModelExample-hq.html +++ b/docs/articles/realModelExample-hq.html @@ -187,13 +187,13 @@
Spatia
## An object of class SpatialDDLS
## Real single-cell profiles:
## 1058 features and 14989 cells
-## rownames: Dgat2 Neil3 Tcf7 ... Tcf7 Rpl19 Rps13 Gimap4
-## colnames: ACCCTTGCAAGTAGTA-1-0 ACACCAAGTATGGGAC-1-1 GGAGCAAGTCGCATTA-1-3 ... GGAGCAAGTCGCATTA-1-3 TGTAGACAGCCACTCG-1-1 ATGATCGGTATCAAGA-1-2 CGCATAAGTCAGTCCG-1-3
+## rownames: Rps3 Rps7 Tmsb4x ... Tmsb4x Cacna1e Mycl Izumo1r
+## colnames: TAACACGAGGAGAGGC-1-2 CCCTAACTCGCGGACT-1-2 CCGATGGTCTGCCTGT-1-2 ... CCGATGGTCTGCCTGT-1-2 GCTACCTAGTTATGGA-1-2 TTTACTGGTGGAATGC-1-1 TGTTACTTCTGAGAAA-1-3
## Spatial experiments:
## 1 experiments
## 1058 features and 1092 spots
-## rownames: Arhgef10l Osm Clec4a3 ... Clec4a3 Ccl17 Tcrg-C2 Actg2
-## colnames: CTGGCGACATAAGTCC-1-1 GGTGAAGTACAGGGAT-1-1 TATTCCACTCAGCTCG-1-1 ... TATTCCACTCAGCTCG-1-1 TGTGTCGCGAGTTGCA-1-0 GAAGTGATTTATCGTG-1-0 AAATCGTGTACCACAA-1-1
+## rownames: Kmo Cd2 Spic ... Spic Gpr141 Klra4 Klrd1
+## colnames: CGCGGGAATTAGGCAG-1-1 ATTCAGTAGCAGGGTC-1-0 CGGTTGACCTGGCATA-1-0 ... CGGTTGACCTGGCATA-1-0 CTAATTTCAACAACAC-1-0 TCCCGTCAGTCCCGCA-1-1 TCCGATGACTGAGCTC-1-1
## Project: SpatialDDLS-Proj
In this case, we are only working on 1 spatial transcriptomics
dataset, but an arbitrary number of SpatialExperiment
@@ -205,19 +205,20 @@
Simulation of mixed transc
Now, we are going to simulate cell composition matrices that will
serve to simulate mixed transcriptional profiles with known cell
proportions. This is done by the genMixedCellProp
function
-in which we can control different aspects such as the number of mixed
-transcriptional profiles to be generated, the number of cells used to
-simulate each mixed profile, etc. These parameters must be decided
-depending on the single-cell reference and the available computational
+in which we can control different aspects, such as the number of mixed
+transcriptional profiles to be generated or the number of cells used to
+simulate each mixed profile. These parameters must be decided depending
+on the size of the single-cell reference and the available computational
resources. For this example, and as standard reference, we will use
num.sim.spots = 10000
and n.cells = 50
. The
-cell type compositions of these mixed profiles will be generated by
-three methods:
+cell type composition of these mixed profiles will be generated by three
+methods:
-- A random sampling of a Dirichlet distribution. Moreover, in order to
-make these proportions more sparse, the
prob.sparity
-parameter controls the probability of having missing cell types in each
-simulated spot, as opposed to a mixture of all cell types.
+- A random sampling of a Dirichlet distribution. Within this set of
+samples, in order to make these proportions more sparse, the
+
prob.sparity
parameter controls the probability of having
+missing cell types in each simulated spot, as opposed to a mixture of
+all cell types.
- Pure mixed transcriptional profiles composed of
n.cells
cells of the same cell type aggregated.
- Transcriptional profiles in which a minimum number of missing cell
@@ -287,7 +288,7 @@
Simulation of mixed transc
a while depending on the number of transcriptional profiles to be
simulated, so be patient! In addition, users can choose the method by
which the mixed profiles will be generated. We recommend summing up raw
-counts, and then normalize samples by log-CPM
+counts, and then normalizing samples to obtain logCPMs
(mixing.function = "AddRawCount"
), but other methods are
available (see Documentation).
@@ -308,11 +309,11 @@
mouseDLN.SDDLS <- trainDeconvModel(
@@ -323,9 +324,9 @@ = FALSE
)
##
- 1/105 [..............................] - ETA: 12s - loss: 0.0815 - accuracy: 0.7812 - mean_absolute_error: 0.0171 - categorical_accuracy: 0.7812
- 79/105 [=====================>........] - ETA: 0s - loss: 0.0729 - accuracy: 0.8896 - mean_absolute_error: 0.0149 - categorical_accuracy: 0.8896
-105/105 [==============================] - 0s 638us/step - loss: 0.0744 - accuracy: 0.8890 - mean_absolute_error: 0.0152 - categorical_accuracy: 0.8890
+ 1/105 [..............................] - ETA: 14s - loss: 0.0705 - accuracy: 0.9688 - mean_absolute_error: 0.0147 - categorical_accuracy: 0.9688
+ 70/105 [===================>..........] - ETA: 0s - loss: 0.0690 - accuracy: 0.8906 - mean_absolute_error: 0.0146 - categorical_accuracy: 0.8906
+105/105 [==============================] - 0s 772us/step - loss: 0.0697 - accuracy: 0.8896 - mean_absolute_error: 0.0148 - categorical_accuracy: 0.8896
Some metrics of the training progress can be shown by setting
verbose = TRUE
. Anyhow, more advanced metrics can be
calculated using the calculateEvalMetrics
function. This
@@ -375,9 +376,9 @@
Finally, we can use our trained model to deconvolute the signals of -each spot using the `deconvSpatialDDLS’ function. By default, the -function uses the trained model to predict cell proportions of two sets -of transcriptional profiles from the ST datasets:
+each spot using thedeconvSpatialDDLS
function. By default,
+this function uses the trained model to predict cell proportions of two
+sets of transcriptional profiles obtained from the ST datasets:
The latter can be used to understand how similar each spot is to its neighbors. Considering the hypothesis that we can infer the cellular -composition of each spot based on their surroundings given the -correlation between spatial location and cell -composition/transcriptional profile, we can use this information to -spatially contextualize our predictions and improve their accuracy. For -furhter mentions, we refer to this process as regularization. Details -about the methodology are explained in the Documentation and Mañanes et al. (2023).
+composition of each spot based on its surroundings given the correlation +between spatial location and cell composition/transcriptional features, +we can use this information to spatially contextualize our predictions +and improve their accuracy. We refer to this process as spatial +regularization. Details about the methodology are explained in the +Documentation and Mañanes et al. +(2023).
mouseDLN.SDDLS <- deconvSpatialDDLS(
mouseDLN.SDDLS, k.spots = 6
@@ -403,7 +405,7 @@ Deconvolution of t
## === Predicting cell type proportions
##
1/35 [..............................] - ETA: 0s
-35/35 [==============================] - 0s 587us/step
+35/35 [==============================] - 0s 598us/step
##
## === Calculating distances in PCA space
## - Using 133 PCs (variance cutoff: 0.8)
@@ -418,35 +420,51 @@ plotSpatialProp
function to
independently plot each cell type:
-for (i in trained.model(mouseDLN.SDDLS) %>% cell.types()) {
- print(
+list.plots <- lapply(
+ X = trained.model(mouseDLN.SDDLS) %>% cell.types(),
+ FUN = \(x) {
plotSpatialProp(
- mouseDLN.SDDLS, index.st = 1, cell.type = i,
- colors = "blues"
- ) + coord_fixed()
- )
-}
+ggarrange(plotlist = list.plots[5:8], align = "hv")
+ggarrange(plotlist = list.plots[9:12], align = "hv")
In addition to the ‘regularized’ cell proportions, we can plot the predictions calculated for the intrinsic and extrinsic transcriptional profiles. For instance, let’s plot those predicted from the extrinsic transcriptional profiles:
-
-for (i in mouseDLN.SDDLS@trained.model@cell.types) {
- print(
+
+list.plots <- lapply(
+ X = trained.model(mouseDLN.SDDLS) %>% cell.types(),
+ FUN = \(x) {
plotSpatialProp(
- mouseDLN.SDDLS, index.st = 1, cell.type = i,
- colors = "blues", prediction = "Extrinsic"
- ) + coord_fixed()
- )
-}
-
+ mouseDLN.SDDLS, index.st = 1, cell.type = x, size.point = 1,
+ colors = "blues", prediction = "Extrinsic"
+ ) + coord_fixed()
+ }
+)
+ggarrange(plotlist = list.plots[1:4], align = "hv")
+ggarrange(plotlist = list.plots[5:8], align = "hv")
+ggarrange(plotlist = list.plots[9:12], align = "hv")
As one might expect, this is a smoothed version of the final
-predictions. It is also possible to visualize distances between
+predictions. It is also possible to visualize distances between the
extrinsic and intrinsic transcriptional profiles of each spot to
understand how the regularization step works by using the
plotDistances
function:
+plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed()
Those spots with distances less than the mean distance were @@ -475,22 +493,22 @@
Interpreting the modelIn order to make predictions more transparent,
SpatialDDLS
includes an additional module designed to provide insights into the model’s decision-making process. It relies on -calculating of predicted classes/loss function gradients with respect to -the input variables, a method popularly known as Vanilla Gradient. These -numeric values are computed for each gene and cell type using the pure -mixed transcriptional profiles previously simulated. Therefore, they can -be interpreted as the extent to which each feature is contributing to -the model’s predictions. While these values are initially calculated at -the sample/gene level, they can be aggregated at the cell type level in -order to assess the relevance of different genes for cell type -proportion predictions. These steps are performed through the -interGradientDL
function: -+calculating the predicted classes/loss function gradients with respect +to the input variables, a method popularly known as Vanilla +Gradient. These numeric values are computed for each gene and +cell type using the pure mixed transcriptional profiles previously +simulated. Therefore, they can be interpreted as the extent to which +each feature is contributing to the model’s predictions. While these +values are initially calculated at the sample/gene level, they can be +aggregated at the cell type level in order to assess the relevance of +different genes for cell type proportion predictions. These steps are +performed through theinterGradientDL
function: +mouseDLN.SDDLS <- interGradientsDL( mouseDLN.SDDLS, scaling = "standardize", method = "class" )
Importantly, depending on the
+and negative gradients must be differently interpreted:method
parameter, positive -and negative gradient must be differently interpreted:
- If gradients with respect to the input variables were calculated using the loss function (
method = "loss"
), genes with @@ -511,51 +529,48 @@Interpreting the modelFor this example, let’s calculate gradients of the class function with respect to the input features and show the top 5 genes with the greatest gradients per cell type: -
+-top.gradients <- topGradientsCellType( mouseDLN.SDDLS, method = "class", top.n.genes = 5 ) sapply( top.gradients, \(x) x$Positive ) %>% as.data.frame()
+## B cells CD4 T cells CD8 T cells cDC1s cDC2s GD T cells Macrophages -## 1 Vpreb3 Ly6c1 Cd8b1 Slc1a3 Gm26917 Slc1a3 1300017J02Rik -## 2 Slc1a3 Igfbp4 Ccr9 Ifi205 Xist Il4 Cst7 -## 3 Snx2 Slc1a3 Cd8a Gatm Slc1a3 Ip6k3 Pla2g2d -## 4 Man1a Satb1 Ppic Lpl Rnf144b Ramp3 Cbr2 -## 5 Cd72 Trat1 Acp5 Ryr2 Ryr2 Ska3 Timd4 -## Migratory DCs Monocytes NK cells pDCs Tregs -## 1 Slc1a3 Map4k4 Slc1a3 Ptgs1 Foxp3 -## 2 Xist Clec4e Klrc1 Clec2d Itgb1 -## 3 Gm26917 Slc1a3 Ugcg Xist Ctla4 -## 4 Clec2d B2m Cd47 Cd200 Izumo1r -## 5 Pde1c Pde1c Jak1 H2-D1 Cxcr3
## B cells CD4 T cells CD8 T cells cDC1s cDC2s GD T cells Macrophages +## 1 Vpreb3 Igfbp4 Cd8b1 Slc16a9 Clec2d Gm26917 1300017J02Rik +## 2 Cd72 Ly6c1 Cd8a Hbb-bs Stk39 Il4 Timd4 +## 3 Slc1a3 Satb1 Ccr9 Tnfsf14 Ryr2 Stk39 Prg3 +## 4 H3f3b Lef1 Acp5 Gatm Ndfip1 Ccr10 Cst7 +## 5 Rfc4 Cd28 Rgcc Ahnak Ugcg Selplg Cd8b1 +## Migratory DCs Monocytes NK cells pDCs Tregs +## 1 D16Ertd472e Ndfip1 Klra9 Clec2d Foxp3 +## 2 Tmem150c Ucp2 Ugcg Clec4e Cxcr3 +## 3 Il15ra Marco Klrc1 H2-K1 Ctla4 +## 4 Samhd1 Ryr2 Ccl3 Ndfip1 Samhd1 +## 5 Clec2d Clec4e Tnfrsf8 Fyn Itgb1
As can be seen, among the top 5 genes some canonical markers for different cell types appear, such as Cd79b for B cells, Cd8a for CD8 T cells, or Foxp3 for Tregs. These are just the top 5 genes, so considering a higher number can provide a more comprehensive understanding of the genes utilizaed by the model.
We also provide the
-plotHeatmapGradsAgg
function for -visualizing N top mean gradients per cell type. This plot highlights +visualizing the top N mean gradients per cell type. This plot highlights genes with high gradients across different cell types, reflecting the multivariate nature of neural networks. It is advisable to examine both the most positive and negative gradients, as these genes significantly contribute to the network’s predictions.+-hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = "class") hh$Positive
+hh$Negative
Finally, we can use the
-plotSpatialGeneExpr
to visualize -the spatial distribution of the top N genes per cell tupe in the ST -dataset. Let’s plot genes for some cell types for demonstration +the spatial distribution of the top N genes per cell type in the ST +dataset. Let’s plot genes for some cell types just for demonstration purposes:the top N genes per cell type and visualize their spatial -distribution in the ST dataset. Let’s plot genes for some cell types -just for demonstration purposes:
-+- +top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) for (i in c("B cells", "CD4 T cells", "CD8 T cells", "Tregs", "Monocytes")) { list.plots <- list() @@ -567,7 +582,7 @@
Interpreting the model } print(ggpubr::ggarrange(plotlist = list.plots, align = "hv")) }
Clustering analysis @@ -575,14 +590,14 @@
Clustering analysis
+distinct cellular niches, information that might be relevant for further +analyses. +mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20)
## No 'index.st' provided. Deconvoluting all SpatialExperiment objects contained in the `spatial.experiments` slot
## === Selected graph-based clustering
-## === Running clustering for slide 1
+plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed()
## No 'index.st' provided. Using first ST dataset
@@ -592,12 +607,13 @@## === Plotting first clustering configuration Clustering.graph.k.20
Clustering analysisComparing deconvoluted cell proportions with colocalization of cell markers
-Finally, we assess whether there is a collocation between the -predicted cell type proportions and the expression of known classic -markers for each cell type. This analysis aims to validate the model’s -predictions by comparing them with well-established cellular markers, -but it does not mean to be a quantitative validation of the model.
-+Finally, we are going to assess whether there is a collocation +between the predicted cell type proportions and the expression of known +classic markers for each cell type. This analysis aims to validate the +model’s predictions by comparing them with well-established cellular +markers, but it does not mean to be a quantitative validation of the +model.
+-customMarkers <- list( "B cells" = c("Cd74", "Cd19", "Cd79a", "Cd79b", "Ly6d"), "CD4 T cells" = c("Cd4", "Lef1", "Fyb"), @@ -612,7 +628,7 @@
= c("Siglech", "Plac8", "Ly6c2", "Vtsb", "Zeb2", "Siglech"), Tregs = c("Ikzf2", "Il2ra", "Foxp3") ) %>% lapply(FUN = function(x) x[x %in% rownames(MouseDLN.ST)])
+-## calculate z-scores exprST <- MouseDLN.ST@assays@data[[1]] logCPM <- edgeR::cpm(exprST, log = TRUE) @@ -621,7 +637,7 @@
= ~{ colMeans(t(scale(t(logCPM[customMarkers[[.x]], , drop = FALSE])))) } ) %>% do.call(cbind, .) colnames(meanZscoresCustom) <- names(customMarkers)
diff --git a/docs/reference/interGradientsDL.html b/docs/reference/interGradientsDL.html index d1ecc36..b28ac90 100644 --- a/docs/reference/interGradientsDL.html +++ b/docs/reference/interGradientsDL.html @@ -249,9 +249,9 @@+color.z.scores <- rev( colorRampPalette(RColorBrewer::brewer.pal(n = 10, name = "RdBu"))(20) ) diff --git a/docs/articles/top-genes-spatial-1.png b/docs/articles/top-genes-spatial-1.png index fc01d8d..889d2ee 100644 Binary files a/docs/articles/top-genes-spatial-1.png and b/docs/articles/top-genes-spatial-1.png differ diff --git a/docs/articles/top-genes-spatial-2.png b/docs/articles/top-genes-spatial-2.png index 84dd008..9d980fb 100644 Binary files a/docs/articles/top-genes-spatial-2.png and b/docs/articles/top-genes-spatial-2.png differ diff --git a/docs/articles/top-genes-spatial-3.png b/docs/articles/top-genes-spatial-3.png index 1766f50..bb94700 100644 Binary files a/docs/articles/top-genes-spatial-3.png and b/docs/articles/top-genes-spatial-3.png differ diff --git a/docs/articles/top-genes-spatial-4.png b/docs/articles/top-genes-spatial-4.png index ca5ca32..f9444f7 100644 Binary files a/docs/articles/top-genes-spatial-4.png and b/docs/articles/top-genes-spatial-4.png differ diff --git a/docs/articles/top-genes-spatial-5.png b/docs/articles/top-genes-spatial-5.png index 87b422a..51554ff 100644 Binary files a/docs/articles/top-genes-spatial-5.png and b/docs/articles/top-genes-spatial-5.png differ diff --git a/docs/extra.css b/docs/extra.css index 71a7ddd..e0f2922 100644 --- a/docs/extra.css +++ b/docs/extra.css @@ -4,7 +4,6 @@ h1 { #toc h2 { font-weight: bolder; - font-size: 10px; } .links h2 { diff --git a/docs/pkgdown.yml b/docs/pkgdown.yml index f820888..b6fbf32 100644 --- a/docs/pkgdown.yml +++ b/docs/pkgdown.yml @@ -5,5 +5,5 @@ articles: hdf5Backend: hdf5Backend.html realModelExample-hq: realModelExample-hq.html realModelExample: realModelExample.html -last_built: 2023-11-29T16:34Z +last_built: 2023-11-30T13:10Z diff --git a/docs/reference/Rplot002.png b/docs/reference/Rplot002.png index 34fe480..d7bef87 100644 Binary files a/docs/reference/Rplot002.png and b/docs/reference/Rplot002.png differ diff --git a/docs/reference/Rplot003.png b/docs/reference/Rplot003.png index ca6b113..9b727c4 100644 Binary files a/docs/reference/Rplot003.png and b/docs/reference/Rplot003.png differ diff --git a/docs/reference/barErrorPlot-1.png b/docs/reference/barErrorPlot-1.png index a920caa..20fc0d9 100644 Binary files a/docs/reference/barErrorPlot-1.png and b/docs/reference/barErrorPlot-1.png differ diff --git a/docs/reference/barErrorPlot-2.png b/docs/reference/barErrorPlot-2.png index 2e9f558..5a3879b 100644 Binary files a/docs/reference/barErrorPlot-2.png and b/docs/reference/barErrorPlot-2.png differ diff --git a/docs/reference/barErrorPlot.html b/docs/reference/barErrorPlot.html index 9d8e946..853560d 100644 --- a/docs/reference/barErrorPlot.html +++ b/docs/reference/barErrorPlot.html @@ -243,9 +243,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 1.5452 +#> - loss: 1.6068 #> - accuracy: 0.125 -#> - mean_absolute_error: 0.238 +#> - mean_absolute_error: 0.2343 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data diff --git a/docs/reference/blandAltmanLehPlot-1.png b/docs/reference/blandAltmanLehPlot-1.png index ebf7e98..e7190e1 100644 Binary files a/docs/reference/blandAltmanLehPlot-1.png and b/docs/reference/blandAltmanLehPlot-1.png differ diff --git a/docs/reference/blandAltmanLehPlot-2.png b/docs/reference/blandAltmanLehPlot-2.png index 6010ee3..bb10e96 100644 Binary files a/docs/reference/blandAltmanLehPlot-2.png and b/docs/reference/blandAltmanLehPlot-2.png differ diff --git a/docs/reference/blandAltmanLehPlot.html b/docs/reference/blandAltmanLehPlot.html index 0a0b12a..1bccc8f 100644 --- a/docs/reference/blandAltmanLehPlot.html +++ b/docs/reference/blandAltmanLehPlot.html @@ -293,10 +293,10 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 1.554 -#> - accuracy: 0.25 -#> - mean_absolute_error: 0.2344 -#> - categorical_accuracy: 0.25 +#> - loss: 1.597 +#> - accuracy: 0.125 +#> - mean_absolute_error: 0.2394 +#> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE @@ -308,6 +308,21 @@
Examples facet.by = "CellType", color.by = "CellType" ) +#> Warning: `stat_contour()`: Zero contours were generated +#> Warning: no non-missing arguments to min; returning Inf +#> Warning: no non-missing arguments to max; returning -Inf +#> Warning: `stat_contour()`: Zero contours were generated +#> Warning: no non-missing arguments to min; returning Inf +#> Warning: no non-missing arguments to max; returning -Inf +#> Warning: `stat_contour()`: Zero contours were generated +#> Warning: no non-missing arguments to min; returning Inf +#> Warning: no non-missing arguments to max; returning -Inf +#> Warning: `stat_contour()`: Zero contours were generated +#> Warning: no non-missing arguments to min; returning Inf +#> Warning: no non-missing arguments to max; returning -Inf +#> Warning: `stat_contour()`: Zero contours were generated +#> Warning: no non-missing arguments to min; returning Inf +#> Warning: no non-missing arguments to max; returning -Inf # Bland-Altman plot of all samples mixed blandAltmanLehPlot( diff --git a/docs/reference/corrExpPredPlot-1.png b/docs/reference/corrExpPredPlot-1.png index d8d78e3..e55767a 100644 Binary files a/docs/reference/corrExpPredPlot-1.png and b/docs/reference/corrExpPredPlot-1.png differ diff --git a/docs/reference/corrExpPredPlot-2.png b/docs/reference/corrExpPredPlot-2.png index 409963c..0ffeccd 100644 Binary files a/docs/reference/corrExpPredPlot-2.png and b/docs/reference/corrExpPredPlot-2.png differ diff --git a/docs/reference/corrExpPredPlot.html b/docs/reference/corrExpPredPlot.html index aaf9ffa..e8b4010 100644 --- a/docs/reference/corrExpPredPlot.html +++ b/docs/reference/corrExpPredPlot.html @@ -298,9 +298,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 1.4361 +#> - loss: 1.5591 #> - accuracy: 0.125 -#> - mean_absolute_error: 0.233 +#> - mean_absolute_error: 0.2384 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data diff --git a/docs/reference/deconvSpatialDDLS.html b/docs/reference/deconvSpatialDDLS.html index 68d6e9b..16f5279 100644 --- a/docs/reference/deconvSpatialDDLS.html +++ b/docs/reference/deconvSpatialDDLS.html @@ -381,9 +381,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 1.5547 +#> - loss: 1.561 #> - accuracy: 0.125 -#> - mean_absolute_error: 0.2371 +#> - mean_absolute_error: 0.2399 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data diff --git a/docs/reference/distErrorPlot-1.png b/docs/reference/distErrorPlot-1.png index 907724c..144b719 100644 Binary files a/docs/reference/distErrorPlot-1.png and b/docs/reference/distErrorPlot-1.png differ diff --git a/docs/reference/distErrorPlot-2.png b/docs/reference/distErrorPlot-2.png index 338b497..40c3d05 100644 Binary files a/docs/reference/distErrorPlot-2.png and b/docs/reference/distErrorPlot-2.png differ diff --git a/docs/reference/distErrorPlot.html b/docs/reference/distErrorPlot.html index c719191..8e49bb8 100644 --- a/docs/reference/distErrorPlot.html +++ b/docs/reference/distErrorPlot.html @@ -313,9 +313,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 1.6536 +#> - loss: 1.44 #> - accuracy: 0.125 -#> - mean_absolute_error: 0.2413 +#> - mean_absolute_error: 0.2287 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data diff --git a/docs/reference/estimateZinbwaveParams.html b/docs/reference/estimateZinbwaveParams.html index 134cbd0..3c9363c 100644 --- a/docs/reference/estimateZinbwaveParams.html +++ b/docs/reference/estimateZinbwaveParams.html @@ -253,7 +253,7 @@
Examples#> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates -#> === Running estimation process (Start time 05:35:11 PM) +#> === Running estimation process (Start time 02:10:35 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: @@ -265,22 +265,22 @@
Examples#> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed -#> 0.026 0.000 0.026 +#> 0.026 0.000 0.027 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed -#> 0.012 0.000 0.012 +#> 0.012 0.000 0.013 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed -#> 0.021 0.000 0.020 +#> 0.021 0.000 0.021 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed -#> 0.007 0.000 0.008 +#> 0.008 0.000 0.008 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 @@ -289,7 +289,7 @@
Examples#> #> DONE #> -#> Invested time: 1.12 +#> Invested time: 1.11
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 0.2716 +#> - loss: 0.1983 #> - accuracy: 1 -#> - mean_absolute_error: 0.2371 +#> - mean_absolute_error: 0.1791 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data diff --git a/docs/reference/plotHeatmapGradsAgg-1.png b/docs/reference/plotHeatmapGradsAgg-1.png index b9cb360..5dc7fd8 100644 Binary files a/docs/reference/plotHeatmapGradsAgg-1.png and b/docs/reference/plotHeatmapGradsAgg-1.png differ diff --git a/docs/reference/plotHeatmapGradsAgg-2.png b/docs/reference/plotHeatmapGradsAgg-2.png index 031c8a1..89004bf 100644 Binary files a/docs/reference/plotHeatmapGradsAgg-2.png and b/docs/reference/plotHeatmapGradsAgg-2.png differ diff --git a/docs/reference/plotHeatmapGradsAgg-3.png b/docs/reference/plotHeatmapGradsAgg-3.png index ce05a96..8fc0a63 100644 Binary files a/docs/reference/plotHeatmapGradsAgg-3.png and b/docs/reference/plotHeatmapGradsAgg-3.png differ diff --git a/docs/reference/plotHeatmapGradsAgg.html b/docs/reference/plotHeatmapGradsAgg.html index b7468dc..e7ce5b3 100644 --- a/docs/reference/plotHeatmapGradsAgg.html +++ b/docs/reference/plotHeatmapGradsAgg.html @@ -214,9 +214,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 0.1777 +#> - loss: 0.2237 #> - accuracy: 1 -#> - mean_absolute_error: 0.1621 +#> - mean_absolute_error: 0.1997 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data diff --git a/docs/reference/simSCProfiles.html b/docs/reference/simSCProfiles.html index ca5e109..ef64356 100644 --- a/docs/reference/simSCProfiles.html +++ b/docs/reference/simSCProfiles.html @@ -273,7 +273,7 @@
Examples#> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates -#> === Running estimation process (Start time 05:35:24 PM) +#> === Running estimation process (Start time 02:10:47 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: @@ -285,22 +285,22 @@
Examples#> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed -#> 0.024 0.000 0.024 +#> 0.025 0.000 0.024 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed -#> 0.011 0.000 0.011 +#> 0.011 0.000 0.010 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed -#> 0.02 0.00 0.02 +#> 0.019 0.000 0.019 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed -#> 0.008 0.000 0.007 +#> 0.007 0.000 0.008 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 diff --git a/docs/reference/spatialPropClustering.html b/docs/reference/spatialPropClustering.html index b3f8fda..2d2ad7d 100644 --- a/docs/reference/spatialPropClustering.html +++ b/docs/reference/spatialPropClustering.html @@ -227,9 +227,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 0.24 +#> - loss: 0.186 #> - accuracy: 1 -#> - mean_absolute_error: 0.2124 +#> - mean_absolute_error: 0.169 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data diff --git a/docs/reference/topGradientsCellType.html b/docs/reference/topGradientsCellType.html index 4bc0014..cd283eb 100644 --- a/docs/reference/topGradientsCellType.html +++ b/docs/reference/topGradientsCellType.html @@ -205,9 +205,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 0.2015 +#> - loss: 0.2941 #> - accuracy: 1 -#> - mean_absolute_error: 0.1817 +#> - mean_absolute_error: 0.2542 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data @@ -218,30 +218,30 @@
Exampleslapply(listGradients, head, n = 5) #> $CellType1 #> $CellType1$Absolute -#> [1] "Gene8" "Gene11" "Gene13" "Gene4" "Gene3" "Gene2" "Gene12" "Gene14" -#> [9] "Gene5" "Gene7" "Gene6" "Gene1" "Gene10" "Gene9" "Gene15" +#> [1] "Gene11" "Gene4" "Gene8" "Gene12" "Gene5" "Gene3" "Gene13" "Gene2" +#> [9] "Gene14" "Gene15" "Gene7" "Gene1" "Gene9" "Gene6" "Gene10" #> #> $CellType1$Positive -#> [1] "Gene8" "Gene11" "Gene13" "Gene4" "Gene3" "Gene2" "Gene12" "Gene14" -#> [9] "Gene5" "Gene7" "Gene6" "Gene1" "Gene10" "Gene9" "Gene15" +#> [1] "Gene11" "Gene4" "Gene8" "Gene12" "Gene5" "Gene3" "Gene13" "Gene2" +#> [9] "Gene14" "Gene15" "Gene7" "Gene1" "Gene9" "Gene6" "Gene10" #> #> $CellType1$Negative -#> [1] "Gene8" "Gene11" "Gene13" "Gene4" "Gene3" "Gene2" "Gene12" "Gene14" -#> [9] "Gene5" "Gene7" "Gene6" "Gene1" "Gene10" "Gene9" "Gene15" +#> [1] "Gene11" "Gene4" "Gene8" "Gene12" "Gene5" "Gene3" "Gene13" "Gene2" +#> [9] "Gene14" "Gene15" "Gene7" "Gene1" "Gene9" "Gene6" "Gene10" #> #> #> $CellType2 #> $CellType2$Absolute -#> [1] "Gene15" "Gene10" "Gene1" "Gene7" "Gene9" "Gene6" "Gene2" "Gene4" -#> [9] "Gene3" "Gene8" "Gene12" "Gene14" "Gene11" "Gene13" "Gene5" +#> [1] "Gene10" "Gene7" "Gene1" "Gene9" "Gene6" "Gene15" "Gene11" "Gene13" +#> [9] "Gene2" "Gene14" "Gene8" "Gene3" "Gene4" "Gene12" "Gene5" #> #> $CellType2$Positive -#> [1] "Gene15" "Gene10" "Gene1" "Gene7" "Gene9" "Gene6" "Gene2" "Gene4" -#> [9] "Gene3" "Gene8" "Gene12" "Gene14" "Gene11" "Gene13" "Gene5" +#> [1] "Gene10" "Gene7" "Gene1" "Gene9" "Gene6" "Gene15" "Gene11" "Gene13" +#> [9] "Gene2" "Gene14" "Gene8" "Gene3" "Gene4" "Gene12" "Gene5" #> #> $CellType2$Negative -#> [1] "Gene15" "Gene10" "Gene1" "Gene7" "Gene9" "Gene6" "Gene2" "Gene4" -#> [9] "Gene3" "Gene8" "Gene12" "Gene14" "Gene11" "Gene13" "Gene5" +#> [1] "Gene10" "Gene7" "Gene1" "Gene9" "Gene6" "Gene15" "Gene11" "Gene13" +#> [9] "Gene2" "Gene14" "Gene8" "Gene3" "Gene4" "Gene12" "Gene5" #> #> # } diff --git a/docs/reference/trainDeconvModel.html b/docs/reference/trainDeconvModel.html index 1ac2fdc..cbbdf82 100644 --- a/docs/reference/trainDeconvModel.html +++ b/docs/reference/trainDeconvModel.html @@ -390,9 +390,9 @@
Examples#> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) -#> - loss: 0.193 +#> - loss: 0.2414 #> - accuracy: 1 -#> - mean_absolute_error: 0.1748 +#> - mean_absolute_error: 0.2121 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data diff --git a/docs/search.json b/docs/search.json index 06610ec..525775b 100644 --- a/docs/search.json +++ b/docs/search.json @@ -1 +1 @@ -[{"path":"/articles/hdf5Backend.html","id":"general-usage","dir":"Articles","previous_headings":"","what":"General usage","title":"Using HFD5 files as back-end","text":"important parameters must considered : file.backend: file path HDF5 file stored. name.dataset.backend: HDF5 files use “file directory”-like structure, possible store one dataset single file. , changing name dataset needed. provided, random dataset name used. compression.level: allows change level compression HDF5 files. integer value 0 9. Note greater compression level, slower processes longer runtime. chunk.dims: HDF5 files created sets chunks, parameter specifies dimensions . block.processing: available, indicates data treated blocks order avoid loading data RAM. block.size: specific simSCProfiles simMixedProfiles. sets number samples simulated iteration. simplest way use setting file.backend parameter.","code":""},{"path":"/articles/hdf5Backend.html","id":"disclaimer","dir":"Articles","previous_headings":"","what":"Disclaimer","title":"Using HFD5 files as back-end","text":"HDF5 files useful tool allows working large datasets otherwise impossible. However, important note running times may longer, accessing data RAM always faster disk. Therefore, recommend using functionality case large datasets limited computational resources. HDF5Array DelayedArray authors point : can load data memory still compute , ’re always going better time way.","code":""},{"path":"/articles/realModelExample-hq.html","id":"loading-data","dir":"Articles","previous_headings":"","what":"Loading data","title":"Get started! Deconvolution of mouse lymph node samples","text":"Firstly, let’s load required packages data: Let’s explore spatial transcriptomics data contained MouseDLN.ST object: regard single-cell RNA-seq data, preprocessing visualization performed, analysis outside scope tutorial.","code":"library(\"SpatialDDLS\") library(\"SingleCellExperiment\") library(\"SpatialExperiment\") library(\"ggplot2\") library(\"ggpubr\") ## in case it is not installed if (!requireNamespace(\"SpatialDDLSdata\", quietly = TRUE)) { if (!requireNamespace(\"devtools\", quietly = TRUE)) { install.packages(\"devtools\") } devtools::install_github(\"diegommcc/SpatialDDLSdata\") } library(\"SpatialDDLSdata\") # SingleCellExperiment with scRNA-seq data(MouseDLN.SCE) # SpatialExperiment with spatial transcriptomics data data(MouseDLN.ST) cbind(spatialCoords(MouseDLN.ST), colData(MouseDLN.ST)) %>% as.data.frame() %>% ggplot(aes(X0, X1, color = lymph_node)) + geom_point() + ggtitle(\"Mouse lymph nodes by condition\") + theme_classic() + coord_fixed()"},{"path":"/articles/realModelExample-hq.html","id":"loading-data-into-a-spatialddls-object","dir":"Articles","previous_headings":"Loading data","what":"Loading data into a SpatialDDLS object","title":"Get started! Deconvolution of mouse lymph node samples","text":"Now, need create SpatialDDLS object, serve central core subsequent steps. suggest including spatial single-cell transcriptomics data enable filtering selection genes present data types analyses. Additionally, recommend filtering genes based expression levels order reduce number dimensions consider meaningful genes. Please refer documentation review implemented strategies (specially sc.n.genes.per.cluster sc.min.mean.counts parameters). can show basic information object: case, working 1 spatial transcriptomics dataset, arbitrary number SpatialExperiment objects can loaded.","code":"mouseDLN.SDDLS <- createSpatialDDLSobject( sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", sc.gene.ID.column = \"GeneSymbol\", sc.cell.type.column = \"broad_cell_types\", st.data = MouseDLN.ST, sc.min.counts = 1, sc.min.cells = 1, sc.filt.genes.cluster = TRUE, sc.n.genes.per.cluster = 150, sc.min.mean.counts = 2, st.spot.ID.column = \"CellID\", st.gene.ID.column = \"GeneSymbol\" ) ## === 1 SpatialExperiment objects provided ## === Processing spatial transcriptomics data ## - Filtering features: ## - Selected features: 13948 ## - Discarded features: 0 ## ## === Processing single-cell data ## - Removing 16 genes without expression in any cell ## 'as(
, \"dgTMatrix\")' is deprecated. ## Use 'as(., \"TsparseMatrix\")' instead. ## See help(\"Deprecated\") and help(\"Matrix-deprecated\"). ## - Filtering features: ## - Selected features: 12350 ## - Discarded features: 488 ## ## === Number of shared genes between single-cell and spatial transcriptomics datasets: 11592 ## - Original # genes in single-cell data: 12350 ## - Original # genes in ST data (object with the greatest # genes): 13948 ## ## === Number of removed mitochondrial genes: 12 ## ## === Number of genes after filtering based on logFC: 1058 ## ## === Final number of dimensions for further analyses: 1058 mouseDLN.SDDLS ## An object of class SpatialDDLS ## Real single-cell profiles: ## 1058 features and 14989 cells ## rownames: Dgat2 Neil3 Tcf7 ... Tcf7 Rpl19 Rps13 Gimap4 ## colnames: ACCCTTGCAAGTAGTA-1-0 ACACCAAGTATGGGAC-1-1 GGAGCAAGTCGCATTA-1-3 ... GGAGCAAGTCGCATTA-1-3 TGTAGACAGCCACTCG-1-1 ATGATCGGTATCAAGA-1-2 CGCATAAGTCAGTCCG-1-3 ## Spatial experiments: ## 1 experiments ## 1058 features and 1092 spots ## rownames: Arhgef10l Osm Clec4a3 ... Clec4a3 Ccl17 Tcrg-C2 Actg2 ## colnames: CTGGCGACATAAGTCC-1-1 GGTGAAGTACAGGGAT-1-1 TATTCCACTCAGCTCG-1-1 ... TATTCCACTCAGCTCG-1-1 TGTGTCGCGAGTTGCA-1-0 GAAGTGATTTATCGTG-1-0 AAATCGTGTACCACAA-1-1 ## Project: SpatialDDLS-Proj"},{"path":"/articles/realModelExample-hq.html","id":"simulation-of-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Simulation of mixed transcriptional profiles","title":"Get started! Deconvolution of mouse lymph node samples","text":"Now, going simulate cell composition matrices serve simulate mixed transcriptional profiles known cell proportions. done genMixedCellProp function can control different aspects number mixed transcriptional profiles generated, number cells used simulate mixed profile, etc. parameters must decided depending single-cell reference available computational resources. example, standard reference, use num.sim.spots = 10000 n.cells = 50. cell type compositions mixed profiles generated three methods: random sampling Dirichlet distribution. Moreover, order make proportions sparse, prob.sparity parameter controls probability missing cell types simulated spot, opposed mixture cell types. Pure mixed transcriptional profiles composed n.cells cells cell type aggregated. Transcriptional profiles minimum number missing cell types imposed. controlled min.zero.prop argument. relative abundance samples generated criteria can controlled proportion.method parameter. Finally, genMixedCellProp function automatically divide reference cell profiles contained single.cell.real slot training test subsets randomly assign n.cells cells generate every mixed transcriptional profile. , can call simMixedProfiles function, generate actual mixed transcriptional profiles using cell composition matrices generated previous step. step may take depending number transcriptional profiles simulated, patient! addition, users can choose method mixed profiles generated. recommend summing raw counts, normalize samples log-CPM (mixing.function = \"AddRawCount\"), methods available (see Documentation).","code":"mouseDLN.SDDLS <- genMixedCellProp( mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", num.sim.spots = 10000, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 0.8, min.zero.prop = 5, balanced.type.cells = TRUE ) ## ## === The number of mixed profiles that will be generated is equal to 10000 ## ## === Training set cells by type: ## - B cells: 5573 ## - CD4 T cells: 1362 ## - CD8 T cells: 2179 ## - cDC1s: 67 ## - cDC2s: 58 ## - GD T cells: 59 ## - Macrophages: 70 ## - Migratory DCs: 199 ## - Monocytes: 53 ## - NK cells: 62 ## - pDCs: 52 ## - Tregs: 260 ## === Test set cells by type: ## - B cells: 2786 ## - CD4 T cells: 681 ## - CD8 T cells: 1089 ## - cDC1s: 33 ## - cDC2s: 29 ## - GD T cells: 29 ## - Macrophages: 35 ## - Migratory DCs: 100 ## - Monocytes: 26 ## - NK cells: 31 ## - pDCs: 26 ## - Tregs: 130 ## === Probability matrix for training data: ## - Mixed spots: 6667 ## - Cell types: 12 ## === Probability matrix for test data: ## - Mixed spots: 3333 ## - Cell types: 12 ## DONE mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) ## === Setting parallel environment to 3 thread(s) ## ## === Generating train mixed profiles: ## ## === Generating test mixed profiles: ## ## DONE"},{"path":"/articles/realModelExample-hq.html","id":"training-a-fully-connected-neural-network-using-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Training a fully-connected neural network using mixed transcriptional profiles","title":"Get started! Deconvolution of mouse lymph node samples","text":"generated set mixed transcriptional profiles known cell composition, can train neural network using training subset evaluate model predicting cell type proportions test subset. trained, model can deconvolute cellular composition new transcriptional profiles, spot spatial transcriptomics experiment. architecture network fully customizable, although experience, hyperparameters used example work cases. Particularly, employ model two hidden layers, consisting 200 neurons, training process involving 60 epochs. metrics training progress can shown setting verbose = TRUE. Anyhow, advanced metrics can calculated using calculateEvalMetrics function. function computes mean absolute error (MAE) mean squared error (MSE) metrics per cell type, providing insight model’s performance cell type. metrics can visualized using various functions: demonstrated, overall performance satisfactory, indicating model capable comprehending distinctive features cell type provide precise predictions cell type composition transcriptional profiles.","code":"mouseDLN.SDDLS <- trainDeconvModel( mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200), verbose = FALSE ) ## 1/105 [..............................] - ETA: 12s - loss: 0.0815 - accuracy: 0.7812 - mean_absolute_error: 0.0171 - categorical_accuracy: 0.7812 79/105 [=====================>........] - ETA: 0s - loss: 0.0729 - accuracy: 0.8896 - mean_absolute_error: 0.0149 - categorical_accuracy: 0.8896 105/105 [==============================] - 0s 638us/step - loss: 0.0744 - accuracy: 0.8890 - mean_absolute_error: 0.0152 - categorical_accuracy: 0.8890 mouseDLN.SDDLS <- calculateEvalMetrics(mouseDLN.SDDLS) distErrorPlot( mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", color.by = \"CellType\", error.labels = FALSE, type = \"boxplot\", size.point = 0.5 ) distErrorPlot( mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", facet.by = \"CellType\", color.by = \"CellType\", error.label = TRUE, type = \"boxplot\" ) corrExpPredPlot( mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", corr = \"both\", size.point = 0.5 ) ## `geom_smooth()` using formula = 'y ~ x'"},{"path":"/articles/realModelExample-hq.html","id":"deconvolution-of-the-spatial-transcriptomics-dataset","dir":"Articles","previous_headings":"Loading data","what":"Deconvolution of the spatial transcriptomics dataset","title":"Get started! Deconvolution of mouse lymph node samples","text":"Finally, can use trained model deconvolute signals spot using `deconvSpatialDDLS’ function. default, function uses trained model predict cell proportions two sets transcriptional profiles ST datasets: ‘Intrinsic’ profiles: actual transcriptional profiles every spot ST dataset. ‘Extrinsic’ profiles: simulated profiles generated surrounding spots every spot. concept create mirrored set transcriptional profiles represent transcriptional features spatial context spot. latter can used understand similar spot neighbors. Considering hypothesis can infer cellular composition spot based surroundings given correlation spatial location cell composition/transcriptional profile, can use information spatially contextualize predictions improve accuracy. furhter mentions, refer process regularization. Details methodology explained Documentation Mañanes et al. (2023). Now, let’s project predicted proportions spatial coordinates: reveal hidden patterns coordinates caused using color scale, can utilize plotSpatialProp function independently plot cell type: addition ‘regularized’ cell proportions, can plot predictions calculated intrinsic extrinsic transcriptional profiles. instance, let’s plot predicted extrinsic transcriptional profiles: one might expect, smoothed version final predictions. also possible visualize distances extrinsic intrinsic transcriptional profiles spot understand regularization step works using plotDistances function: spots distances less mean distance regularized according nearest neighbor spots.","code":"mouseDLN.SDDLS <- deconvSpatialDDLS( mouseDLN.SDDLS, k.spots = 6 ) ## No 'index.st' provided. Deconvoluting all SpatialExperiment objects contained in the `spatial.experiments` slot ## === Normalizing data (LogCPM) ## === Predicting cell type proportions ## 1/35 [..............................] - ETA: 0s 35/35 [==============================] - 0s 587us/step ## ## === Calculating distances in PCA space ## - Using 133 PCs (variance cutoff: 0.8) ## === Calculating alpha factors based on distances ## DONE plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1) for (i in trained.model(mouseDLN.SDDLS) %>% cell.types()) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\" ) + coord_fixed() ) } for (i in mouseDLN.SDDLS@trained.model@cell.types) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\", prediction = \"Extrinsic\" ) + coord_fixed() ) } plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed()"},{"path":"/articles/realModelExample-hq.html","id":"interpreting-the-model","dir":"Articles","previous_headings":"Loading data","what":"Interpreting the model","title":"Get started! Deconvolution of mouse lymph node samples","text":"order make predictions transparent, SpatialDDLS includes additional module designed provide insights model’s decision-making process. relies calculating predicted classes/loss function gradients respect input variables, method popularly known Vanilla Gradient. numeric values computed gene cell type using pure mixed transcriptional profiles previously simulated. Therefore, can interpreted extent feature contributing model’s predictions. values initially calculated sample/gene level, can aggregated cell type level order assess relevance different genes cell type proportion predictions. steps performed interGradientDL function: Importantly, depending method parameter, positive negative gradient must differently interpreted: gradients respect input variables calculated using loss function (method = \"loss\"), genes negative gradients (minimize loss function) positively correlated presence cell type. Conversely, gradients respect input variables calculated using classes (method = \"class\"), genes positive gradients (make probability cell type higher) positively associated cell type. important note markers interpreted cell type markers. Rather, serve indications help interpret model’s performance. addition, due multivariate nature approach, gradients surrogates feature level predictions made considering input variables collectively, thus caution exercised drawing direct conclusions specific gene-cell type relationships. example, let’s calculate gradients class function respect input features show top 5 genes greatest gradients per cell type: can seen, among top 5 genes canonical markers different cell types appear, Cd79b B cells, Cd8a CD8 T cells, Foxp3 Tregs. just top 5 genes, considering higher number can provide comprehensive understanding genes utilizaed model. also provide plotHeatmapGradsAgg function visualizing N top mean gradients per cell type. plot highlights genes high gradients across different cell types, reflecting multivariate nature neural networks. advisable examine positive negative gradients, genes significantly contribute network’s predictions. Finally, can use plotSpatialGeneExpr visualize spatial distribution top N genes per cell tupe ST dataset. Let’s plot genes cell types demonstration purposes: top N genes per cell type visualize spatial distribution ST dataset. Let’s plot genes cell types just demonstration purposes:","code":"mouseDLN.SDDLS <- interGradientsDL( mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\" ) top.gradients <- topGradientsCellType( mouseDLN.SDDLS, method = \"class\", top.n.genes = 5 ) sapply( top.gradients, \\(x) x$Positive ) %>% as.data.frame() ## B cells CD4 T cells CD8 T cells cDC1s cDC2s GD T cells Macrophages ## 1 Vpreb3 Ly6c1 Cd8b1 Slc1a3 Gm26917 Slc1a3 1300017J02Rik ## 2 Slc1a3 Igfbp4 Ccr9 Ifi205 Xist Il4 Cst7 ## 3 Snx2 Slc1a3 Cd8a Gatm Slc1a3 Ip6k3 Pla2g2d ## 4 Man1a Satb1 Ppic Lpl Rnf144b Ramp3 Cbr2 ## 5 Cd72 Trat1 Acp5 Ryr2 Ryr2 Ska3 Timd4 ## Migratory DCs Monocytes NK cells pDCs Tregs ## 1 Slc1a3 Map4k4 Slc1a3 Ptgs1 Foxp3 ## 2 Xist Clec4e Klrc1 Clec2d Itgb1 ## 3 Gm26917 Slc1a3 Ugcg Xist Ctla4 ## 4 Clec2d B2m Cd47 Cd200 Izumo1r ## 5 Pde1c Pde1c Jak1 H2-D1 Cxcr3 hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\") hh$Positive hh$Negative top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) for (i in c(\"B cells\", \"CD4 T cells\", \"CD8 T cells\", \"Tregs\", \"Monocytes\")) { list.plots <- list() for (j in top.genes[[i]][[\"Absolute\"]]) { list.plots[[j]] <- plotSpatialGeneExpr( mouseDLN.SDDLS, index.st = 1, gene = j, size.point = 0.5, title = paste0(i, \" - \", j) ) + coord_fixed() + theme(legend.position = \"none\") ## legend removed just for viz } print(ggpubr::ggarrange(plotlist = list.plots, align = \"hv\")) }"},{"path":"/articles/realModelExample-hq.html","id":"clustering-analysis","dir":"Articles","previous_headings":"Loading data","what":"Clustering analysis","title":"Get started! Deconvolution of mouse lymph node samples","text":"SpatialDDLS R package also includes functions cluster ST dataset according predicted cell composition spot. functionality enables dissect ST datasets distinct cellular niches, can relevant information analyses.","code":"mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20) ## No 'index.st' provided. Deconvoluting all SpatialExperiment objects contained in the `spatial.experiments` slot ## === Selected graph-based clustering ## === Running clustering for slide 1 plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed() ## No 'index.st' provided. Using first ST dataset ## === Plotting first clustering configuration Clustering.graph.k.20"},{"path":"/articles/realModelExample-hq.html","id":"comparing-deconvoluted-cell-proportions-with-colocalization-of-cell-markers","dir":"Articles","previous_headings":"Loading data","what":"Comparing deconvoluted cell proportions with colocalization of cell markers","title":"Get started! Deconvolution of mouse lymph node samples","text":"Finally, assess whether collocation predicted cell type proportions expression known classic markers cell type. analysis aims validate model’s predictions comparing well-established cellular markers, mean quantitative validation model.","code":"customMarkers <- list( \"B cells\" = c(\"Cd74\", \"Cd19\", \"Cd79a\", \"Cd79b\", \"Ly6d\"), \"CD4 T cells\" = c(\"Cd4\", \"Lef1\", \"Fyb\"), \"CD8 T cells\" = c(\"Cd8b1\", \"Cd8a\", \"Trac\"), cDC1s = c(\"Xcr1\", \"Irf8\"), cDC2s = c(\"Irf4\", \"Cd4\"), \"GD T cells\" = c(\"Il7r\", \"Id2\"), Macrophages = c(\"Lyz2\", \"Lyz1\", \"Cd86\", \"Ly6c1\"), \"Migratory DCs\" = c(\"Ccl5\", \"Anxa3\", \"Fscn1\"), Monocytes = c(\"Fcer1g\", \"Cst3\", \"Lst1\", \"Itgam\", \"Kit\", \"Fcgr3\"), \"NK cells\" = c(\"Nkg7\", \"Il2rb\", \"Gzma\"), pDCs = c(\"Siglech\", \"Plac8\", \"Ly6c2\", \"Vtsb\", \"Zeb2\", \"Siglech\"), Tregs = c(\"Ikzf2\", \"Il2ra\", \"Foxp3\") ) %>% lapply(FUN = function(x) x[x %in% rownames(MouseDLN.ST)]) ## calculate z-scores exprST <- MouseDLN.ST@assays@data[[1]] logCPM <- edgeR::cpm(exprST, log = TRUE) meanZscoresCustom <- purrr::map( .x = names(customMarkers), .f = ~{ colMeans(t(scale(t(logCPM[customMarkers[[.x]], , drop = FALSE])))) } ) %>% do.call(cbind, .) colnames(meanZscoresCustom) <- names(customMarkers) color.z.scores <- rev( colorRampPalette(RColorBrewer::brewer.pal(n = 10, name = \"RdBu\"))(20) ) st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) ) colnames(st.coor) <- paste(\"Spatial\", 1:2) dfPlotLong <- reshape2::melt( as.data.frame(cbind(st.coor, meanZscoresCustom)), id.vars = c(\"Spatial 1\", \"Spatial 2\"), variable.name = \"CellType\", value.name = \"Zscore\" ) dfPlotLong %>% ggplot( aes(x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = Zscore) ) + geom_point(size = 0.5) + theme_classic() + ggtitle(\"Mean z-score of cell type markers\") + scale_color_gradientn(colors = color.z.scores, limit = c(-2, 2)) + theme( plot.title = element_text(face = \"bold\", hjust = 0.5), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank() ) + coord_fixed() + facet_wrap(~ CellType)"},{"path":[]},{"path":"/articles/realModelExample.html","id":"loading-data","dir":"Articles","previous_headings":"","what":"Loading data","title":"Deconvolution of mouse lymph node samples","text":"Firstly, let’s load required packages data: Let’s explore spatial transcriptomics data contained MouseDLN.ST object: plot chunk spatialdata-cond regard single-cell RNA-seq data, preprocessing visualization performed, analysis outside scope tutorial.","code":"library(\"SpatialDDLS\") ## Error in library(\"SpatialDDLS\"): there is no package called 'SpatialDDLS' library(\"SingleCellExperiment\") library(\"SpatialExperiment\") library(\"ggplot2\") library(\"ggpubr\") ## in case it is not installed if (!requireNamespace(\"SpatialDDLSdata\", quietly = TRUE)) { if (!requireNamespace(\"devtools\", quietly = TRUE)) { install.packages(\"devtools\") } devtools::install_github(\"diegommcc/SpatialDDLSdata\") } library(\"SpatialDDLSdata\") # SingleCellExperiment with scRNA-seq data(MouseDLN.SCE) # SpatialExperiment with spatial transcriptomics data data(MouseDLN.ST) cbind(spatialCoords(MouseDLN.ST), colData(MouseDLN.ST)) %>% as.data.frame() %>% ggplot(aes(X0, X1, color = lymph_node)) + geom_point() + ggtitle(\"Mouse lymph nodes by condition\") + theme_classic() + coord_fixed()"},{"path":"/articles/realModelExample.html","id":"loading-data-into-a-spatialddls-object","dir":"Articles","previous_headings":"Loading data","what":"Loading data into a SpatialDDLS object","title":"Deconvolution of mouse lymph node samples","text":"Now, need create SpatialDDLS object, serve central core subsequent steps. suggest including spatial single-cell transcriptomics data enable filtering selection genes present data types analyses. Additionally, recommend filtering genes based expression levels order reduce number dimensions consider meaningful genes. Please refer documentation review implemented strategies (specially sc.n.genes.per.cluster sc.min.mean.counts parameters). can show basic information object: case, working 1 spatial transcriptomics dataset, arbitrary number SpatialExperiment objects can loaded.","code":"mouseDLN.SDDLS <- createSpatialDDLSobject( sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", sc.gene.ID.column = \"GeneSymbol\", sc.cell.type.column = \"broad_cell_types\", st.data = MouseDLN.ST, sc.min.counts = 1, sc.min.cells = 1, sc.filt.genes.cluster = TRUE, sc.n.genes.per.cluster = 150, sc.min.mean.counts = 2, st.spot.ID.column = \"CellID\", st.gene.ID.column = \"GeneSymbol\" ) ## Error in createSpatialDDLSobject(sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", : could not find function \"createSpatialDDLSobject\" mouseDLN.SDDLS ## Error in eval(expr, envir, enclos): object 'mouseDLN.SDDLS' not found"},{"path":"/articles/realModelExample.html","id":"simulation-of-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Simulation of mixed transcriptional profiles","title":"Deconvolution of mouse lymph node samples","text":"Now, going simulate cell composition matrices serve simulate mixed transcriptional profiles known cell proportions. done genMixedCellProp function can control different aspects number mixed transcriptional profiles generated, number cells used simulate mixed profile, etc. parameters must decided depending single-cell reference available computational resources. example, standard reference, use num.sim.spots = 10000 n.cells = 50. cell type compositions mixed profiles generated three methods: random sampling Dirichlet distribution. Moreover, order make proportions sparse, prob.sparity parameter controls probability missing cell types simulated spot, opposed mixture cell types. Pure mixed transcriptional profiles composed n.cells cells cell type aggregated. Transcriptional profiles minimum number missing cell types imposed. controlled min.zero.prop argument. relative abundance samples generated criteria can controlled proportion.method parameter. Finally, genMixedCellProp function automatically divide reference cell profiles contained single.cell.real slot training test subsets randomly assign n.cells cells generate every mixed transcriptional profile. , can call simMixedProfiles function, generate actual mixed transcriptional profiles using cell composition matrices generated previous step. step may take depending number transcriptional profiles simulated, patient! addition, users can choose method mixed profiles generated. recommend summing raw counts, normalize samples log-CPM (mixing.function = \"AddRawCount\"), methods available (see Documentation).","code":"mouseDLN.SDDLS <- genMixedCellProp( mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", num.sim.spots = 10000, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 1, min.zero.prop = 5, balanced.type.cells = TRUE, verbose = TRUE ) ## Error in genMixedCellProp(mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", : could not find function \"genMixedCellProp\" mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) ## Error in simMixedProfiles(mouseDLN.SDDLS, threads = 3): could not find function \"simMixedProfiles\""},{"path":"/articles/realModelExample.html","id":"training-a-fully-connected-neural-network-using-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Training a fully-connected neural network using mixed transcriptional profiles","title":"Deconvolution of mouse lymph node samples","text":"generated set mixed transcriptional profiles known cell composition, can train neural network using training subset evaluate model predicting cell type proportions test subset. trained, model can deconvolute cellular composition new transcriptional profiles, spot spatial transcriptomics experiment. architecture network fully customizable, although experience, hyperparameters used example work cases. Particularly, employ model two hidden layers, consisting 200 neurons, training process involving 60 epochs. default, metrics performance model displayed. advanced metrics can calculated using calculateEvalMetrics function. function computes mean absolute error (MAE) mean squared error (MSE) metrics per cell type, providing insight model’s performance cell type. metrics can visualized using various functions: demonstrated, overall performance satisfactory, indicating model capable comprehending distinctive features cell type provide precise predictions cell type composition transcriptional profiles.","code":"mouseDLN.SDDLS <- trainDeconvModel( mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200) ) ## Error in trainDeconvModel(mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, : could not find function \"trainDeconvModel\" mouseDLN.SDDLS <- calculateEvalMetrics(mouseDLN.SDDLS) ## Error in calculateEvalMetrics(mouseDLN.SDDLS): could not find function \"calculateEvalMetrics\" distErrorPlot( mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", color.by = \"CellType\", error.labels = FALSE, type = \"boxplot\", size.point = 0.5 ) ## Error in distErrorPlot(mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", : could not find function \"distErrorPlot\" distErrorPlot( mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", facet.by = \"CellType\", color.by = \"CellType\", error.label = TRUE, type = \"boxplot\" ) ## Error in distErrorPlot(mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", : could not find function \"distErrorPlot\" corrExpPredPlot( mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", corr = \"both\", size.point = 0.5 ) ## Error in corrExpPredPlot(mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", : could not find function \"corrExpPredPlot\""},{"path":"/articles/realModelExample.html","id":"deconvolution-of-the-spatial-transcriptomics-dataset","dir":"Articles","previous_headings":"Loading data","what":"Deconvolution of the spatial transcriptomics dataset","title":"Deconvolution of mouse lymph node samples","text":"Finally, can use trained model deconvolute signals spot using `deconvSpatialDDLS’ function. default, function uses trained model predict cell proportions two sets transcriptional profiles ST datasets: ‘Intrinsic’ profiles: actual transcriptional profiles every spot ST dataset. ‘Extrinsic’ profiles: simulated profiles generated surrounding spots every spot. concept create mirrored set transcriptional profiles represent transcriptional features spatial context spot. latter can used understand similar spot neighbors. Considering hypothesis can infer cellular composition spot based surroundings given correlation spatial location cell composition/transcriptional profile, can use information spatially contextualize predictions improve accuracy. furhter mentions, refer process regularization. Details methodology explained Documentation Mañanes et al. (2023). Now, let’s project predicted proportions spatial coordinates: reveal hidden patterns coordinates caused using color scale, can utilize plotSpatialProp function independently plot cell type: addition ‘regularized’ cell proportions, can plot predictions calculated intrinsic extrinsic transcriptional profiles. instance, let’s plot predicted extrinsic transcriptional profiles: one might expect, smoothed version final predictions. also possible visualize distances extrinsic intrinsic transcriptional profiles spot understand regularization step works using plotDistances function: spots distances less mean distance regularized according nearest neighbor spots. can observe spots using following chunk code:","code":"mouseDLN.SDDLS <- deconvSpatialDDLS( mouseDLN.SDDLS, k.spots = 6 ) ## Error in deconvSpatialDDLS(mouseDLN.SDDLS, k.spots = 6): could not find function \"deconvSpatialDDLS\" plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1) ## Error in plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1): could not find function \"plotSpatialPropAll\" for (i in trained.model(mouseDLN.SDDLS) %>% cell.types()) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\" ) + coord_fixed() ) } ## Error in cell.types(.): could not find function \"cell.types\" for (i in mouseDLN.SDDLS@trained.model@cell.types) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\", prediction = \"Extrinsic\" ) + coord_fixed() ) } ## Error in eval(expr, envir, enclos): object 'mouseDLN.SDDLS' not found plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed() ## Error in plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5): could not find function \"plotDistances\" st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) )[, 1:2] ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'spatialCoords': could not find function \"spatial.experiments\" colnames(st.coor) <- paste(\"Spatial\", 1:2) ## Error: object 'st.coor' not found st.pred <- deconv.spots(object = mouseDLN.SDDLS, index.st = 1) ## Error in deconv.spots(object = mouseDLN.SDDLS, index.st = 1): could not find function \"deconv.spots\" alpha.factors <- st.pred[[\"Alpha.Factors\"]] ## Error in eval(expr, envir, enclos): object 'st.pred' not found dfPlot <- as.data.frame(cbind(st.coor, alpha.factors)) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': object 'st.coor' not found ggplot( dfPlot, aes( x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = alpha.factors ) ) + geom_point(size = 1.5) + scale_color_gradient2() + ggtitle(\"Distances\") + SpatialDDLSTheme() + coord_fixed() ## Error in eval(expr, envir, enclos): object 'dfPlot' not found"},{"path":"/articles/realModelExample.html","id":"interpreting-the-model","dir":"Articles","previous_headings":"Loading data","what":"Interpreting the model","title":"Deconvolution of mouse lymph node samples","text":"order make predictions transparent, SpatialDDLS includes additional module designed provide insights model’s decision-making process. relies calculating predicted classes/loss function gradients respect input variables, method popularly known Vanilla Gradient. numeric values computed gene cell type using pure mixed transcriptional profiles previously simulated. Therefore, can interpreted extent feature contributing model’s predictions. values initially calculated sample/gene level, can aggregated cell type level order assess relevance different genes cell type proportion predictions. steps performed interGradientDL function: Importantly, depending method parameter, positive negative gradient must differently interpreted: gradients respect input variables calculated using loss function (method = \"loss\"), genes negative gradients (minimize loss function) positively correlated presence cell type. Conversely, gradients respect input variables calculated using classes (method = \"class\"), genes positive gradients (make probability cell type higher) positively associated cell type. important note markers interpreted cell type markers. Rather, serve indications help interpret model’s performance. addition, due multivariate nature approach, gradients surrogates feature level predictions made considering input variables collectively, thus caution exercised drawing direct conclusions specific gene-cell type relationships. example, let’s calculate gradients class function respect input features show top 5 genes greatest gradients per cell type: can seen, among top 5 genes canonical markers different cell types appear, Cd79b B cells, Cd8a CD8 T cells, Foxp3 Tregs. just top 5 genes, considering higher number can provide comprehensive understanding genes utilizaed model. also provide plotHeatmapGradsAgg function visualizing N top mean gradients per cell type. plot highlights genes high gradients across different cell types, reflecting multivariate nature neural networks. advisable examine positive negative gradients, genes significantly contribute network’s predictions. Finally, can use plotSpatialGeneExpr visualize spatial distribution top N genes per cell tupe ST dataset. Let’s plot genes cell types demonstration purposes: top N genes per cell type visualize spatial distribution ST dataset. Let’s plot genes cell types just demonstration purposes:","code":"mouseDLN.SDDLS <- interGradientsDL( mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\" ) ## Error in interGradientsDL(mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\"): could not find function \"interGradientsDL\" top.gradients <- topGradientsCellType( mouseDLN.SDDLS, method = \"class\", top.n.genes = 5 ) ## Error in topGradientsCellType(mouseDLN.SDDLS, method = \"class\", top.n.genes = 5): could not find function \"topGradientsCellType\" sapply( top.gradients, \\(x) x$Positive ) %>% as.data.frame() ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': error in evaluating the argument 'X' in selecting a method for function 'sapply': object 'top.gradients' not found hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\") ## Error in plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\"): could not find function \"plotHeatmapGradsAgg\" hh$Positive ## Error in eval(expr, envir, enclos): object 'hh' not found hh$Negative ## Error in eval(expr, envir, enclos): object 'hh' not found top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) ## Error in topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4): could not find function \"topGradientsCellType\" for (i in c(\"B cells\", \"CD4 T cells\", \"CD8 T cells\", \"Tregs\", \"Monocytes\")) { list.plots <- list() for (j in top.genes[[i]][[\"Absolute\"]]) { list.plots[[j]] <- plotSpatialGeneExpr( mouseDLN.SDDLS, index.st = 1, gene = j, size.point = 0.5, title = paste0(i, \" - \", j) ) + coord_fixed() + theme(legend.position = \"none\") ## legend removed just for viz } print(ggpubr::ggarrange(plotlist = list.plots, align = \"hv\")) } ## Error in eval(expr, envir, enclos): object 'top.genes' not found"},{"path":"/articles/realModelExample.html","id":"clustering-analysis","dir":"Articles","previous_headings":"Loading data","what":"Clustering analysis","title":"Deconvolution of mouse lymph node samples","text":"SpatialDDLS R package also includes functions cluster ST dataset according predicted cell composition spot. functionality enables dissect ST datasets distinct cellular niches, can relevant information analyses.","code":"mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20) ## Error in spatialPropClustering(mouseDLN.SDDLS, k.nn = 20): could not find function \"spatialPropClustering\" plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed() ## Error in plotSpatialClustering(mouseDLN.SDDLS): could not find function \"plotSpatialClustering\""},{"path":"/articles/realModelExample.html","id":"comparing-deconvoluted-cell-proportions-with-colocalization-of-cell-markers","dir":"Articles","previous_headings":"Loading data","what":"Comparing deconvoluted cell proportions with colocalization of cell markers","title":"Deconvolution of mouse lymph node samples","text":"Finally, assess whether collocation predicted cell type proportions expression known classic markers cell type. analysis aims validate model’s predictions comparing well-established cellular markers, mean quantitative validation model.","code":"customMarkers <- list( \"B cells\" = c(\"Cd74\", \"Cd19\", \"Cd79a\", \"Cd79b\", \"Ly6d\"), \"CD4 T cells\" = c(\"Cd4\", \"Lef1\", \"Fyb\"), \"CD8 T cells\" = c(\"Cd8b1\", \"Cd8a\", \"Trac\"), cDC1s = c(\"Xcr1\", \"Irf8\"), cDC2s = c(\"Irf4\", \"Cd4\"), \"GD T cells\" = c(\"Il7r\", \"Id2\"), Macrophages = c(\"Lyz2\", \"Lyz1\", \"Cd86\", \"Ly6c1\"), \"Migratory DCs\" = c(\"Ccl5\", \"Anxa3\", \"Fscn1\"), Monocytes = c(\"Fcer1g\", \"Cst3\", \"Lst1\", \"Itgam\", \"Kit\", \"Fcgr3\"), \"NK cells\" = c(\"Nkg7\", \"Il2rb\", \"Gzma\"), pDCs = c(\"Siglech\", \"Plac8\", \"Ly6c2\", \"Vtsb\", \"Zeb2\", \"Siglech\"), Tregs = c(\"Ikzf2\", \"Il2ra\", \"Foxp3\") ) %>% lapply(FUN = function(x) x[x %in% rownames(MouseDLN.ST)]) ## calculate z-scores exprST <- MouseDLN.ST@assays@data[[1]] logCPM <- edgeR::cpm(exprST, log = TRUE) meanZscoresCustom <- purrr::map( .x = names(customMarkers), .f = ~{ colMeans(t(scale(t(logCPM[customMarkers[[.x]], , drop = FALSE])))) } ) %>% do.call(cbind, .) colnames(meanZscoresCustom) <- names(customMarkers) color.z.scores <- rev(colorRampPalette(RColorBrewer::brewer.pal(n = 10, name = \"RdBu\"))(20)) st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) ) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'spatialCoords': could not find function \"spatial.experiments\" colnames(st.coor) <- paste(\"Spatial\", 1:2) ## Error: object 'st.coor' not found dfPlotLong <- reshape2::melt( as.data.frame(cbind(st.coor, meanZscoresCustom)), id.vars = c(\"Spatial 1\", \"Spatial 2\"), variable.name = \"CellType\", value.name = \"Zscore\" ) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': object 'st.coor' not found dfPlotLong %>% ggplot( aes(x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = Zscore) ) + geom_point(size = 0.5) + theme_classic() + ggtitle(\"Mean z-score of cell type markers\") + scale_color_gradientn(colors = color.z.scores, limit = c(-2, 2)) + theme( plot.title = element_text(face = \"bold\", hjust = 0.5), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank() ) + coord_fixed() + facet_wrap(~ CellType) + coord_fixed() ## Error in eval(expr, envir, enclos): object 'dfPlotLong' not found"},{"path":[]},{"path":"/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Diego Mañanes. Author, maintainer. Carlos Torroja. Author. Fatima Sanchez-Cabo. Author.","code":""},{"path":"/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Mañanes D, Torroja C, Sanchez-Cabo F (2023). SpatialDDLS: Deconvolution Spatial Transcriptomics Data Based Neural Networks. R package version 1.0.0, https://github.com/diegommcc/SpatialDDLS, https://diegommcc.github.io/SpatialDDLS/.","code":"@Manual{, title = {SpatialDDLS: Deconvolution of Spatial Transcriptomics Data Based on Neural Networks}, author = {Diego Mañanes and Carlos Torroja and Fatima Sanchez-Cabo}, year = {2023}, note = {R package version 1.0.0, https://github.com/diegommcc/SpatialDDLS}, url = {https://diegommcc.github.io/SpatialDDLS/}, }"},{"path":"/index.html","id":"spatialddls-","dir":"","previous_headings":"","what":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","title":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","text":"SpatialDDLS R package provides neural network-based solution cell type deconvolution spatial transcriptomics data. package takes advantage single-cell RNA sequencing (scRNA-seq) data simulate mixed transcriptional profiles known cell composition train fully-connected neural networks predict cell type composition spatial transcriptomics spots. resulting trained models can applied new spatial transcriptomics data predict cell type proportions, allowing accurate cell type identification characterization spatially-resolved transcriptomic data. Overall, SpatialDDLS powerful tool cell type deconvolution spatial transcriptomics data, providing reliable, fast flexible solution researchers field. details algorithm functionalities implemented package, see https://diegommcc.github.io/SpatialDDLS/.","code":""},{"path":"/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","text":"SpatialDDLS already available CRAN: version development available GitHub can installed follows: package depends tensorflow keras R packages, working Python interpreter Tensorflow Python library installed needed. installTFpython function provides easy way install conda environment named spatialddls-env necessary dependencies covered. recommend installing TensorFlow Python library way, although custom installation possible.","code":"install.packages(\"SpatialDDLS\") if (!requireNamespace(\"devtools\", quietly = TRUE)) install.packages(\"devtools\") devtools::install_github(\"diegommcc/SpatialDDLS\") library(\"SpatialDDLS\") installTFpython(install.conda = TRUE)"},{"path":[]},{"path":"/reference/DeconvDLModel-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The DeconvDLModel Class — DeconvDLModel-class","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"DeconvDLModel object stores information related deep neural network models. consists trained model, training history, predictions test data. running calculateEvalMetrics, possible find performance evaluation model test data (see ?calculateEvalMetrics details).","code":""},{"path":"/reference/DeconvDLModel-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"steps related Deep Learning carried using keras tensorflow packages, use R6 classes system. want save DeconvDLModel object RDS file, SpatialDDLS provides saveRDS generic function transforms R6 object containing trained model native valid R object. Specifically, model converted list architecture network weights learned training, minimum information needed use model predictor. want keep optimizer state, see ?saveTrainedModelAsH5. want store either DeconvDLModel SpatialDDLS objects disk RDA files, see ?preparingToSave.","code":""},{"path":"/reference/DeconvDLModel-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"model Trained deep neural network. slot can contain R6 keras.engine.sequential.Sequential object list two elements: architecture model resulting weights training. training.history List evolution selected metrics training. test.metrics Performance model test data. test.pred Predicted cell type proportions test data. cell.types Vector cell types considered model. features Vector features (genes) considered model. features used subsequent predictions. test.deconv.metrics Performance model test data cell type. slot generated calculateEvalMetrics function (see ?calculateEvalMetrics details). interpret.gradients Gradients interpretation. SpatialDDLS provides functions better understand prediction made model (see ?interGradientsDL details). slot list either one two elements: gradients either loss function predicted class respect input variables using pure (one cell type) mixed transcriptional profiles. gradients can interpreted extent model using variables predict cell type proportions.","code":""},{"path":"/reference/PropCellTypes-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The PropCellTypes Class — PropCellTypes-class","title":"The PropCellTypes Class — PropCellTypes-class","text":"PropCellTypes class data storage class contains information related cell type composition matrices used simulate mixed transcriptional profiles. matrix stored prob.matrix slot slots contain additional information generated process required subsequent steps.","code":""},{"path":"/reference/PropCellTypes-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The PropCellTypes Class — PropCellTypes-class","text":"See ?genMixedCellProp function information cell type composition matrices generated. Plots cell type proportion distributions can accessed using showProbPlot function (see ?showProbPlot details).","code":""},{"path":"/reference/PropCellTypes-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The PropCellTypes Class — PropCellTypes-class","text":"prob.matrix Matrix cell type proportions simulate mixed transcriptional profiles. cell.names Matrix containing cells used generate simulated mixed transcriptional profiles. set.list List cells sorted cell type. set Vector containing cell names present object. method Vector indicating method cell type proportions generated. plots Plots showing cell type proportion distributions. See ?showProbPlot details. type.data Character indicating type data contained: 'train' 'test'.","code":""},{"path":"/reference/SpatialDDLS-Rpackage.html","id":null,"dir":"Reference","previous_headings":"","what":"SpatialDDLS: an R package to deconvolute spatial transcriptomics data using\ndeep neural networks — SpatialDDLS-Rpackage","title":"SpatialDDLS: an R package to deconvolute spatial transcriptomics data using\ndeep neural networks — SpatialDDLS-Rpackage","text":"SpatialDDLS R package provides neural network-based solution cell type deconvolution spatial transcriptomics data. package takes advantage single-cell RNA sequencing (scRNA-seq) data simulate mixed transcriptional profiles known cell composition train fully-connected neural networks predict cell type composition spatial transcriptomics spots. resulting trained models can applied new spatial transcriptomics data predict cell type proportions, allowing accurate cell type identification characterization spatially-resolved transcriptomic data. Finally, predictions forced keep spatial consistency process refer spatial regularization. Overall, SpatialDDLS powerful tool cell type deconvolution spatial transcriptomics data, providing reliable, fast flexible solution researchers field. See Mañanes et al. (2023) (doi:10.1101/2023.08.31.555677 ) examples (https://diegommcc.github.io/SpatialDDLS/) details.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The SpatialDDLS Class — SpatialDDLS-class","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"SpatialDDLS object core SpatialDDLS package. object stores different intermediate data needed construction new deconvolution models, spatial transcriptomics profiles deconvoluted, predicted cell type proportions.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"object uses classes store different types data generated workflow: SingleCellExperiment class single-cell RNA-Seq data storage, using sparse matrix Matrix package (dgCMatrix class) HDF5Array class case using HDF5 files back-end (see information). SpatialExperiment class spatial transcriptomics data storage. ZinbModel class estimated parameters simulation new single-cell profiles. SummarizedExperiment class simulated mixed transcriptional profiles storage. PropCellTypes class composition cell type matrices. See ?PropCellTypes details. DeconvDLModel class store information related deep neural network models. See ?DeconvDLModel details. order provide way work large amounts data RAM-constrained machines, provide possibility using HDF5 files back-end store count matrices real simulated single-cell profiles using HDF5Array DelayedArray classes homonymous packages.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"single.cell.real Real single-cell data stored SingleCellExperiment object. count matrix stored either dgCMatrix HDF5Array objects. spatial.experiments List SpatialExperiment objects deconvoluted. zinb.params ZinbModel object estimated parameters simulation new single-cell expression profiles. single.cell.simul Simulated single-cell expression profiles using ZINB-WaVE model. prob.cell.types PropCellTypes class cell composition matrices built simulation mixed transcriptional profiles known cell composition. mixed.profiles List simulated train test mixed transcriptional profiles. entry SummarizedExperiment object. Count matrices can stored HDF5Array objects using HDF5 files back-end case RAM limitations. trained.model DeconvDLModel object information related deconvolution model. See ?DeconvDLModel details. deconv.spots Deconvolution results. consists list element corresponds results SpatialExperiment object contained spatial.experiments slot. project Name project. version Version SpatialDDLS object built .","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The Class ZinbParametersModel — ZinbParametersModel-class","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"ZinbParametersModel class wrapper class ZinbModel class zinbwave package.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"wrapper class contains zinbwave.model slot, holds valid ZinbModel object.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"zinbwave.model valid ZinbModel object.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 .","code":""},{"path":"/reference/barErrorPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate bar error plots — barErrorPlot","title":"Generate bar error plots — barErrorPlot","text":"Generate bar error plots cell type (CellType) number different cell types (nCellTypes) test mixed transcriptional profiles.","code":""},{"path":"/reference/barErrorPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate bar error plots — barErrorPlot","text":"","code":"barErrorPlot( object, error = \"MSE\", by = \"CellType\", dispersion = \"se\", filter.sc = TRUE, title = NULL, angle = NULL, theme = NULL )"},{"path":"/reference/barErrorPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate bar error plots — barErrorPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. error 'MAE' 'MSE'. Variable used show errors. Available options : 'nCellTypes', 'CellType'. dispersion Standard error ('se') standard deviation ('sd'). former default. filter.sc Boolean indicating whether single-cell profiles filtered correlation results associated mixed transcriptional profiles shown (TRUE default). title Title plot. angle Angle ticks. theme ggplot2 theme.","code":""},{"path":"/reference/barErrorPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate bar error plots — barErrorPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/barErrorPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate bar error plots — barErrorPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.5452 #> - accuracy: 0.125 #> - mean_absolute_error: 0.238 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # bar error plots barErrorPlot( object = SDDLS, error = \"MSE\", by = \"CellType\" ) barErrorPlot( object = SDDLS, error = \"MAE\", by = \"nCellTypes\" ) # }"},{"path":"/reference/barPlotCellTypes.html","id":null,"dir":"Reference","previous_headings":"","what":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"Bar plot deconvoluted cell type proportions.","code":""},{"path":"/reference/barPlotCellTypes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"","code":"barPlotCellTypes( data, colors = NULL, set = NULL, prediction = \"Regularized\", color.line = NA, x.label = \"Spots\", rm.x.text = FALSE, title = \"Results of deconvolution\", legend.title = \"Cell types\", angle = 90, theme = NULL, index.st = NULL )"},{"path":"/reference/barPlotCellTypes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"data SpatialDDLS object deconv.spots slot containing predicted cell type proportions. colors Vector colors used. set Type simplification performed deconvolution. can simpli.set simpli.maj (NULL default). prediction Set predicted cell proportions plotted. can \"Regularized\", \"Intrinsic\" \"Extrinsic\". color.line Color border bars. x.label Label x-axis. rm.x.text Logical value indicating whether remove x-axis ticks (name samples). title Title plot. legend.title Title legend plot. angle Angle text ticks. theme ggplot2 theme. index.st Name index element wanted shown deconv.spots slot.","code":""},{"path":"/reference/barPlotCellTypes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"ggplot object provided cell proportions represented bar plot.","code":""},{"path":[]},{"path":"/reference/blandAltmanLehPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"Generate Bland-Altman agreement plots predicted expected cell type proportions test data. Bland-Altman agreement plots can shown mixed split either cell type (CellType) number cell types present spots (nCellTypes). See facet.argument examples information.","code":""},{"path":"/reference/blandAltmanLehPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"","code":"blandAltmanLehPlot( object, colors, color.by = \"CellType\", facet.by = NULL, log.2 = FALSE, filter.sc = TRUE, density = TRUE, color.density = \"darkblue\", size.point = 0.05, alpha.point = 1, ncol = NULL, nrow = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/blandAltmanLehPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. colors Vector colors used. color.Variable used color data. Options nCellTypes CellType. facet.Variable used show data different panels. NULL, plot split different panels. Options nCellTypes (number different cell types) CellType (cell type). log.2 Whether show Bland-Altman agreement plot log2 space (FALSE default). filter.sc Boolean indicating whether single-cell profiles filtered correlations results associated mixed spot profiles shown (TRUE default). density Boolean indicating whether density lines shown (TRUE default). color.density Color density lines density argument TRUE. size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). ncol Number columns facet.used. nrow Number rows facet.used. title Title plot. theme ggplot2 theme. ... Additional argument facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/blandAltmanLehPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/blandAltmanLehPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.554 #> - accuracy: 0.25 #> - mean_absolute_error: 0.2344 #> - categorical_accuracy: 0.25 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # Bland-Altman plot by cell type blandAltmanLehPlot( object = SDDLS, facet.by = \"CellType\", color.by = \"CellType\" ) # Bland-Altman plot of all samples mixed blandAltmanLehPlot( object = SDDLS, facet.by = NULL, color.by = \"CellType\", alpha.point = 0.3, log2 = TRUE ) # }"},{"path":"/reference/calculateEvalMetrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"Calculate evaluation metrics test mixed transcriptional profiles. default, absolute error (AbsErr), proportional absolute error (ppAbsErr), squared error (SqrErr), proportional squared error (ppSqrErr) calculated test mixed profile. addition, metrics aggregated according three criteria: cell type (CellType), probability bins ranges 0.1 (pBin), number different cell types present spot (nCellTypes).","code":""},{"path":"/reference/calculateEvalMetrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"","code":"calculateEvalMetrics(object)"},{"path":"/reference/calculateEvalMetrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"object SpatialDDLS object trained model trained.model slot actual cell proportions test mixed profiles prob.cell.types slot.","code":""},{"path":"/reference/calculateEvalMetrics.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"SpatialDDLS object DeconvDLModel object. calculated metrics stored test.deconv.metrics slot DeconvDLModel object.","code":""},{"path":[]},{"path":"/reference/cell.names.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"Get set cell.names slot PropCellTypes object","code":""},{"path":"/reference/cell.names.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"","code":"cell.names(object) cell.names(object) <- value"},{"path":"/reference/cell.names.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"object PropCellTypes object. value Matrix containing names mixed transcriptional profiles simulated rows cells used simulate columns.","code":""},{"path":"/reference/cell.types.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"Get set cell.types slot DeconvDLModel object","code":""},{"path":"/reference/cell.types.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"","code":"cell.types(object) cell.types(object) <- value"},{"path":"/reference/cell.types.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"object DeconvDLModel object. value Vector cell types considered deep neural network model.","code":""},{"path":"/reference/corrExpPredPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"Generate correlation plots predicted expected cell type proportions test data. Correlation plots can shown mixed either split cell type (CellType) number different cell types present spots (nCellTypes).","code":""},{"path":"/reference/corrExpPredPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"","code":"corrExpPredPlot( object, colors, facet.by = NULL, color.by = \"CellType\", corr = \"both\", filter.sc = TRUE, pos.x.label = 0.01, pos.y.label = 0.95, sep.labels = 0.15, size.point = 0.1, alpha.point = 1, ncol = NULL, nrow = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/corrExpPredPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. colors Vector colors used. facet.Show data different panels. Options nCellTypes (number different cell types) CellType (cell type) (NULL default). color.Variable used color data. Options nCellTypes CellType. corr Correlation value shown annotation plot. Available metrics Pearson's correlation coefficient ('pearson') concordance correlation coefficient ('ccc'). can 'pearson', 'ccc' '' (default). filter.sc Boolean indicating whether single-cell profiles filtered mixed transcriptional profile errors shown (TRUE default). pos.x.label X-axis position correlation annotations (0.95 default). pos.y.label Y-axis position correlation annotations (0.1 default). sep.labels Space separating annotations corr equal '' (0.15 default). size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). ncol Number columns facet.NULL. nrow Number rows facet.different NULL. title Title plot. theme ggplot2 theme. ... Additional arguments facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/corrExpPredPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/corrExpPredPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"","code":"# \\donttest{ set.seed(123) set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.4361 #> - accuracy: 0.125 #> - mean_absolute_error: 0.233 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # correlations by cell type corrExpPredPlot( object = SDDLS, facet.by = \"CellType\", color.by = \"CellType\", corr = \"both\" ) #> `geom_smooth()` using formula = 'y ~ x' # correlations of all samples mixed corrExpPredPlot( object = SDDLS, facet.by = NULL, color.by = \"CellType\", corr = \"ccc\", pos.x.label = 0.2, alpha.point = 0.3 ) #> `geom_smooth()` using formula = 'y ~ x' # }"},{"path":"/reference/createSpatialDDLSobject.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a SpatialDDLS object — createSpatialDDLSobject","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"Create SpatialDDLS object providing single-cell RNA-seq data. Additionally, spatial transcriptomics data contained SpatialDDLS objects can also provided. recommended provide types data use genes shared experiments.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"","code":"createSpatialDDLSobject( sc.data, sc.cell.ID.column, sc.cell.type.column, sc.gene.ID.column, st.data, st.spot.ID.column, st.gene.ID.column, filter.mt.genes = \"^mt-\", sc.filt.genes.cluster = TRUE, sc.min.mean.counts = 1, sc.n.genes.per.cluster = 300, top.n.genes = 2000, sc.min.counts = 0, sc.min.cells = 0, st.min.counts = 0, st.min.spots = 0, st.n.slides = 3, shared.genes = TRUE, sc.name.dataset.h5 = NULL, sc.file.backend = NULL, sc.name.dataset.backend = NULL, sc.compression.level = NULL, sc.chunk.dims = NULL, sc.block.processing = FALSE, verbose = TRUE, project = \"SpatialDDLS-Proj\" )"},{"path":"/reference/createSpatialDDLSobject.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"sc.data Single-cell RNA-seq profiles used reference. data provided files, single.cell.real must vector three elements: single-cell counts, cells metadata genes metadata. hand, data provided SingleCellExperiment object, single-cell counts must present assay slot, cells metadata colData slot, genes metadata rowData slot. sc.cell.ID.column Name number column cells metadata corresponding cell names expression matrix (single-cell RNA-seq data). sc.cell.type.column Name column number corresponding cell types cells metadata. sc.gene.ID.column Name number column genes metadata corresponding names used features/genes (single-cell RNA-seq data). st.data Spatial transcriptomics datasets deconvoluted. can single SpatialExperiment object list . st.spot.ID.column Name number column spots metadata corresponding spot names expression matrix (spatial transcriptomics data). st.gene.ID.column Name number column genes metadata corresponding names used features/genes (spatial transcriptomics data). filter.mt.genes Regular expression matching mitochondrial genes ruled (^mt- default). NULL, filtering performed. sc.filt.genes.cluster Whether filter single-cell RNA-seq genes according minimum threshold non-zero average counts per cell type (sc.min.mean.counts). TRUE default. sc.min.mean.counts Minimum non-zero average counts per cluster filter genes. 1 default. sc.n.genes.per.cluster Top n genes highest logFC per cluster. 300 default. See Details section details. top.n.genes Maximum number genes used downstream steps (2000 default). case number genes filtering greater top.n.genes, genes set according variability across whole single-cell dataset. sc.min.counts Minimum gene counts filter (0 default; single-cell RNA-seq data). sc.min.cells Minimum cells min.counts (0 default; single-cell RNA-seq data). st.min.counts Minimum gene counts filter (0 default; spatial transcriptomics data). st.min.spots Minimum cells min.counts (0 default; spatial transcriptomics data). st.n.slides Minimum number slides (SpatialExperiment objects) gene expressed order keep . parameter applicable multiple SpatialExperiment objects provided. Genes present least st.n.slides discarded. filtering desired, set st.n.slides = 1. shared.genes set TRUE, genes present isngle-cell spatial transcriptomics data retained processing (TRUE default). sc.name.dataset.h5 Name data set HDF5 file provided single-cell RNA-seq data. sc.file.backend Valid file path store loaded single-cell RNA-seq data HDF5 file. provided, data stored HDF5 file back-end using DelayedArray HDF5Array packages instead loaded RAM. suitable situations large amounts data stored memory. Note operations data performed blocks (.e subsets determined size), may result longer execution times. NULL default. sc.name.dataset.backend Name HDF5 file dataset used. Note exist. NULL (default), random dataset name generated. sc.compression.level compression level used sc.file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. sc.chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered SpatialDDLS object simulation, one sample order increase read times following steps. larger number columns written chunk may lead longer read times. sc.block.processing Boolean indicating whether single-cell RNA-seq data treated blocks (data provided HDF5 file). FALSE default. Note using functionality suitable cases possible load data RAM therefore execution times longer. verbose Show informative messages execution (TRUE default). project Name project SpatialDDLS object.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"SpatialDDLS object single-cell RNA-seq data provided loaded single.cell.real slot SingleCellExperiment object. spatial transcriptomics data provided, loaded spatial.experiments slot.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"Filtering genes order reduce number dimensions used subsequent steps, createSpatialDDLSobject implements different strategies aimed removing useless genes deconvolution: Filtering cell level: genes less expressed determined cutoff N cells removed. See sc.min.cells/st.min.cells sc.min.counts/st.min.cells parameters. Filtering cluster level (scRNA-seq data): sc.filt.genes.cluster == TRUE, createSpatialDDLSobject sets cutoff non-zero average counts per cluster (sc.min.mean.counts parameter) take sc.n.genes.per.cluster genes highest logFC per cluster. LogFCs calculated using normalized logCPM cluster respect average whole dataset). Finally, number remaining genes greater top.n.genes, genes ranked based variance top.n.genes variable genes used downstream analyses. Single-cell RNA-seq data Single-cell RNA-seq data can provided files (formats allowed: tsv, tsv.gz, mtx (sparse matrix) hdf5) SingleCellExperiment object. Data stored single.cell.real slot, must consist three pieces information: Single-cell counts: genes rows cells columns. Cells metadata: annotations (columns) cell (rows). Genes metadata: annotations (columns) gene (rows). data provided files, single.cell.real argument must vector three elements ordered first file corresponds count matrix, second cells metadata, last genes metadata. hand, data provided SingleCellExperiment object, must contain single-cell counts assay, cells metadata colData, genes metadata rowData. Data must provided without transformation (e.g. log-transformation), raw counts preferred. Spatial transcriptomics data must SpatialExperiment object (list one slide going deconvoluted) containing information single-cell RNA-seq data: count matrix, spots metadata, genes metadata. Please, make sure gene identifiers used spatial single-cell transcriptomics data consistent.","code":""},{"path":[]},{"path":"/reference/createSpatialDDLSobject.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) counts <- matrix( rpois(30, lambda = 5), ncol = 6, dimnames = list(paste0(\"Gene\", 1:5), paste0(\"Spot\", 1:6)) ) coordinates <- matrix( c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), ncol = 2 ) ste <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", 1:5)), colData = data.frame(Cell_ID = paste0(\"Spot\", 1:6)), spatialCoords = coordinates ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", st.data = ste, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 5 #> - Discarded features: 0 #> #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === Number of shared genes between single-cell and spatial transcriptomics datasets: 5 #> - Original # genes in single-cell data: 40 #> - Original # genes in ST data (object with the greatest # genes): 5 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 5"},{"path":"/reference/deconv.spots.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"Get set deconv.spots slot SpatialDDLS object","code":""},{"path":"/reference/deconv.spots.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"","code":"deconv.spots(object, index.st = NULL) deconv.spots(object, index.st = NULL) <- value"},{"path":"/reference/deconv.spots.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"object SpatialDDLS object. index.st Name index predicted cell proportions (spatial.experiments slot). NULL (default), results returned. value List predicted cell type proportions experiments stored spatial.experiments slot.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":null,"dir":"Reference","previous_headings":"","what":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"Deconvolute spatial transcriptomics data using trained model SpatialDDLS object. trained model used predict cell proportions two mirrored transcriptional profiles: 'Intrinsic' profiles: transcriptional profiles spot ST dataset. 'Extrinsic' profiles: profiles simulated surrounding spots spot. prediction, cell proportions intrinsic profiles (intrinsic cell proportions) regularized based similarity intrinsic extrinsic profiles order maintain spatial consistency. approach leverages transcriptional spatial information. details, see Mañanes et al., 2023 Details section.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"","code":"deconvSpatialDDLS( object, index.st, normalize = TRUE, scaling = \"standardize\", k.spots = 4, pca.space = TRUE, pca.var = 0.8, metric = \"euclidean\", alpha.cutoff = \"mean\", alpha.quantile = 0.5, simplify.set = NULL, simplify.majority = NULL, use.generator = FALSE, batch.size = 64, verbose = TRUE )"},{"path":"/reference/deconvSpatialDDLS.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"object SpatialDDLS object trained.model spatial.experiments slots. index.st Name index dataset/slide stored SpatialDDLS object (spatial.experiments slot) deconvolute. missing, datasets deconvoluted. normalize Normalize data (logCPM) deconvolution (TRUE default). scaling scale data training. Options include \"standardize\" (values centered around mean unit standard deviation) \"rescale\" (values shifted rescaled end ranging 0 1). normalize = FALSE, data scaled. k.spots Number nearest spots considered spot regularization simulation extrinsic transcriptional profiles. greater, smoother regularization (4 default). pca.space Whether use PCA space calculate distances intrinsic extrinsic transcriptional profiles (TRUE default). pca.var Threshold explained variance (0.2 1) used choose number PCs used pca.space == TRUE. metric Metric used measure distance/similarity intrinsic extrinsic transcriptional profiles. may 'euclidean', 'cosine' 'pearson' ('euclidean' default). alpha.cutoff Minimum distance regularization. may 'mean' (spots transcriptional distances shorter mean distance dataset modified) 'quantile' (spots transcriptional distances shorter alpha.quantile quantile used). 'mean' default. alpha.quantile Quantile used alpha.cutoff == 'quantile'. 0.5 default. simplify.set List specifying cell types compressed new label name list item. See examples details. provided, results stored list 'raw' 'simpli.set' elements. simplify.majority List specifying cell types compressed cell type highest proportion spot. Unlike simplify.set, new labels created. provided, results stored list 'raw' 'simpli.majority' elements. use.generator Boolean indicating whether use generators prediction (FALSE default). batch.size Number samples per batch. use.generator = TRUE. verbose Show informative messages execution.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"SpatialDDLS object deconv.spots slot. output list containing 'Regularized', 'Intrinsic' 'Extrinsic' deconvoluted cell proportions, 'Distances' intrinsic extrinsic transcriptional profiles, 'Weight.factors' final weights used regularize intrinsic cell proportions. simplify.set /simplify.majority provided, deconv.spots slot contain list raw simplified results.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"deconvolution process involves two main steps: predicting cell proportions based transcriptome using trained neural network model, regularization cell proportions based spatial location spot. regularization step, mirrored version spot simulated based N-nearest spots. refer profiles 'extrinsic' profiles, whereas transcriptional profiles spot called 'intrinsic' profiles. Extrinsic profiles used regularize predictions based intrinsic profiles. rationale spots surrounded transcriptionally similar spots similar cell compositions, therefore predicted proportions can smoothed preserve spatial consistency. hand, spots surrounded dissimilar spots predicted neighbors, thus can predicted transcriptional profiles likely due presenting specific cell compositions. Regarding working os SpatialDDLS: first, extrinsic profiles simulated based N-nearest spots spot summing transcriptomes. Distances extrinsic intrinsic profiles spot calculated similar/dissimilar spots identified. two sets transcriptional profiles used input trained neural network model, according calculated distances, weighted mean predicted proportions spot calculated. Spots distances intrinsic extrinsic profiles greater alpha.cutoff regularized, whereas spots distances less alpha.cutoff contribute weighted mean. Weights calculated rescaling distances less alpha.cutoff 0 0.5, maximum extent extrinsic profile can modified predictions based intrinsic profiles 0.5 (regular mean). details, see Mañanes et al., 2023. function requires SpatialDDLS object trained deep neural network model (trained.model slot, spatial transcriptomics datasets deconvoluted spatial.experiments slot. See ?createSpatialDDLSobject ?loadSTProfiles details.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"Mañanes, D., Rivero-García, ., Jimenez-Carretero, D., Torres, M., Sancho, D., Torroja, C., Sánchez-Cabo, F. (2023). SpatialDDLS: R package deconvolute spatial transcriptomics data using neural networks. biorxiv. doi: doi:10.1101/2023.08.31.555677 .","code":""},{"path":[]},{"path":"/reference/deconvSpatialDDLS.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of SDDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.5547 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2371 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # simulating spatial data ngenes <- sample(3:40, size = 1) ncells <- sample(3:40, size = 1) counts <- matrix( rpois(ngenes * ncells, lambda = 5), ncol = ncells, dimnames = list(paste0(\"Gene\", seq(ngenes)), paste0(\"Spot\", seq(ncells))) ) coordinates <- matrix( rep(c(1, 2), ncells), ncol = 2 ) st <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", seq(ngenes))), colData = data.frame(Cell_ID = paste0(\"Spot\", seq(ncells))), spatialCoords = coordinates ) SDDLS <- loadSTProfiles( object = SDDLS, st.data = st, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 33 #> - Discarded features: 0 #> # simplify arguments simplify <- list(CellGroup1 = c(\"CellType1\", \"CellType2\", \"CellType4\"), CellGroup2 = c(\"CellType3\", \"CellType5\")) SDDLS <- deconvSpatialDDLS( object = SDDLS, index.st = 1, simplify.set = simplify, simplify.majority = simplify ) #> === Filtering out 18 features in data that are not present in trained model #> === Normalizing data (LogCPM) #> === Predicting cell type proportions #> #> === Calculating distances in PCA space #> - Using 12 PCs (variance cutoff: 0.8) #> === Calculating alpha factors based on distances #> === Note that only regularized proportions will be simplified #> DONE # }"},{"path":"/reference/distErrorPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate box or violin plots showing error distribution — distErrorPlot","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"Generate box violin plots show errors distributed. Errors can shown mixed either split cell type (CellType) number cell types present spots (nCellTypes). See facet.argument examples details.","code":""},{"path":"/reference/distErrorPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"","code":"distErrorPlot( object, error, colors, x.by = \"pBin\", facet.by = NULL, color.by = \"nCellTypes\", filter.sc = TRUE, error.label = FALSE, pos.x.label = 4.6, pos.y.label = NULL, size.point = 0.1, alpha.point = 1, type = \"violinplot\", ylimit = NULL, nrow = NULL, ncol = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/distErrorPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. error Error represented. Available metric errors : absolute error ('AbsErr'), proportional absolute error ('ppAbsErr'), squared error ('SqrErr'), proportional squared error ('ppSqrErr'). colors Vector colors used. x.Variable used X-axis. facet.NULL, best choice pBin (probability bins). Options: nCellTypes (number different cell types), CellType (cell type), pBin. facet.Show data different panels. Options nCellTypes (number different cell types) CellType (cell type) (NULL default). color.Variable used color data. Options nCellTypes CellType. filter.sc Boolean indicating whether single-cell profiles filtered mixed transcriptional profile errors shown (TRUE default). error.label Boolean indicating whether show average error plot annotation (FALSE default). pos.x.label X-axis position error annotations. pos.y.label Y-axis position error annotations. size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). type Type plot: 'boxplot' 'violinplot' (latter default). ylimit Upper limit Y-axis required (NULL default). nrow Number rows facet.NULL. ncol Number columns facet.NULL. title Title plot. theme ggplot2 theme. ... Additional arguments facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/distErrorPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/distErrorPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample( x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE ) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.6536 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2413 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # representation, for more examples, see the vignettes distErrorPlot( object = SDDLS, error = \"AbsErr\", facet.by = \"CellType\", color.by = \"nCellTypes\", error.label = TRUE ) #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. distErrorPlot( object = SDDLS, error = \"AbsErr\", x.by = \"CellType\", facet.by = NULL, color.by = \"CellType\", error.label = TRUE ) # }"},{"path":"/reference/estimateZinbwaveParams.html","id":null,"dir":"Reference","previous_headings":"","what":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"Estimate parameters ZINB-WaVE model using real single-cell RNA-Seq data set reference simulate new single-cell profiles increase signal underrepresented cell types. step needed size single-cell RNA-seq dataset small underrepresented cell types. step, simSCProfiles function use estimated parameters simulate new single-cell profiles. See ?simSCProfiles information.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"","code":"estimateZinbwaveParams( object, cell.type.column, cell.ID.column, gene.ID.column, cell.cov.columns, gene.cov.columns, subset.cells = NULL, proportional = TRUE, set.type = \"All\", threads = 1, verbose = TRUE )"},{"path":"/reference/estimateZinbwaveParams.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"object SpatialDDLS object single.cell.real slot. cell.type.column Name column number corresponding cell type cell cells metadata. cell.ID.column Name column number corresponding cell names expression matrix cells metadata. gene.ID.column Name column number corresponding notation used features/genes genes metadata. cell.cov.columns Name column number(s) cells metadata used covariates model fitting (covariates used, set empty NULL). gene.cov.columns Name column number(s) genes metadata used covariates model fitting (covariates used, set empty NULL). subset.cells Number cells fit ZINB-WaVE model. Useful original data set large fit model. Set value according original data set resources available computer. NULL (default), cells used. Must integer greater equal number cell types considered less equal total number cells. proportional TRUE, original cell type proportions subset cells generated subset.cells altered far possible. FALSE, cell types number cells far possible (TRUE default). set.type Cell type(s) evaluate ('' default). recommended fitting model cell types rather using subset capture total variability present original experiment even subset cell types simulated. threads Number threads used estimation (1 default). set parallel environment, BiocParallel package must installed. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"SpatialDDLS object zinb.params slot containing ZinbParametersModel object. object contains slot estimated ZINB-WaVE parameters real single-cell RNA-Seq data.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"ZINB-WaVE flexible model zero-inflated count data. function carries model fit real single-cell data modeling \\(Y_{ij}\\) (count feature \\(j\\) sample \\(\\)) random variable following zero-inflated negative binomial (ZINB) distribution. estimated parameters used simulation new single-cell expression profiles sampling negative binomial distribution inserting dropouts binomial distribution. , SpatialDDLS uses zinbFit function zinbwave package (Risso et al., 2018). details model, see Risso et al., 2018.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 . Torroja, C. Sánchez-Cabo, F. (2019). digitalDLSorter: Deep Learning algorithm quantify immune cell populations based scRNA-Seq data. Frontiers Genetics 10, 978. doi: doi:10.3389/fgene.2019.00978 .","code":""},{"path":[]},{"path":"/reference/estimateZinbwaveParams.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"","code":"set.seed(123) # reproducibility sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- estimateZinbwaveParams( object = SDDLS, cell.type.column = \"Cell_Type\", cell.ID.column = \"Cell_ID\", gene.ID.column = \"Gene_ID\", subset.cells = 2, verbose = TRUE ) #> === Setting parallel environment to 1 thread(s) #> === Estimating parameters for all cell types in the experiment #> === Creating cell model matrix based on Cell_Type columns: #> \t~Cell_Type #> === Number of cells for each cell type: #> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates #> === Running estimation process (Start time 05:35:11 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: #> ok #> Initialize parameters: #> ok #> Optimize parameters: #> Iteration 1 #> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed #> 0.026 0.000 0.026 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed #> 0.012 0.000 0.012 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed #> 0.021 0.000 0.020 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed #> 0.007 0.000 0.008 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 #> penalized log-likelihood = -54.6055197876494 #> ok #> #> DONE #> #> Invested time: 1.12"},{"path":"/reference/features.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set features slot in a\nDeconvDLModel object — features","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"Get set features slot DeconvDLModel object","code":""},{"path":"/reference/features.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"","code":"features(object) features(object) <- value"},{"path":"/reference/features.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"object DeconvDLModel object. value Vector features (genes) considered deep neural network model.","code":""},{"path":"/reference/genMixedCellProp.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate training and test cell type composition matrices — genMixedCellProp","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"Generate training test cell type composition matrices simulation mixed transcriptional profiles known cell composition using single-cell expression profiles. resulting PropCellTypes object contain information needed simulate new mixed transcriptional profiles. Note function simulate mixed profiles, task performed simMixedProfiles trainDeconvModel functions (see Documentation).","code":""},{"path":"/reference/genMixedCellProp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"","code":"genMixedCellProp( object, cell.ID.column, cell.type.column, num.sim.spots, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 1, min.zero.prop = NULL, balanced.type.cells = TRUE, verbose = TRUE )"},{"path":"/reference/genMixedCellProp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"object SpatialDDLS object single.cell.real slot , optionally, single.cell.simul slot. cell.ID.column Name column number corresponding cell names cells metadata. cell.type.column Name column number corresponding cell types cells metadata. num.sim.spots Number mixed profiles simulated. recommended adjust number according number available single-cell profiles. n.cells Specifies number cells randomly selected combined generate simulated mixed profiles. default, set 100. controls level noise present simulated data, determines many single-cell profiles combined produce spot. train.freq.cells Proportion cells used simulate training mixed transcriptional profiles (2/3 default). train.freq.spots Proportion mixed transcriptional profiles used training, relative total number simulated spots (num.sim.spots). default value 2/3. proportion.method Vector three elements controls proportion simulated proportions generated method: random sampling Dirichlet distribution, \"pure\" spots (1 cell type), spots specified number different cell types (determined min.zero.prop), respectively. default, 40% simulated proportions follow Dirichlet distribution, 30% consist one cell type, 30% specified number different cell types. prob.sparity affects proportions generated first method (Dirichlet distribution). determines probability missing cell types simulated spot, opposed mixture cell types. higher value parameter result sparse simulated samples. min.zero.prop parameter controls minimum number cell types absent simulated spot. NULL (default), value half total number different cell types, increasing result spots composed fewer cell types. helps create sparse proportions cover wider range situations model training. balanced.type.cells Boolean indicating whether training test cells split balanced way considering cell types (TRUE default). verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/genMixedCellProp.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"SpatialDDLS object prob.cell.types slot containing list two PropCellTypes objects (training test). information structure class, see ?PropCellTypes.","code":""},{"path":"/reference/genMixedCellProp.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"First, single-cell profiles randomly divided two subsets, 2/3 data training 1/3 testing. default setting ratio can changed using train.freq.cells parameter. Next, total num.sim.spots mixed proportions simulated using Dirichlet distribution. simulation takes account probability missing cell types spot, can adjusted using prob.sparity parameter. mixed sample, n.cells single-cell profiles randomly selected combined generate simulated mixed sample. addition Dirichlet-based proportions, pure spots (containing one cell type) spots containing specified number different cell types (determined min.zero.prop patameter) also generated order cover situations cell types present. proportion simulated spots generated method can controlled using proportion.method parameter. visualize distribution cell type proportions generated method, showProbPlot function can used.","code":""},{"path":[]},{"path":"/reference/genMixedCellProp.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE"},{"path":"/reference/getProbMatrix.html","id":null,"dir":"Reference","previous_headings":"","what":"Getter function for the cell composition matrix — getProbMatrix","title":"Getter function for the cell composition matrix — getProbMatrix","text":"Getter function cell composition matrix. function allows access cell composition matrix simulated mixed transcriptional profiles.","code":""},{"path":"/reference/getProbMatrix.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Getter function for the cell composition matrix — getProbMatrix","text":"","code":"getProbMatrix(object, type.data)"},{"path":"/reference/getProbMatrix.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Getter function for the cell composition matrix — getProbMatrix","text":"object SpatialDDLS object prob.cell.types slot. type.data Subset data return: train test.","code":""},{"path":"/reference/getProbMatrix.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Getter function for the cell composition matrix — getProbMatrix","text":"Cell type proportion matrix.","code":""},{"path":[]},{"path":"/reference/installTFpython.html","id":null,"dir":"Reference","previous_headings":"","what":"Install Python dependencies for SpatialDDLS — installTFpython","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"function facilitates installation required Python dependencies SpatialDDLS package. requires Python interpreter TensorFlow Python library dependencies. utilizes reticulate package installer tensorflow R package perform installation. Conda environments used new environment named SpatialDDLS-env. function intended simplify installation process SpatialDDLS automatically installing Miniconda creating new environment named SpatialDDLS-env. users wish use different Python conda environment, see tensorflow::use_condaenv function package vignettes information.","code":""},{"path":"/reference/installTFpython.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"","code":"installTFpython(conda = \"auto\", install.conda = FALSE, miniconda.path = NULL)"},{"path":"/reference/installTFpython.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"conda Path conda executable. Using \"auto\" (default) allows reticulate automatically find appropriate conda binary. install.conda Boolean indicating installing miniconda automatically using reticulate. TRUE, conda argument ignored. FALSE default. miniconda.path install.conda TRUE, can set path miniconda installed. NULL, conda find automatically proper place.","code":""},{"path":"/reference/installTFpython.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"return value, called side effects: installation conda environment Python interpreter Tensorflow","code":""},{"path":"/reference/installTFpython.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"","code":"if (FALSE) { notesInstallation <- installTFpython( method = \"auto\", conda = \"auto\", install.conda = TRUE ) }"},{"path":"/reference/interGradientsDL.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"function enables users gain insights interpretability deconvolution model. calculates gradients classes/loss function respect input features used training. numeric values calculated per gene cell type pure mixed transcriptional profiles, providing information extent feature influences model's prediction cell proportions cell type.","code":""},{"path":"/reference/interGradientsDL.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"","code":"interGradientsDL( object, method = \"class\", normalize = TRUE, scaling = \"standardize\", verbose = TRUE )"},{"path":"/reference/interGradientsDL.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"object SpatialDDLS object containing trained deconvolution model (trained.model slot) pure mixed transcriptional profiles (mixed.profiles slot). method Method calculate gradients respect inputs. can 'class' (gradients predicted classes w.r.t. inputs), 'loss' (gradients loss w.r.t. inputs) ''. normalize Whether normalize data using logCPM (TRUE default). parameter considered method used simulate mixed transcriptional profiles (simMixedProfiles function) \"AddRawCount\". Otherwise, data already normalized. parameter set according transformation used train model. scaling scale data. can : \"standardize\" (values centered around mean unit standard deviation), \"rescale\" (values shifted rescaled end ranging 0 1, default) \"none\" (scaling performed). parameter set according transformation used train model. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/interGradientsDL.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"Object containing gradients interpret.gradients slot DeconvDLModel object (trained.model slot).","code":""},{"path":"/reference/interGradientsDL.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"Gradients classes / loss function respect input features calculated exclusively using pure mixed transcriptional profiles composed single cell type. Consequently, numbers can interpreted extent feature used predict cell type proportion. Gradients calculated sample level gene, mean gradients cell type reported. additional details, see Mañanes et al., 2023.","code":""},{"path":[]},{"path":"/reference/interGradientsDL.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.2716 #> - accuracy: 1 #> - mean_absolute_error: 0.2371 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) # }"},{"path":"/reference/loadSTProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"function loads SpatialExperiment object (list several SpatialExperiment objects) SpatialDDLS object.","code":""},{"path":"/reference/loadSTProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"","code":"loadSTProfiles( object, st.data, st.spot.ID.column, st.gene.ID.column, st.min.counts = 0, st.min.spots = 0, st.n.slides = 3, verbose = TRUE )"},{"path":"/reference/loadSTProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"object SpatialDDLS object. st.data SpatialExperiment object (list several SpatialExperiment objects) deconvoluted. st.spot.ID.column Name number column spots metadata corresponding spot names expression matrix. st.gene.ID.column Name number column genes metadata corresponding names used features/genes. st.min.counts Minimum gene counts filter (0 default). st.min.spots Minimum spots min.counts (0 default). st.n.slides Minimum number slides (SpatialExperiment objects) gene expressed order keep . parameter applicable multiple SpatialExperiment objects provided. Genes present least st.n.slides discarded. filtering desired, set st.n.slides = 1. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/loadSTProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"SpatialDDLS object provided spatial trainscriptomics data loaded spatial.experiments slot.","code":""},{"path":"/reference/loadSTProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"recommended perform step creating SpatialDDLS object using createSpatialDDLSobject function order keep genes shared spatial transcriptomics single-cell transcriptomics data used reference. addition, please, make sure gene identifiers used spatial single-cell transcriptomics data consistent.","code":""},{"path":[]},{"path":"/reference/loadSTProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 ## simulating a SpatialExperiment object counts <- matrix(rpois(30, lambda = 5), ncol = 6) rownames(counts) <- paste0(\"Gene\", 1:5) colnames(counts) <- paste0(\"Spot\", 1:6) coordinates <- matrix( c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), ncol = 2 ) ste <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", 1:5)), colData = data.frame(Cell_ID = paste0(\"Spot\", 1:6)), spatialCoords = coordinates ) ## previous SpatialDDLS object SDDLS <- loadSTProfiles( object = SDDLS, st.data = ste, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 5 #> - Discarded features: 0 #> # }"},{"path":"/reference/loadTrainedModelFromH5.html","id":null,"dir":"Reference","previous_headings":"","what":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"Load HDF5 file trained deep neural network model SpatialDDLS object. Note HDF5 file must valid trained model (keras object).","code":""},{"path":"/reference/loadTrainedModelFromH5.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"","code":"loadTrainedModelFromH5(object, file.path, reset.slot = FALSE)"},{"path":"/reference/loadTrainedModelFromH5.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"object SpatialDDLS object trained.model slot. file.path Valid file path model stored. reset.slot Deletes trained.slot already exists. new DeconvDLModel object formed, contain slots (FALSE default).","code":""},{"path":"/reference/loadTrainedModelFromH5.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"SpatialDDLS object trained.model slot new keras DNN model incorporated.","code":""},{"path":[]},{"path":"/reference/method.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set method slot in a PropCellTypes\nobject — method","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"Get set method slot PropCellTypes object","code":""},{"path":"/reference/method.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"","code":"method(object) method(object) <- value"},{"path":"/reference/method.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"object PropCellTypes object. value Vector containing method cell type proportions generated.","code":""},{"path":"/reference/mixed.profiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"Get set mixed.profiles slot SpatialDDLS object","code":""},{"path":"/reference/mixed.profiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"","code":"mixed.profiles(object, type.data = \"both\") mixed.profiles(object, type.data = \"both\") <- value"},{"path":"/reference/mixed.profiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"object SpatialDDLS object. type.data Type data return. can '' (default), 'train', 'test'. value List two SummarizedExperiment objects, train test, one containing simulated mixed transcriptional profiles.","code":""},{"path":"/reference/model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set model slot in a DeconvDLModel\nobject — model","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"Get set model slot DeconvDLModel object","code":""},{"path":"/reference/model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"","code":"model(object) model(object) <- value"},{"path":"/reference/model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"object DeconvDLModel object. value keras.engine.sequential.Sequential object trained deep neural network model.","code":""},{"path":"/reference/plotDistances.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot distances between intrinsic and extrinsic profiles — plotDistances","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"Color spots spatial coordinates according distances intrinsic extrinsic transcriptional profiles.","code":""},{"path":"/reference/plotDistances.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"","code":"plotDistances( object, index.st, mid.scale = \"mean\", size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotDistances.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list provided. mid.scale midpoint diverging scale. may 'mean' 'median' (former default). size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotDistances.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotHeatmapGradsAgg.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"Plot heatmap showing top positive negative gene average gradients per cell type.","code":""},{"path":"/reference/plotHeatmapGradsAgg.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"","code":"plotHeatmapGradsAgg( object, method = \"class\", top.n.genes = 15, scale.gradients = TRUE )"},{"path":"/reference/plotHeatmapGradsAgg.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"object SpatialDDLS object DeconvDLModel object containing gradients interpret.gradients slot. method Method calculate gradients respect input features. can 'class' (gradients predicted classes w.r.t. input features) 'loss' (gradients loss w.r.t. input features) ('class' default). top.n.genes Top n genes (positive negative) taken per cell type. scale.gradients Whether calculate feature-wise z-scores gradients (TRUE default).","code":""},{"path":"/reference/plotHeatmapGradsAgg.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"list Heatmap-class objects, one top positive another one top negative gradients.","code":""},{"path":[]},{"path":"/reference/plotHeatmapGradsAgg.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.1777 #> - accuracy: 1 #> - mean_absolute_error: 0.1621 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) plotHeatmapGradsAgg(SDDLS, top.n.genes = 2) #> $Absolute #> #> $Positive #> #> $Negative #> # }"},{"path":"/reference/plotSpatialClustering.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"Color spots spatial coordinates according results clustering based predicted proportions.","code":""},{"path":"/reference/plotSpatialClustering.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"","code":"plotSpatialClustering( object, index.st, method, k.nn, k.centers, colors, size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialClustering.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. method Clustering method results plot. can \"graph\" \"k.means\". missing, first configuration found object plotted. k.nn Number nearest neighbors used method == \"graph\". k.centers Number k centers used method == \"k.means\". colors Vector colors used. size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialClustering.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialGeneExpr.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"Color spots spatial coordinates according logCPM values particular gene.","code":""},{"path":"/reference/plotSpatialGeneExpr.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"","code":"plotSpatialGeneExpr( object, index.st, gene, colors = \"spectral\", size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialGeneExpr.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. gene Gene color spots . colors Color scale used. can \"blues\" \"spectral\" (latter default). size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialGeneExpr.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialProp.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"Color spots spatial coordinates according predicted proportions particular cell type. Color scale adapted depending range predicted proportions.","code":""},{"path":"/reference/plotSpatialProp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"","code":"plotSpatialProp( object, index.st, cell.type, colors = \"blues\", set = \"raw\", prediction = \"Regularized\", limits = NULL, size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialProp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. cell.type Cell type predicted proportions color spots . colors Color scale used. can \"blues\" \"spectral\" (former default). set results simplified (see ?deconvSpatialDDLS details), results plot (raw default). prediction can \"Regularized\", \"Intrinsic\" \"Extrinsic\" (\"Regularized\" default). limits vector two elements indicating wanted limits color scale. NULL (default), color scale adjusted max min predicted proportions. size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialProp.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialPropAll.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"Color spots spatial coordinates plot according predicted cell type proportions. cell types represented together using color scale 0 1.","code":""},{"path":"/reference/plotSpatialPropAll.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"","code":"plotSpatialPropAll( object, index.st, colors = \"blues\", set = \"raw\", prediction = \"Regularized\", size.point = 0.1, title = NULL, nrow = NULL, ncol = NULL, theme = NULL )"},{"path":"/reference/plotSpatialPropAll.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. colors Color scale used. can \"blues\" \"spectral\" (former default). set results simplified (see ?deconvSpatialDDLS details), results plot (raw default). prediction can \"Regularized\", \"Intrinsic\" \"Extrinsic\" (\"Regularized\" default). size.point Size points (0.1 default). title Title plot. nrow Number rows split plot. ncol Number columns split plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialPropAll.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotTrainingHistory.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"Plot training history trained SpatialDDLS deep neural network model.","code":""},{"path":"/reference/plotTrainingHistory.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"","code":"plotTrainingHistory( object, title = \"History of metrics during training\", metrics = NULL )"},{"path":"/reference/plotTrainingHistory.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"object SpatialDDLS object trained.model slot. title Title plot. metrics Metrics plotted. NULL (default), metrics available DeconvDLModel object plotted.","code":""},{"path":"/reference/plotTrainingHistory.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"ggplot object progression selected metrics training.","code":""},{"path":[]},{"path":"/reference/plots.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set plots slot in a PropCellTypes\nobject — plots","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"Get set plots slot PropCellTypes object","code":""},{"path":"/reference/plots.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"","code":"plots(object) plots(object) <- value"},{"path":"/reference/plots.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"object PropCellTypes object. value List lists plots showing distribution cell proportions generated method.","code":""},{"path":"/reference/preparingToSave.html","id":null,"dir":"Reference","previous_headings":"","what":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"function prepares SpatialDDLS object saved RDA file contains DeconvDLModel object trained DNN model.","code":""},{"path":"/reference/preparingToSave.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"","code":"preparingToSave(object)"},{"path":"/reference/preparingToSave.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"object SpatialDDLS object trained.data slot containing DeconvDLModel object trained DNN model.","code":""},{"path":"/reference/preparingToSave.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"SpatialDDLS DeconvDLModel object trained keras model transformed keras.engine.sequential.Sequential class list architecture JSON-like character object, weights list.","code":""},{"path":"/reference/preparingToSave.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"Since keras models saved natively R objects, function saves structure model JSON-like character object weights list. allows retrieval model making predictions. important note state optimizer saved, model's architecture weights. save entire model, please see saveTrainedModelAsH5 loadTrainedModelFromH5 functions. also possible save SpatialDDLS object RDS file saveRDS function without preparation.","code":""},{"path":[]},{"path":"/reference/prob.cell.types.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"Get set prob.cell.types slot SpatialDDLS object","code":""},{"path":"/reference/prob.cell.types.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"","code":"prob.cell.types(object, type.data = \"both\") prob.cell.types(object, type.data = \"both\") <- value"},{"path":"/reference/prob.cell.types.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"object SpatialDDLS object. type.data Type data return. can '' (default), 'train', 'test'. value List two PropCellTypes objects corresponding train test data.","code":""},{"path":"/reference/prob.matrix.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"Get set prob.matrix slot PropCellTypes object","code":""},{"path":"/reference/prob.matrix.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"","code":"prob.matrix(object) prob.matrix(object) <- value"},{"path":"/reference/prob.matrix.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"object PropCellTypes object. value Matrix cell types columns samples rows.","code":""},{"path":"/reference/project.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set project slot in a SpatialDDLS\nobject — project","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"Get set project slot SpatialDDLS object","code":""},{"path":"/reference/project.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"","code":"project(object) project(object) <- value"},{"path":"/reference/project.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"object SpatialDDLS object. value Character indicating name project.","code":""},{"path":"/reference/saveRDS.html","id":null,"dir":"Reference","previous_headings":"","what":"Save SpatialDDLS objects as RDS files — saveRDS","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"Save SpatialDDLS DeconvDLModel objects RDS files. keras models stored natively R objects (e.g. RData RDS files). saving architecture JSON-like character object weights list, possible retrieve functional model make new predictions. trained.model slot empty, function behave usual. Note: option, state optimizer saved, model's architecture weights. possible save entire model HDF5 file saveTrainedModelAsH5 function load SpatialDDLS object loadTrainedModelFromH5 function. See documentation details.","code":""},{"path":"/reference/saveRDS.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"","code":"saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL ) # S4 method for DeconvDLModel saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL ) # S4 method for SpatialDDLS saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL )"},{"path":"/reference/saveRDS.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"object SpatialDDLS DeconvDLModel object saved file File path object saved ascii logical. TRUE NA, ASCII representation written; otherwise (default), binary one used. See comments help save. version workspace format version use. NULL specifies current default version (3). supported value 2, default R 1.4.0 R 3.5.0. compress logical specifying whether saving named file use \"gzip\" compression, one \"gzip\", \"bzip2\" \"xz\" indicate type compression used. Ignored file connection. refhook hook function handling reference objects.","code":""},{"path":"/reference/saveRDS.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"return value, saves SpatialDDLS object RDS file disk.","code":""},{"path":[]},{"path":"/reference/saveTrainedModelAsH5.html","id":null,"dir":"Reference","previous_headings":"","what":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"Save trained SpatialDDLS deep neural network model disk HDF5 file. Note function save DeconvDLModel object, trained keras model. alternative saveRDS preparingToSave functions want keep state optimizer.","code":""},{"path":"/reference/saveTrainedModelAsH5.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"","code":"saveTrainedModelAsH5(object, file.path, overwrite = FALSE)"},{"path":"/reference/saveTrainedModelAsH5.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"object SpatialDDLS object trained.model slot. file.path Valid file path save model . overwrite Overwrite file already exists.","code":""},{"path":"/reference/saveTrainedModelAsH5.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"return value, saves keras DNN trained model HDF5 file disk.","code":""},{"path":[]},{"path":"/reference/set.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set set slot in a PropCellTypes\nobject — set","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"Get set set slot PropCellTypes object","code":""},{"path":"/reference/set.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"","code":"set(object) set(object) <- value"},{"path":"/reference/set.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"object PropCellTypes object. value vector containing names cells present object.","code":""},{"path":"/reference/set.list.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set set.list slot in a\nPropCellTypes object — set.list","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"Get set set.list slot PropCellTypes object","code":""},{"path":"/reference/set.list.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"","code":"set.list(object) set.list(object) <- value"},{"path":"/reference/set.list.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"object PropCellTypes object. value List cells sorted corresponding cell type.","code":""},{"path":"/reference/showProbPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"Show distribution plots cell proportions generated genMixedCellProp function.","code":""},{"path":"/reference/showProbPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"","code":"showProbPlot(object, type.data, set, type.plot = \"boxplot\")"},{"path":"/reference/showProbPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"object SpatialDDLS object prob.cell.types slot plot slot. type.data Subset data show: train test. set Integer determining 6 different subsets display. type.plot Character determining type visualization display. can 'boxplot', 'violinplot', 'linesplot' 'ncelltypes'. See Description information.","code":""},{"path":"/reference/showProbPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"ggplot object.","code":""},{"path":"/reference/showProbPlot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"frequencies determine proportion different cell types used simulation mixed transcriptional profiles. Proportions generated method (see ?genMixedCellProp) can visualized three ways: box plots, violin plots, lines plots. can also plot probabilities based number different cell types present samples setting type.plot = 'nCellTypes'.","code":""},{"path":[]},{"path":"/reference/showProbPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE showProbPlot( SDDLS, type.data = \"train\", set = 1, type.plot = \"boxplot\" )"},{"path":"/reference/simMixedProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Simulate training and test mixed spot profiles — simMixedProfiles","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Simulate training test mixed spot transcriptional profiles using cell composition matrices generated genMixedCellProp function.","code":""},{"path":"/reference/simMixedProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"","code":"simMixedProfiles( object, type.data = \"both\", mixing.function = \"AddRawCount\", file.backend = NULL, compression.level = NULL, block.processing = FALSE, block.size = 1000, chunk.dims = NULL, threads = 1, verbose = TRUE )"},{"path":"/reference/simMixedProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"object SpatialDDLS object single.cell.real/single.cell.simul, prob.cell.types slots. type.data Type data generate: 'train', 'test' '' (last default). mixing.function Function used build mixed transcriptional profiles. may : \"AddRawCount\": single-cell profiles (raw counts) added across cells. , log-CPMs calculated (default). \"MeanCPM\": single-cell profiles (raw counts) transformed CPMs cross-cell averages calculated. , log2(CPM + 1) calculated. \"AddCPM\": single-cell profiles (raw counts) transformed CPMs added across cells. , log-CPMs calculated. file.backend Valid file path store simulated mixed expression profiles HDF5 file (NULL default). provided, data stored HDF5 files used back-end using DelayedArray, HDF5Array rhdf5 packages instead loading data RAM. Note operations matrix performed blocks (.e subsets determined size) may result longer execution times. compression.level compression level used file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. block.processing Boolean indicating whether data simulated blocks (file.backend used, FALSE default). functionality suitable cases possible load data memory, leads longer execution times. block.size block.processing = TRUE. Number mixed expression profiles simulated iteration. Larger numbers result higher memory usage shorter execution times. Set accordingly available computational resources (1000 default). chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered SpatialDDLS object simulation, single sample reduce read times following steps. larger number columns written chunk can lead longer read times. threads Number threads used simulation (1 default). verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/simMixedProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"SpatialDDLS object mixed.profiles slot containing list one two entries (depending selected type.data argument): 'train' 'test'. entry consists SummarizedExperiment object simulated mixed slot profiles.","code":""},{"path":"/reference/simMixedProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Mixed profiles generated assumption expression level particular gene given spot sum expression levels cell types make weighted proportions. practice, described Torroja Sanchez-Cabo, 2019, profiles generated summing gene expression levels determined number cells specified known cell composition matrix. number simulated spots cells used simulate spot determined genMixedCellProp function. step can avoided using ..fly argument trainDeconvModel function. SpatialDDLS allows use HDF5 files back-end store simulated data using DelayedArray HDF5Array packages. functionality allows work without keeping data loaded RAM, useful computationally heavy steps neural network training RAM-limited machines. must provide valid file path file.backend argument store resulting file '.h5' extension. option slows execution times, subsequent transformations data done blocks. Note use file.backend argument block.processing = FALSE, mixed profiles simulated one step , thus, loaded RAM. , matrix written HDF5 file. avoid RAM collapse, profiles can simulated written HDF5 files blocks block.size size setting block.processing = TRUE. recommend option accordingly computational resources available number simulated spots generated, , cases, necessary.","code":""},{"path":"/reference/simMixedProfiles.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Fischer B, Smith M Pau, G (2020). rhdf5: R Interface HDF5. R package version 2.34.0. Pagès H, Hickey P Lun (2020). DelayedArray: unified framework working transparently -disk -memory array-like datasets. R package version 0.16.0. Pagès H (2020). HDF5Array: HDF5 backend DelayedArray objects. R package version 1.18.0.","code":""},{"path":[]},{"path":"/reference/simMixedProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE SDDLS <- simMixedProfiles(SDDLS, verbose = TRUE) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE"},{"path":"/reference/simSCProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"Simulate single-cell expression profiles randomly sampling negative binomial distribution inserting dropouts sampling binomial distribution using ZINB-WaVE parameters estimated estimateZinbwaveParams function.","code":""},{"path":"/reference/simSCProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"","code":"simSCProfiles( object, cell.ID.column, cell.type.column, n.cells, suffix.names = \"_Simul\", cell.types = NULL, file.backend = NULL, name.dataset.backend = NULL, compression.level = NULL, block.processing = FALSE, block.size = 1000, chunk.dims = NULL, verbose = TRUE )"},{"path":"/reference/simSCProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"object SpatialDDLS object single.cell.real zinb.params slots. cell.ID.column Name column number corresponding cell names expression matrix cells metadata. cell.type.column Name column number corresponding cell type cell cells metadata. n.cells Number simulated cells generated per cell type (.e. 10 different cell types dataset, n.cells = 100, 1000 cell profiles simulated). suffix.names Suffix used simulated cells. suffix must unique simulated cells, make sure suffix appear real cell names. cell.types Vector indicating cell types simulate. NULL (default), n.cells single-cell profiles cell types simulated. file.backend Valid file path store simulated single-cell expression profiles HDF5 file (NULL default). provided, data stored HDF5 files used back-end using DelayedArray, HDF5Array rhdf5 packages instead loading data RAM memory. suitable situations large amounts data loaded memory. Note operations data performed blocks (.e subsets determined size) may result longer execution times. name.dataset.backend Name dataset HDF5 file used. Note exist. NULL (default), random dataset name used. compression.level compression level used file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. block.processing Boolean indicating whether data simulated blocks (file.backend used, FALSE default). functionality suitable cases possible load data memory leads larger execution times. block.size block.processing = TRUE. Number single-cell expression profiles simulated iteration process. Larger numbers result higher memory usage shorter execution times. Set according available computational resources (1000 default). Note greater total number simulated cells. chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered ZINB-WaVE model simulation single sample order reduce read times following steps. larger number columns written chunk can lead longer read times subsequent steps. Note greater dimensions simulated matrix. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/simSCProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"SpatialDDLS object single.cell.simul slot containing SingleCellExperiment object simulated single-cell expression profiles.","code":""},{"path":"/reference/simSCProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"step, see ?estimateZinbwaveParams. described Torroja Sanchez-Cabo, 2019, function simulates given number transcriptional profiles cell type provided randomly sampling negative binomial distribution \\(\\mu\\) \\(\\theta\\) estimated parameters inserting dropouts sampling binomial distribution probability pi. parameters estimated single-cell real data using estimateZinbwaveParams function. uses ZINB-WaVE model (Risso et al., 2018). details model, see ?estimateZinbwaveParams Risso et al., 2018. file.backend argument allows create HDF5 file simulated single-cell profiles used back-end work data stored disk instead loaded RAM. file.backend argument used block.processing = FALSE, single-cell profiles simulated one step , therefore, loaded RAM memory. , data written HDF5 file. avoid collapse RAM memory many single-cell profiles goin simulated, single-cell profiles can simulated written HDF5 files blocks block.size size setting block.processing = TRUE.","code":""},{"path":"/reference/simSCProfiles.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 . Torroja, C. Sánchez-Cabo, F. (2019). digitalDLSorter: Deep Learning algorithm quantify immune cell populations based scRNA-Seq data. Frontiers Genetics 10, 978. doi: doi:10.3389/fgene.2019.00978 .","code":""},{"path":[]},{"path":"/reference/simSCProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"","code":"set.seed(123) # reproducibility sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- estimateZinbwaveParams( object = SDDLS, cell.type.column = \"Cell_Type\", cell.ID.column = \"Cell_ID\", gene.ID.column = \"Gene_ID\", subset.cells = 2, verbose = TRUE ) #> === Setting parallel environment to 1 thread(s) #> === Estimating parameters for all cell types in the experiment #> === Creating cell model matrix based on Cell_Type columns: #> \t~Cell_Type #> === Number of cells for each cell type: #> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates #> === Running estimation process (Start time 05:35:24 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: #> ok #> Initialize parameters: #> ok #> Optimize parameters: #> Iteration 1 #> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed #> 0.024 0.000 0.024 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed #> 0.011 0.000 0.011 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed #> 0.02 0.00 0.02 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed #> 0.008 0.000 0.007 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 #> penalized log-likelihood = -54.6055197876494 #> ok #> #> DONE #> #> Invested time: 0.14 SDDLS <- simSCProfiles( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", n.cells = 2, verbose = TRUE ) #> === Getting parameters from model: #> - mu: 2, 15 #> - pi: 2, 15 #> - Theta: 15 #> === Selected cell type(s) from ZINB-WaVE model (2 cell type(s)): #> - CellType2 #> - CellType1 #> === Simulated matrix dimensions: #> - n (cells): 4 #> - J (genes): 15 #> - i (# entries): 60 #> #> DONE"},{"path":"/reference/single.cell.real.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"Get set single.cell.real slot SpatialDDLS object","code":""},{"path":"/reference/single.cell.real.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"","code":"single.cell.real(object) single.cell.real(object) <- value"},{"path":"/reference/single.cell.real.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"object SpatialDDLS object. value SingleCellExperiment object real single-cell profiles.","code":""},{"path":"/reference/single.cell.simul.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"Get set single.cell.simul slot SpatialDDLS object","code":""},{"path":"/reference/single.cell.simul.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"","code":"single.cell.simul(object) single.cell.simul(object) <- value"},{"path":"/reference/single.cell.simul.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"object SpatialDDLS object. value SingleCellExperiment object simulated single-cell profiles.","code":""},{"path":"/reference/spatial.experiments.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"Get set spatial.experiments slot SpatialDDLS object","code":""},{"path":"/reference/spatial.experiments.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"","code":"spatial.experiments(object, index.st = NULL) spatial.experiments(object, index.st = NULL) <- value"},{"path":"/reference/spatial.experiments.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data within list. can either position name named list provided. NULL (default), data contained spatial.experiments slot returned. value List element SpatialExperiment object. can named list.","code":""},{"path":"/reference/spatialPropClustering.html","id":null,"dir":"Reference","previous_headings":"","what":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"Cluster spatial transcriptomics data according cell proportions predicted spot. allows segregate ST data niches similar cell composition.","code":""},{"path":"/reference/spatialPropClustering.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"","code":"spatialPropClustering( object, index.st, method = \"graph\", k.nn = 10, k.centers = 5, verbose = TRUE )"},{"path":"/reference/spatialPropClustering.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"object SpatialDDLS object deconvoluted ST datasets. index.st Name index dataset/slide already deconvoluted clustered. missing, datasets already deconvoluted clustered. method Clustering method. can graph (nearest neighbor graph created Louvain algorithm used detect communities) k.means (k-means algorithm run specified number centers (k.centers parameter)). k.nn integer specifying number nearest neighbors used graph construction (10 default). method == \"graph\". k.centers integer specifying number centers k-means algorithm (5 default). method == \"k.means\". verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/spatialPropClustering.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"SpatialDDLS object containing computed clusters column slot colData SpatialExperiment objects.","code":""},{"path":[]},{"path":"/reference/spatialPropClustering.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.24 #> - accuracy: 1 #> - mean_absolute_error: 0.2124 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE # simulating spatial data ngenes <- sample(3:40, size = 1) ncells <- sample(3:40, size = 1) counts <- matrix( rpois(ngenes * ncells, lambda = 5), ncol = ncells, dimnames = list(paste0(\"Gene\", seq(ngenes)), paste0(\"Spot\", seq(ncells))) ) coordinates <- matrix( rep(c(1, 2), ncells), ncol = 2 ) st <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", seq(ngenes))), colData = data.frame(Cell_ID = paste0(\"Spot\", seq(ncells))), spatialCoords = coordinates ) SDDLS <- loadSTProfiles( object = SDDLS, st.data = st, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 19 #> - Discarded features: 0 #> SDDLS <- deconvSpatialDDLS( SDDLS, index.st = 1 ) #> === Filtering out 4 features in data that are not present in trained model #> === Normalizing data (LogCPM) #> === Predicting cell type proportions #> #> === Calculating distances in PCA space #> - Using 3 PCs (variance cutoff: 0.8) #> === Calculating alpha factors based on distances #> DONE SDDLS <- spatialPropClustering(SDDLS, index.st = 1, k.nn = 5) #> === Selected graph-based clustering #> === Running clustering for slide 1 # }"},{"path":"/reference/test.deconv.metrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"Get set test.deconv.metrics slot DeconvDLModel object","code":""},{"path":"/reference/test.deconv.metrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"","code":"test.deconv.metrics(object, metrics = \"All\") test.deconv.metrics(object, metrics = \"All\") <- value"},{"path":"/reference/test.deconv.metrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"object DeconvDLModel object. metrics Metrics show ('' default) value List evaluation metrics assess performance model sample test data.","code":""},{"path":"/reference/test.metrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"Get set test.metrics slot DeconvDLModel object","code":""},{"path":"/reference/test.metrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"","code":"test.metrics(object) test.metrics(object) <- value"},{"path":"/reference/test.metrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"object DeconvDLModel object. value List evaluation metrics prediction test data.","code":""},{"path":"/reference/test.pred.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"Get set test.pred slot DeconvDLModel object","code":""},{"path":"/reference/test.pred.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"","code":"test.pred(object) test.pred(object) <- value"},{"path":"/reference/test.pred.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"object DeconvDLModel object. value Matrix object prediction results test data.","code":""},{"path":"/reference/topGradientsCellType.html","id":null,"dir":"Reference","previous_headings":"","what":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"Retrieve feature names largest/smallest gradients per cell type. genes can used visualize spatial expression ST data (plotGeneSpatial function) plot calculated gradients heatmap (plotGradHeatmap function).","code":""},{"path":"/reference/topGradientsCellType.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"","code":"topGradientsCellType(object, method = \"class\", top.n.genes = 15)"},{"path":"/reference/topGradientsCellType.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"object SpatialDDLS object DeconvDLModel object containing gradients interpret.gradients slot. method Method gradients calculated . can either 'class' (gradients predicted classes w.r.t. inputs) 'loss' (gradients loss w.r.t. input features). top.n.genes Top n genes (positive negative) taken per cell type.","code":""},{"path":"/reference/topGradientsCellType.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"List gene names top positive negative gradients per cell type.","code":""},{"path":[]},{"path":"/reference/topGradientsCellType.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.2015 #> - accuracy: 1 #> - mean_absolute_error: 0.1817 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) listGradients <- topGradientsCellType(SDDLS) lapply(listGradients, head, n = 5) #> $CellType1 #> $CellType1$Absolute #> [1] \"Gene8\" \"Gene11\" \"Gene13\" \"Gene4\" \"Gene3\" \"Gene2\" \"Gene12\" \"Gene14\" #> [9] \"Gene5\" \"Gene7\" \"Gene6\" \"Gene1\" \"Gene10\" \"Gene9\" \"Gene15\" #> #> $CellType1$Positive #> [1] \"Gene8\" \"Gene11\" \"Gene13\" \"Gene4\" \"Gene3\" \"Gene2\" \"Gene12\" \"Gene14\" #> [9] \"Gene5\" \"Gene7\" \"Gene6\" \"Gene1\" \"Gene10\" \"Gene9\" \"Gene15\" #> #> $CellType1$Negative #> [1] \"Gene8\" \"Gene11\" \"Gene13\" \"Gene4\" \"Gene3\" \"Gene2\" \"Gene12\" \"Gene14\" #> [9] \"Gene5\" \"Gene7\" \"Gene6\" \"Gene1\" \"Gene10\" \"Gene9\" \"Gene15\" #> #> #> $CellType2 #> $CellType2$Absolute #> [1] \"Gene15\" \"Gene10\" \"Gene1\" \"Gene7\" \"Gene9\" \"Gene6\" \"Gene2\" \"Gene4\" #> [9] \"Gene3\" \"Gene8\" \"Gene12\" \"Gene14\" \"Gene11\" \"Gene13\" \"Gene5\" #> #> $CellType2$Positive #> [1] \"Gene15\" \"Gene10\" \"Gene1\" \"Gene7\" \"Gene9\" \"Gene6\" \"Gene2\" \"Gene4\" #> [9] \"Gene3\" \"Gene8\" \"Gene12\" \"Gene14\" \"Gene11\" \"Gene13\" \"Gene5\" #> #> $CellType2$Negative #> [1] \"Gene15\" \"Gene10\" \"Gene1\" \"Gene7\" \"Gene9\" \"Gene6\" \"Gene2\" \"Gene4\" #> [9] \"Gene3\" \"Gene8\" \"Gene12\" \"Gene14\" \"Gene11\" \"Gene13\" \"Gene5\" #> #> # }"},{"path":"/reference/trainDeconvModel.html","id":null,"dir":"Reference","previous_headings":"","what":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"Train deep neural network model using training data SpatialDDLS object. model used deconvolute spatial transcriptomics data biological context single-cell RNA-seq data used train . addition, trained model evaluated using test data, prediction results obtained determine performance (see ?calculateEvalMetrics).","code":""},{"path":"/reference/trainDeconvModel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"","code":"trainDeconvModel( object, type.data.train = \"mixed\", type.data.test = \"mixed\", batch.size = 64, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200), activation.fun = \"relu\", dropout.rate = 0.25, loss = \"kullback_leibler_divergence\", metrics = c(\"accuracy\", \"mean_absolute_error\", \"categorical_accuracy\"), normalize = TRUE, scaling = \"standardize\", norm.batch.layers = TRUE, custom.model = NULL, shuffle = TRUE, sc.downsampling = NULL, use.generator = FALSE, on.the.fly = FALSE, agg.function = \"AddRawCount\", threads = 1, view.metrics.plot = TRUE, verbose = TRUE )"},{"path":"/reference/trainDeconvModel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"object SpatialDDLS object single.cell.real/single.cell.simul, prob.cell.types, mixed.profiles slots (last ..fly = FALSE). type.data.train Type profiles used training. can '', 'single-cell' 'mixed' ('mixed' default). type.data.test Type profiles used evaluation. can '', 'single-cell' 'mixed' ('mixed' default). batch.size Number samples per gradient update (64 default). num.epochs Number epochs train model (60 default). num.hidden.layers Number hidden layers neural network (2 default). number must equal length num.units argument. num.units Vector indicating number neurons per hidden layer (c(200, 200) default). length vector must equal num.hidden.layers argument. activation.fun Activation function ('relu' default). See keras documentation know available activation functions. dropout.rate Float 0 1 indicating fraction input neurons dropped layer dropouts (0.25 default). default, SpatialDDLS implements 1 dropout layer per hidden layer. loss Character indicating loss function selected model training ('kullback_leibler_divergence' default). See keras documentation know available loss functions. metrics Vector metrics used assess model performance training evaluation (c(\"accuracy\", \"mean_absolute_error\", \"categorical_accuracy\") default). See keras documentation know available performance metrics. normalize Whether normalize data using logCPM (TRUE default). parameter considered method used simulate mixed transcriptional profiles (simMixedProfiles function) \"AddRawCount\". Otherwise, data already normalized. scaling scale data training. can : \"standardize\" (values centered around mean unit standard deviation), \"rescale\" (values shifted rescaled end ranging 0 1) \"none\" (scaling performed). \"standardize\" default. norm.batch.layers Whether include batch normalization layers hidden dense layer (TRUE default). custom.model allows use custom neural network architecture. must keras.engine.sequential.Sequential object number input neurons equal number considered features/genes, number output neurons equal number cell types considered (NULL default). provided, arguments related neural network architecture ignored. shuffle Boolean indicating whether data shuffled (TRUE default). sc.downsampling used type.data.train equal '' 'single-cell'. allows set maximum number single-cell profiles specific cell type training avoid unbalanced representation classes (NULL default). use.generator Boolean indicating whether use generators training test. Generators automatically used ..fly = TRUE HDF5 files used, can activated user demand (FALSE default). ..fly Boolean indicating whether simulated data generated 'fly' training (FALSE default). agg.function ..fly == TRUE, function used build mixed transcriptional profiles. may : \"AddRawCount\" (default): single-cell profiles (raw counts) added across cells. , log-CPMs calculated. \"MeanCPM\": single-cell profiles (raw counts) transformed logCPM cross-cell averages calculated. \"AddCPM\": single-cell profiles (raw counts) transformed CPMs added across cells. , log-CPMs calculated. threads Number threads used simulation mixed transcriptional profiles ..fly = TRUE (1 default). view.metrics.plot Boolean indicating whether show plots loss evaluation metrics training (TRUE default). keras R allows see model progression training working RStudio. verbose Boolean indicating whether display model progression training model architecture information (TRUE default).","code":""},{"path":"/reference/trainDeconvModel.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"SpatialDDLS object trained.model slot containing DeconvDLModel object. information structure class, see ?DeconvDLModel.","code":""},{"path":"/reference/trainDeconvModel.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"Simulation mixed transcriptional profiles 'fly' trainDeconvModel can avoid storing simulated mixed spot profiles using ..fly argument. functionality aims reducing simMixedProfiles function's memory usage: simulated profiles built batch training/evaluation. Neural network architecture possible change model's architecture: number hidden layers, number neurons hidden layer, dropout rate, activation function, loss function. customized models, possible provide pre-built model custom.model argument (keras.engine.sequential.Sequential object) necessary number input neurons equal number considered features/genes, number output neurons equal number considered cell types.","code":""},{"path":[]},{"path":"/reference/trainDeconvModel.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.193 #> - accuracy: 1 #> - mean_absolute_error: 0.1748 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE # }"},{"path":"/reference/trained.model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"Get set trained.model slot SpatialDDLS object","code":""},{"path":"/reference/trained.model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"","code":"trained.model(object) trained.model(object) <- value"},{"path":"/reference/trained.model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"object SpatialDDLS object. value DeconvDLModel object.","code":""},{"path":"/reference/training.history.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set training.history slot in a\nDeconvDLModel object — training.history","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"Get set training.history slot DeconvDLModel object","code":""},{"path":"/reference/training.history.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"","code":"training.history(object) training.history(object) <- value"},{"path":"/reference/training.history.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"object DeconvDLModel object. value keras_training_history object training history deep neural network model.","code":""},{"path":"/reference/zinb.params.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"Get set zinb.params slot SpatialDDLS object","code":""},{"path":"/reference/zinb.params.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"","code":"zinb.params(object) zinb.params(object) <- value"},{"path":"/reference/zinb.params.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"object SpatialDDLS object. value ZinbParametersModel object valid ZinbModel object.","code":""},{"path":"/reference/zinbwave.model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"Get set zinbwave.model slot ZinbParametersModel object","code":""},{"path":"/reference/zinbwave.model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"","code":"zinbwave.model(object) zinbwave.model(object) <- value"},{"path":"/reference/zinbwave.model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"object ZinbParametersModel object. value ZinbModel object estimated parameters simulate new single-cell profiles.","code":""},{"path":"/news/index.html","id":"spatialddls-010-2023-04-08","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 0.1.0 (2023-04-08)","title":"SpatialDDLS 0.1.0 (2023-04-08)","text":"CRAN release: 2023-05-07 Added NEWS.md file track changes.","code":""},{"path":"/news/index.html","id":"spatialddls-020-2023-10-04","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 0.2.0 (2023-10-04)","title":"SpatialDDLS 0.2.0 (2023-10-04)","text":"Added vignette explaining HDF5 file usage (hdf5Backend.Rmd vignette). Mixed transcriptional profiles now stored raw counts rather normalized values order make calculations transparent. Scale factor normalization can chosen (10e3 now default option).","code":""},{"path":"/news/index.html","id":"spatialddls-100-2023-12-01","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 1.0.0 (2023-12-01)","title":"SpatialDDLS 1.0.0 (2023-12-01)","text":"Regularization predicted cell proportions incorporated. Functions classes relying deconvSpatialDDLS function modified. Added set functions clustering analysis based predicted cell proportions (spatialClustering.R file). Added module neural network interpretation based vanilla gradient (interGradientsDL.R file)","code":""}] +[{"path":"/articles/hdf5Backend.html","id":"general-usage","dir":"Articles","previous_headings":"","what":"General usage","title":"Using HFD5 files as back-end","text":"important parameters must considered : file.backend: file path HDF5 file stored. name.dataset.backend: HDF5 files use “file directory”-like structure, possible store one dataset single file. , changing name dataset needed. provided, random dataset name used. compression.level: allows change level compression HDF5 files. integer value 0 9. Note greater compression level, slower processes longer runtime. chunk.dims: HDF5 files created sets chunks, parameter specifies dimensions . block.processing: available, indicates data treated blocks order avoid loading data RAM. block.size: specific simSCProfiles simMixedProfiles. sets number samples simulated iteration. simplest way use setting file.backend parameter.","code":""},{"path":"/articles/hdf5Backend.html","id":"disclaimer","dir":"Articles","previous_headings":"","what":"Disclaimer","title":"Using HFD5 files as back-end","text":"HDF5 files useful tool allows working large datasets otherwise impossible. However, important note running times may longer, accessing data RAM always faster disk. Therefore, recommend using functionality case large datasets limited computational resources. HDF5Array DelayedArray authors point : can load data memory still compute , ’re always going better time way.","code":""},{"path":"/articles/realModelExample-hq.html","id":"loading-data","dir":"Articles","previous_headings":"","what":"Loading data","title":"Get started! Deconvolution of mouse lymph node samples","text":"Firstly, let’s load required packages data: Let’s explore spatial transcriptomics data contained MouseDLN.ST object: regard single-cell RNA-seq data, preprocessing visualization performed, analysis outside scope tutorial.","code":"library(\"SpatialDDLS\") library(\"SingleCellExperiment\") library(\"SpatialExperiment\") library(\"ggplot2\") library(\"ggpubr\") ## in case it is not installed if (!requireNamespace(\"SpatialDDLSdata\", quietly = TRUE)) { if (!requireNamespace(\"devtools\", quietly = TRUE)) { install.packages(\"devtools\") } devtools::install_github(\"diegommcc/SpatialDDLSdata\") } library(\"SpatialDDLSdata\") # SingleCellExperiment with scRNA-seq data(MouseDLN.SCE) # SpatialExperiment with spatial transcriptomics data data(MouseDLN.ST) cbind(spatialCoords(MouseDLN.ST), colData(MouseDLN.ST)) %>% as.data.frame() %>% ggplot(aes(X0, X1, color = lymph_node)) + geom_point() + ggtitle(\"Mouse lymph nodes by condition\") + theme_classic() + coord_fixed()"},{"path":"/articles/realModelExample-hq.html","id":"loading-data-into-a-spatialddls-object","dir":"Articles","previous_headings":"Loading data","what":"Loading data into a SpatialDDLS object","title":"Get started! Deconvolution of mouse lymph node samples","text":"Now, need create SpatialDDLS object, serve central core subsequent steps. suggest including spatial single-cell transcriptomics data enable filtering selection genes present data types analyses. Additionally, recommend filtering genes based expression levels order reduce number dimensions consider meaningful genes. Please refer documentation review implemented strategies (specially sc.n.genes.per.cluster sc.min.mean.counts parameters). can show basic information object: case, working 1 spatial transcriptomics dataset, arbitrary number SpatialExperiment objects can loaded.","code":"mouseDLN.SDDLS <- createSpatialDDLSobject( sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", sc.gene.ID.column = \"GeneSymbol\", sc.cell.type.column = \"broad_cell_types\", st.data = MouseDLN.ST, sc.min.counts = 1, sc.min.cells = 1, sc.filt.genes.cluster = TRUE, sc.n.genes.per.cluster = 150, sc.min.mean.counts = 2, st.spot.ID.column = \"CellID\", st.gene.ID.column = \"GeneSymbol\" ) ## === 1 SpatialExperiment objects provided ## === Processing spatial transcriptomics data ## - Filtering features: ## - Selected features: 13948 ## - Discarded features: 0 ## ## === Processing single-cell data ## - Removing 16 genes without expression in any cell ## 'as( , \"dgTMatrix\")' is deprecated. ## Use 'as(., \"TsparseMatrix\")' instead. ## See help(\"Deprecated\") and help(\"Matrix-deprecated\"). ## - Filtering features: ## - Selected features: 12350 ## - Discarded features: 488 ## ## === Number of shared genes between single-cell and spatial transcriptomics datasets: 11592 ## - Original # genes in single-cell data: 12350 ## - Original # genes in ST data (object with the greatest # genes): 13948 ## ## === Number of removed mitochondrial genes: 12 ## ## === Number of genes after filtering based on logFC: 1058 ## ## === Final number of dimensions for further analyses: 1058 mouseDLN.SDDLS ## An object of class SpatialDDLS ## Real single-cell profiles: ## 1058 features and 14989 cells ## rownames: Rps3 Rps7 Tmsb4x ... Tmsb4x Cacna1e Mycl Izumo1r ## colnames: TAACACGAGGAGAGGC-1-2 CCCTAACTCGCGGACT-1-2 CCGATGGTCTGCCTGT-1-2 ... CCGATGGTCTGCCTGT-1-2 GCTACCTAGTTATGGA-1-2 TTTACTGGTGGAATGC-1-1 TGTTACTTCTGAGAAA-1-3 ## Spatial experiments: ## 1 experiments ## 1058 features and 1092 spots ## rownames: Kmo Cd2 Spic ... Spic Gpr141 Klra4 Klrd1 ## colnames: CGCGGGAATTAGGCAG-1-1 ATTCAGTAGCAGGGTC-1-0 CGGTTGACCTGGCATA-1-0 ... CGGTTGACCTGGCATA-1-0 CTAATTTCAACAACAC-1-0 TCCCGTCAGTCCCGCA-1-1 TCCGATGACTGAGCTC-1-1 ## Project: SpatialDDLS-Proj"},{"path":"/articles/realModelExample-hq.html","id":"simulation-of-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Simulation of mixed transcriptional profiles","title":"Get started! Deconvolution of mouse lymph node samples","text":"Now, going simulate cell composition matrices serve simulate mixed transcriptional profiles known cell proportions. done genMixedCellProp function can control different aspects, number mixed transcriptional profiles generated number cells used simulate mixed profile. parameters must decided depending size single-cell reference available computational resources. example, standard reference, use num.sim.spots = 10000 n.cells = 50. cell type composition mixed profiles generated three methods: random sampling Dirichlet distribution. Within set samples, order make proportions sparse, prob.sparity parameter controls probability missing cell types simulated spot, opposed mixture cell types. Pure mixed transcriptional profiles composed n.cells cells cell type aggregated. Transcriptional profiles minimum number missing cell types imposed. controlled min.zero.prop argument. relative abundance samples generated criteria can controlled proportion.method parameter. Finally, genMixedCellProp function automatically divide reference cell profiles contained single.cell.real slot training test subsets randomly assign n.cells cells generate every mixed transcriptional profile. , can call simMixedProfiles function, generate actual mixed transcriptional profiles using cell composition matrices generated previous step. step may take depending number transcriptional profiles simulated, patient! addition, users can choose method mixed profiles generated. recommend summing raw counts, normalizing samples obtain logCPMs (mixing.function = \"AddRawCount\"), methods available (see Documentation).","code":"mouseDLN.SDDLS <- genMixedCellProp( mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", num.sim.spots = 10000, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 0.8, min.zero.prop = 5, balanced.type.cells = TRUE ) ## ## === The number of mixed profiles that will be generated is equal to 10000 ## ## === Training set cells by type: ## - B cells: 5573 ## - CD4 T cells: 1362 ## - CD8 T cells: 2179 ## - cDC1s: 67 ## - cDC2s: 58 ## - GD T cells: 59 ## - Macrophages: 70 ## - Migratory DCs: 199 ## - Monocytes: 53 ## - NK cells: 62 ## - pDCs: 52 ## - Tregs: 260 ## === Test set cells by type: ## - B cells: 2786 ## - CD4 T cells: 681 ## - CD8 T cells: 1089 ## - cDC1s: 33 ## - cDC2s: 29 ## - GD T cells: 29 ## - Macrophages: 35 ## - Migratory DCs: 100 ## - Monocytes: 26 ## - NK cells: 31 ## - pDCs: 26 ## - Tregs: 130 ## === Probability matrix for training data: ## - Mixed spots: 6667 ## - Cell types: 12 ## === Probability matrix for test data: ## - Mixed spots: 3333 ## - Cell types: 12 ## DONE mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) ## === Setting parallel environment to 3 thread(s) ## ## === Generating train mixed profiles: ## ## === Generating test mixed profiles: ## ## DONE"},{"path":"/articles/realModelExample-hq.html","id":"training-a-fully-connected-neural-network-using-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Training a fully-connected neural network using mixed transcriptional profiles","title":"Get started! Deconvolution of mouse lymph node samples","text":"generated set mixed transcriptional profiles known cell composition, can train neural network using training subset evaluate model predicting cell type proportions test subset. trained, model can deconvolute cellular composition new transcriptional profiles, spots spatial transcriptomics experiment. architecture network fully customizable, although experience, hyperparameters used example work cases. Particularly, employ model two hidden layers, consisting 200 neurons, training process involving 60 epochs. metrics training progress can shown setting verbose = TRUE. Anyhow, advanced metrics can calculated using calculateEvalMetrics function. function computes mean absolute error (MAE) mean squared error (MSE) metrics per cell type, providing insight model’s performance cell type. metrics can visualized using various functions: demonstrated, overall performance satisfactory, indicating model capable comprehending distinctive features cell type provide precise predictions cell type composition transcriptional profiles.","code":"mouseDLN.SDDLS <- trainDeconvModel( mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200), verbose = FALSE ) ## 1/105 [..............................] - ETA: 14s - loss: 0.0705 - accuracy: 0.9688 - mean_absolute_error: 0.0147 - categorical_accuracy: 0.9688 70/105 [===================>..........] - ETA: 0s - loss: 0.0690 - accuracy: 0.8906 - mean_absolute_error: 0.0146 - categorical_accuracy: 0.8906 105/105 [==============================] - 0s 772us/step - loss: 0.0697 - accuracy: 0.8896 - mean_absolute_error: 0.0148 - categorical_accuracy: 0.8896 mouseDLN.SDDLS <- calculateEvalMetrics(mouseDLN.SDDLS) distErrorPlot( mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", color.by = \"CellType\", error.labels = FALSE, type = \"boxplot\", size.point = 0.5 ) distErrorPlot( mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", facet.by = \"CellType\", color.by = \"CellType\", error.label = TRUE, type = \"boxplot\" ) corrExpPredPlot( mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", corr = \"both\", size.point = 0.5 ) ## `geom_smooth()` using formula = 'y ~ x'"},{"path":"/articles/realModelExample-hq.html","id":"deconvolution-of-the-spatial-transcriptomics-dataset","dir":"Articles","previous_headings":"Loading data","what":"Deconvolution of the spatial transcriptomics dataset","title":"Get started! Deconvolution of mouse lymph node samples","text":"Finally, can use trained model deconvolute signals spot using deconvSpatialDDLS function. default, function uses trained model predict cell proportions two sets transcriptional profiles obtained ST datasets: ‘Intrinsic’ profiles: actual transcriptional profiles every spot ST dataset. ‘Extrinsic’ profiles: simulated profiles generated surrounding spots every spot. concept create mirrored set transcriptional profiles represent transcriptional features spatial context spot. latter can used understand similar spot neighbors. Considering hypothesis can infer cellular composition spot based surroundings given correlation spatial location cell composition/transcriptional features, can use information spatially contextualize predictions improve accuracy. refer process spatial regularization. Details methodology explained Documentation Mañanes et al. (2023). Now, let’s project predicted proportions spatial coordinates: reveal hidden patterns coordinates caused using color scale, can utilize plotSpatialProp function independently plot cell type: addition ‘regularized’ cell proportions, can plot predictions calculated intrinsic extrinsic transcriptional profiles. instance, let’s plot predicted extrinsic transcriptional profiles: one might expect, smoothed version final predictions. also possible visualize distances extrinsic intrinsic transcriptional profiles spot understand regularization step works using plotDistances function: spots distances less mean distance regularized according nearest neighbor spots.","code":"mouseDLN.SDDLS <- deconvSpatialDDLS( mouseDLN.SDDLS, k.spots = 6 ) ## No 'index.st' provided. Deconvoluting all SpatialExperiment objects contained in the `spatial.experiments` slot ## === Normalizing data (LogCPM) ## === Predicting cell type proportions ## 1/35 [..............................] - ETA: 0s 35/35 [==============================] - 0s 598us/step ## ## === Calculating distances in PCA space ## - Using 133 PCs (variance cutoff: 0.8) ## === Calculating alpha factors based on distances ## DONE plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1) list.plots <- lapply( X = trained.model(mouseDLN.SDDLS) %>% cell.types(), FUN = \\(x) { plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = x, size.point = 1, colors = \"blues\" ) + coord_fixed() } ) ggarrange(plotlist = list.plots[1:4], align = \"hv\") ggarrange(plotlist = list.plots[5:8], align = \"hv\") ggarrange(plotlist = list.plots[9:12], align = \"hv\") list.plots <- lapply( X = trained.model(mouseDLN.SDDLS) %>% cell.types(), FUN = \\(x) { plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = x, size.point = 1, colors = \"blues\", prediction = \"Extrinsic\" ) + coord_fixed() } ) ggarrange(plotlist = list.plots[1:4], align = \"hv\") ggarrange(plotlist = list.plots[5:8], align = \"hv\") ggarrange(plotlist = list.plots[9:12], align = \"hv\") plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed()"},{"path":"/articles/realModelExample-hq.html","id":"interpreting-the-model","dir":"Articles","previous_headings":"Loading data","what":"Interpreting the model","title":"Get started! Deconvolution of mouse lymph node samples","text":"order make predictions transparent, SpatialDDLS includes additional module designed provide insights model’s decision-making process. relies calculating predicted classes/loss function gradients respect input variables, method popularly known Vanilla Gradient. numeric values computed gene cell type using pure mixed transcriptional profiles previously simulated. Therefore, can interpreted extent feature contributing model’s predictions. values initially calculated sample/gene level, can aggregated cell type level order assess relevance different genes cell type proportion predictions. steps performed interGradientDL function: Importantly, depending method parameter, positive negative gradients must differently interpreted: gradients respect input variables calculated using loss function (method = \"loss\"), genes negative gradients (minimize loss function) positively correlated presence cell type. Conversely, gradients respect input variables calculated using classes (method = \"class\"), genes positive gradients (make probability cell type higher) positively associated cell type. important note markers interpreted cell type markers. Rather, serve indications help interpret model’s performance. addition, due multivariate nature approach, gradients surrogates feature level predictions made considering input variables collectively, thus caution exercised drawing direct conclusions specific gene-cell type relationships. example, let’s calculate gradients class function respect input features show top 5 genes greatest gradients per cell type: can seen, among top 5 genes canonical markers different cell types appear, Cd79b B cells, Cd8a CD8 T cells, Foxp3 Tregs. just top 5 genes, considering higher number can provide comprehensive understanding genes utilizaed model. also provide plotHeatmapGradsAgg function visualizing top N mean gradients per cell type. plot highlights genes high gradients across different cell types, reflecting multivariate nature neural networks. advisable examine positive negative gradients, genes significantly contribute network’s predictions. Finally, can use plotSpatialGeneExpr visualize spatial distribution top N genes per cell type ST dataset. Let’s plot genes cell types just demonstration purposes:","code":"mouseDLN.SDDLS <- interGradientsDL( mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\" ) top.gradients <- topGradientsCellType( mouseDLN.SDDLS, method = \"class\", top.n.genes = 5 ) sapply( top.gradients, \\(x) x$Positive ) %>% as.data.frame() ## B cells CD4 T cells CD8 T cells cDC1s cDC2s GD T cells Macrophages ## 1 Vpreb3 Igfbp4 Cd8b1 Slc16a9 Clec2d Gm26917 1300017J02Rik ## 2 Cd72 Ly6c1 Cd8a Hbb-bs Stk39 Il4 Timd4 ## 3 Slc1a3 Satb1 Ccr9 Tnfsf14 Ryr2 Stk39 Prg3 ## 4 H3f3b Lef1 Acp5 Gatm Ndfip1 Ccr10 Cst7 ## 5 Rfc4 Cd28 Rgcc Ahnak Ugcg Selplg Cd8b1 ## Migratory DCs Monocytes NK cells pDCs Tregs ## 1 D16Ertd472e Ndfip1 Klra9 Clec2d Foxp3 ## 2 Tmem150c Ucp2 Ugcg Clec4e Cxcr3 ## 3 Il15ra Marco Klrc1 H2-K1 Ctla4 ## 4 Samhd1 Ryr2 Ccl3 Ndfip1 Samhd1 ## 5 Clec2d Clec4e Tnfrsf8 Fyn Itgb1 hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\") hh$Positive hh$Negative top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) for (i in c(\"B cells\", \"CD4 T cells\", \"CD8 T cells\", \"Tregs\", \"Monocytes\")) { list.plots <- list() for (j in top.genes[[i]][[\"Absolute\"]]) { list.plots[[j]] <- plotSpatialGeneExpr( mouseDLN.SDDLS, index.st = 1, gene = j, size.point = 0.5, title = paste0(i, \" - \", j) ) + coord_fixed() + theme(legend.position = \"none\") ## legend removed just for viz } print(ggpubr::ggarrange(plotlist = list.plots, align = \"hv\")) }"},{"path":"/articles/realModelExample-hq.html","id":"clustering-analysis","dir":"Articles","previous_headings":"Loading data","what":"Clustering analysis","title":"Get started! Deconvolution of mouse lymph node samples","text":"SpatialDDLS R package also includes functions cluster ST dataset according predicted cell composition spot. functionality enables dissect ST datasets distinct cellular niches, information might relevant analyses.","code":"mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20) ## No 'index.st' provided. Deconvoluting all SpatialExperiment objects contained in the `spatial.experiments` slot ## === Selected graph-based clustering ## === Running clustering for slide 1 plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed() ## No 'index.st' provided. Using first ST dataset ## === Plotting first clustering configuration Clustering.graph.k.20"},{"path":"/articles/realModelExample-hq.html","id":"comparing-deconvoluted-cell-proportions-with-colocalization-of-cell-markers","dir":"Articles","previous_headings":"Loading data","what":"Comparing deconvoluted cell proportions with colocalization of cell markers","title":"Get started! Deconvolution of mouse lymph node samples","text":"Finally, going assess whether collocation predicted cell type proportions expression known classic markers cell type. analysis aims validate model’s predictions comparing well-established cellular markers, mean quantitative validation model.","code":"customMarkers <- list( \"B cells\" = c(\"Cd74\", \"Cd19\", \"Cd79a\", \"Cd79b\", \"Ly6d\"), \"CD4 T cells\" = c(\"Cd4\", \"Lef1\", \"Fyb\"), \"CD8 T cells\" = c(\"Cd8b1\", \"Cd8a\", \"Trac\"), cDC1s = c(\"Xcr1\", \"Irf8\"), cDC2s = c(\"Irf4\", \"Cd4\"), \"GD T cells\" = c(\"Il7r\", \"Id2\"), Macrophages = c(\"Lyz2\", \"Lyz1\", \"Cd86\", \"Ly6c1\"), \"Migratory DCs\" = c(\"Ccl5\", \"Anxa3\", \"Fscn1\"), Monocytes = c(\"Fcer1g\", \"Cst3\", \"Lst1\", \"Itgam\", \"Kit\", \"Fcgr3\"), \"NK cells\" = c(\"Nkg7\", \"Il2rb\", \"Gzma\"), pDCs = c(\"Siglech\", \"Plac8\", \"Ly6c2\", \"Vtsb\", \"Zeb2\", \"Siglech\"), Tregs = c(\"Ikzf2\", \"Il2ra\", \"Foxp3\") ) %>% lapply(FUN = function(x) x[x %in% rownames(MouseDLN.ST)]) ## calculate z-scores exprST <- MouseDLN.ST@assays@data[[1]] logCPM <- edgeR::cpm(exprST, log = TRUE) meanZscoresCustom <- purrr::map( .x = names(customMarkers), .f = ~{ colMeans(t(scale(t(logCPM[customMarkers[[.x]], , drop = FALSE])))) } ) %>% do.call(cbind, .) colnames(meanZscoresCustom) <- names(customMarkers) color.z.scores <- rev( colorRampPalette(RColorBrewer::brewer.pal(n = 10, name = \"RdBu\"))(20) ) st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) ) colnames(st.coor) <- paste(\"Spatial\", 1:2) dfPlotLong <- reshape2::melt( as.data.frame(cbind(st.coor, meanZscoresCustom)), id.vars = c(\"Spatial 1\", \"Spatial 2\"), variable.name = \"CellType\", value.name = \"Zscore\" ) dfPlotLong %>% ggplot( aes(x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = Zscore) ) + geom_point(size = 0.5) + theme_classic() + ggtitle(\"Mean z-score of cell type markers\") + scale_color_gradientn(colors = color.z.scores, limit = c(-2, 2)) + theme( plot.title = element_text(face = \"bold\", hjust = 0.5), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank() ) + coord_fixed() + facet_wrap(~ CellType)"},{"path":[]},{"path":"/articles/realModelExample.html","id":"loading-data","dir":"Articles","previous_headings":"","what":"Loading data","title":"Deconvolution of mouse lymph node samples","text":"Firstly, let’s load required packages data: Let’s explore spatial transcriptomics data contained MouseDLN.ST object: plot chunk spatialdata-cond regard single-cell RNA-seq data, preprocessing visualization performed, analysis outside scope tutorial.","code":"library(\"SpatialDDLS\") ## Error in library(\"SpatialDDLS\"): there is no package called 'SpatialDDLS' library(\"SingleCellExperiment\") library(\"SpatialExperiment\") library(\"ggplot2\") library(\"ggpubr\") ## in case it is not installed if (!requireNamespace(\"SpatialDDLSdata\", quietly = TRUE)) { if (!requireNamespace(\"devtools\", quietly = TRUE)) { install.packages(\"devtools\") } devtools::install_github(\"diegommcc/SpatialDDLSdata\") } library(\"SpatialDDLSdata\") # SingleCellExperiment with scRNA-seq data(MouseDLN.SCE) # SpatialExperiment with spatial transcriptomics data data(MouseDLN.ST) cbind(spatialCoords(MouseDLN.ST), colData(MouseDLN.ST)) %>% as.data.frame() %>% ggplot(aes(X0, X1, color = lymph_node)) + geom_point() + ggtitle(\"Mouse lymph nodes by condition\") + theme_classic() + coord_fixed()"},{"path":"/articles/realModelExample.html","id":"loading-data-into-a-spatialddls-object","dir":"Articles","previous_headings":"Loading data","what":"Loading data into a SpatialDDLS object","title":"Deconvolution of mouse lymph node samples","text":"Now, need create SpatialDDLS object, serve central core subsequent steps. suggest including spatial single-cell transcriptomics data enable filtering selection genes present data types analyses. Additionally, recommend filtering genes based expression levels order reduce number dimensions consider meaningful genes. Please refer documentation review implemented strategies (specially sc.n.genes.per.cluster sc.min.mean.counts parameters). can show basic information object: case, working 1 spatial transcriptomics dataset, arbitrary number SpatialExperiment objects can loaded.","code":"mouseDLN.SDDLS <- createSpatialDDLSobject( sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", sc.gene.ID.column = \"GeneSymbol\", sc.cell.type.column = \"broad_cell_types\", st.data = MouseDLN.ST, sc.min.counts = 1, sc.min.cells = 1, sc.filt.genes.cluster = TRUE, sc.n.genes.per.cluster = 150, sc.min.mean.counts = 2, st.spot.ID.column = \"CellID\", st.gene.ID.column = \"GeneSymbol\" ) ## Error in createSpatialDDLSobject(sc.data = MouseDLN.SCE, sc.cell.ID.column = \"CellID\", : could not find function \"createSpatialDDLSobject\" mouseDLN.SDDLS ## Error in eval(expr, envir, enclos): object 'mouseDLN.SDDLS' not found"},{"path":"/articles/realModelExample.html","id":"simulation-of-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Simulation of mixed transcriptional profiles","title":"Deconvolution of mouse lymph node samples","text":"Now, going simulate cell composition matrices serve simulate mixed transcriptional profiles known cell proportions. done genMixedCellProp function can control different aspects number mixed transcriptional profiles generated, number cells used simulate mixed profile, etc. parameters must decided depending single-cell reference available computational resources. example, standard reference, use num.sim.spots = 10000 n.cells = 50. cell type compositions mixed profiles generated three methods: random sampling Dirichlet distribution. Moreover, order make proportions sparse, prob.sparity parameter controls probability missing cell types simulated spot, opposed mixture cell types. Pure mixed transcriptional profiles composed n.cells cells cell type aggregated. Transcriptional profiles minimum number missing cell types imposed. controlled min.zero.prop argument. relative abundance samples generated criteria can controlled proportion.method parameter. Finally, genMixedCellProp function automatically divide reference cell profiles contained single.cell.real slot training test subsets randomly assign n.cells cells generate every mixed transcriptional profile. , can call simMixedProfiles function, generate actual mixed transcriptional profiles using cell composition matrices generated previous step. step may take depending number transcriptional profiles simulated, patient! addition, users can choose method mixed profiles generated. recommend summing raw counts, normalize samples log-CPM (mixing.function = \"AddRawCount\"), methods available (see Documentation).","code":"mouseDLN.SDDLS <- genMixedCellProp( mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", num.sim.spots = 10000, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 1, min.zero.prop = 5, balanced.type.cells = TRUE, verbose = TRUE ) ## Error in genMixedCellProp(mouseDLN.SDDLS, cell.ID.column = \"CellID\", cell.type.column = \"broad_cell_types\", : could not find function \"genMixedCellProp\" mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) ## Error in simMixedProfiles(mouseDLN.SDDLS, threads = 3): could not find function \"simMixedProfiles\""},{"path":"/articles/realModelExample.html","id":"training-a-fully-connected-neural-network-using-mixed-transcriptional-profiles","dir":"Articles","previous_headings":"Loading data","what":"Training a fully-connected neural network using mixed transcriptional profiles","title":"Deconvolution of mouse lymph node samples","text":"generated set mixed transcriptional profiles known cell composition, can train neural network using training subset evaluate model predicting cell type proportions test subset. trained, model can deconvolute cellular composition new transcriptional profiles, spot spatial transcriptomics experiment. architecture network fully customizable, although experience, hyperparameters used example work cases. Particularly, employ model two hidden layers, consisting 200 neurons, training process involving 60 epochs. default, metrics performance model displayed. advanced metrics can calculated using calculateEvalMetrics function. function computes mean absolute error (MAE) mean squared error (MSE) metrics per cell type, providing insight model’s performance cell type. metrics can visualized using various functions: demonstrated, overall performance satisfactory, indicating model capable comprehending distinctive features cell type provide precise predictions cell type composition transcriptional profiles.","code":"mouseDLN.SDDLS <- trainDeconvModel( mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200) ) ## Error in trainDeconvModel(mouseDLN.SDDLS, num.epochs = 60, num.hidden.layers = 2, : could not find function \"trainDeconvModel\" mouseDLN.SDDLS <- calculateEvalMetrics(mouseDLN.SDDLS) ## Error in calculateEvalMetrics(mouseDLN.SDDLS): could not find function \"calculateEvalMetrics\" distErrorPlot( mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", color.by = \"CellType\", error.labels = FALSE, type = \"boxplot\", size.point = 0.5 ) ## Error in distErrorPlot(mouseDLN.SDDLS, error = \"AbsErr\", x.by = \"CellType\", : could not find function \"distErrorPlot\" distErrorPlot( mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", facet.by = \"CellType\", color.by = \"CellType\", error.label = TRUE, type = \"boxplot\" ) ## Error in distErrorPlot(mouseDLN.SDDLS, x.by = \"pBin\", error = \"AbsErr\", : could not find function \"distErrorPlot\" corrExpPredPlot( mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", corr = \"both\", size.point = 0.5 ) ## Error in corrExpPredPlot(mouseDLN.SDDLS, color.by = \"CellType\", facet.by = \"CellType\", : could not find function \"corrExpPredPlot\""},{"path":"/articles/realModelExample.html","id":"deconvolution-of-the-spatial-transcriptomics-dataset","dir":"Articles","previous_headings":"Loading data","what":"Deconvolution of the spatial transcriptomics dataset","title":"Deconvolution of mouse lymph node samples","text":"Finally, can use trained model deconvolute signals spot using `deconvSpatialDDLS’ function. default, function uses trained model predict cell proportions two sets transcriptional profiles ST datasets: ‘Intrinsic’ profiles: actual transcriptional profiles every spot ST dataset. ‘Extrinsic’ profiles: simulated profiles generated surrounding spots every spot. concept create mirrored set transcriptional profiles represent transcriptional features spatial context spot. latter can used understand similar spot neighbors. Considering hypothesis can infer cellular composition spot based surroundings given correlation spatial location cell composition/transcriptional profile, can use information spatially contextualize predictions improve accuracy. furhter mentions, refer process regularization. Details methodology explained Documentation Mañanes et al. (2023). Now, let’s project predicted proportions spatial coordinates: reveal hidden patterns coordinates caused using color scale, can utilize plotSpatialProp function independently plot cell type: addition ‘regularized’ cell proportions, can plot predictions calculated intrinsic extrinsic transcriptional profiles. instance, let’s plot predicted extrinsic transcriptional profiles: one might expect, smoothed version final predictions. also possible visualize distances extrinsic intrinsic transcriptional profiles spot understand regularization step works using plotDistances function: spots distances less mean distance regularized according nearest neighbor spots. can observe spots using following chunk code:","code":"mouseDLN.SDDLS <- deconvSpatialDDLS( mouseDLN.SDDLS, k.spots = 6 ) ## Error in deconvSpatialDDLS(mouseDLN.SDDLS, k.spots = 6): could not find function \"deconvSpatialDDLS\" plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1) ## Error in plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1): could not find function \"plotSpatialPropAll\" for (i in trained.model(mouseDLN.SDDLS) %>% cell.types()) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\" ) + coord_fixed() ) } ## Error in cell.types(.): could not find function \"cell.types\" for (i in mouseDLN.SDDLS@trained.model@cell.types) { print( plotSpatialProp( mouseDLN.SDDLS, index.st = 1, cell.type = i, colors = \"blues\", prediction = \"Extrinsic\" ) + coord_fixed() ) } ## Error in eval(expr, envir, enclos): object 'mouseDLN.SDDLS' not found plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed() ## Error in plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5): could not find function \"plotDistances\" st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) )[, 1:2] ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'spatialCoords': could not find function \"spatial.experiments\" colnames(st.coor) <- paste(\"Spatial\", 1:2) ## Error: object 'st.coor' not found st.pred <- deconv.spots(object = mouseDLN.SDDLS, index.st = 1) ## Error in deconv.spots(object = mouseDLN.SDDLS, index.st = 1): could not find function \"deconv.spots\" alpha.factors <- st.pred[[\"Alpha.Factors\"]] ## Error in eval(expr, envir, enclos): object 'st.pred' not found dfPlot <- as.data.frame(cbind(st.coor, alpha.factors)) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': object 'st.coor' not found ggplot( dfPlot, aes( x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = alpha.factors ) ) + geom_point(size = 1.5) + scale_color_gradient2() + ggtitle(\"Distances\") + SpatialDDLSTheme() + coord_fixed() ## Error in eval(expr, envir, enclos): object 'dfPlot' not found"},{"path":"/articles/realModelExample.html","id":"interpreting-the-model","dir":"Articles","previous_headings":"Loading data","what":"Interpreting the model","title":"Deconvolution of mouse lymph node samples","text":"order make predictions transparent, SpatialDDLS includes additional module designed provide insights model’s decision-making process. relies calculating predicted classes/loss function gradients respect input variables, method popularly known Vanilla Gradient. numeric values computed gene cell type using pure mixed transcriptional profiles previously simulated. Therefore, can interpreted extent feature contributing model’s predictions. values initially calculated sample/gene level, can aggregated cell type level order assess relevance different genes cell type proportion predictions. steps performed interGradientDL function: Importantly, depending method parameter, positive negative gradient must differently interpreted: gradients respect input variables calculated using loss function (method = \"loss\"), genes negative gradients (minimize loss function) positively correlated presence cell type. Conversely, gradients respect input variables calculated using classes (method = \"class\"), genes positive gradients (make probability cell type higher) positively associated cell type. important note markers interpreted cell type markers. Rather, serve indications help interpret model’s performance. addition, due multivariate nature approach, gradients surrogates feature level predictions made considering input variables collectively, thus caution exercised drawing direct conclusions specific gene-cell type relationships. example, let’s calculate gradients class function respect input features show top 5 genes greatest gradients per cell type: can seen, among top 5 genes canonical markers different cell types appear, Cd79b B cells, Cd8a CD8 T cells, Foxp3 Tregs. just top 5 genes, considering higher number can provide comprehensive understanding genes utilizaed model. also provide plotHeatmapGradsAgg function visualizing N top mean gradients per cell type. plot highlights genes high gradients across different cell types, reflecting multivariate nature neural networks. advisable examine positive negative gradients, genes significantly contribute network’s predictions. Finally, can use plotSpatialGeneExpr visualize spatial distribution top N genes per cell tupe ST dataset. Let’s plot genes cell types demonstration purposes: top N genes per cell type visualize spatial distribution ST dataset. Let’s plot genes cell types just demonstration purposes:","code":"mouseDLN.SDDLS <- interGradientsDL( mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\" ) ## Error in interGradientsDL(mouseDLN.SDDLS, scaling = \"standardize\", method = \"class\"): could not find function \"interGradientsDL\" top.gradients <- topGradientsCellType( mouseDLN.SDDLS, method = \"class\", top.n.genes = 5 ) ## Error in topGradientsCellType(mouseDLN.SDDLS, method = \"class\", top.n.genes = 5): could not find function \"topGradientsCellType\" sapply( top.gradients, \\(x) x$Positive ) %>% as.data.frame() ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': error in evaluating the argument 'X' in selecting a method for function 'sapply': object 'top.gradients' not found hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\") ## Error in plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = \"class\"): could not find function \"plotHeatmapGradsAgg\" hh$Positive ## Error in eval(expr, envir, enclos): object 'hh' not found hh$Negative ## Error in eval(expr, envir, enclos): object 'hh' not found top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) ## Error in topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4): could not find function \"topGradientsCellType\" for (i in c(\"B cells\", \"CD4 T cells\", \"CD8 T cells\", \"Tregs\", \"Monocytes\")) { list.plots <- list() for (j in top.genes[[i]][[\"Absolute\"]]) { list.plots[[j]] <- plotSpatialGeneExpr( mouseDLN.SDDLS, index.st = 1, gene = j, size.point = 0.5, title = paste0(i, \" - \", j) ) + coord_fixed() + theme(legend.position = \"none\") ## legend removed just for viz } print(ggpubr::ggarrange(plotlist = list.plots, align = \"hv\")) } ## Error in eval(expr, envir, enclos): object 'top.genes' not found"},{"path":"/articles/realModelExample.html","id":"clustering-analysis","dir":"Articles","previous_headings":"Loading data","what":"Clustering analysis","title":"Deconvolution of mouse lymph node samples","text":"SpatialDDLS R package also includes functions cluster ST dataset according predicted cell composition spot. functionality enables dissect ST datasets distinct cellular niches, can relevant information analyses.","code":"mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20) ## Error in spatialPropClustering(mouseDLN.SDDLS, k.nn = 20): could not find function \"spatialPropClustering\" plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed() ## Error in plotSpatialClustering(mouseDLN.SDDLS): could not find function \"plotSpatialClustering\""},{"path":"/articles/realModelExample.html","id":"comparing-deconvoluted-cell-proportions-with-colocalization-of-cell-markers","dir":"Articles","previous_headings":"Loading data","what":"Comparing deconvoluted cell proportions with colocalization of cell markers","title":"Deconvolution of mouse lymph node samples","text":"Finally, assess whether collocation predicted cell type proportions expression known classic markers cell type. analysis aims validate model’s predictions comparing well-established cellular markers, mean quantitative validation model.","code":"customMarkers <- list( \"B cells\" = c(\"Cd74\", \"Cd19\", \"Cd79a\", \"Cd79b\", \"Ly6d\"), \"CD4 T cells\" = c(\"Cd4\", \"Lef1\", \"Fyb\"), \"CD8 T cells\" = c(\"Cd8b1\", \"Cd8a\", \"Trac\"), cDC1s = c(\"Xcr1\", \"Irf8\"), cDC2s = c(\"Irf4\", \"Cd4\"), \"GD T cells\" = c(\"Il7r\", \"Id2\"), Macrophages = c(\"Lyz2\", \"Lyz1\", \"Cd86\", \"Ly6c1\"), \"Migratory DCs\" = c(\"Ccl5\", \"Anxa3\", \"Fscn1\"), Monocytes = c(\"Fcer1g\", \"Cst3\", \"Lst1\", \"Itgam\", \"Kit\", \"Fcgr3\"), \"NK cells\" = c(\"Nkg7\", \"Il2rb\", \"Gzma\"), pDCs = c(\"Siglech\", \"Plac8\", \"Ly6c2\", \"Vtsb\", \"Zeb2\", \"Siglech\"), Tregs = c(\"Ikzf2\", \"Il2ra\", \"Foxp3\") ) %>% lapply(FUN = function(x) x[x %in% rownames(MouseDLN.ST)]) ## calculate z-scores exprST <- MouseDLN.ST@assays@data[[1]] logCPM <- edgeR::cpm(exprST, log = TRUE) meanZscoresCustom <- purrr::map( .x = names(customMarkers), .f = ~{ colMeans(t(scale(t(logCPM[customMarkers[[.x]], , drop = FALSE])))) } ) %>% do.call(cbind, .) colnames(meanZscoresCustom) <- names(customMarkers) color.z.scores <- rev(colorRampPalette(RColorBrewer::brewer.pal(n = 10, name = \"RdBu\"))(20)) st.coor <- SpatialExperiment::spatialCoords( spatial.experiments(object = mouseDLN.SDDLS, index.st = 1) ) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'spatialCoords': could not find function \"spatial.experiments\" colnames(st.coor) <- paste(\"Spatial\", 1:2) ## Error: object 'st.coor' not found dfPlotLong <- reshape2::melt( as.data.frame(cbind(st.coor, meanZscoresCustom)), id.vars = c(\"Spatial 1\", \"Spatial 2\"), variable.name = \"CellType\", value.name = \"Zscore\" ) ## Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'as.data.frame': object 'st.coor' not found dfPlotLong %>% ggplot( aes(x = .data[[\"Spatial 1\"]], y = .data[[\"Spatial 2\"]], color = Zscore) ) + geom_point(size = 0.5) + theme_classic() + ggtitle(\"Mean z-score of cell type markers\") + scale_color_gradientn(colors = color.z.scores, limit = c(-2, 2)) + theme( plot.title = element_text(face = \"bold\", hjust = 0.5), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank() ) + coord_fixed() + facet_wrap(~ CellType) + coord_fixed() ## Error in eval(expr, envir, enclos): object 'dfPlotLong' not found"},{"path":[]},{"path":"/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Diego Mañanes. Author, maintainer. Carlos Torroja. Author. Fatima Sanchez-Cabo. Author.","code":""},{"path":"/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Mañanes D, Torroja C, Sanchez-Cabo F (2023). SpatialDDLS: Deconvolution Spatial Transcriptomics Data Based Neural Networks. R package version 1.0.0, https://github.com/diegommcc/SpatialDDLS, https://diegommcc.github.io/SpatialDDLS/.","code":"@Manual{, title = {SpatialDDLS: Deconvolution of Spatial Transcriptomics Data Based on Neural Networks}, author = {Diego Mañanes and Carlos Torroja and Fatima Sanchez-Cabo}, year = {2023}, note = {R package version 1.0.0, https://github.com/diegommcc/SpatialDDLS}, url = {https://diegommcc.github.io/SpatialDDLS/}, }"},{"path":"/index.html","id":"spatialddls-","dir":"","previous_headings":"","what":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","title":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","text":"SpatialDDLS R package provides neural network-based solution cell type deconvolution spatial transcriptomics data. package takes advantage single-cell RNA sequencing (scRNA-seq) data simulate mixed transcriptional profiles known cell composition train fully-connected neural networks predict cell type composition spatial transcriptomics spots. resulting trained models can applied new spatial transcriptomics data predict cell type proportions, allowing accurate cell type identification characterization spatially-resolved transcriptomic data. Overall, SpatialDDLS powerful tool cell type deconvolution spatial transcriptomics data, providing reliable, fast flexible solution researchers field. details algorithm functionalities implemented package, see https://diegommcc.github.io/SpatialDDLS/.","code":""},{"path":"/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Deconvolution of Spatial Transcriptomics Data Based on Neural Networks","text":"SpatialDDLS already available CRAN: version development available GitHub can installed follows: package depends tensorflow keras R packages, working Python interpreter Tensorflow Python library installed needed. installTFpython function provides easy way install conda environment named spatialddls-env necessary dependencies covered. recommend installing TensorFlow Python library way, although custom installation possible.","code":"install.packages(\"SpatialDDLS\") if (!requireNamespace(\"devtools\", quietly = TRUE)) install.packages(\"devtools\") devtools::install_github(\"diegommcc/SpatialDDLS\") library(\"SpatialDDLS\") installTFpython(install.conda = TRUE)"},{"path":[]},{"path":"/reference/DeconvDLModel-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The DeconvDLModel Class — DeconvDLModel-class","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"DeconvDLModel object stores information related deep neural network models. consists trained model, training history, predictions test data. running calculateEvalMetrics, possible find performance evaluation model test data (see ?calculateEvalMetrics details).","code":""},{"path":"/reference/DeconvDLModel-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"steps related Deep Learning carried using keras tensorflow packages, use R6 classes system. want save DeconvDLModel object RDS file, SpatialDDLS provides saveRDS generic function transforms R6 object containing trained model native valid R object. Specifically, model converted list architecture network weights learned training, minimum information needed use model predictor. want keep optimizer state, see ?saveTrainedModelAsH5. want store either DeconvDLModel SpatialDDLS objects disk RDA files, see ?preparingToSave.","code":""},{"path":"/reference/DeconvDLModel-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The DeconvDLModel Class — DeconvDLModel-class","text":"model Trained deep neural network. slot can contain R6 keras.engine.sequential.Sequential object list two elements: architecture model resulting weights training. training.history List evolution selected metrics training. test.metrics Performance model test data. test.pred Predicted cell type proportions test data. cell.types Vector cell types considered model. features Vector features (genes) considered model. features used subsequent predictions. test.deconv.metrics Performance model test data cell type. slot generated calculateEvalMetrics function (see ?calculateEvalMetrics details). interpret.gradients Gradients interpretation. SpatialDDLS provides functions better understand prediction made model (see ?interGradientsDL details). slot list either one two elements: gradients either loss function predicted class respect input variables using pure (one cell type) mixed transcriptional profiles. gradients can interpreted extent model using variables predict cell type proportions.","code":""},{"path":"/reference/PropCellTypes-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The PropCellTypes Class — PropCellTypes-class","title":"The PropCellTypes Class — PropCellTypes-class","text":"PropCellTypes class data storage class contains information related cell type composition matrices used simulate mixed transcriptional profiles. matrix stored prob.matrix slot slots contain additional information generated process required subsequent steps.","code":""},{"path":"/reference/PropCellTypes-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The PropCellTypes Class — PropCellTypes-class","text":"See ?genMixedCellProp function information cell type composition matrices generated. Plots cell type proportion distributions can accessed using showProbPlot function (see ?showProbPlot details).","code":""},{"path":"/reference/PropCellTypes-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The PropCellTypes Class — PropCellTypes-class","text":"prob.matrix Matrix cell type proportions simulate mixed transcriptional profiles. cell.names Matrix containing cells used generate simulated mixed transcriptional profiles. set.list List cells sorted cell type. set Vector containing cell names present object. method Vector indicating method cell type proportions generated. plots Plots showing cell type proportion distributions. See ?showProbPlot details. type.data Character indicating type data contained: 'train' 'test'.","code":""},{"path":"/reference/SpatialDDLS-Rpackage.html","id":null,"dir":"Reference","previous_headings":"","what":"SpatialDDLS: an R package to deconvolute spatial transcriptomics data using\ndeep neural networks — SpatialDDLS-Rpackage","title":"SpatialDDLS: an R package to deconvolute spatial transcriptomics data using\ndeep neural networks — SpatialDDLS-Rpackage","text":"SpatialDDLS R package provides neural network-based solution cell type deconvolution spatial transcriptomics data. package takes advantage single-cell RNA sequencing (scRNA-seq) data simulate mixed transcriptional profiles known cell composition train fully-connected neural networks predict cell type composition spatial transcriptomics spots. resulting trained models can applied new spatial transcriptomics data predict cell type proportions, allowing accurate cell type identification characterization spatially-resolved transcriptomic data. Finally, predictions forced keep spatial consistency process refer spatial regularization. Overall, SpatialDDLS powerful tool cell type deconvolution spatial transcriptomics data, providing reliable, fast flexible solution researchers field. See Mañanes et al. (2023) (doi:10.1101/2023.08.31.555677 ) examples (https://diegommcc.github.io/SpatialDDLS/) details.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The SpatialDDLS Class — SpatialDDLS-class","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"SpatialDDLS object core SpatialDDLS package. object stores different intermediate data needed construction new deconvolution models, spatial transcriptomics profiles deconvoluted, predicted cell type proportions.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"object uses classes store different types data generated workflow: SingleCellExperiment class single-cell RNA-Seq data storage, using sparse matrix Matrix package (dgCMatrix class) HDF5Array class case using HDF5 files back-end (see information). SpatialExperiment class spatial transcriptomics data storage. ZinbModel class estimated parameters simulation new single-cell profiles. SummarizedExperiment class simulated mixed transcriptional profiles storage. PropCellTypes class composition cell type matrices. See ?PropCellTypes details. DeconvDLModel class store information related deep neural network models. See ?DeconvDLModel details. order provide way work large amounts data RAM-constrained machines, provide possibility using HDF5 files back-end store count matrices real simulated single-cell profiles using HDF5Array DelayedArray classes homonymous packages.","code":""},{"path":"/reference/SpatialDDLS-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The SpatialDDLS Class — SpatialDDLS-class","text":"single.cell.real Real single-cell data stored SingleCellExperiment object. count matrix stored either dgCMatrix HDF5Array objects. spatial.experiments List SpatialExperiment objects deconvoluted. zinb.params ZinbModel object estimated parameters simulation new single-cell expression profiles. single.cell.simul Simulated single-cell expression profiles using ZINB-WaVE model. prob.cell.types PropCellTypes class cell composition matrices built simulation mixed transcriptional profiles known cell composition. mixed.profiles List simulated train test mixed transcriptional profiles. entry SummarizedExperiment object. Count matrices can stored HDF5Array objects using HDF5 files back-end case RAM limitations. trained.model DeconvDLModel object information related deconvolution model. See ?DeconvDLModel details. deconv.spots Deconvolution results. consists list element corresponds results SpatialExperiment object contained spatial.experiments slot. project Name project. version Version SpatialDDLS object built .","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":null,"dir":"Reference","previous_headings":"","what":"The Class ZinbParametersModel — ZinbParametersModel-class","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"ZinbParametersModel class wrapper class ZinbModel class zinbwave package.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"wrapper class contains zinbwave.model slot, holds valid ZinbModel object.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"slots","dir":"Reference","previous_headings":"","what":"Slots","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"zinbwave.model valid ZinbModel object.","code":""},{"path":"/reference/ZinbParametersModel-class.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"The Class ZinbParametersModel — ZinbParametersModel-class","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 .","code":""},{"path":"/reference/barErrorPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate bar error plots — barErrorPlot","title":"Generate bar error plots — barErrorPlot","text":"Generate bar error plots cell type (CellType) number different cell types (nCellTypes) test mixed transcriptional profiles.","code":""},{"path":"/reference/barErrorPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate bar error plots — barErrorPlot","text":"","code":"barErrorPlot( object, error = \"MSE\", by = \"CellType\", dispersion = \"se\", filter.sc = TRUE, title = NULL, angle = NULL, theme = NULL )"},{"path":"/reference/barErrorPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate bar error plots — barErrorPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. error 'MAE' 'MSE'. Variable used show errors. Available options : 'nCellTypes', 'CellType'. dispersion Standard error ('se') standard deviation ('sd'). former default. filter.sc Boolean indicating whether single-cell profiles filtered correlation results associated mixed transcriptional profiles shown (TRUE default). title Title plot. angle Angle ticks. theme ggplot2 theme.","code":""},{"path":"/reference/barErrorPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate bar error plots — barErrorPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/barErrorPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate bar error plots — barErrorPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.6068 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2343 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # bar error plots barErrorPlot( object = SDDLS, error = \"MSE\", by = \"CellType\" ) barErrorPlot( object = SDDLS, error = \"MAE\", by = \"nCellTypes\" ) # }"},{"path":"/reference/barPlotCellTypes.html","id":null,"dir":"Reference","previous_headings":"","what":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"Bar plot deconvoluted cell type proportions.","code":""},{"path":"/reference/barPlotCellTypes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"","code":"barPlotCellTypes( data, colors = NULL, set = NULL, prediction = \"Regularized\", color.line = NA, x.label = \"Spots\", rm.x.text = FALSE, title = \"Results of deconvolution\", legend.title = \"Cell types\", angle = 90, theme = NULL, index.st = NULL )"},{"path":"/reference/barPlotCellTypes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"data SpatialDDLS object deconv.spots slot containing predicted cell type proportions. colors Vector colors used. set Type simplification performed deconvolution. can simpli.set simpli.maj (NULL default). prediction Set predicted cell proportions plotted. can \"Regularized\", \"Intrinsic\" \"Extrinsic\". color.line Color border bars. x.label Label x-axis. rm.x.text Logical value indicating whether remove x-axis ticks (name samples). title Title plot. legend.title Title legend plot. angle Angle text ticks. theme ggplot2 theme. index.st Name index element wanted shown deconv.spots slot.","code":""},{"path":"/reference/barPlotCellTypes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Bar plot of deconvoluted cell type proportions — barPlotCellTypes","text":"ggplot object provided cell proportions represented bar plot.","code":""},{"path":[]},{"path":"/reference/blandAltmanLehPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"Generate Bland-Altman agreement plots predicted expected cell type proportions test data. Bland-Altman agreement plots can shown mixed split either cell type (CellType) number cell types present spots (nCellTypes). See facet.argument examples information.","code":""},{"path":"/reference/blandAltmanLehPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"","code":"blandAltmanLehPlot( object, colors, color.by = \"CellType\", facet.by = NULL, log.2 = FALSE, filter.sc = TRUE, density = TRUE, color.density = \"darkblue\", size.point = 0.05, alpha.point = 1, ncol = NULL, nrow = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/blandAltmanLehPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. colors Vector colors used. color.Variable used color data. Options nCellTypes CellType. facet.Variable used show data different panels. NULL, plot split different panels. Options nCellTypes (number different cell types) CellType (cell type). log.2 Whether show Bland-Altman agreement plot log2 space (FALSE default). filter.sc Boolean indicating whether single-cell profiles filtered correlations results associated mixed spot profiles shown (TRUE default). density Boolean indicating whether density lines shown (TRUE default). color.density Color density lines density argument TRUE. size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). ncol Number columns facet.used. nrow Number rows facet.used. title Title plot. theme ggplot2 theme. ... Additional argument facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/blandAltmanLehPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/blandAltmanLehPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate Bland-Altman agreement plots between predicted and expected cell\ntype proportions of test data — blandAltmanLehPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.597 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2394 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # Bland-Altman plot by cell type blandAltmanLehPlot( object = SDDLS, facet.by = \"CellType\", color.by = \"CellType\" ) #> Warning: `stat_contour()`: Zero contours were generated #> Warning: no non-missing arguments to min; returning Inf #> Warning: no non-missing arguments to max; returning -Inf #> Warning: `stat_contour()`: Zero contours were generated #> Warning: no non-missing arguments to min; returning Inf #> Warning: no non-missing arguments to max; returning -Inf #> Warning: `stat_contour()`: Zero contours were generated #> Warning: no non-missing arguments to min; returning Inf #> Warning: no non-missing arguments to max; returning -Inf #> Warning: `stat_contour()`: Zero contours were generated #> Warning: no non-missing arguments to min; returning Inf #> Warning: no non-missing arguments to max; returning -Inf #> Warning: `stat_contour()`: Zero contours were generated #> Warning: no non-missing arguments to min; returning Inf #> Warning: no non-missing arguments to max; returning -Inf # Bland-Altman plot of all samples mixed blandAltmanLehPlot( object = SDDLS, facet.by = NULL, color.by = \"CellType\", alpha.point = 0.3, log2 = TRUE ) # }"},{"path":"/reference/calculateEvalMetrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"Calculate evaluation metrics test mixed transcriptional profiles. default, absolute error (AbsErr), proportional absolute error (ppAbsErr), squared error (SqrErr), proportional squared error (ppSqrErr) calculated test mixed profile. addition, metrics aggregated according three criteria: cell type (CellType), probability bins ranges 0.1 (pBin), number different cell types present spot (nCellTypes).","code":""},{"path":"/reference/calculateEvalMetrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"","code":"calculateEvalMetrics(object)"},{"path":"/reference/calculateEvalMetrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"object SpatialDDLS object trained model trained.model slot actual cell proportions test mixed profiles prob.cell.types slot.","code":""},{"path":"/reference/calculateEvalMetrics.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate evaluation metrics on test mixed transcriptional profiles — calculateEvalMetrics","text":"SpatialDDLS object DeconvDLModel object. calculated metrics stored test.deconv.metrics slot DeconvDLModel object.","code":""},{"path":[]},{"path":"/reference/cell.names.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"Get set cell.names slot PropCellTypes object","code":""},{"path":"/reference/cell.names.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"","code":"cell.names(object) cell.names(object) <- value"},{"path":"/reference/cell.names.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set cell.names slot in a\nPropCellTypes object — cell.names","text":"object PropCellTypes object. value Matrix containing names mixed transcriptional profiles simulated rows cells used simulate columns.","code":""},{"path":"/reference/cell.types.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"Get set cell.types slot DeconvDLModel object","code":""},{"path":"/reference/cell.types.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"","code":"cell.types(object) cell.types(object) <- value"},{"path":"/reference/cell.types.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set cell.types slot in a\nDeconvDLModel object — cell.types","text":"object DeconvDLModel object. value Vector cell types considered deep neural network model.","code":""},{"path":"/reference/corrExpPredPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"Generate correlation plots predicted expected cell type proportions test data. Correlation plots can shown mixed either split cell type (CellType) number different cell types present spots (nCellTypes).","code":""},{"path":"/reference/corrExpPredPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"","code":"corrExpPredPlot( object, colors, facet.by = NULL, color.by = \"CellType\", corr = \"both\", filter.sc = TRUE, pos.x.label = 0.01, pos.y.label = 0.95, sep.labels = 0.15, size.point = 0.1, alpha.point = 1, ncol = NULL, nrow = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/corrExpPredPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. colors Vector colors used. facet.Show data different panels. Options nCellTypes (number different cell types) CellType (cell type) (NULL default). color.Variable used color data. Options nCellTypes CellType. corr Correlation value shown annotation plot. Available metrics Pearson's correlation coefficient ('pearson') concordance correlation coefficient ('ccc'). can 'pearson', 'ccc' '' (default). filter.sc Boolean indicating whether single-cell profiles filtered mixed transcriptional profile errors shown (TRUE default). pos.x.label X-axis position correlation annotations (0.95 default). pos.y.label Y-axis position correlation annotations (0.1 default). sep.labels Space separating annotations corr equal '' (0.15 default). size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). ncol Number columns facet.NULL. nrow Number rows facet.different NULL. title Title plot. theme ggplot2 theme. ... Additional arguments facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/corrExpPredPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/corrExpPredPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate correlation plots between predicted and expected cell type\nproportions of test data — corrExpPredPlot","text":"","code":"# \\donttest{ set.seed(123) set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.5591 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2384 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # correlations by cell type corrExpPredPlot( object = SDDLS, facet.by = \"CellType\", color.by = \"CellType\", corr = \"both\" ) #> `geom_smooth()` using formula = 'y ~ x' # correlations of all samples mixed corrExpPredPlot( object = SDDLS, facet.by = NULL, color.by = \"CellType\", corr = \"ccc\", pos.x.label = 0.2, alpha.point = 0.3 ) #> `geom_smooth()` using formula = 'y ~ x' # }"},{"path":"/reference/createSpatialDDLSobject.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a SpatialDDLS object — createSpatialDDLSobject","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"Create SpatialDDLS object providing single-cell RNA-seq data. Additionally, spatial transcriptomics data contained SpatialDDLS objects can also provided. recommended provide types data use genes shared experiments.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"","code":"createSpatialDDLSobject( sc.data, sc.cell.ID.column, sc.cell.type.column, sc.gene.ID.column, st.data, st.spot.ID.column, st.gene.ID.column, filter.mt.genes = \"^mt-\", sc.filt.genes.cluster = TRUE, sc.min.mean.counts = 1, sc.n.genes.per.cluster = 300, top.n.genes = 2000, sc.min.counts = 0, sc.min.cells = 0, st.min.counts = 0, st.min.spots = 0, st.n.slides = 3, shared.genes = TRUE, sc.name.dataset.h5 = NULL, sc.file.backend = NULL, sc.name.dataset.backend = NULL, sc.compression.level = NULL, sc.chunk.dims = NULL, sc.block.processing = FALSE, verbose = TRUE, project = \"SpatialDDLS-Proj\" )"},{"path":"/reference/createSpatialDDLSobject.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"sc.data Single-cell RNA-seq profiles used reference. data provided files, single.cell.real must vector three elements: single-cell counts, cells metadata genes metadata. hand, data provided SingleCellExperiment object, single-cell counts must present assay slot, cells metadata colData slot, genes metadata rowData slot. sc.cell.ID.column Name number column cells metadata corresponding cell names expression matrix (single-cell RNA-seq data). sc.cell.type.column Name column number corresponding cell types cells metadata. sc.gene.ID.column Name number column genes metadata corresponding names used features/genes (single-cell RNA-seq data). st.data Spatial transcriptomics datasets deconvoluted. can single SpatialExperiment object list . st.spot.ID.column Name number column spots metadata corresponding spot names expression matrix (spatial transcriptomics data). st.gene.ID.column Name number column genes metadata corresponding names used features/genes (spatial transcriptomics data). filter.mt.genes Regular expression matching mitochondrial genes ruled (^mt- default). NULL, filtering performed. sc.filt.genes.cluster Whether filter single-cell RNA-seq genes according minimum threshold non-zero average counts per cell type (sc.min.mean.counts). TRUE default. sc.min.mean.counts Minimum non-zero average counts per cluster filter genes. 1 default. sc.n.genes.per.cluster Top n genes highest logFC per cluster. 300 default. See Details section details. top.n.genes Maximum number genes used downstream steps (2000 default). case number genes filtering greater top.n.genes, genes set according variability across whole single-cell dataset. sc.min.counts Minimum gene counts filter (0 default; single-cell RNA-seq data). sc.min.cells Minimum cells min.counts (0 default; single-cell RNA-seq data). st.min.counts Minimum gene counts filter (0 default; spatial transcriptomics data). st.min.spots Minimum cells min.counts (0 default; spatial transcriptomics data). st.n.slides Minimum number slides (SpatialExperiment objects) gene expressed order keep . parameter applicable multiple SpatialExperiment objects provided. Genes present least st.n.slides discarded. filtering desired, set st.n.slides = 1. shared.genes set TRUE, genes present isngle-cell spatial transcriptomics data retained processing (TRUE default). sc.name.dataset.h5 Name data set HDF5 file provided single-cell RNA-seq data. sc.file.backend Valid file path store loaded single-cell RNA-seq data HDF5 file. provided, data stored HDF5 file back-end using DelayedArray HDF5Array packages instead loaded RAM. suitable situations large amounts data stored memory. Note operations data performed blocks (.e subsets determined size), may result longer execution times. NULL default. sc.name.dataset.backend Name HDF5 file dataset used. Note exist. NULL (default), random dataset name generated. sc.compression.level compression level used sc.file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. sc.chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered SpatialDDLS object simulation, one sample order increase read times following steps. larger number columns written chunk may lead longer read times. sc.block.processing Boolean indicating whether single-cell RNA-seq data treated blocks (data provided HDF5 file). FALSE default. Note using functionality suitable cases possible load data RAM therefore execution times longer. verbose Show informative messages execution (TRUE default). project Name project SpatialDDLS object.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"SpatialDDLS object single-cell RNA-seq data provided loaded single.cell.real slot SingleCellExperiment object. spatial transcriptomics data provided, loaded spatial.experiments slot.","code":""},{"path":"/reference/createSpatialDDLSobject.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"Filtering genes order reduce number dimensions used subsequent steps, createSpatialDDLSobject implements different strategies aimed removing useless genes deconvolution: Filtering cell level: genes less expressed determined cutoff N cells removed. See sc.min.cells/st.min.cells sc.min.counts/st.min.cells parameters. Filtering cluster level (scRNA-seq data): sc.filt.genes.cluster == TRUE, createSpatialDDLSobject sets cutoff non-zero average counts per cluster (sc.min.mean.counts parameter) take sc.n.genes.per.cluster genes highest logFC per cluster. LogFCs calculated using normalized logCPM cluster respect average whole dataset). Finally, number remaining genes greater top.n.genes, genes ranked based variance top.n.genes variable genes used downstream analyses. Single-cell RNA-seq data Single-cell RNA-seq data can provided files (formats allowed: tsv, tsv.gz, mtx (sparse matrix) hdf5) SingleCellExperiment object. Data stored single.cell.real slot, must consist three pieces information: Single-cell counts: genes rows cells columns. Cells metadata: annotations (columns) cell (rows). Genes metadata: annotations (columns) gene (rows). data provided files, single.cell.real argument must vector three elements ordered first file corresponds count matrix, second cells metadata, last genes metadata. hand, data provided SingleCellExperiment object, must contain single-cell counts assay, cells metadata colData, genes metadata rowData. Data must provided without transformation (e.g. log-transformation), raw counts preferred. Spatial transcriptomics data must SpatialExperiment object (list one slide going deconvoluted) containing information single-cell RNA-seq data: count matrix, spots metadata, genes metadata. Please, make sure gene identifiers used spatial single-cell transcriptomics data consistent.","code":""},{"path":[]},{"path":"/reference/createSpatialDDLSobject.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a SpatialDDLS object — createSpatialDDLSobject","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) counts <- matrix( rpois(30, lambda = 5), ncol = 6, dimnames = list(paste0(\"Gene\", 1:5), paste0(\"Spot\", 1:6)) ) coordinates <- matrix( c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), ncol = 2 ) ste <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", 1:5)), colData = data.frame(Cell_ID = paste0(\"Spot\", 1:6)), spatialCoords = coordinates ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", st.data = ste, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 5 #> - Discarded features: 0 #> #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === Number of shared genes between single-cell and spatial transcriptomics datasets: 5 #> - Original # genes in single-cell data: 40 #> - Original # genes in ST data (object with the greatest # genes): 5 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 5"},{"path":"/reference/deconv.spots.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"Get set deconv.spots slot SpatialDDLS object","code":""},{"path":"/reference/deconv.spots.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"","code":"deconv.spots(object, index.st = NULL) deconv.spots(object, index.st = NULL) <- value"},{"path":"/reference/deconv.spots.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set deconv.spots slot in a\nSpatialDDLS object — deconv.spots","text":"object SpatialDDLS object. index.st Name index predicted cell proportions (spatial.experiments slot). NULL (default), results returned. value List predicted cell type proportions experiments stored spatial.experiments slot.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":null,"dir":"Reference","previous_headings":"","what":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"Deconvolute spatial transcriptomics data using trained model SpatialDDLS object. trained model used predict cell proportions two mirrored transcriptional profiles: 'Intrinsic' profiles: transcriptional profiles spot ST dataset. 'Extrinsic' profiles: profiles simulated surrounding spots spot. prediction, cell proportions intrinsic profiles (intrinsic cell proportions) regularized based similarity intrinsic extrinsic profiles order maintain spatial consistency. approach leverages transcriptional spatial information. details, see Mañanes et al., 2023 Details section.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"","code":"deconvSpatialDDLS( object, index.st, normalize = TRUE, scaling = \"standardize\", k.spots = 4, pca.space = TRUE, pca.var = 0.8, metric = \"euclidean\", alpha.cutoff = \"mean\", alpha.quantile = 0.5, simplify.set = NULL, simplify.majority = NULL, use.generator = FALSE, batch.size = 64, verbose = TRUE )"},{"path":"/reference/deconvSpatialDDLS.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"object SpatialDDLS object trained.model spatial.experiments slots. index.st Name index dataset/slide stored SpatialDDLS object (spatial.experiments slot) deconvolute. missing, datasets deconvoluted. normalize Normalize data (logCPM) deconvolution (TRUE default). scaling scale data training. Options include \"standardize\" (values centered around mean unit standard deviation) \"rescale\" (values shifted rescaled end ranging 0 1). normalize = FALSE, data scaled. k.spots Number nearest spots considered spot regularization simulation extrinsic transcriptional profiles. greater, smoother regularization (4 default). pca.space Whether use PCA space calculate distances intrinsic extrinsic transcriptional profiles (TRUE default). pca.var Threshold explained variance (0.2 1) used choose number PCs used pca.space == TRUE. metric Metric used measure distance/similarity intrinsic extrinsic transcriptional profiles. may 'euclidean', 'cosine' 'pearson' ('euclidean' default). alpha.cutoff Minimum distance regularization. may 'mean' (spots transcriptional distances shorter mean distance dataset modified) 'quantile' (spots transcriptional distances shorter alpha.quantile quantile used). 'mean' default. alpha.quantile Quantile used alpha.cutoff == 'quantile'. 0.5 default. simplify.set List specifying cell types compressed new label name list item. See examples details. provided, results stored list 'raw' 'simpli.set' elements. simplify.majority List specifying cell types compressed cell type highest proportion spot. Unlike simplify.set, new labels created. provided, results stored list 'raw' 'simpli.majority' elements. use.generator Boolean indicating whether use generators prediction (FALSE default). batch.size Number samples per batch. use.generator = TRUE. verbose Show informative messages execution.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"SpatialDDLS object deconv.spots slot. output list containing 'Regularized', 'Intrinsic' 'Extrinsic' deconvoluted cell proportions, 'Distances' intrinsic extrinsic transcriptional profiles, 'Weight.factors' final weights used regularize intrinsic cell proportions. simplify.set /simplify.majority provided, deconv.spots slot contain list raw simplified results.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"deconvolution process involves two main steps: predicting cell proportions based transcriptome using trained neural network model, regularization cell proportions based spatial location spot. regularization step, mirrored version spot simulated based N-nearest spots. refer profiles 'extrinsic' profiles, whereas transcriptional profiles spot called 'intrinsic' profiles. Extrinsic profiles used regularize predictions based intrinsic profiles. rationale spots surrounded transcriptionally similar spots similar cell compositions, therefore predicted proportions can smoothed preserve spatial consistency. hand, spots surrounded dissimilar spots predicted neighbors, thus can predicted transcriptional profiles likely due presenting specific cell compositions. Regarding working os SpatialDDLS: first, extrinsic profiles simulated based N-nearest spots spot summing transcriptomes. Distances extrinsic intrinsic profiles spot calculated similar/dissimilar spots identified. two sets transcriptional profiles used input trained neural network model, according calculated distances, weighted mean predicted proportions spot calculated. Spots distances intrinsic extrinsic profiles greater alpha.cutoff regularized, whereas spots distances less alpha.cutoff contribute weighted mean. Weights calculated rescaling distances less alpha.cutoff 0 0.5, maximum extent extrinsic profile can modified predictions based intrinsic profiles 0.5 (regular mean). details, see Mañanes et al., 2023. function requires SpatialDDLS object trained deep neural network model (trained.model slot, spatial transcriptomics datasets deconvoluted spatial.experiments slot. See ?createSpatialDDLSobject ?loadSTProfiles details.","code":""},{"path":"/reference/deconvSpatialDDLS.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"Mañanes, D., Rivero-García, ., Jimenez-Carretero, D., Torres, M., Sancho, D., Torroja, C., Sánchez-Cabo, F. (2023). SpatialDDLS: R package deconvolute spatial transcriptomics data using neural networks. biorxiv. doi: doi:10.1101/2023.08.31.555677 .","code":""},{"path":[]},{"path":"/reference/deconvSpatialDDLS.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Deconvolute spatial transcriptomics data using trained model — deconvSpatialDDLS","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample(x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of SDDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.561 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2399 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # simulating spatial data ngenes <- sample(3:40, size = 1) ncells <- sample(3:40, size = 1) counts <- matrix( rpois(ngenes * ncells, lambda = 5), ncol = ncells, dimnames = list(paste0(\"Gene\", seq(ngenes)), paste0(\"Spot\", seq(ncells))) ) coordinates <- matrix( rep(c(1, 2), ncells), ncol = 2 ) st <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", seq(ngenes))), colData = data.frame(Cell_ID = paste0(\"Spot\", seq(ncells))), spatialCoords = coordinates ) SDDLS <- loadSTProfiles( object = SDDLS, st.data = st, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 33 #> - Discarded features: 0 #> # simplify arguments simplify <- list(CellGroup1 = c(\"CellType1\", \"CellType2\", \"CellType4\"), CellGroup2 = c(\"CellType3\", \"CellType5\")) SDDLS <- deconvSpatialDDLS( object = SDDLS, index.st = 1, simplify.set = simplify, simplify.majority = simplify ) #> === Filtering out 18 features in data that are not present in trained model #> === Normalizing data (LogCPM) #> === Predicting cell type proportions #> #> === Calculating distances in PCA space #> - Using 12 PCs (variance cutoff: 0.8) #> === Calculating alpha factors based on distances #> === Note that only regularized proportions will be simplified #> DONE # }"},{"path":"/reference/distErrorPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate box or violin plots showing error distribution — distErrorPlot","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"Generate box violin plots show errors distributed. Errors can shown mixed either split cell type (CellType) number cell types present spots (nCellTypes). See facet.argument examples details.","code":""},{"path":"/reference/distErrorPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"","code":"distErrorPlot( object, error, colors, x.by = \"pBin\", facet.by = NULL, color.by = \"nCellTypes\", filter.sc = TRUE, error.label = FALSE, pos.x.label = 4.6, pos.y.label = NULL, size.point = 0.1, alpha.point = 1, type = \"violinplot\", ylimit = NULL, nrow = NULL, ncol = NULL, title = NULL, theme = NULL, ... )"},{"path":"/reference/distErrorPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"object SpatialDDLS object trained.model slot containing metrics test.deconv.metrics slot DeconvDLModel object. error Error represented. Available metric errors : absolute error ('AbsErr'), proportional absolute error ('ppAbsErr'), squared error ('SqrErr'), proportional squared error ('ppSqrErr'). colors Vector colors used. x.Variable used X-axis. facet.NULL, best choice pBin (probability bins). Options: nCellTypes (number different cell types), CellType (cell type), pBin. facet.Show data different panels. Options nCellTypes (number different cell types) CellType (cell type) (NULL default). color.Variable used color data. Options nCellTypes CellType. filter.sc Boolean indicating whether single-cell profiles filtered mixed transcriptional profile errors shown (TRUE default). error.label Boolean indicating whether show average error plot annotation (FALSE default). pos.x.label X-axis position error annotations. pos.y.label Y-axis position error annotations. size.point Size points (0.1 default). alpha.point Alpha points (0.1 default). type Type plot: 'boxplot' 'violinplot' (latter default). ylimit Upper limit Y-axis required (NULL default). nrow Number rows facet.NULL. ncol Number columns facet.NULL. title Title plot. theme ggplot2 theme. ... Additional arguments facet_wrap function ggplot2 facet.NULL.","code":""},{"path":"/reference/distErrorPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/distErrorPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate box or violin plots showing error distribution — distErrorPlot","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 20, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(20))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(20)), Cell_Type = sample( x = paste0(\"CellType\", seq(6)), size = 20, replace = TRUE ) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 3 #> - CellType2: 1 #> - CellType3: 3 #> - CellType4: 2 #> - CellType5: 3 #> - CellType6: 2 #> === Test set cells by type: #> - CellType1: 1 #> - CellType2: 1 #> - CellType3: 1 #> - CellType4: 1 #> - CellType5: 1 #> - CellType6: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 6 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 6 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE # training of DDLS model SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 15, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 6) 1206 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 6) 24 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 6) 0 #> ===================================================================== #> Total params: 46,230 #> Trainable params: 45,418 #> Non-trainable params: 812 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 1.44 #> - accuracy: 0.125 #> - mean_absolute_error: 0.2287 #> - categorical_accuracy: 0.125 #> #> === Generating prediction results using test data #> DONE # evaluation using test data SDDLS <- calculateEvalMetrics(object = SDDLS) # representation, for more examples, see the vignettes distErrorPlot( object = SDDLS, error = \"AbsErr\", facet.by = \"CellType\", color.by = \"nCellTypes\", error.label = TRUE ) #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. #> Warning: Groups with fewer than two data points have been dropped. distErrorPlot( object = SDDLS, error = \"AbsErr\", x.by = \"CellType\", facet.by = NULL, color.by = \"CellType\", error.label = TRUE ) # }"},{"path":"/reference/estimateZinbwaveParams.html","id":null,"dir":"Reference","previous_headings":"","what":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"Estimate parameters ZINB-WaVE model using real single-cell RNA-Seq data set reference simulate new single-cell profiles increase signal underrepresented cell types. step needed size single-cell RNA-seq dataset small underrepresented cell types. step, simSCProfiles function use estimated parameters simulate new single-cell profiles. See ?simSCProfiles information.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"","code":"estimateZinbwaveParams( object, cell.type.column, cell.ID.column, gene.ID.column, cell.cov.columns, gene.cov.columns, subset.cells = NULL, proportional = TRUE, set.type = \"All\", threads = 1, verbose = TRUE )"},{"path":"/reference/estimateZinbwaveParams.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"object SpatialDDLS object single.cell.real slot. cell.type.column Name column number corresponding cell type cell cells metadata. cell.ID.column Name column number corresponding cell names expression matrix cells metadata. gene.ID.column Name column number corresponding notation used features/genes genes metadata. cell.cov.columns Name column number(s) cells metadata used covariates model fitting (covariates used, set empty NULL). gene.cov.columns Name column number(s) genes metadata used covariates model fitting (covariates used, set empty NULL). subset.cells Number cells fit ZINB-WaVE model. Useful original data set large fit model. Set value according original data set resources available computer. NULL (default), cells used. Must integer greater equal number cell types considered less equal total number cells. proportional TRUE, original cell type proportions subset cells generated subset.cells altered far possible. FALSE, cell types number cells far possible (TRUE default). set.type Cell type(s) evaluate ('' default). recommended fitting model cell types rather using subset capture total variability present original experiment even subset cell types simulated. threads Number threads used estimation (1 default). set parallel environment, BiocParallel package must installed. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"SpatialDDLS object zinb.params slot containing ZinbParametersModel object. object contains slot estimated ZINB-WaVE parameters real single-cell RNA-Seq data.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"ZINB-WaVE flexible model zero-inflated count data. function carries model fit real single-cell data modeling \\(Y_{ij}\\) (count feature \\(j\\) sample \\(\\)) random variable following zero-inflated negative binomial (ZINB) distribution. estimated parameters used simulation new single-cell expression profiles sampling negative binomial distribution inserting dropouts binomial distribution. , SpatialDDLS uses zinbFit function zinbwave package (Risso et al., 2018). details model, see Risso et al., 2018.","code":""},{"path":"/reference/estimateZinbwaveParams.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 . Torroja, C. Sánchez-Cabo, F. (2019). digitalDLSorter: Deep Learning algorithm quantify immune cell populations based scRNA-Seq data. Frontiers Genetics 10, 978. doi: doi:10.3389/fgene.2019.00978 .","code":""},{"path":[]},{"path":"/reference/estimateZinbwaveParams.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Estimate parameters of the ZINB-WaVE model to simulate new single-cell\nRNA-Seq expression profiles — estimateZinbwaveParams","text":"","code":"set.seed(123) # reproducibility sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- estimateZinbwaveParams( object = SDDLS, cell.type.column = \"Cell_Type\", cell.ID.column = \"Cell_ID\", gene.ID.column = \"Gene_ID\", subset.cells = 2, verbose = TRUE ) #> === Setting parallel environment to 1 thread(s) #> === Estimating parameters for all cell types in the experiment #> === Creating cell model matrix based on Cell_Type columns: #> \t~Cell_Type #> === Number of cells for each cell type: #> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates #> === Running estimation process (Start time 02:10:35 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: #> ok #> Initialize parameters: #> ok #> Optimize parameters: #> Iteration 1 #> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed #> 0.026 0.000 0.027 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed #> 0.012 0.000 0.013 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed #> 0.021 0.000 0.021 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed #> 0.008 0.000 0.008 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 #> penalized log-likelihood = -54.6055197876494 #> ok #> #> DONE #> #> Invested time: 1.11"},{"path":"/reference/features.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set features slot in a\nDeconvDLModel object — features","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"Get set features slot DeconvDLModel object","code":""},{"path":"/reference/features.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"","code":"features(object) features(object) <- value"},{"path":"/reference/features.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set features slot in a\nDeconvDLModel object — features","text":"object DeconvDLModel object. value Vector features (genes) considered deep neural network model.","code":""},{"path":"/reference/genMixedCellProp.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate training and test cell type composition matrices — genMixedCellProp","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"Generate training test cell type composition matrices simulation mixed transcriptional profiles known cell composition using single-cell expression profiles. resulting PropCellTypes object contain information needed simulate new mixed transcriptional profiles. Note function simulate mixed profiles, task performed simMixedProfiles trainDeconvModel functions (see Documentation).","code":""},{"path":"/reference/genMixedCellProp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"","code":"genMixedCellProp( object, cell.ID.column, cell.type.column, num.sim.spots, n.cells = 50, train.freq.cells = 2/3, train.freq.spots = 2/3, proportion.method = c(0.4, 0.3, 0.3), prob.sparity = 1, min.zero.prop = NULL, balanced.type.cells = TRUE, verbose = TRUE )"},{"path":"/reference/genMixedCellProp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"object SpatialDDLS object single.cell.real slot , optionally, single.cell.simul slot. cell.ID.column Name column number corresponding cell names cells metadata. cell.type.column Name column number corresponding cell types cells metadata. num.sim.spots Number mixed profiles simulated. recommended adjust number according number available single-cell profiles. n.cells Specifies number cells randomly selected combined generate simulated mixed profiles. default, set 100. controls level noise present simulated data, determines many single-cell profiles combined produce spot. train.freq.cells Proportion cells used simulate training mixed transcriptional profiles (2/3 default). train.freq.spots Proportion mixed transcriptional profiles used training, relative total number simulated spots (num.sim.spots). default value 2/3. proportion.method Vector three elements controls proportion simulated proportions generated method: random sampling Dirichlet distribution, \"pure\" spots (1 cell type), spots specified number different cell types (determined min.zero.prop), respectively. default, 40% simulated proportions follow Dirichlet distribution, 30% consist one cell type, 30% specified number different cell types. prob.sparity affects proportions generated first method (Dirichlet distribution). determines probability missing cell types simulated spot, opposed mixture cell types. higher value parameter result sparse simulated samples. min.zero.prop parameter controls minimum number cell types absent simulated spot. NULL (default), value half total number different cell types, increasing result spots composed fewer cell types. helps create sparse proportions cover wider range situations model training. balanced.type.cells Boolean indicating whether training test cells split balanced way considering cell types (TRUE default). verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/genMixedCellProp.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"SpatialDDLS object prob.cell.types slot containing list two PropCellTypes objects (training test). information structure class, see ?PropCellTypes.","code":""},{"path":"/reference/genMixedCellProp.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"First, single-cell profiles randomly divided two subsets, 2/3 data training 1/3 testing. default setting ratio can changed using train.freq.cells parameter. Next, total num.sim.spots mixed proportions simulated using Dirichlet distribution. simulation takes account probability missing cell types spot, can adjusted using prob.sparity parameter. mixed sample, n.cells single-cell profiles randomly selected combined generate simulated mixed sample. addition Dirichlet-based proportions, pure spots (containing one cell type) spots containing specified number different cell types (determined min.zero.prop patameter) also generated order cover situations cell types present. proportion simulated spots generated method can controlled using proportion.method parameter. visualize distribution cell type proportions generated method, showProbPlot function can used.","code":""},{"path":[]},{"path":"/reference/genMixedCellProp.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate training and test cell type composition matrices — genMixedCellProp","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE"},{"path":"/reference/getProbMatrix.html","id":null,"dir":"Reference","previous_headings":"","what":"Getter function for the cell composition matrix — getProbMatrix","title":"Getter function for the cell composition matrix — getProbMatrix","text":"Getter function cell composition matrix. function allows access cell composition matrix simulated mixed transcriptional profiles.","code":""},{"path":"/reference/getProbMatrix.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Getter function for the cell composition matrix — getProbMatrix","text":"","code":"getProbMatrix(object, type.data)"},{"path":"/reference/getProbMatrix.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Getter function for the cell composition matrix — getProbMatrix","text":"object SpatialDDLS object prob.cell.types slot. type.data Subset data return: train test.","code":""},{"path":"/reference/getProbMatrix.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Getter function for the cell composition matrix — getProbMatrix","text":"Cell type proportion matrix.","code":""},{"path":[]},{"path":"/reference/installTFpython.html","id":null,"dir":"Reference","previous_headings":"","what":"Install Python dependencies for SpatialDDLS — installTFpython","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"function facilitates installation required Python dependencies SpatialDDLS package. requires Python interpreter TensorFlow Python library dependencies. utilizes reticulate package installer tensorflow R package perform installation. Conda environments used new environment named SpatialDDLS-env. function intended simplify installation process SpatialDDLS automatically installing Miniconda creating new environment named SpatialDDLS-env. users wish use different Python conda environment, see tensorflow::use_condaenv function package vignettes information.","code":""},{"path":"/reference/installTFpython.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"","code":"installTFpython(conda = \"auto\", install.conda = FALSE, miniconda.path = NULL)"},{"path":"/reference/installTFpython.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"conda Path conda executable. Using \"auto\" (default) allows reticulate automatically find appropriate conda binary. install.conda Boolean indicating installing miniconda automatically using reticulate. TRUE, conda argument ignored. FALSE default. miniconda.path install.conda TRUE, can set path miniconda installed. NULL, conda find automatically proper place.","code":""},{"path":"/reference/installTFpython.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"return value, called side effects: installation conda environment Python interpreter Tensorflow","code":""},{"path":"/reference/installTFpython.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Install Python dependencies for SpatialDDLS — installTFpython","text":"","code":"if (FALSE) { notesInstallation <- installTFpython( method = \"auto\", conda = \"auto\", install.conda = TRUE ) }"},{"path":"/reference/interGradientsDL.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"function enables users gain insights interpretability deconvolution model. calculates gradients classes/loss function respect input features used training. numeric values calculated per gene cell type pure mixed transcriptional profiles, providing information extent feature influences model's prediction cell proportions cell type.","code":""},{"path":"/reference/interGradientsDL.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"","code":"interGradientsDL( object, method = \"class\", normalize = TRUE, scaling = \"standardize\", verbose = TRUE )"},{"path":"/reference/interGradientsDL.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"object SpatialDDLS object containing trained deconvolution model (trained.model slot) pure mixed transcriptional profiles (mixed.profiles slot). method Method calculate gradients respect inputs. can 'class' (gradients predicted classes w.r.t. inputs), 'loss' (gradients loss w.r.t. inputs) ''. normalize Whether normalize data using logCPM (TRUE default). parameter considered method used simulate mixed transcriptional profiles (simMixedProfiles function) \"AddRawCount\". Otherwise, data already normalized. parameter set according transformation used train model. scaling scale data. can : \"standardize\" (values centered around mean unit standard deviation), \"rescale\" (values shifted rescaled end ranging 0 1, default) \"none\" (scaling performed). parameter set according transformation used train model. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/interGradientsDL.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"Object containing gradients interpret.gradients slot DeconvDLModel object (trained.model slot).","code":""},{"path":"/reference/interGradientsDL.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"Gradients classes / loss function respect input features calculated exclusively using pure mixed transcriptional profiles composed single cell type. Consequently, numbers can interpreted extent feature used predict cell type proportion. Gradients calculated sample level gene, mean gradients cell type reported. additional details, see Mañanes et al., 2023.","code":""},{"path":[]},{"path":"/reference/interGradientsDL.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate gradients of predicted cell types/loss function with respect to\ninput features for interpreting trained deconvolution models — interGradientsDL","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.1983 #> - accuracy: 1 #> - mean_absolute_error: 0.1791 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) # }"},{"path":"/reference/loadSTProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"function loads SpatialExperiment object (list several SpatialExperiment objects) SpatialDDLS object.","code":""},{"path":"/reference/loadSTProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"","code":"loadSTProfiles( object, st.data, st.spot.ID.column, st.gene.ID.column, st.min.counts = 0, st.min.spots = 0, st.n.slides = 3, verbose = TRUE )"},{"path":"/reference/loadSTProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"object SpatialDDLS object. st.data SpatialExperiment object (list several SpatialExperiment objects) deconvoluted. st.spot.ID.column Name number column spots metadata corresponding spot names expression matrix. st.gene.ID.column Name number column genes metadata corresponding names used features/genes. st.min.counts Minimum gene counts filter (0 default). st.min.spots Minimum spots min.counts (0 default). st.n.slides Minimum number slides (SpatialExperiment objects) gene expressed order keep . parameter applicable multiple SpatialExperiment objects provided. Genes present least st.n.slides discarded. filtering desired, set st.n.slides = 1. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/loadSTProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"SpatialDDLS object provided spatial trainscriptomics data loaded spatial.experiments slot.","code":""},{"path":"/reference/loadSTProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"recommended perform step creating SpatialDDLS object using createSpatialDDLSobject function order keep genes shared spatial transcriptomics single-cell transcriptomics data used reference. addition, please, make sure gene identifiers used spatial single-cell transcriptomics data consistent.","code":""},{"path":[]},{"path":"/reference/loadSTProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Loads spatial transcriptomics data into a SpatialDDLS object — loadSTProfiles","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 ## simulating a SpatialExperiment object counts <- matrix(rpois(30, lambda = 5), ncol = 6) rownames(counts) <- paste0(\"Gene\", 1:5) colnames(counts) <- paste0(\"Spot\", 1:6) coordinates <- matrix( c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), ncol = 2 ) ste <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", 1:5)), colData = data.frame(Cell_ID = paste0(\"Spot\", 1:6)), spatialCoords = coordinates ) ## previous SpatialDDLS object SDDLS <- loadSTProfiles( object = SDDLS, st.data = ste, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 5 #> - Discarded features: 0 #> # }"},{"path":"/reference/loadTrainedModelFromH5.html","id":null,"dir":"Reference","previous_headings":"","what":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"Load HDF5 file trained deep neural network model SpatialDDLS object. Note HDF5 file must valid trained model (keras object).","code":""},{"path":"/reference/loadTrainedModelFromH5.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"","code":"loadTrainedModelFromH5(object, file.path, reset.slot = FALSE)"},{"path":"/reference/loadTrainedModelFromH5.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"object SpatialDDLS object trained.model slot. file.path Valid file path model stored. reset.slot Deletes trained.slot already exists. new DeconvDLModel object formed, contain slots (FALSE default).","code":""},{"path":"/reference/loadTrainedModelFromH5.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Load from an HDF5 file a trained deep neural network model into a\nSpatialDDLS object — loadTrainedModelFromH5","text":"SpatialDDLS object trained.model slot new keras DNN model incorporated.","code":""},{"path":[]},{"path":"/reference/method.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set method slot in a PropCellTypes\nobject — method","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"Get set method slot PropCellTypes object","code":""},{"path":"/reference/method.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"","code":"method(object) method(object) <- value"},{"path":"/reference/method.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set method slot in a PropCellTypes\nobject — method","text":"object PropCellTypes object. value Vector containing method cell type proportions generated.","code":""},{"path":"/reference/mixed.profiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"Get set mixed.profiles slot SpatialDDLS object","code":""},{"path":"/reference/mixed.profiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"","code":"mixed.profiles(object, type.data = \"both\") mixed.profiles(object, type.data = \"both\") <- value"},{"path":"/reference/mixed.profiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set mixed.profiles slot in a SpatialDDLS\nobject — mixed.profiles","text":"object SpatialDDLS object. type.data Type data return. can '' (default), 'train', 'test'. value List two SummarizedExperiment objects, train test, one containing simulated mixed transcriptional profiles.","code":""},{"path":"/reference/model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set model slot in a DeconvDLModel\nobject — model","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"Get set model slot DeconvDLModel object","code":""},{"path":"/reference/model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"","code":"model(object) model(object) <- value"},{"path":"/reference/model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set model slot in a DeconvDLModel\nobject — model","text":"object DeconvDLModel object. value keras.engine.sequential.Sequential object trained deep neural network model.","code":""},{"path":"/reference/plotDistances.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot distances between intrinsic and extrinsic profiles — plotDistances","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"Color spots spatial coordinates according distances intrinsic extrinsic transcriptional profiles.","code":""},{"path":"/reference/plotDistances.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"","code":"plotDistances( object, index.st, mid.scale = \"mean\", size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotDistances.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list provided. mid.scale midpoint diverging scale. may 'mean' 'median' (former default). size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotDistances.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot distances between intrinsic and extrinsic profiles — plotDistances","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotHeatmapGradsAgg.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"Plot heatmap showing top positive negative gene average gradients per cell type.","code":""},{"path":"/reference/plotHeatmapGradsAgg.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"","code":"plotHeatmapGradsAgg( object, method = \"class\", top.n.genes = 15, scale.gradients = TRUE )"},{"path":"/reference/plotHeatmapGradsAgg.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"object SpatialDDLS object DeconvDLModel object containing gradients interpret.gradients slot. method Method calculate gradients respect input features. can 'class' (gradients predicted classes w.r.t. input features) 'loss' (gradients loss w.r.t. input features) ('class' default). top.n.genes Top n genes (positive negative) taken per cell type. scale.gradients Whether calculate feature-wise z-scores gradients (TRUE default).","code":""},{"path":"/reference/plotHeatmapGradsAgg.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"list Heatmap-class objects, one top positive another one top negative gradients.","code":""},{"path":[]},{"path":"/reference/plotHeatmapGradsAgg.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot a heatmap of gradients of classes / loss function wtih respect to the\ninput — plotHeatmapGradsAgg","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.2237 #> - accuracy: 1 #> - mean_absolute_error: 0.1997 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) plotHeatmapGradsAgg(SDDLS, top.n.genes = 2) #> $Absolute #> #> $Positive #> #> $Negative #> # }"},{"path":"/reference/plotSpatialClustering.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"Color spots spatial coordinates according results clustering based predicted proportions.","code":""},{"path":"/reference/plotSpatialClustering.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"","code":"plotSpatialClustering( object, index.st, method, k.nn, k.centers, colors, size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialClustering.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. method Clustering method results plot. can \"graph\" \"k.means\". missing, first configuration found object plotted. k.nn Number nearest neighbors used method == \"graph\". k.centers Number k centers used method == \"k.means\". colors Vector colors used. size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialClustering.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot results of clustering based on predicted cell proportions — plotSpatialClustering","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialGeneExpr.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"Color spots spatial coordinates according logCPM values particular gene.","code":""},{"path":"/reference/plotSpatialGeneExpr.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"","code":"plotSpatialGeneExpr( object, index.st, gene, colors = \"spectral\", size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialGeneExpr.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. gene Gene color spots . colors Color scale used. can \"blues\" \"spectral\" (latter default). size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialGeneExpr.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot normalized gene expression data (logCPM) in spatial coordinates — plotSpatialGeneExpr","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialProp.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"Color spots spatial coordinates according predicted proportions particular cell type. Color scale adapted depending range predicted proportions.","code":""},{"path":"/reference/plotSpatialProp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"","code":"plotSpatialProp( object, index.st, cell.type, colors = \"blues\", set = \"raw\", prediction = \"Regularized\", limits = NULL, size.point = 1, title = NULL, theme = NULL )"},{"path":"/reference/plotSpatialProp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. cell.type Cell type predicted proportions color spots . colors Color scale used. can \"blues\" \"spectral\" (former default). set results simplified (see ?deconvSpatialDDLS details), results plot (raw default). prediction can \"Regularized\", \"Intrinsic\" \"Extrinsic\" (\"Regularized\" default). limits vector two elements indicating wanted limits color scale. NULL (default), color scale adjusted max min predicted proportions. size.point Size points (0.1 default). title Title plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialProp.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot predicted proportions for a specific cell type using spatial coordinates\nof spots — plotSpatialProp","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotSpatialPropAll.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"Color spots spatial coordinates plot according predicted cell type proportions. cell types represented together using color scale 0 1.","code":""},{"path":"/reference/plotSpatialPropAll.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"","code":"plotSpatialPropAll( object, index.st, colors = \"blues\", set = \"raw\", prediction = \"Regularized\", size.point = 0.1, title = NULL, nrow = NULL, ncol = NULL, theme = NULL )"},{"path":"/reference/plotSpatialPropAll.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data plotted. can either position name named list SpatialExperiment objects provided. colors Color scale used. can \"blues\" \"spectral\" (former default). set results simplified (see ?deconvSpatialDDLS details), results plot (raw default). prediction can \"Regularized\", \"Intrinsic\" \"Extrinsic\" (\"Regularized\" default). size.point Size points (0.1 default). title Title plot. nrow Number rows split plot. ncol Number columns split plot. theme ggplot2 theme.","code":""},{"path":"/reference/plotSpatialPropAll.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot predicted proportions for all cell types using spatial coordinates of\nspots — plotSpatialPropAll","text":"ggplot object.","code":""},{"path":[]},{"path":"/reference/plotTrainingHistory.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"Plot training history trained SpatialDDLS deep neural network model.","code":""},{"path":"/reference/plotTrainingHistory.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"","code":"plotTrainingHistory( object, title = \"History of metrics during training\", metrics = NULL )"},{"path":"/reference/plotTrainingHistory.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"object SpatialDDLS object trained.model slot. title Title plot. metrics Metrics plotted. NULL (default), metrics available DeconvDLModel object plotted.","code":""},{"path":"/reference/plotTrainingHistory.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Plot training history of a trained SpatialDDLS deep neural network model — plotTrainingHistory","text":"ggplot object progression selected metrics training.","code":""},{"path":[]},{"path":"/reference/plots.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set plots slot in a PropCellTypes\nobject — plots","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"Get set plots slot PropCellTypes object","code":""},{"path":"/reference/plots.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"","code":"plots(object) plots(object) <- value"},{"path":"/reference/plots.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set plots slot in a PropCellTypes\nobject — plots","text":"object PropCellTypes object. value List lists plots showing distribution cell proportions generated method.","code":""},{"path":"/reference/preparingToSave.html","id":null,"dir":"Reference","previous_headings":"","what":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"function prepares SpatialDDLS object saved RDA file contains DeconvDLModel object trained DNN model.","code":""},{"path":"/reference/preparingToSave.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"","code":"preparingToSave(object)"},{"path":"/reference/preparingToSave.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"object SpatialDDLS object trained.data slot containing DeconvDLModel object trained DNN model.","code":""},{"path":"/reference/preparingToSave.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"SpatialDDLS DeconvDLModel object trained keras model transformed keras.engine.sequential.Sequential class list architecture JSON-like character object, weights list.","code":""},{"path":"/reference/preparingToSave.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Prepare SpatialDDLS object to be saved as an RDA file — preparingToSave","text":"Since keras models saved natively R objects, function saves structure model JSON-like character object weights list. allows retrieval model making predictions. important note state optimizer saved, model's architecture weights. save entire model, please see saveTrainedModelAsH5 loadTrainedModelFromH5 functions. also possible save SpatialDDLS object RDS file saveRDS function without preparation.","code":""},{"path":[]},{"path":"/reference/prob.cell.types.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"Get set prob.cell.types slot SpatialDDLS object","code":""},{"path":"/reference/prob.cell.types.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"","code":"prob.cell.types(object, type.data = \"both\") prob.cell.types(object, type.data = \"both\") <- value"},{"path":"/reference/prob.cell.types.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set prob.cell.types slot in a\nSpatialDDLS object — prob.cell.types","text":"object SpatialDDLS object. type.data Type data return. can '' (default), 'train', 'test'. value List two PropCellTypes objects corresponding train test data.","code":""},{"path":"/reference/prob.matrix.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"Get set prob.matrix slot PropCellTypes object","code":""},{"path":"/reference/prob.matrix.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"","code":"prob.matrix(object) prob.matrix(object) <- value"},{"path":"/reference/prob.matrix.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set prob.matrix slot in a\nPropCellTypes object — prob.matrix","text":"object PropCellTypes object. value Matrix cell types columns samples rows.","code":""},{"path":"/reference/project.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set project slot in a SpatialDDLS\nobject — project","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"Get set project slot SpatialDDLS object","code":""},{"path":"/reference/project.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"","code":"project(object) project(object) <- value"},{"path":"/reference/project.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set project slot in a SpatialDDLS\nobject — project","text":"object SpatialDDLS object. value Character indicating name project.","code":""},{"path":"/reference/saveRDS.html","id":null,"dir":"Reference","previous_headings":"","what":"Save SpatialDDLS objects as RDS files — saveRDS","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"Save SpatialDDLS DeconvDLModel objects RDS files. keras models stored natively R objects (e.g. RData RDS files). saving architecture JSON-like character object weights list, possible retrieve functional model make new predictions. trained.model slot empty, function behave usual. Note: option, state optimizer saved, model's architecture weights. possible save entire model HDF5 file saveTrainedModelAsH5 function load SpatialDDLS object loadTrainedModelFromH5 function. See documentation details.","code":""},{"path":"/reference/saveRDS.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"","code":"saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL ) # S4 method for DeconvDLModel saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL ) # S4 method for SpatialDDLS saveRDS( object, file, ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL )"},{"path":"/reference/saveRDS.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"object SpatialDDLS DeconvDLModel object saved file File path object saved ascii logical. TRUE NA, ASCII representation written; otherwise (default), binary one used. See comments help save. version workspace format version use. NULL specifies current default version (3). supported value 2, default R 1.4.0 R 3.5.0. compress logical specifying whether saving named file use \"gzip\" compression, one \"gzip\", \"bzip2\" \"xz\" indicate type compression used. Ignored file connection. refhook hook function handling reference objects.","code":""},{"path":"/reference/saveRDS.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Save SpatialDDLS objects as RDS files — saveRDS","text":"return value, saves SpatialDDLS object RDS file disk.","code":""},{"path":[]},{"path":"/reference/saveTrainedModelAsH5.html","id":null,"dir":"Reference","previous_headings":"","what":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"Save trained SpatialDDLS deep neural network model disk HDF5 file. Note function save DeconvDLModel object, trained keras model. alternative saveRDS preparingToSave functions want keep state optimizer.","code":""},{"path":"/reference/saveTrainedModelAsH5.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"","code":"saveTrainedModelAsH5(object, file.path, overwrite = FALSE)"},{"path":"/reference/saveTrainedModelAsH5.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"object SpatialDDLS object trained.model slot. file.path Valid file path save model . overwrite Overwrite file already exists.","code":""},{"path":"/reference/saveTrainedModelAsH5.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Save a trained SpatialDDLS deep neural network model to\ndisk as an HDF5 file — saveTrainedModelAsH5","text":"return value, saves keras DNN trained model HDF5 file disk.","code":""},{"path":[]},{"path":"/reference/set.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set set slot in a PropCellTypes\nobject — set","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"Get set set slot PropCellTypes object","code":""},{"path":"/reference/set.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"","code":"set(object) set(object) <- value"},{"path":"/reference/set.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set set slot in a PropCellTypes\nobject — set","text":"object PropCellTypes object. value vector containing names cells present object.","code":""},{"path":"/reference/set.list.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set set.list slot in a\nPropCellTypes object — set.list","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"Get set set.list slot PropCellTypes object","code":""},{"path":"/reference/set.list.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"","code":"set.list(object) set.list(object) <- value"},{"path":"/reference/set.list.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set set.list slot in a\nPropCellTypes object — set.list","text":"object PropCellTypes object. value List cells sorted corresponding cell type.","code":""},{"path":"/reference/showProbPlot.html","id":null,"dir":"Reference","previous_headings":"","what":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"Show distribution plots cell proportions generated genMixedCellProp function.","code":""},{"path":"/reference/showProbPlot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"","code":"showProbPlot(object, type.data, set, type.plot = \"boxplot\")"},{"path":"/reference/showProbPlot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"object SpatialDDLS object prob.cell.types slot plot slot. type.data Subset data show: train test. set Integer determining 6 different subsets display. type.plot Character determining type visualization display. can 'boxplot', 'violinplot', 'linesplot' 'ncelltypes'. See Description information.","code":""},{"path":"/reference/showProbPlot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"ggplot object.","code":""},{"path":"/reference/showProbPlot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"frequencies determine proportion different cell types used simulation mixed transcriptional profiles. Proportions generated method (see ?genMixedCellProp) can visualized three ways: box plots, violin plots, lines plots. can also plot probabilities based number different cell types present samples setting type.plot = 'nCellTypes'.","code":""},{"path":[]},{"path":"/reference/showProbPlot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Show distribution plots of the cell proportions generated by\ngenMixedCellProp — showProbPlot","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", project = \"Simul_example\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE showProbPlot( SDDLS, type.data = \"train\", set = 1, type.plot = \"boxplot\" )"},{"path":"/reference/simMixedProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Simulate training and test mixed spot profiles — simMixedProfiles","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Simulate training test mixed spot transcriptional profiles using cell composition matrices generated genMixedCellProp function.","code":""},{"path":"/reference/simMixedProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"","code":"simMixedProfiles( object, type.data = \"both\", mixing.function = \"AddRawCount\", file.backend = NULL, compression.level = NULL, block.processing = FALSE, block.size = 1000, chunk.dims = NULL, threads = 1, verbose = TRUE )"},{"path":"/reference/simMixedProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"object SpatialDDLS object single.cell.real/single.cell.simul, prob.cell.types slots. type.data Type data generate: 'train', 'test' '' (last default). mixing.function Function used build mixed transcriptional profiles. may : \"AddRawCount\": single-cell profiles (raw counts) added across cells. , log-CPMs calculated (default). \"MeanCPM\": single-cell profiles (raw counts) transformed CPMs cross-cell averages calculated. , log2(CPM + 1) calculated. \"AddCPM\": single-cell profiles (raw counts) transformed CPMs added across cells. , log-CPMs calculated. file.backend Valid file path store simulated mixed expression profiles HDF5 file (NULL default). provided, data stored HDF5 files used back-end using DelayedArray, HDF5Array rhdf5 packages instead loading data RAM. Note operations matrix performed blocks (.e subsets determined size) may result longer execution times. compression.level compression level used file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. block.processing Boolean indicating whether data simulated blocks (file.backend used, FALSE default). functionality suitable cases possible load data memory, leads longer execution times. block.size block.processing = TRUE. Number mixed expression profiles simulated iteration. Larger numbers result higher memory usage shorter execution times. Set accordingly available computational resources (1000 default). chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered SpatialDDLS object simulation, single sample reduce read times following steps. larger number columns written chunk can lead longer read times. threads Number threads used simulation (1 default). verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/simMixedProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"SpatialDDLS object mixed.profiles slot containing list one two entries (depending selected type.data argument): 'train' 'test'. entry consists SummarizedExperiment object simulated mixed slot profiles.","code":""},{"path":"/reference/simMixedProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Mixed profiles generated assumption expression level particular gene given spot sum expression levels cell types make weighted proportions. practice, described Torroja Sanchez-Cabo, 2019, profiles generated summing gene expression levels determined number cells specified known cell composition matrix. number simulated spots cells used simulate spot determined genMixedCellProp function. step can avoided using ..fly argument trainDeconvModel function. SpatialDDLS allows use HDF5 files back-end store simulated data using DelayedArray HDF5Array packages. functionality allows work without keeping data loaded RAM, useful computationally heavy steps neural network training RAM-limited machines. must provide valid file path file.backend argument store resulting file '.h5' extension. option slows execution times, subsequent transformations data done blocks. Note use file.backend argument block.processing = FALSE, mixed profiles simulated one step , thus, loaded RAM. , matrix written HDF5 file. avoid RAM collapse, profiles can simulated written HDF5 files blocks block.size size setting block.processing = TRUE. recommend option accordingly computational resources available number simulated spots generated, , cases, necessary.","code":""},{"path":"/reference/simMixedProfiles.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"Fischer B, Smith M Pau, G (2020). rhdf5: R Interface HDF5. R package version 2.34.0. Pagès H, Hickey P Lun (2020). DelayedArray: unified framework working transparently -disk -memory array-like datasets. R package version 0.16.0. Pagès H (2020). HDF5Array: HDF5 backend DelayedArray objects. R package version 1.18.0.","code":""},{"path":[]},{"path":"/reference/simMixedProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simulate training and test mixed spot profiles — simMixedProfiles","text":"","code":"set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(100, lambda = 5), nrow = 40, ncol = 30, dimnames = list(paste0(\"Gene\", seq(40)), paste0(\"RHC\", seq(30))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(30)), Cell_Type = sample(x = paste0(\"CellType\", seq(4)), size = 30, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(40)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 40 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 40 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 10, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 10 #> #> === Training set cells by type: #> - CellType1: 5 #> - CellType2: 5 #> - CellType3: 5 #> - CellType4: 5 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 3 #> - CellType3: 3 #> - CellType4: 2 #> === Probability matrix for training data: #> - Mixed spots: 7 #> - Cell types: 4 #> === Probability matrix for test data: #> - Mixed spots: 3 #> - Cell types: 4 #> DONE SDDLS <- simMixedProfiles(SDDLS, verbose = TRUE) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE"},{"path":"/reference/simSCProfiles.html","id":null,"dir":"Reference","previous_headings":"","what":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"Simulate single-cell expression profiles randomly sampling negative binomial distribution inserting dropouts sampling binomial distribution using ZINB-WaVE parameters estimated estimateZinbwaveParams function.","code":""},{"path":"/reference/simSCProfiles.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"","code":"simSCProfiles( object, cell.ID.column, cell.type.column, n.cells, suffix.names = \"_Simul\", cell.types = NULL, file.backend = NULL, name.dataset.backend = NULL, compression.level = NULL, block.processing = FALSE, block.size = 1000, chunk.dims = NULL, verbose = TRUE )"},{"path":"/reference/simSCProfiles.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"object SpatialDDLS object single.cell.real zinb.params slots. cell.ID.column Name column number corresponding cell names expression matrix cells metadata. cell.type.column Name column number corresponding cell type cell cells metadata. n.cells Number simulated cells generated per cell type (.e. 10 different cell types dataset, n.cells = 100, 1000 cell profiles simulated). suffix.names Suffix used simulated cells. suffix must unique simulated cells, make sure suffix appear real cell names. cell.types Vector indicating cell types simulate. NULL (default), n.cells single-cell profiles cell types simulated. file.backend Valid file path store simulated single-cell expression profiles HDF5 file (NULL default). provided, data stored HDF5 files used back-end using DelayedArray, HDF5Array rhdf5 packages instead loading data RAM memory. suitable situations large amounts data loaded memory. Note operations data performed blocks (.e subsets determined size) may result longer execution times. name.dataset.backend Name dataset HDF5 file used. Note exist. NULL (default), random dataset name used. compression.level compression level used file.backend provided. integer value 0 (compression) 9 (highest slowest compression). See ?getHDF5DumpCompressionLevel HDF5Array package information. block.processing Boolean indicating whether data simulated blocks (file.backend used, FALSE default). functionality suitable cases possible load data memory leads larger execution times. block.size block.processing = TRUE. Number single-cell expression profiles simulated iteration process. Larger numbers result higher memory usage shorter execution times. Set according available computational resources (1000 default). Note greater total number simulated cells. chunk.dims Specifies dimensions HDF5 chunk . NULL, default value vector two items: number genes considered ZINB-WaVE model simulation single sample order reduce read times following steps. larger number columns written chunk can lead longer read times subsequent steps. Note greater dimensions simulated matrix. verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/simSCProfiles.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"SpatialDDLS object single.cell.simul slot containing SingleCellExperiment object simulated single-cell expression profiles.","code":""},{"path":"/reference/simSCProfiles.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"step, see ?estimateZinbwaveParams. described Torroja Sanchez-Cabo, 2019, function simulates given number transcriptional profiles cell type provided randomly sampling negative binomial distribution \\(\\mu\\) \\(\\theta\\) estimated parameters inserting dropouts sampling binomial distribution probability pi. parameters estimated single-cell real data using estimateZinbwaveParams function. uses ZINB-WaVE model (Risso et al., 2018). details model, see ?estimateZinbwaveParams Risso et al., 2018. file.backend argument allows create HDF5 file simulated single-cell profiles used back-end work data stored disk instead loaded RAM. file.backend argument used block.processing = FALSE, single-cell profiles simulated one step , therefore, loaded RAM memory. , data written HDF5 file. avoid collapse RAM memory many single-cell profiles goin simulated, single-cell profiles can simulated written HDF5 files blocks block.size size setting block.processing = TRUE.","code":""},{"path":"/reference/simSCProfiles.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"Risso, D., Perraudeau, F., Gribkova, S. et al. (2018). general flexible method signal extraction single-cell RNA-seq data. Nat Commun 9, 284. doi: doi:10.1038/s41467-017-02554-5 . Torroja, C. Sánchez-Cabo, F. (2019). digitalDLSorter: Deep Learning algorithm quantify immune cell populations based scRNA-Seq data. Frontiers Genetics 10, 978. doi: doi:10.3389/fgene.2019.00978 .","code":""},{"path":[]},{"path":"/reference/simSCProfiles.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simulate new single-cell RNA-Seq expression profiles using the ZINB-WaVE\nmodel parameters — simSCProfiles","text":"","code":"set.seed(123) # reproducibility sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE, project = \"Simul_example\" ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- estimateZinbwaveParams( object = SDDLS, cell.type.column = \"Cell_Type\", cell.ID.column = \"Cell_ID\", gene.ID.column = \"Gene_ID\", subset.cells = 2, verbose = TRUE ) #> === Setting parallel environment to 1 thread(s) #> === Estimating parameters for all cell types in the experiment #> === Creating cell model matrix based on Cell_Type columns: #> \t~Cell_Type #> === Number of cells for each cell type: #> - CellType1: 1 #> - CellType2: 1 #> === Creating gene model matrix without gene covariates #> === Running estimation process (Start time 02:10:47 PM) #> === Removing genes without expression in any cell #> >>> Fitting ZINB-WaVE model #> Create model: #> ok #> Initialize parameters: #> ok #> Optimize parameters: #> Iteration 1 #> penalized log-likelihood = -83.120329137823 #> After dispersion optimization = -56.133558863131 #> user system elapsed #> 0.025 0.000 0.024 #> After right optimization = -54.6057641481247 #> After orthogonalization = -54.6057641481247 #> user system elapsed #> 0.011 0.000 0.010 #> After left optimization = -54.6055360468243 #> After orthogonalization = -54.6055360468243 #> Iteration 2 #> penalized log-likelihood = -54.6055360468243 #> After dispersion optimization = -54.6055360468243 #> user system elapsed #> 0.019 0.000 0.019 #> After right optimization = -54.605527995469 #> After orthogonalization = -54.605527995469 #> user system elapsed #> 0.007 0.000 0.008 #> After left optimization = -54.6055197876494 #> After orthogonalization = -54.6055197876494 #> Iteration 3 #> penalized log-likelihood = -54.6055197876494 #> ok #> #> DONE #> #> Invested time: 0.14 SDDLS <- simSCProfiles( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", n.cells = 2, verbose = TRUE ) #> === Getting parameters from model: #> - mu: 2, 15 #> - pi: 2, 15 #> - Theta: 15 #> === Selected cell type(s) from ZINB-WaVE model (2 cell type(s)): #> - CellType2 #> - CellType1 #> === Simulated matrix dimensions: #> - n (cells): 4 #> - J (genes): 15 #> - i (# entries): 60 #> #> DONE"},{"path":"/reference/single.cell.real.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"Get set single.cell.real slot SpatialDDLS object","code":""},{"path":"/reference/single.cell.real.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"","code":"single.cell.real(object) single.cell.real(object) <- value"},{"path":"/reference/single.cell.real.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set single.cell.real slot in a\nSpatialDDLS object — single.cell.real","text":"object SpatialDDLS object. value SingleCellExperiment object real single-cell profiles.","code":""},{"path":"/reference/single.cell.simul.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"Get set single.cell.simul slot SpatialDDLS object","code":""},{"path":"/reference/single.cell.simul.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"","code":"single.cell.simul(object) single.cell.simul(object) <- value"},{"path":"/reference/single.cell.simul.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set single.cell.simul slot in a\nSpatialDDLS object — single.cell.simul","text":"object SpatialDDLS object. value SingleCellExperiment object simulated single-cell profiles.","code":""},{"path":"/reference/spatial.experiments.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"Get set spatial.experiments slot SpatialDDLS object","code":""},{"path":"/reference/spatial.experiments.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"","code":"spatial.experiments(object, index.st = NULL) spatial.experiments(object, index.st = NULL) <- value"},{"path":"/reference/spatial.experiments.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set spatial.experiments slot in a\nSpatialDDLS object — spatial.experiments","text":"object SpatialDDLS object. index.st Index spatial transcriptomics data within list. can either position name named list provided. NULL (default), data contained spatial.experiments slot returned. value List element SpatialExperiment object. can named list.","code":""},{"path":"/reference/spatialPropClustering.html","id":null,"dir":"Reference","previous_headings":"","what":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"Cluster spatial transcriptomics data according cell proportions predicted spot. allows segregate ST data niches similar cell composition.","code":""},{"path":"/reference/spatialPropClustering.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"","code":"spatialPropClustering( object, index.st, method = \"graph\", k.nn = 10, k.centers = 5, verbose = TRUE )"},{"path":"/reference/spatialPropClustering.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"object SpatialDDLS object deconvoluted ST datasets. index.st Name index dataset/slide already deconvoluted clustered. missing, datasets already deconvoluted clustered. method Clustering method. can graph (nearest neighbor graph created Louvain algorithm used detect communities) k.means (k-means algorithm run specified number centers (k.centers parameter)). k.nn integer specifying number nearest neighbors used graph construction (10 default). method == \"graph\". k.centers integer specifying number centers k-means algorithm (5 default). method == \"k.means\". verbose Show informative messages execution (TRUE default).","code":""},{"path":"/reference/spatialPropClustering.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"SpatialDDLS object containing computed clusters column slot colData SpatialExperiment objects.","code":""},{"path":[]},{"path":"/reference/spatialPropClustering.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cluster spatial data based on predicted cell proportions — spatialPropClustering","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.186 #> - accuracy: 1 #> - mean_absolute_error: 0.169 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE # simulating spatial data ngenes <- sample(3:40, size = 1) ncells <- sample(3:40, size = 1) counts <- matrix( rpois(ngenes * ncells, lambda = 5), ncol = ncells, dimnames = list(paste0(\"Gene\", seq(ngenes)), paste0(\"Spot\", seq(ncells))) ) coordinates <- matrix( rep(c(1, 2), ncells), ncol = 2 ) st <- SpatialExperiment::SpatialExperiment( assays = list(counts = as.matrix(counts)), rowData = data.frame(Gene_ID = paste0(\"Gene\", seq(ngenes))), colData = data.frame(Cell_ID = paste0(\"Spot\", seq(ncells))), spatialCoords = coordinates ) SDDLS <- loadSTProfiles( object = SDDLS, st.data = st, st.spot.ID.column = \"Cell_ID\", st.gene.ID.column = \"Gene_ID\" ) #> === 1 SpatialExperiment objects provided #> === Processing spatial transcriptomics data #> - Filtering features: #> - Selected features: 19 #> - Discarded features: 0 #> SDDLS <- deconvSpatialDDLS( SDDLS, index.st = 1 ) #> === Filtering out 4 features in data that are not present in trained model #> === Normalizing data (LogCPM) #> === Predicting cell type proportions #> #> === Calculating distances in PCA space #> - Using 3 PCs (variance cutoff: 0.8) #> === Calculating alpha factors based on distances #> DONE SDDLS <- spatialPropClustering(SDDLS, index.st = 1, k.nn = 5) #> === Selected graph-based clustering #> === Running clustering for slide 1 # }"},{"path":"/reference/test.deconv.metrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"Get set test.deconv.metrics slot DeconvDLModel object","code":""},{"path":"/reference/test.deconv.metrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"","code":"test.deconv.metrics(object, metrics = \"All\") test.deconv.metrics(object, metrics = \"All\") <- value"},{"path":"/reference/test.deconv.metrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.deconv.metrics slot in a\nDeconvDLModel object — test.deconv.metrics","text":"object DeconvDLModel object. metrics Metrics show ('' default) value List evaluation metrics assess performance model sample test data.","code":""},{"path":"/reference/test.metrics.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"Get set test.metrics slot DeconvDLModel object","code":""},{"path":"/reference/test.metrics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"","code":"test.metrics(object) test.metrics(object) <- value"},{"path":"/reference/test.metrics.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.metrics slot in a\nDeconvDLModel object — test.metrics","text":"object DeconvDLModel object. value List evaluation metrics prediction test data.","code":""},{"path":"/reference/test.pred.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"Get set test.pred slot DeconvDLModel object","code":""},{"path":"/reference/test.pred.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"","code":"test.pred(object) test.pred(object) <- value"},{"path":"/reference/test.pred.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set test.pred slot in a\nDeconvDLModel object — test.pred","text":"object DeconvDLModel object. value Matrix object prediction results test data.","code":""},{"path":"/reference/topGradientsCellType.html","id":null,"dir":"Reference","previous_headings":"","what":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"Retrieve feature names largest/smallest gradients per cell type. genes can used visualize spatial expression ST data (plotGeneSpatial function) plot calculated gradients heatmap (plotGradHeatmap function).","code":""},{"path":"/reference/topGradientsCellType.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"","code":"topGradientsCellType(object, method = \"class\", top.n.genes = 15)"},{"path":"/reference/topGradientsCellType.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"object SpatialDDLS object DeconvDLModel object containing gradients interpret.gradients slot. method Method gradients calculated . can either 'class' (gradients predicted classes w.r.t. inputs) 'loss' (gradients loss w.r.t. input features). top.n.genes Top n genes (positive negative) taken per cell type.","code":""},{"path":"/reference/topGradientsCellType.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"List gene names top positive negative gradients per cell type.","code":""},{"path":[]},{"path":"/reference/topGradientsCellType.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get top genes with largest/smallest gradients per cell type — topGradientsCellType","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.2941 #> - accuracy: 1 #> - mean_absolute_error: 0.2542 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE ## calculating gradients SDDLS <- interGradientsDL(SDDLS) listGradients <- topGradientsCellType(SDDLS) lapply(listGradients, head, n = 5) #> $CellType1 #> $CellType1$Absolute #> [1] \"Gene11\" \"Gene4\" \"Gene8\" \"Gene12\" \"Gene5\" \"Gene3\" \"Gene13\" \"Gene2\" #> [9] \"Gene14\" \"Gene15\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene10\" #> #> $CellType1$Positive #> [1] \"Gene11\" \"Gene4\" \"Gene8\" \"Gene12\" \"Gene5\" \"Gene3\" \"Gene13\" \"Gene2\" #> [9] \"Gene14\" \"Gene15\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene10\" #> #> $CellType1$Negative #> [1] \"Gene11\" \"Gene4\" \"Gene8\" \"Gene12\" \"Gene5\" \"Gene3\" \"Gene13\" \"Gene2\" #> [9] \"Gene14\" \"Gene15\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene10\" #> #> #> $CellType2 #> $CellType2$Absolute #> [1] \"Gene10\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene15\" \"Gene11\" \"Gene13\" #> [9] \"Gene2\" \"Gene14\" \"Gene8\" \"Gene3\" \"Gene4\" \"Gene12\" \"Gene5\" #> #> $CellType2$Positive #> [1] \"Gene10\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene15\" \"Gene11\" \"Gene13\" #> [9] \"Gene2\" \"Gene14\" \"Gene8\" \"Gene3\" \"Gene4\" \"Gene12\" \"Gene5\" #> #> $CellType2$Negative #> [1] \"Gene10\" \"Gene7\" \"Gene1\" \"Gene9\" \"Gene6\" \"Gene15\" \"Gene11\" \"Gene13\" #> [9] \"Gene2\" \"Gene14\" \"Gene8\" \"Gene3\" \"Gene4\" \"Gene12\" \"Gene5\" #> #> # }"},{"path":"/reference/trainDeconvModel.html","id":null,"dir":"Reference","previous_headings":"","what":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"Train deep neural network model using training data SpatialDDLS object. model used deconvolute spatial transcriptomics data biological context single-cell RNA-seq data used train . addition, trained model evaluated using test data, prediction results obtained determine performance (see ?calculateEvalMetrics).","code":""},{"path":"/reference/trainDeconvModel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"","code":"trainDeconvModel( object, type.data.train = \"mixed\", type.data.test = \"mixed\", batch.size = 64, num.epochs = 60, num.hidden.layers = 2, num.units = c(200, 200), activation.fun = \"relu\", dropout.rate = 0.25, loss = \"kullback_leibler_divergence\", metrics = c(\"accuracy\", \"mean_absolute_error\", \"categorical_accuracy\"), normalize = TRUE, scaling = \"standardize\", norm.batch.layers = TRUE, custom.model = NULL, shuffle = TRUE, sc.downsampling = NULL, use.generator = FALSE, on.the.fly = FALSE, agg.function = \"AddRawCount\", threads = 1, view.metrics.plot = TRUE, verbose = TRUE )"},{"path":"/reference/trainDeconvModel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"object SpatialDDLS object single.cell.real/single.cell.simul, prob.cell.types, mixed.profiles slots (last ..fly = FALSE). type.data.train Type profiles used training. can '', 'single-cell' 'mixed' ('mixed' default). type.data.test Type profiles used evaluation. can '', 'single-cell' 'mixed' ('mixed' default). batch.size Number samples per gradient update (64 default). num.epochs Number epochs train model (60 default). num.hidden.layers Number hidden layers neural network (2 default). number must equal length num.units argument. num.units Vector indicating number neurons per hidden layer (c(200, 200) default). length vector must equal num.hidden.layers argument. activation.fun Activation function ('relu' default). See keras documentation know available activation functions. dropout.rate Float 0 1 indicating fraction input neurons dropped layer dropouts (0.25 default). default, SpatialDDLS implements 1 dropout layer per hidden layer. loss Character indicating loss function selected model training ('kullback_leibler_divergence' default). See keras documentation know available loss functions. metrics Vector metrics used assess model performance training evaluation (c(\"accuracy\", \"mean_absolute_error\", \"categorical_accuracy\") default). See keras documentation know available performance metrics. normalize Whether normalize data using logCPM (TRUE default). parameter considered method used simulate mixed transcriptional profiles (simMixedProfiles function) \"AddRawCount\". Otherwise, data already normalized. scaling scale data training. can : \"standardize\" (values centered around mean unit standard deviation), \"rescale\" (values shifted rescaled end ranging 0 1) \"none\" (scaling performed). \"standardize\" default. norm.batch.layers Whether include batch normalization layers hidden dense layer (TRUE default). custom.model allows use custom neural network architecture. must keras.engine.sequential.Sequential object number input neurons equal number considered features/genes, number output neurons equal number cell types considered (NULL default). provided, arguments related neural network architecture ignored. shuffle Boolean indicating whether data shuffled (TRUE default). sc.downsampling used type.data.train equal '' 'single-cell'. allows set maximum number single-cell profiles specific cell type training avoid unbalanced representation classes (NULL default). use.generator Boolean indicating whether use generators training test. Generators automatically used ..fly = TRUE HDF5 files used, can activated user demand (FALSE default). ..fly Boolean indicating whether simulated data generated 'fly' training (FALSE default). agg.function ..fly == TRUE, function used build mixed transcriptional profiles. may : \"AddRawCount\" (default): single-cell profiles (raw counts) added across cells. , log-CPMs calculated. \"MeanCPM\": single-cell profiles (raw counts) transformed logCPM cross-cell averages calculated. \"AddCPM\": single-cell profiles (raw counts) transformed CPMs added across cells. , log-CPMs calculated. threads Number threads used simulation mixed transcriptional profiles ..fly = TRUE (1 default). view.metrics.plot Boolean indicating whether show plots loss evaluation metrics training (TRUE default). keras R allows see model progression training working RStudio. verbose Boolean indicating whether display model progression training model architecture information (TRUE default).","code":""},{"path":"/reference/trainDeconvModel.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"SpatialDDLS object trained.model slot containing DeconvDLModel object. information structure class, see ?DeconvDLModel.","code":""},{"path":"/reference/trainDeconvModel.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"Simulation mixed transcriptional profiles 'fly' trainDeconvModel can avoid storing simulated mixed spot profiles using ..fly argument. functionality aims reducing simMixedProfiles function's memory usage: simulated profiles built batch training/evaluation. Neural network architecture possible change model's architecture: number hidden layers, number neurons hidden layer, dropout rate, activation function, loss function. customized models, possible provide pre-built model custom.model argument (keras.engine.sequential.Sequential object) necessary number input neurons equal number considered features/genes, number output neurons equal number considered cell types.","code":""},{"path":[]},{"path":"/reference/trainDeconvModel.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Train deconvolution model for spatial transcriptomics data — trainDeconvModel","text":"","code":"# \\donttest{ set.seed(123) sce <- SingleCellExperiment::SingleCellExperiment( assays = list( counts = matrix( rpois(30, lambda = 5), nrow = 15, ncol = 10, dimnames = list(paste0(\"Gene\", seq(15)), paste0(\"RHC\", seq(10))) ) ), colData = data.frame( Cell_ID = paste0(\"RHC\", seq(10)), Cell_Type = sample(x = paste0(\"CellType\", seq(2)), size = 10, replace = TRUE) ), rowData = data.frame( Gene_ID = paste0(\"Gene\", seq(15)) ) ) SDDLS <- createSpatialDDLSobject( sc.data = sce, sc.cell.ID.column = \"Cell_ID\", sc.gene.ID.column = \"Gene_ID\", sc.filt.genes.cluster = FALSE ) #> === Spatial transcriptomics data not provided #> === Processing single-cell data #> - Filtering features: #> - Selected features: 15 #> - Discarded features: 0 #> #> === No mitochondrial genes were found by using ^mt- as regrex #> #> === Final number of dimensions for further analyses: 15 SDDLS <- genMixedCellProp( object = SDDLS, cell.ID.column = \"Cell_ID\", cell.type.column = \"Cell_Type\", num.sim.spots = 50, verbose = TRUE ) #> #> === The number of mixed profiles that will be generated is equal to 50 #> #> === Training set cells by type: #> - CellType1: 4 #> - CellType2: 3 #> === Test set cells by type: #> - CellType1: 2 #> - CellType2: 1 #> === Probability matrix for training data: #> - Mixed spots: 34 #> - Cell types: 2 #> === Probability matrix for test data: #> - Mixed spots: 16 #> - Cell types: 2 #> DONE SDDLS <- simMixedProfiles(SDDLS) #> === Setting parallel environment to 1 thread(s) #> #> === Generating train mixed profiles: #> #> === Generating test mixed profiles: #> #> DONE SDDLS <- trainDeconvModel( object = SDDLS, batch.size = 12, num.epochs = 5 ) #> === Training and test from stored data #> Using only simulated mixed samples #> Using only simulated mixed samples #> Model: \"SpatialDDLS\" #> _____________________________________________________________________ #> Layer (type) Output Shape Param # #> ===================================================================== #> Dense1 (Dense) (None, 200) 3200 #> _____________________________________________________________________ #> BatchNormalization1 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation1 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout1 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense2 (Dense) (None, 200) 40200 #> _____________________________________________________________________ #> BatchNormalization2 (BatchNorm (None, 200) 800 #> _____________________________________________________________________ #> Activation2 (Activation) (None, 200) 0 #> _____________________________________________________________________ #> Dropout2 (Dropout) (None, 200) 0 #> _____________________________________________________________________ #> Dense3 (Dense) (None, 2) 402 #> _____________________________________________________________________ #> BatchNormalization3 (BatchNorm (None, 2) 8 #> _____________________________________________________________________ #> ActivationSoftmax (Activation) (None, 2) 0 #> ===================================================================== #> Total params: 45,410 #> Trainable params: 44,606 #> Non-trainable params: 804 #> _____________________________________________________________________ #> #> === Training DNN with 34 samples: #> #> === Evaluating DNN in test data (16 samples) #> - loss: 0.2414 #> - accuracy: 1 #> - mean_absolute_error: 0.2121 #> - categorical_accuracy: 1 #> #> === Generating prediction results using test data #> DONE # }"},{"path":"/reference/trained.model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"Get set trained.model slot SpatialDDLS object","code":""},{"path":"/reference/trained.model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"","code":"trained.model(object) trained.model(object) <- value"},{"path":"/reference/trained.model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set trained.model slot in a\nSpatialDDLS object — trained.model","text":"object SpatialDDLS object. value DeconvDLModel object.","code":""},{"path":"/reference/training.history.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set training.history slot in a\nDeconvDLModel object — training.history","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"Get set training.history slot DeconvDLModel object","code":""},{"path":"/reference/training.history.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"","code":"training.history(object) training.history(object) <- value"},{"path":"/reference/training.history.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set training.history slot in a\nDeconvDLModel object — training.history","text":"object DeconvDLModel object. value keras_training_history object training history deep neural network model.","code":""},{"path":"/reference/zinb.params.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"Get set zinb.params slot SpatialDDLS object","code":""},{"path":"/reference/zinb.params.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"","code":"zinb.params(object) zinb.params(object) <- value"},{"path":"/reference/zinb.params.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set zinb.params slot in a\nSpatialDDLS object — zinb.params","text":"object SpatialDDLS object. value ZinbParametersModel object valid ZinbModel object.","code":""},{"path":"/reference/zinbwave.model.html","id":null,"dir":"Reference","previous_headings":"","what":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"Get set zinbwave.model slot ZinbParametersModel object","code":""},{"path":"/reference/zinbwave.model.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"","code":"zinbwave.model(object) zinbwave.model(object) <- value"},{"path":"/reference/zinbwave.model.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get and set zinbwave.model slot in a\nZinbParametersModel object — zinbwave.model","text":"object ZinbParametersModel object. value ZinbModel object estimated parameters simulate new single-cell profiles.","code":""},{"path":"/news/index.html","id":"spatialddls-010-2023-04-08","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 0.1.0 (2023-04-08)","title":"SpatialDDLS 0.1.0 (2023-04-08)","text":"CRAN release: 2023-05-07 Added NEWS.md file track changes.","code":""},{"path":"/news/index.html","id":"spatialddls-020-2023-10-04","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 0.2.0 (2023-10-04)","title":"SpatialDDLS 0.2.0 (2023-10-04)","text":"Added vignette explaining HDF5 file usage (hdf5Backend.Rmd vignette). Mixed transcriptional profiles now stored raw counts rather normalized values order make calculations transparent. Scale factor normalization can chosen (10e3 now default option).","code":""},{"path":"/news/index.html","id":"spatialddls-100-2023-12-01","dir":"Changelog","previous_headings":"","what":"SpatialDDLS 1.0.0 (2023-12-01)","title":"SpatialDDLS 1.0.0 (2023-12-01)","text":"Regularization predicted cell proportions incorporated. Functions classes relying deconvSpatialDDLS function modified. Added set functions clustering analysis based predicted cell proportions (spatialClustering.R file). Added module neural network interpretation based vanilla gradient (interGradientsDL.R file)","code":""}] diff --git a/pkgdown/extra.css b/pkgdown/extra.css index 71a7ddd..e0f2922 100644 --- a/pkgdown/extra.css +++ b/pkgdown/extra.css @@ -4,7 +4,6 @@ h1 { #toc h2 { font-weight: bolder; - font-size: 10px; } .links h2 { diff --git a/vignettes/abserr-celltype-1.png b/vignettes/abserr-celltype-1.png index 084970e..a01aedf 100644 Binary files a/vignettes/abserr-celltype-1.png and b/vignettes/abserr-celltype-1.png differ diff --git a/vignettes/abserr-celltype-sep-1.png b/vignettes/abserr-celltype-sep-1.png index d7b0f54..251fb9c 100644 Binary files a/vignettes/abserr-celltype-sep-1.png and b/vignettes/abserr-celltype-sep-1.png differ diff --git a/vignettes/clustering-1.png b/vignettes/clustering-1.png index ef76bc6..4b0f59e 100644 Binary files a/vignettes/clustering-1.png and b/vignettes/clustering-1.png differ diff --git a/vignettes/corr-pred-1.png b/vignettes/corr-pred-1.png index 087ebd6..f10e446 100644 Binary files a/vignettes/corr-pred-1.png and b/vignettes/corr-pred-1.png differ diff --git a/vignettes/negative-grad-1.png b/vignettes/negative-grad-1.png index d692c75..67686c5 100644 Binary files a/vignettes/negative-grad-1.png and b/vignettes/negative-grad-1.png differ diff --git a/vignettes/positive-grad-1.png b/vignettes/positive-grad-1.png index 4a7c242..8c2f223 100644 Binary files a/vignettes/positive-grad-1.png and b/vignettes/positive-grad-1.png differ diff --git a/vignettes/pred-spatial-1.png b/vignettes/pred-spatial-1.png index 03f4acf..95bc9ba 100644 Binary files a/vignettes/pred-spatial-1.png and b/vignettes/pred-spatial-1.png differ diff --git a/vignettes/pred-spatial-sep-1.png b/vignettes/pred-spatial-sep-1.png index 81164d4..b9254f8 100644 Binary files a/vignettes/pred-spatial-sep-1.png and b/vignettes/pred-spatial-sep-1.png differ diff --git a/vignettes/pred-spatial-sep-2.png b/vignettes/pred-spatial-sep-2.png index 587c75b..30e980e 100644 Binary files a/vignettes/pred-spatial-sep-2.png and b/vignettes/pred-spatial-sep-2.png differ diff --git a/vignettes/pred-spatial-sep-3.png b/vignettes/pred-spatial-sep-3.png index deaf1c1..d1fd6d4 100644 Binary files a/vignettes/pred-spatial-sep-3.png and b/vignettes/pred-spatial-sep-3.png differ diff --git a/vignettes/pred-spatial-sep-extrinsic-1.png b/vignettes/pred-spatial-sep-extrinsic-1.png index bc089b7..7017111 100644 Binary files a/vignettes/pred-spatial-sep-extrinsic-1.png and b/vignettes/pred-spatial-sep-extrinsic-1.png differ diff --git a/vignettes/pred-spatial-sep-extrinsic-2.png b/vignettes/pred-spatial-sep-extrinsic-2.png index 96a276c..a9948e5 100644 Binary files a/vignettes/pred-spatial-sep-extrinsic-2.png and b/vignettes/pred-spatial-sep-extrinsic-2.png differ diff --git a/vignettes/pred-spatial-sep-extrinsic-3.png b/vignettes/pred-spatial-sep-extrinsic-3.png index 5757e08..9da2933 100644 Binary files a/vignettes/pred-spatial-sep-extrinsic-3.png and b/vignettes/pred-spatial-sep-extrinsic-3.png differ diff --git a/vignettes/realModelExample-hq.Rmd b/vignettes/realModelExample-hq.Rmd index 547ecb3..17e9024 100644 --- a/vignettes/realModelExample-hq.Rmd +++ b/vignettes/realModelExample-hq.Rmd @@ -93,9 +93,9 @@ In this case, we are only working on 1 spatial transcriptomics dataset, but an a ## Simulation of mixed transcriptional profiles -Now, we are going to simulate cell composition matrices that will serve to simulate mixed transcriptional profiles with known cell proportions. This is done by the `genMixedCellProp` function in which we can control different aspects such as the number of mixed transcriptional profiles to be generated, the number of cells used to simulate each mixed profile, etc. These parameters must be decided depending on the single-cell reference and the available computational resources. For this example, and as standard reference, we will use `num.sim.spots = 10000` and `n.cells = 50`. The cell type compositions of these mixed profiles will be generated by three methods: +Now, we are going to simulate cell composition matrices that will serve to simulate mixed transcriptional profiles with known cell proportions. This is done by the `genMixedCellProp` function in which we can control different aspects, such as the number of mixed transcriptional profiles to be generated or the number of cells used to simulate each mixed profile. These parameters must be decided depending on the size of the single-cell reference and the available computational resources. For this example, and as standard reference, we will use `num.sim.spots = 10000` and `n.cells = 50`. The cell type composition of these mixed profiles will be generated by three methods: -* A random sampling of a Dirichlet distribution. Moreover, in order to make these proportions more sparse, the `prob.sparity` parameter controls the probability of having missing cell types in each simulated spot, as opposed to a mixture of all cell types. +* A random sampling of a Dirichlet distribution. Within this set of samples, in order to make these proportions more sparse, the `prob.sparity` parameter controls the probability of having missing cell types in each simulated spot, as opposed to a mixture of all cell types. * Pure mixed transcriptional profiles composed of `n.cells` cells of the same cell type aggregated. * Transcriptional profiles in which a minimum number of missing cell types will be imposed. This is controlled by the `min.zero.prop` argument. @@ -117,7 +117,7 @@ mouseDLN.SDDLS <- genMixedCellProp( ) ``` -Then, we can call the `simMixedProfiles` function, which will generate the actual mixed transcriptional profiles using the cell composition matrices generated in the previous step. This step may take a while depending on the number of transcriptional profiles to be simulated, so be patient! In addition, users can choose the method by which the mixed profiles will be generated. We recommend summing up raw counts, and then normalize samples by log-CPM (`mixing.function = "AddRawCount"`), but other methods are available (see Documentation). +Then, we can call the `simMixedProfiles` function, which will generate the actual mixed transcriptional profiles using the cell composition matrices generated in the previous step. This step may take a while depending on the number of transcriptional profiles to be simulated, so be patient! In addition, users can choose the method by which the mixed profiles will be generated. We recommend summing up raw counts, and then normalizing samples to obtain logCPMs (`mixing.function = "AddRawCount"`), but other methods are available (see Documentation). ```{r} mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) @@ -125,7 +125,7 @@ mouseDLN.SDDLS <- simMixedProfiles(mouseDLN.SDDLS, threads = 3) ## Training a fully-connected neural network using mixed transcriptional profiles -Having generated a set of mixed transcriptional profiles with known cell composition, we can then train a neural network using the training subset and evaluate the model by predicting cell type proportions on the test subset. Once trained, the model can deconvolute the cellular composition of new transcriptional profiles, such as each spot in a spatial transcriptomics experiment. The architecture of the network is fully customizable, although in our experience, the hyperparameters used in this example work for most of the cases. Particularly, we will employ a model with two hidden layers, each consisting of 200 neurons, and a training process involving 60 epochs. +Having generated a set of mixed transcriptional profiles with known cell composition, we can then train a neural network using the training subset and evaluate the model by predicting cell type proportions on the test subset. Once trained, the model can deconvolute the cellular composition of new transcriptional profiles, such as spots in a spatial transcriptomics experiment. The architecture of the network is fully customizable, although in our experience, the hyperparameters used in this example work for most of the cases. Particularly, we will employ a model with two hidden layers, each consisting of 200 neurons, and a training process involving 60 epochs. ```{r} mouseDLN.SDDLS <- trainDeconvModel( @@ -179,12 +179,12 @@ As demonstrated, the overall performance is satisfactory, indicating that the mo ## Deconvolution of the spatial transcriptomics dataset -Finally, we can use our trained model to deconvolute the signals of each spot using the `deconvSpatialDDLS' function. By default, the function uses the trained model to predict cell proportions of two sets of transcriptional profiles from the ST datasets: +Finally, we can use our trained model to deconvolute the signals of each spot using the `deconvSpatialDDLS` function. By default, this function uses the trained model to predict cell proportions of two sets of transcriptional profiles obtained from the ST datasets: * 'Intrinsic' profiles: these are the actual transcriptional profiles of every spot in the ST dataset. * 'Extrinsic' profiles: these are simulated profiles generated from the surrounding spots of every spot. The concept is to create a mirrored set of transcriptional profiles that represent the transcriptional features of the spatial context of each spot. -The latter can be used to understand how similar each spot is to its neighbors. Considering the hypothesis that we can infer the cellular composition of each spot based on their surroundings given the correlation between spatial location and cell composition/transcriptional profile, we can use this information to spatially contextualize our predictions and improve their accuracy. For furhter mentions, we refer to this process as regularization. Details about the methodology are explained in the Documentation and @Mananes2023. +The latter can be used to understand how similar each spot is to its neighbors. Considering the hypothesis that we can infer the cellular composition of each spot based on its surroundings given the correlation between spatial location and cell composition/transcriptional features, we can use this information to spatially contextualize our predictions and improve their accuracy. We refer to this process as spatial regularization. Details about the methodology are explained in the Documentation and @Mananes2023. ```{r} mouseDLN.SDDLS <- deconvSpatialDDLS( @@ -200,31 +200,39 @@ plotSpatialPropAll(mouseDLN.SDDLS, index.st = 1) To reveal hidden patterns in the coordinates caused by using the same color scale, we can utilize the `plotSpatialProp` function to independently plot each cell type: -```{r, pred-spatial-sep} -for (i in trained.model(mouseDLN.SDDLS) %>% cell.types()) { - print( +```{r, pred-spatial-sep,fig.height=7, fig.width=10} +list.plots <- lapply( + X = trained.model(mouseDLN.SDDLS) %>% cell.types(), + FUN = \(x) { plotSpatialProp( - mouseDLN.SDDLS, index.st = 1, cell.type = i, - colors = "blues" - ) + coord_fixed() - ) -} + mouseDLN.SDDLS, index.st = 1, cell.type = x, size.point = 1, + colors = "blues" + ) + coord_fixed() + } +) +ggarrange(plotlist = list.plots[1:4], align = "hv") +ggarrange(plotlist = list.plots[5:8], align = "hv") +ggarrange(plotlist = list.plots[9:12], align = "hv") ``` In addition to the 'regularized' cell proportions, we can plot the predictions calculated for the intrinsic and extrinsic transcriptional profiles. For instance, let's plot those predicted from the extrinsic transcriptional profiles: -```{r, pred-spatial-sep-extrinsic} -for (i in mouseDLN.SDDLS@trained.model@cell.types) { - print( +```{r, pred-spatial-sep-extrinsic, fig.height=7, fig.width=10} +list.plots <- lapply( + X = trained.model(mouseDLN.SDDLS) %>% cell.types(), + FUN = \(x) { plotSpatialProp( - mouseDLN.SDDLS, index.st = 1, cell.type = i, - colors = "blues", prediction = "Extrinsic" - ) + coord_fixed() - ) -} + mouseDLN.SDDLS, index.st = 1, cell.type = x, size.point = 1, + colors = "blues", prediction = "Extrinsic" + ) + coord_fixed() + } +) +ggarrange(plotlist = list.plots[1:4], align = "hv") +ggarrange(plotlist = list.plots[5:8], align = "hv") +ggarrange(plotlist = list.plots[9:12], align = "hv") ``` -As one might expect, this is a smoothed version of the final predictions. It is also possible to visualize distances between extrinsic and intrinsic transcriptional profiles of each spot to understand how the regularization step works by using the `plotDistances` function: +As one might expect, this is a smoothed version of the final predictions. It is also possible to visualize distances between the extrinsic and intrinsic transcriptional profiles of each spot to understand how the regularization step works by using the `plotDistances` function: ```{r, distances} plotDistances(mouseDLN.SDDLS, index.st = 1, size.point = 1.5) + coord_fixed() @@ -253,7 +261,7 @@ Those spots with distances less than the mean distance were regularized accordin ## Interpreting the model -In order to make predictions more transparent, `SpatialDDLS` includes an additional module designed to provide insights into the model's decision-making process. It relies on calculating of predicted classes/loss function gradients with respect to the input variables, a method popularly known as Vanilla Gradient. These numeric values are computed for each gene and cell type using the pure mixed transcriptional profiles previously simulated. Therefore, they can be interpreted as the extent to which each feature is contributing to the model's predictions. While these values are initially calculated at the sample/gene level, they can be aggregated at the cell type level in order to assess the relevance of different genes for cell type proportion predictions. These steps are performed through the `interGradientDL` function: +In order to make predictions more transparent, `SpatialDDLS` includes an additional module designed to provide insights into the model's decision-making process. It relies on calculating the predicted classes/loss function gradients with respect to the input variables, a method popularly known as **Vanilla Gradient**. These numeric values are computed for each gene and cell type using the pure mixed transcriptional profiles previously simulated. Therefore, they can be interpreted as the extent to which each feature is contributing to the model's predictions. While these values are initially calculated at the sample/gene level, they can be aggregated at the cell type level in order to assess the relevance of different genes for cell type proportion predictions. These steps are performed through the `interGradientDL` function: ```{r} mouseDLN.SDDLS <- interGradientsDL( @@ -261,7 +269,7 @@ mouseDLN.SDDLS <- interGradientsDL( ) ``` -Importantly, depending on the `method` parameter, positive and negative gradient must be differently interpreted: +Importantly, depending on the `method` parameter, positive and negative gradients must be differently interpreted: * If gradients with respect to the input variables were calculated using the loss function (`method = "loss"`), genes with negative gradients (those that minimize the loss function) will be positively correlated with the presence of each cell type. * Conversely, if gradients with respect to the input variables were calculated using classes (`method = "class"`), genes with positive gradients (those that make the probability of being a cell type higher) will be positively associated with each cell type. @@ -281,7 +289,7 @@ sapply( As can be seen, among the top 5 genes some canonical markers for different cell types appear, such as Cd79b for B cells, Cd8a for CD8 T cells, or Foxp3 for Tregs. These are just the top 5 genes, so considering a higher number can provide a more comprehensive understanding of the genes utilizaed by the model. -We also provide the `plotHeatmapGradsAgg` function for visualizing N top mean gradients per cell type. This plot highlights genes with high gradients across different cell types, reflecting the multivariate nature of neural networks. It is advisable to examine both the most positive and negative gradients, as these genes significantly contribute to the network's predictions. +We also provide the `plotHeatmapGradsAgg` function for visualizing the top N mean gradients per cell type. This plot highlights genes with high gradients across different cell types, reflecting the multivariate nature of neural networks. It is advisable to examine both the most positive and negative gradients, as these genes significantly contribute to the network's predictions. ```{r, positive-grad, fig.height=8, fig.width=6} hh <- plotHeatmapGradsAgg(mouseDLN.SDDLS, top.n.genes = 4, method = "class") @@ -292,11 +300,9 @@ hh$Positive hh$Negative ``` -Finally, we can use the `plotSpatialGeneExpr` to visualize the spatial distribution of the top N genes per cell tupe in the ST dataset. Let's plot genes for some cell types for demonstration purposes: - -the top N genes per cell type and visualize their spatial distribution in the ST dataset. Let's plot genes for some cell types just for demonstration purposes: +Finally, we can use the `plotSpatialGeneExpr` to visualize the spatial distribution of the top N genes per cell type in the ST dataset. Let's plot genes for some cell types just for demonstration purposes: -```{r, top-genes-spatial, fig.height=6, fig.width=8} +```{r, top-genes-spatial, fig.height=7, fig.width=10} top.genes <- topGradientsCellType(mouseDLN.SDDLS, top.n.genes = 4) for (i in c("B cells", "CD4 T cells", "CD8 T cells", "Tregs", "Monocytes")) { list.plots <- list() @@ -312,7 +318,7 @@ for (i in c("B cells", "CD4 T cells", "CD8 T cells", "Tregs", "Monocytes")) { ## Clustering analysis -The `SpatialDDLS` R package also includes some functions to cluster the ST dataset according to the predicted cell composition of each spot. This functionality enables to dissect the ST datasets into distinct cellular niches, which can be a relevant information for further analyses. +The `SpatialDDLS` R package also includes some functions to cluster the ST dataset according to the predicted cell composition of each spot. This functionality enables to dissect the ST datasets into distinct cellular niches, information that might be relevant for further analyses. ```{r} mouseDLN.SDDLS <- spatialPropClustering(mouseDLN.SDDLS, k.nn = 20) @@ -325,7 +331,7 @@ plotSpatialClustering(mouseDLN.SDDLS) + coord_fixed() ## Comparing deconvoluted cell proportions with colocalization of cell markers -Finally, we assess whether there is a collocation between the predicted cell type proportions and the expression of known classic markers for each cell type. This analysis aims to validate the model's predictions by comparing them with well-established cellular markers, but it does not mean to be a quantitative validation of the model. +Finally, we are going to assess whether there is a collocation between the predicted cell type proportions and the expression of known classic markers for each cell type. This analysis aims to validate the model's predictions by comparing them with well-established cellular markers, but it does not mean to be a quantitative validation of the model. ```{r} customMarkers <- list( diff --git a/vignettes/top-genes-spatial-1.png b/vignettes/top-genes-spatial-1.png index fc01d8d..889d2ee 100644 Binary files a/vignettes/top-genes-spatial-1.png and b/vignettes/top-genes-spatial-1.png differ diff --git a/vignettes/top-genes-spatial-2.png b/vignettes/top-genes-spatial-2.png index 84dd008..9d980fb 100644 Binary files a/vignettes/top-genes-spatial-2.png and b/vignettes/top-genes-spatial-2.png differ diff --git a/vignettes/top-genes-spatial-3.png b/vignettes/top-genes-spatial-3.png index 1766f50..bb94700 100644 Binary files a/vignettes/top-genes-spatial-3.png and b/vignettes/top-genes-spatial-3.png differ diff --git a/vignettes/top-genes-spatial-4.png b/vignettes/top-genes-spatial-4.png index ca5ca32..f9444f7 100644 Binary files a/vignettes/top-genes-spatial-4.png and b/vignettes/top-genes-spatial-4.png differ diff --git a/vignettes/top-genes-spatial-5.png b/vignettes/top-genes-spatial-5.png index 87b422a..51554ff 100644 Binary files a/vignettes/top-genes-spatial-5.png and b/vignettes/top-genes-spatial-5.png differ