Last updated: 2020-06-04
Checks: 7 0
Knit directory: STUtility_web_site/
This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.
Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.
Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.
The command set.seed(20191031)
was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.
Great job! Recording the operating system, R version, and package versions is critical for reproducibility.
Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.
Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.
The results in this page were generated with repository version 3ed4e82. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.
Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish
or wflow_git_commit
). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:
Ignored files:
Ignored: .DS_Store
Ignored: analysis/.DS_Store
Ignored: analysis/manual_annotation.png
Ignored: analysis/visualization_3D.Rmd
Ignored: pre_data/
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.
These are the previous versions of the repository in which changes were made to the R Markdown (analysis/image_processing.Rmd
) and HTML (docs/image_processing.html
) files. If you’ve configured a remote Git repository (see ?wflow_git_remote
), click on the hyperlinks in the table below to view the files as they were in that past version.
File | Version | Author | Date | Message |
---|---|---|---|---|
html | f71b0c0 | Ludvig Larsson | 2020-06-04 | Build site. |
html | 8a54a4d | Ludvig Larsson | 2020-06-04 | Build site. |
html | 5e466eb | Ludvig Larsson | 2020-06-04 | Build site. |
html | 377408d | Ludvig Larsson | 2020-06-04 | Build site. |
html | ed54ffb | Ludvig Larsson | 2020-06-04 | Build site. |
html | f14518c | Ludvig Larsson | 2020-06-04 | Build site. |
html | efd885b | Ludvig Larsson | 2020-06-04 | Build site. |
html | 4f42429 | Ludvig Larsson | 2020-06-04 | Build site. |
Rmd | 3660612 | Ludvig Larsson | 2020-06-04 | update website |
html | f677bf1 | jbergenstrahle | 2020-04-01 | Build site. |
Rmd | d1999a1 | jbergenstrahle | 2020-04-01 | Refs added |
html | dad142d | jbergenstrahle | 2020-01-11 | Build site. |
Rmd | 36df0f2 | jbergenstrahle | 2020-01-11 | Changed to 10x public data |
html | fb06450 | jbergenstrahle | 2020-01-11 | Build site. |
Rmd | 6444381 | jbergenstrahle | 2020-01-10 | Removed MultipleFeature.. |
Rmd | 5cb8ab1 | jbergenstrahle | 2019-12-02 | update2 |
Rmd | 8f9876e | jbergenstrahle | 2019-11-29 | Update |
html | be8be1d | Ludvig Larsson | 2019-10-31 | Build site. |
Rmd | 7cdf8e1 | Ludvig Larsson | 2019-10-31 | Changed font size |
html | f42af97 | Ludvig Larsson | 2019-10-31 | Build site. |
Rmd | 50c8053 | Ludvig Larsson | 2019-10-31 | Added theme |
html | 0754921 | Ludvig Larsson | 2019-10-31 | Build site. |
Rmd | 9bd8396 | Ludvig Larsson | 2019-10-31 | Added theme |
html | 908fe2c | Ludvig Larsson | 2019-10-31 | Build site. |
html | 54787b5 | Ludvig Larsson | 2019-10-31 | Build site. |
html | d96da86 | Ludvig Larsson | 2019-10-31 | Build site. |
Rmd | e4e84dc | Ludvig Larsson | 2019-10-31 | Added theme |
library(STutility)
With the Seurat object created, we are ready to load the H&E images from the file paths provided in the infoTable. The LoadImages() function allow you to load the images into the Seurat object and will automatically save a scaled down version of each image that you can use for plotting.
You should be aware that the resolution is by default very low (400 pixels wide). The first reason for this is that STUtility makes it possible to apply various image transformations to the images, but since these processing steps are slow and requires significant amounts of memory, it is much faster to learn the transformations on a small image and later apply the transformations to a higher resolution image. The second reason is that drawing higher resoltuion images inside RStudio can be extremely slow and clumsy to work with interactively.
NOTE: If you ever need to reload your images or load them in higher resolution you must make sure that the image paths are correct. If you have moved the images or changed your working directory, reloading the images will not work.
se <- LoadImages(se, time.resolve = F, verbose = T)
If you want to have a quick look at the sections you can draw them in the RStudio Viewer using the ImagePlot
function. If you specify method = "raster"
the images will be drawn as a plot instead.
ImagePlot(se, method = "raster", darken = TRUE, type = "raw")
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
OBS: We have noted that some systems experience memory problems due to large size image information not being cleared when removing old objects. If this is the case, the user can set time.resolve = TRUE
, which will add a small garbage collection step to avoid this issue.
NOTE: time.resolve is set to TRUE as default in the current version. This will imply that the process takes approximately 5 sec longer per sample.
The core of an ST experiment is the interplay between quantitative RNAseq data and qualitative image data. Working in R, the handling of image information and plotting of multiple samples can get a bit cumbersome, especially if the images are of higher resolution. Typically, we rarely find much use of plotting multiple samples together with the tissue images within this framework. Instead, the general tip is to perform the various plots using only the expression data, and after finding anything of interest that warrants further analysis - take out that sample and plot it individually together with the stained tissue image.
For example, we can visualize the number of RNA features and RNA counts on the ST array coordinates and quickly verify where we capture more material from the tissue.
# TODO: make sure that levels are set in facets
ST.FeaturePlot(object = se,
features = c("nFeature_RNA"),
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
ncol = 2,
grid.ncol = 1,
dark.theme = T)
ST.FeaturePlot(object = se,
features = c("nCount_RNA"),
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
ncol = 2,
grid.ncol = 1,
dark.theme = T)
To overlay a spatial feature heatmaps on top of the HE image we use the FeatureOverlay() function. Handling large images gets clumsy so we recommend to work with down-scaled versions of the images that takes up less memory.
FeatureOverlay(se,
features = "Cck",
pt.size = 1.5,
pt.alpha = 0.5,
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
dark.theme = T,
type = "raw")
You can see that by default, the first sample was selected for the feature overlay. If you wish to visualize another sample you can specify the sample.index
parameter. If you wish to plot several features side by side, you can just specify as many as you want. The layout of the Overlay plots are controlled by the ncols.samples
and the ncols.features
parameters. ncols.samples
can be used to adjust how many columns should be drawn for the sections in your Seurat object while the ncols.features
controls how many columns should be drawn for the selected features. Here we are drawing 4 features on 1 section so if we want to draw the features a layout of 2x2 we can simply set ncols.features = 2
FeatureOverlay(se,
features = c("Cck", "Calb2", "Dcn", "Nrgn"),
pt.alpha = 0.5,
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
dark.theme = T,
type = "raw",
ncols.features = 2)
If you want to highlight only the regions with high feature values, you can add some opacity to the spots using the add.alpha
parameter. Setting add.alpha = TRUE
will add opacity to the spots scaled by the feature values, meaning that spots with high values will be visible and spots with low values will be transparent.
FeatureOverlay(se,
features = c("Cck", "Calb2", "Dcn", "Nrgn"),
pt.alpha = 0.5,
add.alpha = TRUE,
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
dark.theme = T,
type = "raw",
ncols.features = 2)
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
Within the overlay area you also have a section number in the top left corner as well as a scale bar (showing the width of 500 microns) in the top right corner which can be disabled using the sample.label
and show.sb
options. Another thing we can do is to pass a custom theme (compatible with ggplot2 plots) if you wish to change the plot appearance.
Now we can for example disable the section number, scale bar, plot title and remove the legend from the plots.
customtheme <- theme(legend.position = "None", plot.title = element_blank())
FeatureOverlay(se,
features = c("Cck", "Calb2", "Dcn", "Nrgn"),
pt.alpha = 0.5,
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
dark.theme = T,
type = "raw",
ncols.features = 2,
sample.label = FALSE,
show.sb = FALSE,
custom.theme = customtheme)
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
Another feature that can be useful for visualization purposes is to mask the background of the HE images. The function MaskImages()
can be used to remove the background currently works well for tissues with a clearly defined border. Since masking is a non trivial problem, it is possible that the masking will fail for certain tissue types. If this happens you can try to modify the parameters in MaskImages()
or create your own masking function to see if you can obtain better results (see ?MaskImages
for more details).
NOTE: the image procesing methods have been optimized for small images and if you have loaded images in higher resolution there is a greater risk that some steps will fail. If you still wish to use images with higher resolution there are instructions on how to do this in the Resolution section below.
se <- MaskImages(object = se)
There are 5 types of images which can be stored into the Seurat object; “raw”, “masked”, “masked.masks”, “processed” and “processed.masks”. “raw” represents the original HE images without any modifications. In the “masked” images, the background have been removed using a binary mask which is stored under the name “masked.masks”. “processed” images have been further modified by applying rigid transformations such as rotations and shifts and these images also have the corresponding “processed.masks”.
You can look at the HE images using the ImagePlot() function.The ImagePlot function will automatically label the samples from 1 to N where N is the total number of samples. If you are running the function within RStudio you can take advantage of the Viewer panel to explore the images. Setting method=“raster” and the plot function will use the default plotting device in R. You can also change the layout of the images by forcing a different number of columns by setting ncols.
# Plot HE images
ImagePlot(se, ncols = 2, method = "raster", type = "raw", darken = T) # Raw image
ImagePlot(se, ncols = 2, method = "raster", type = "masked", darken = T) # Masked image
ImagePlot(se, ncols = 2, method = "raster", type = "masked.masks") # Mask
If you follow along the test set in this vignette, you will notice that the samples are not quite aligned with respect to each other on the array. We have implemented three different methods to align or process images; AlignImages()
, WarpImages()
and ManualAlignImages()
.
The automatic alignment method (AlignImages()
) first tries to detect the tissue edges from each image. By default, the first image (reference.index = 1
) is used as a reference but you can specify any sample with the reference.index
option. Then, for each image, a transformation matrix is learned that can be used to map coordinates to the reference image. This alignment method will sometimes fail and in that case you can align the images manually instead using the ManualAlignImages()
function. This is typically required when; (1) the tissue is bigger than the image and therefore outside the frame, (2) the tissue has a symmetrical shape (for example if the tissue has a round shape, it will be difficult to find an optimal alignment using the tissue edges), (3) the masking has failed.
The actual transformation is done using the imwarp()
function from the imager R package using a “backward” transformation strategy. This method makes sure that every pixel is painted using linear interpolation so the aligned images will experience some quality loss.
The automatic alignment should only be used on tissue sections with the same morphology, so to demonstrate this we’ll look at the “2k” array mouse brain data.
# Look at the HE images from the "2k" array mouse brain dataset
ImagePlot(se, method = "raster", darken = TRUE, type = "raw", ncols = 4)
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
First we need to mask the images and then we can apply the automatic alignment method. As you can see, the automatic alignment method can apply rotations, translations and reflections to the images.
se <- se %>% MaskImages() %>% AlignImages()
ImagePlot(se, method = "raster", darken = TRUE, type = "processed", ncols = 4)
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
An alternative method is to apply rigid transformations to the images using the WarpImages()
function. This function takes a list of transformations for the samples of your choice and converts the transformations into mapping functions which can be used to warp the images.
The available transformations are; “center.x”, “center.y”, “mirror.x”, “mirror.y” and “angle”
Remember that you need to mask the images before processing them!
load("pre_data/preSaved_10xHippo.RData")
transforms <- list("2" = list("angle" = 90))
se.rotate90 <- WarpImages(se, transforms)
ImagePlot(se.rotate90, method = "raster", darken = T)
transforms <- list("2" = list("mirror.x" = T))
se.mirrorx <- WarpImages(se, transforms)
ImagePlot(se.mirrorx, method = "raster", darken = T)
transforms <- list("2" = list("mirror.y" = T))
se.mirrory <- WarpImages(se, transforms)
ImagePlot(se.mirrory, method = "raster", darken = T)
Any transformations applied to the images will also be applied to the coordinates used to map gene expression values onto the images. If you want to draw the plots on other images you can pass one of “raw”, “masked”, “processed” to the type
option in the FeatureOverlay
function.
heatmap.colors <- c("dark blue", "cyan", "yellow", "red", "dark red")
ST.FeaturePlot(se, features = "Cck", cols = heatmap.colors, dark.theme = T)
ST.FeaturePlot(se.rotate90, features = "Cck", cols = heatmap.colors, dark.theme = T)
ST.FeaturePlot(se.mirrorx, features = "Cck", cols = heatmap.colors, dark.theme = T)
ST.FeaturePlot(se.mirrory, features = "Cck", cols = heatmap.colors, dark.theme = T)
So far we have only plotted section 1 using the FeatureOverlay
function. If you want to draw feature heatmaps on multiple section at the same time you can do this by specifing several sections in the sampleids
option
FeatureOverlay(se, features = "Nrgn",
sampleids = 1:2,
pt.alpha = 0.5,
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
method = "raster",
dark.theme = T, ncols.samples = 2)
Version | Author | Date |
---|---|---|
4f42429 | Ludvig Larsson | 2020-06-04 |
As mentioned before, we can change the type
parameter in the FeatureOverlay()
function to override the default use of processed images.
FeatureOverlay(object = se, features = c("Nrgn", "Cck"),
cols = c("dark blue", "cyan", "yellow", "red", "dark red"),
pt.alpha = 0.5,
sampleids = 2,
type = "raw",
dark.theme = T)
A work by Joseph Bergenstråhle and Ludvig Larsson
sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Mojave 10.14.6
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] parallel stats4 stats graphics grDevices utils datasets
[8] methods base
other attached packages:
[1] STutility_0.1.0 ggplot2_3.3.0
[3] SingleCellExperiment_1.10.1 SummarizedExperiment_1.18.1
[5] DelayedArray_0.14.0 matrixStats_0.56.0
[7] Biobase_2.48.0 GenomicRanges_1.40.0
[9] GenomeInfoDb_1.24.0 IRanges_2.22.1
[11] S4Vectors_0.26.0 BiocGenerics_0.34.0
[13] Seurat_3.1.5 workflowr_1.6.2
loaded via a namespace (and not attached):
[1] reticulate_1.15 tidyselect_1.0.0 htmlwidgets_1.5.1
[4] grid_4.0.0 Rtsne_0.15 munsell_0.5.0
[7] codetools_0.2-16 ica_1.0-2 units_0.6-6
[10] future_1.17.0 miniUI_0.1.1.1 withr_2.2.0
[13] colorspace_1.4-1 knitr_1.28 uuid_0.1-4
[16] ROCR_1.0-11 tensor_1.5 listenv_0.8.0
[19] labeling_0.3 git2r_0.27.1 GenomeInfoDbData_1.2.3
[22] polyclip_1.10-0 farver_2.0.3 rprojroot_1.3-2
[25] coda_0.19-3 LearnBayes_2.15.1 vctrs_0.3.0
[28] xfun_0.13 R6_2.4.1 doParallel_1.0.15
[31] rsvd_1.0.3 Morpho_2.8 ggiraph_0.7.0
[34] manipulateWidget_0.10.1 bitops_1.0-6 spatstat.utils_1.17-0
[37] assertthat_0.2.1 promises_1.1.0 scales_1.1.0
[40] imager_0.42.1 gtable_0.3.0 npsurv_0.4-0.1
[43] globals_0.12.5 bmp_0.3 goftest_1.2-2
[46] rlang_0.4.6 zeallot_0.1.0 akima_0.6-2
[49] systemfonts_0.2.1 splines_4.0.0 lazyeval_0.2.2
[52] rgl_0.100.54 yaml_2.2.1 reshape2_1.4.4
[55] abind_1.4-5 crosstalk_1.1.0.1 backports_1.1.6
[58] httpuv_1.5.2 tools_4.0.0 spData_0.3.5
[61] ellipsis_0.3.0 raster_3.1-5 RColorBrewer_1.1-2
[64] Rvcg_0.19.1 ggridges_0.5.2 Rcpp_1.0.4.6
[67] plyr_1.8.6 zlibbioc_1.34.0 classInt_0.4-3
[70] purrr_0.3.4 RCurl_1.98-1.2 rpart_4.1-15
[73] dbscan_1.1-5 deldir_0.1-25 viridis_0.5.1
[76] pbapply_1.4-2 cowplot_1.0.0 zoo_1.8-8
[79] ggrepel_0.8.2 cluster_2.1.0 colorRamps_2.3
[82] fs_1.4.1 magrittr_1.5 data.table_1.12.8
[85] magick_2.3 readbitmap_0.1.5 gmodels_2.18.1
[88] lmtest_0.9-37 RANN_2.6.1 whisker_0.4
[91] fitdistrplus_1.0-14 patchwork_1.0.0 shinyjs_1.1
[94] lsei_1.2-0.1 mime_0.9 evaluate_0.14
[97] xtable_1.8-4 jpeg_0.1-8.1 gridExtra_2.3
[100] compiler_4.0.0 tibble_3.0.1 KernSmooth_2.23-17
[103] crayon_1.3.4 htmltools_0.4.0 mgcv_1.8-31
[106] later_1.0.0 spdep_1.1-3 tiff_0.1-5
[109] tidyr_1.0.3 expm_0.999-4 DBI_1.1.0
[112] MASS_7.3-51.6 sf_0.9-3 boot_1.3-25
[115] Matrix_1.2-18 gdata_2.18.0 igraph_1.2.5
[118] pkgconfig_2.0.3 sp_1.4-1 plotly_4.9.2.1
[121] xml2_1.3.2 foreach_1.5.0 webshot_0.5.2
[124] XVector_0.28.0 stringr_1.4.0 digest_0.6.25
[127] sctransform_0.2.1 RcppAnnoy_0.0.16 tsne_0.1-3
[130] spatstat.data_1.4-3 rmarkdown_2.1 leiden_0.3.3
[133] uwot_0.1.8 gdtools_0.2.2 gtools_3.8.2
[136] shiny_1.4.0.2 lifecycle_0.2.0 nlme_3.1-147
[139] jsonlite_1.6.1 viridisLite_0.3.0 pillar_1.4.4
[142] lattice_0.20-41 fastmap_1.0.1 httr_1.4.1
[145] survival_3.1-12 glue_1.4.0 spatstat_1.63-3
[148] png_0.1-7 iterators_1.0.12 class_7.3-17
[151] stringi_1.4.6 dplyr_0.8.5 irlba_2.3.3
[154] e1071_1.7-3 future.apply_1.5.0 ape_5.3