graphics_bioinf.R 25.1 KB
Newer Older
1 2 3 4 5 6
## ----options, include=FALSE----------------------------------------------
library(knitr)
options(digits=3, width=80)
golden_ratio <- (1 + sqrt(5)) / 2
opts_chunk$set(echo=TRUE,tidy=FALSE,include=TRUE,
               dev=c('png', 'pdf', 'svg'), fig.height = 5, fig.width = 4 * golden_ratio, comment = '  ', dpi = 300,
7
cache = TRUE, warning = FALSE)
8 9 10 11

## ---- echo=FALSE, cache=FALSE--------------------------------------------
print(date())

12
## ----required_packages_and_data, echo = TRUE, cache=FALSE, message=FALSE----
13
library("scran")
14
library("readxl")
15 16
library("BiocStyle")
library("knitr")
17
library("MASS")
18 19 20 21 22 23 24 25 26 27 28 29
library("RColorBrewer")
library("stringr")
library("pheatmap")
library("matrixStats")
library("purrr")
library("readr")
library("factoextra")
library("magrittr")
library("entropy")
library("forcats")
library("readxl")
library("DESeq2")
30 31
library("broom")
library("locfit")
32
library("recount")
33 34 35
library("psych")
library("vsn")
library("matrixStats")
36
library("pheatmap")
37
library("tidyverse")
38 39
library("Rtsne")
library("devtools")
40
library("ggthemes")
41
library("scar")
42

43
theme_set(theme_solarized(base_size = 18))
44 45 46 47 48 49 50 51 52 53

data_dir <- file.path("data/")


## ----import_data---------------------------------------------------------
load(file.path(data_dir, "mtec_counts.RData"))
load(file.path(data_dir, "mtec_cell_anno.RData"))
load(file.path(data_dir, "mtec_gene_anno.RData"))
load(file.path(data_dir, "tras.RData"))

54
## ----mtec_count_table----------------------------------------------------
55 56
mtec_counts

57
## ----mtec_cell_anno------------------------------------------------------
58 59
mtec_cell_anno

60
## ----trasENSEMBL---------------------------------------------------------
61 62 63
tras
mtec_gene_anno

64 65 66
## ----tidy_count----------------------------------------------------------
mtec_counts_tidy <- gather(mtec_counts, key = "cell_id", value = "count",
                           -ensembl_id) %>%
67 68
                           dplyr::mutate(
                                  is_tra = ensembl_id %in% tras$gene.ids,
69 70 71 72 73 74
                                  is_detected = count > 0) %>%
                           left_join(mtec_cell_anno, 
                                    by = c("cell_id" = "cellID"))

## ----tra_per_cell--------------------------------------------------------

75
tra_detected <- dplyr::filter(mtec_counts_tidy, is_detected == TRUE, 
76
                       SurfaceMarker == "None") %>%
77
                dplyr::mutate(is_tra = ifelse(is_tra, "tra", "not_a_tra")) %>%
78 79 80
                group_by(cell_id, is_tra) %>% 
                tally() %>%
                spread(key = is_tra, value = n) %>%
81
                dplyr::mutate(total_detected = sum(tra, not_a_tra))
82 83 84

tra_detected

85
## ----travsall, fig.cap="Total number of genes vs TRA"--------------------
86 87 88 89 90 91 92 93 94 95
scatter_tra <- ggplot(tra_detected, aes(x = total_detected, y = tra))+ 
               geom_point() +
               coord_equal()

scatter_tra

## ----more_layers---------------------------------------------------------
scatter_tra + 
  geom_rug(alpha = I(0.2))

96
## ----ex_geom, echo=FALSE, results="hide", fig.show="hide", message=FALSE----
97 98 99
ggplot(tra_detected, aes(x = total_detected, y = tra))

scatter_tra +
100
  geom_smooth(color = "coral3") +
101
  geom_smooth(method = "lm")
102

103 104 105 106
## ----regresssion_tra-----------------------------------------------------
lm_tra <- lm(tra ~ total_detected, data = tra_detected)
lm_tra

107
## ----loessExampleLinFit, dependson="fit_model"---------------------------
108 109
sim_data <- tibble(x = seq(from=1, to=10, length.out=100),
                   y = x^3 +x^2  + rnorm(100,mean=0, sd=60))
110

111 112 113
ggplot(aes(x, y), data = sim_data) +
  geom_point() +
  geom_smooth(method = "lm")
114 115


116
## ----loessExampleFit, dependson="loessExampleLinFit"---------------------
117

118 119
sim_data$locFit  <- predict(locfit(y~lp(x, nn=0.5, deg=1), data=sim_data),
                         newdata = sim_data$x)
120

121 122 123 124 125
ggplot(aes(x, y), data = sim_data) +
  geom_point() +
  geom_smooth(method = "lm") +
  ggtitle("Linear vs. local regression") +
  geom_line(aes(x = x, y = locFit), color = "coral3")
126 127


128
## ----loessExercise, dependson="loessExampleLinFit", echo=FALSE, fig.show="hide", results="hide"----
129

130
sim_data$locFit  <- predict(locfit(y~lp(x, nn=0.2, deg=1), data=sim_data),
131 132
                         newdata = sim_data$x)

133 134 135
scar_fit <- scar(sim_data$x, sim_data$y, shape = c("in"))
sim_data$scar <- scar_fit$componentfit + scar_fit$constant

136
ggplot(aes(x, y), data = sim_data) +
137 138 139 140
  geom_point()  +
  ggtitle("Local vs. shape constrained regression") +
  geom_line(aes(x = x, y = locFit), color = "coral3") + 
  geom_line(aes(x = x, y = scar), color = "royalblue")
141

142

143
## ----compCells-----------------------------------------------------------
144

145 146 147 148 149 150
ggplot(aes(x = cell_id, y = log(count)), 
           data = filter(mtec_counts_tidy, 
                         cell_id %in% c("cell77", "cell6S35"),
                         is_detected == TRUE)) +
                         
      geom_boxplot()
151 152


153
## ----import_crc----------------------------------------------------------
154 155 156 157
if(!file.exists("SRP022054/rse_gene.Rdata")){
  download_study("SRP022054", type = "rse-gene")
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
load(file.path("SRP022054", "rse_gene.Rdata"))
crc_data <- rse_gene
crc_data 

## ----sumexp, echo=FALSE--------------------------------------------------
par(mar=c(0,0,0,0))
plot(1,1,xlim=c(0,100),ylim=c(0,100),bty="n",
     type="n",xlab="",ylab="",xaxt="n",yaxt="n")
polygon(c(45,80,80,45),c(10,10,70,70),col=rgb(1,0,0,.5),border=NA)
polygon(c(45,80,80,45),c(68,68,70,70),col=rgb(1,0,0,.5),border=NA)
text(62.5,40,"assay(s)")
text(62.5,30,"e.g. 'counts'")
polygon(c(20,40,40,20),c(10,10,70,70),col=rgb(0,0,1,.5),border=NA)
polygon(c(20,40,40,20),c(68,68,70,70),col=rgb(0,0,1,.5),border=NA)
text(30,40,"rowData")
polygon(c(45,80,80,45),c(75,75,90,90),col=rgb(.5,0,.5,.5),border=NA)
polygon(c(45,47,47,45),c(75,75,90,90),col=rgb(.5,0,.5,.5),border=NA)
text(62.5,82.5,"colData")

## ----pre_crc-------------------------------------------------------------
counts_crc <- assay(crc_data)
counts_crc[1:5, 1:5]

181
## ----crc_filtering-------------------------------------------------------
182
counts_crc <- counts_crc[rowMeans(counts_crc) >= 20, ]
183
dim(counts_crc)
184 185

## ----pre_crc_genes-------------------------------------------------------
186 187
tail(colnames(colData(crc_data)))
colData(crc_data)[1:5, c("title", "mapped_read_count")]
188 189
nrow(colData(crc_data))

190 191 192 193 194 195 196 197 198
## ----create_crc_col_data-------------------------------------------------

col_data_crc  <- select(as.data.frame(colData(crc_data)),
       title, mapped_read_count) %>% 
       rownames_to_column(var = "sample_id") %>%
       as_tibble() %>%
       tidyr::extract(title, into = c("quantification", "patient", "tissue"),
               regex = "([[:alnum:]]+)_([[:alnum:]]+)_([[:alnum:]]+)") %>% 
       dplyr::filter(quantification == "mRNA")
199 200

counts_crc <- counts_crc[, col_data_crc$sample_id]      
201 202

## ----mrna_counts---------------------------------------------------------
203 204
counts_crc_tidy <- rownames_to_column(data.frame(counts_crc),
                                      var = "ensembl_id") %>%
205 206 207 208 209 210 211 212 213 214 215
                   as_tibble() %>%
                   gather(key = "sample_id", value = "count", -ensembl_id) %>%
                   dplyr::filter(sample_id %in% col_data_crc$sample_id) 

sample_medians <- group_by(counts_crc_tidy, sample_id) %>%
                    dplyr::filter(count > 0) %>%
                    summarize(sample_median = median(log2(count)))

counts_crc_tidy <- left_join(counts_crc_tidy, sample_medians, 
                            by = c("sample_id" = "sample_id")) %>%
                    dplyr::arrange(sample_median) %>%
216 217
                    dplyr::mutate(sample_id_by_median = 
                                    as_factor(sample_id)) %>%
218 219 220 221 222 223 224 225 226
                   left_join(col_data_crc)

count_boxplot <- ggplot(counts_crc_tidy, 
                 aes(x = sample_id_by_median, 
                     y = log2(count), 
                     fill = sample_id) ) + 
                 geom_boxplot() +
                 ylim(c(0, 10)) + 
                 scale_fill_brewer(palette = "Paired") +
227
                 ggtitle("Boxplots of raw counts") +
228 229 230 231
                 theme(axis.text.x = element_text(angle = 90, hjust = 1))

count_boxplot                  

232
## ----exp_boxplot, results="hide", echo=FALSE, fig.show="hide"------------
233 234 235 236 237 238
count_boxplot_tissue <- ggplot(counts_crc_tidy,
                 aes(x = sample_id_by_median, 
                     y = log2(count), 
                     fill = tissue)) + 
                 geom_boxplot() +
                 ylim(c(0, 10)) + 
239 240 241
                 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
                 ggtitle("Boxplots of raw counts") +
                 scale_fill_brewer(palette = "Dark2") 
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

count_boxplot_tissue

count_boxplot_tissue + facet_grid( patient ~ .)


## ----calcsf--------------------------------------------------------------
crc_sf <- estimateSizeFactorsForMatrix(counts_crc[, col_data_crc$sample_id])

sample_medians_sf <- left_join(sample_medians, 
                               tibble(sample_id = names(crc_sf),
                                      sf = crc_sf)) %>%
mutate(s_med_count_scaled = 2^sample_median /geometric.mean(2^sample_median)) %>%
                     dplyr::arrange(sf)

ggplot(sample_medians_sf, aes(x = s_med_count_scaled,
                              y = sf)) +
      ggtitle("Size factors versus scaled median") +
      geom_point() 
      
counts_crc_tidy <- left_join(counts_crc_tidy, 
                             dplyr::select(sample_medians_sf, sample_id, sf))

## ----norm_data-----------------------------------------------------------
counts_crc_tidy <- mutate(counts_crc_tidy, count_norm = count / sf )

268 269 270 271 272 273 274 275 276 277 278 279 280
## ----boxplot_norm, eval=TRUE, fig.show="hide", echo=FALSE, warning = FALSE----
count_boxplot_norm <- ggplot(counts_crc_tidy, 
                 aes(x = sample_id_by_median, 
                     y = log2(count_norm), 
                     fill = sample_id) ) + 
                 geom_boxplot() +
                 ylim(c(0, 10)) + 
                 scale_fill_tableau(palette = "cyclic") +
                 ggtitle("Boxplots of normalized counts") +
                 theme(axis.text.x = element_text(angle = 90, hjust = 1))

count_boxplot_norm

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
## ----MAplot_function-----------------------------------------------------

glog2 <- function(x) ((asinh(x)-log(2))/log(2))


ref_sample <- group_by(counts_crc_tidy, ensembl_id) %>%
              summarize(ref_sample = mean(glog2(count_norm ))) 

counts_crc_tidy <- left_join(counts_crc_tidy, ref_sample) %>%
                   mutate(M = ref_sample - glog2(count_norm), 
                          A = (ref_sample + glog2(count_norm))/ 2)



## ----createMAs, fig.wide="TRUE"------------------------------------------

colorscale <- scale_fill_gradientn(
colors = rev(brewer.pal(9, "YlGnBu")),
values = c(0, exp(seq(-5, 0, length.out = 200))^0.5))

ma_pl <- ggplot(aes(A, M), data = sample_frac(counts_crc_tidy, 
                                              size =  0.1)) +
         facet_wrap(~ sample_id) +
         geom_hex(binwidth = c(0.5, 0.5)) +
         geom_smooth(method = "loess", se = FALSE, col = "#5D84C5", span = .4) +
         geom_hline(aes(yintercept = 0), col = "#9850C3") +
         ylim(c(-5, 5)) +
         coord_fixed(ratio = 2) +
         colorscale +
         ggtitle("MA plots (vs reference sample)")

ma_pl


## ----ex_data_norm_plot, results="hide", fig.show="hide", echo=FALSE------

comp_data <- tibble(x = seq(0, 10, by = 0.1),
              log2 = log2(x),
              glog2 = glog2(x)) %>%
               gather(key = "func", 
                      value = "value", log2, glog2)

ggplot(data = comp_data, 
       aes(x = x, y = value, color = func)) +
      geom_line()


ma_pl_points <- ggplot(aes(A, M), data = sample_frac(counts_crc_tidy, 
                                              size =  0.1)) +
         facet_wrap(~ sample_id) +
         geom_point(alpha = 0.1) +
         geom_smooth(method = "loess", se = FALSE, col = "#5D84C5", span = .4) +
         geom_hline(aes(yintercept = 0), col = "#9850C3") +
         ylim(c(-5, 5)) +
         coord_fixed(ratio = 2) +
         ggtitle("MA plot (vs ref sample)")

ma_pl_points 
339 340 341


## ----scran_norm----------------------------------------------------------
342 343
mtec_scran_sf <- tibble(scran_sf = computeSumFactors(
                                    as.matrix(mtec_counts[, -1])),
344 345 346 347 348
                        cell_id = colnames(mtec_counts)[-1])

mtec_cell_anno <- left_join(mtec_cell_anno, mtec_scran_sf, 
                            by = c("cellID" = "cell_id"))

349 350 351 352 353 354
## ----compar_sf, echo=FALSE, eval=FALSE-----------------------------------
## 
## ggplot(mtec_cell_anno, aes(x = sizeFactor, y = scran_sf)) +
##       ggtitle("SCRAN vs. classical size factors") +
##       geom_point() +
##       geom_smooth()
355 356

## ----createNormCounts----------------------------------------------------
357 358
counts_norm_crc_mat <- select(counts_crc_tidy, sample_id, ensembl_id, 
                              count_norm) %>%
359 360
                         spread(key = sample_id, value = count_norm) %>%
                         {
361
                           tmp <- as.data.frame(.)
362 363 364 365 366 367
                           rownames(tmp) <- tmp$ensembl_id
                           tmp
                         } %>%
                         select(-ensembl_id) %>%
                         as.matrix() 

368 369
mean_sd <- meanSdPlot(counts_norm_crc_mat, plot  = FALSE)$gg +
           ylim(c(0, 1000)) 
370

371
mean_sd
372 373

## ----varStabCountData----------------------------------------------------
374
counts_norm_vst_crc <- varianceStabilizingTransformation(counts_crc)
375

376
meanSdPlot(counts_norm_vst_crc)
377

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
## ----pcaCRCdata----------------------------------------------------------

compute_pca <- function(data_mat, ntop = 500, ...){
  
  pvars <- rowVars(data_mat)
  select <- order(pvars, decreasing = TRUE)[seq_len(min(ntop,
                                                        length(pvars)))]
  
  
  PCA <- prcomp(t(data_mat)[, select], center = TRUE, scale. = FALSE)
  percentVar <- round(100*PCA$sdev^2/sum(PCA$sdev^2),1)
  
  
  return(list(pca = data.frame(PC1 = PCA$x[,1], PC2 = PCA$x[,2],
                      PC3 = PCA$x[,3], PC4 = PCA$x[,4], ...),
393 394
              perc_var = percentVar,
              selected_vars = select))
395 396 397 398 399 400 401 402

}


pca <- compute_pca(counts_norm_vst_crc, 
            patient = col_data_crc$patient,
            tissue = col_data_crc$tissue)

403
names(pca)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
sum(pca$perc_var[1:4])

## ----vizPca, fig.height = 3, fig.width = 10------------------------------

sd_ratio <- sqrt(pca$perc_var[2] / pca$perc_var[1])

pca_plot <- ggplot(pca$pca, aes(x = PC1,  y = PC2,
                color =  patient,
                shape = tissue)) +
       geom_point(size = 4) +
       ggtitle("PC1 vs PC2, top variable genes") +
       labs(x = paste0("PC1, VarExp:", round(pca$perc_var[1],4)),
       y = paste0("PC2, VarExp:", round(pca$perc_var[2],4))) +
       coord_fixed(ratio = sd_ratio) +
       scale_colour_brewer(palette="Dark2")
       
pca_plot      


423
## ----pca23, echo=FALSE, results="hide"-----------------------------------
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
sd_ratio_2 <- sqrt(pca$perc_var[3] / pca$perc_var[2])


pca_plot_2 <- ggplot(pca$pca, aes(x = PC2,  y = PC3,
                color =  patient,
                shape = tissue)) +
       geom_point(size = 4) +
       ggtitle("PC2 vs PC3, top variable genes") +
       labs(x = paste0("PC2, VarExp:", round(pca$perc_var[2],4)),
       y = paste0("PC3, VarExp:", round(pca$perc_var[3],4))) +
       coord_fixed(ratio = sd_ratio_2) +
       scale_colour_brewer(palette="Dark2")
       
pca_plot_2 

## ----heatmap, fig.height = 5, eval=TRUE----------------------------------
441 442 443 444 445 446 447 448 449 450 451 452


create_dist_mat <- function(data, anno, method = "pearson"){
 
  dists <- as.matrix(get_dist(t(data), method = method))
  diag(dists) <- NA
   
  rownames(dists) <-  anno
  colnames(dists) <- anno 
  
  return(dists)
}
453 454 455 456 457 458 459

if(!("cl_anno" %in% colnames(col_data_crc))){
 col_data_crc <- unite(col_data_crc, cl_anno, patient, tissue, remove = FALSE)
}


hmcol <- colorRampPalette(brewer.pal(9, "GnBu"))(100)
460 461 462 463
pheatmap(create_dist_mat(counts_norm_vst_crc, 
                         anno = col_data_crc$cl_anno,
                         method = "euclidian"),
         trace="none", col = rev(hmcol))
464

465
## ----pc_regression, warning=FALSE----------------------------------------
466 467

lm_pc1 <- lm(t(counts_norm_vst_crc) ~ pca$pca$PC1)
468 469 470 471 472 473 474 475 476 477 478 479 480 481
gene_means <- tidy(lm_pc1) %>% 
              filter(term == "(Intercept)") %>%
              select(response, estimate)

cleaned_data <- t(residuals(lm_pc1)) + gene_means$estimate

# sanity check whether gene wise means are equal
all.equal(rowMeans(cleaned_data), rowMeans(counts_norm_vst_crc))

## ----heatmapCleanedData--------------------------------------------------
hmcol <- colorRampPalette(brewer.pal(9, "RdPu"))(255)
pheatmap(create_dist_mat(cleaned_data, 
                         anno = col_data_crc$cl_anno,
                         method = "euclidean"),
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
         trace="none", col = hmcol)


## ----eurodist------------------------------------------------------------
as.matrix(eurodist)[1:4, 1:4]

## ----mdsEurope, echo=TRUE------------------------------------------------

loc <- cmdscale(eurodist)
x <- loc[, 1]
y <- -loc[, 2] # reflect so North is at the top

coord <- tibble(x, y, cities = rownames(loc))

ggplot(coord, aes(x = x, y = y)) + 
  geom_point() +
  geom_label(aes(label = cities)) +
  ggtitle("Map of Europe computed by MDS")
500 501


502 503
## ----scalingSingleCell---------------------------------------------------
tcell_log_counts <- as.data.frame(
504
  read_csv(file.path(data_dir, "nbt.3102-S7.csv")))
505 506 507 508 509 510
rownames(tcell_log_counts) <- tcell_log_counts$X1
tcell_log_counts$X1 <- NULL
tcell_log_counts <- as.matrix(tcell_log_counts)

tcell_log_counts[1:5, 1:5]

511
dist_tcells <- get_dist(tcell_log_counts, method = "spearman")
512

513
scaling_tcells <- as_tibble(isoMDS(dist_tcells, k = 2)$points)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
colnames(scaling_tcells) <- c("MDS_dimension_1", "MDS_dimension_2")
scaling_tcells <- add_column(scaling_tcells, cell_id = labels(dist_tcells), 
           .before = "MDS_dimension_1")


## ----plotScalingSingleCell, dependson="scalingSingleCell"----------------
gata3_idx <- which( "Gata3" == colnames(tcell_log_counts))
gata3_idx

gata3_exp <- tcell_log_counts[, gata3_idx]
gata3_group <- cut(gata3_exp, 
             breaks = quantile(gata3_exp, probs = seq(0, 1, 0.2)),
             labels = c("very low", "low", "medium", "high", 'very high'),
             include.lowest	= TRUE)

scaling_tcells <- add_column(scaling_tcells, gata3_group, .after = "cell_id")

mds_plot_tcells <- ggplot(scaling_tcells, aes(x = MDS_dimension_1, 
                                              MDS_dimension_2,
                     color = fct_rev(gata3_group))) +
                    geom_point(size = 3) +
535
                    ggtitle("Kruskal MDS of the T-cell single cell data") +
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
                    scale_color_brewer(palette = "RdBu", direction = 1) +
                    coord_equal()


mds_plot_tcells


## ----checkScaling--------------------------------------------------------
dist_tcells_mds <- get_dist(select(scaling_tcells,
                           MDS_dimension_1, MDS_dimension_2),
                           method = "euclidean")

data_dist <- tibble(org_distance = as.vector(dist_tcells),
                    mds_distance = as.vector(dist_tcells_mds))


ggplot(data_dist, aes(x = org_distance, y = mds_distance)) +
553
       geom_hex(binwidth = .05) +
554 555 556 557 558 559 560
       geom_smooth(color = "grey10") +
       scale_fill_distiller(palette = "YlOrRd", direction = 1) + 
       ggtitle(label = "Shepard plot",  
               subtitle = "Original vs MDS distances") +
       coord_equal()


561
## ----ex_sheppard_plot, echo=FALSE, results="hide"------------------------
562 563
ggplot(data_dist, aes(x = org_distance, y = mds_distance)) +
       stat_density2d(aes(fill = ..level..),  geom = "polygon",
564
                      n = 100, h = c(0.2, 0.2)) +
565 566 567 568 569 570 571
       geom_smooth(color = "grey10") +
       scale_fill_distiller(palette = "YlGn", direction = 1) + 
       ggtitle(label = "Shepard plot",  
               subtitle = "Original vs MDS distances") +
       coord_equal()


572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
## ----sammonScaling, eval=FALSE, echo=FALSE-------------------------------
## scaling_tcells_sam <- as_tibble(sammon(dist_tcells)$points)
## colnames(scaling_tcells_sam) <- c("MDS_dimension_1", "MDS_dimension_2")
## scaling_tcells_sam <- add_column(scaling_tcells_sam, cell_id = labels(dist_tcells),
##            .before = "MDS_dimension_1")
## 
## mds_plot_tcells_sam <- ggplot(scaling_tcells_sam, aes(x = MDS_dimension_1,
##                                               MDS_dimension_2,
##                      color = fct_rev(gata3_group))) +
##                     geom_point(size = 3) +
##                     ggtitle("Sammon Scaling of the T-cell single cell data") +
##                     scale_color_brewer(palette = "RdBu", direction = 1) +
##                     coord_equal()
## mds_plot_tcells_sam
## 
## dist_tcells_mds_sam <- get_dist(select(scaling_tcells_sam,
##                            MDS_dimension_1, MDS_dimension_2),
##                            method = "euclidean")
## 
## data_dist_sam <- tibble(org_distance = as.vector(dist_tcells),
##                     mds_distance = as.vector(dist_tcells_mds_sam))
## 
## 
## ggplot(data_dist_sam, aes(x = org_distance, y = mds_distance)) +
##        geom_hex(binwidth = 0.1) +
##        geom_smooth(color = "grey10") +
##        scale_fill_distiller(palette = "RdPu", direction = 1) +
##        ggtitle(label = "Shepard plot Sammon",
##                subtitle = "Original vs MDS distances") +
##        coord_equal()
## 

## ----runtSNE-------------------------------------------------------------

run_tsne <- function(X, perplexity = 20, pca = FALSE, max_iter = 5000, 
      verbose = FALSE, is_distance = TRUE, seed=123L, ...){
  
  set.seed(seed)
  
  tX <- Rtsne(X, perplexity = perplexity, pca = pca, max_iter = max_iter, 
      verbose = verbose, is_distance = is_distance)$Y
  
  if(class(X) == "dist"){
    labs <- labels(X)
  } else {
    labs <- rownames(X)
  }
  
 # browser()
  
  colnames(tX) <- c("tSNE_dimension_1", "tSNE_dimension_2")
  tX <- add_column(as_tibble(tX), 
                   cell_id = labs,
             .before = "tSNE_dimension_1")
  tX
  
}
629

630 631 632 633 634 635 636 637 638 639 640 641 642

## ----tSNEtCell-----------------------------------------------------------

tcell_tsne <- run_tsne(dist_tcells, perplexity = 5, 
                       pca = FALSE, max_iter = 5000, 
      verbose = FALSE, is_distance = TRUE, seed = 123)


tcell_tsne

tsne_plot_tcells_5 <- ggplot(tcell_tsne,
                              aes(x = tSNE_dimension_1,
                                      tSNE_dimension_2,
643 644
                     color = fct_rev(gata3_group))) +
                    geom_point(size = 3) +
645
                    ggtitle("t-SNE plot of the T-cell single cell data") +
646 647 648
                    scale_color_brewer(palette = "RdBu", direction = 1) +
                    coord_equal()

649
tsne_plot_tcells_5
650 651


652 653 654 655 656 657
## ----compareOrgtSNE, fig.wide="TRUE"-------------------------------------

dist_tcells_tSNE <- get_dist(select(tcell_tsne,
                           tSNE_dimension_1, 
                           tSNE_dimension_2),
                           method = "euclidean")
658 659 660



661 662 663 664 665 666 667 668 669
data_dist_tSNE <- tibble(org_distance = as.vector(dist_tcells),
                    tSNE_distance = as.vector(dist_tcells_tSNE))



ggplot(data_dist_tSNE, aes(x = org_distance, y = tSNE_distance)) +
       geom_hex(binwidth = c(0.05, 0.3)) +
       geom_smooth(color = "grey10", method = "loess", span = 0.5) +
       scale_fill_distiller(palette = "BrBG", direction = 1) +
670
       ggtitle(label = "Shepard plot for t-SNE",
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
               subtitle = "Original vs tSNE distances") +
      coord_fixed(1/(max(data_dist_tSNE$tSNE_distance)
                     - min(data_dist_tSNE$tSNE_distance))) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1))


## ----tSNE, eval=FALSE, echo=FALSE, fig.show="hide"-----------------------
## tcell_tsne_20 <- run_tsne(dist_tcells, perplexity = 20,
##                        pca = FALSE, max_iter = 5000,
##       verbose = FALSE, is_distance = TRUE, seed = 123)
## 
## 
## 
## tsne_plot_tcells_20 <- ggplot(tcell_tsne_20,
##                               aes(x = tSNE_dimension_1,
##                                       tSNE_dimension_2,
##                      color = fct_rev(gata3_group))) +
##                     geom_point(size = 3) +
##                     ggtitle("t-SNE plot of the T-cell single cell data") +
##                     scale_color_brewer(palette = "RdBu", direction = 1) +
##                     coord_equal()
## 
## tsne_plot_tcells_5
## tsne_plot_tcells_20
## 
## tcell_tsne_org <- run_tsne(tcell_log_counts, perplexity = 5,
##                        pca = FALSE, max_iter = 5000,
##       verbose = FALSE, is_distance = FALSE, seed = 123)
## 
## 
## 
## tsne_plot_tcells_org <- ggplot(tcell_tsne_org,
##                               aes(x = tSNE_dimension_1,
##                                       tSNE_dimension_2,
##                      color = fct_rev(gata3_group))) +
##                     geom_point(size = 3) +
##                     ggtitle("t-SNE plot of the T-cell single cell data") +
##                     scale_color_brewer(palette = "RdBu", direction = 1) +
##                     coord_equal()
## 
## 
## 

714 715 716
## ----session_info, cache = FALSE-----------------------------------------
sessionInfo()

717 718 719 720 721 722 723 724 725

## ----unloaAll, echo=FALSE, message=FALSE, eval = FALSE-------------------
## 
## pkgs <- loaded_packages() %>%
##         filter(package != "devtools") %>%
##         {.$path}
## 
## walk(pkgs, unload)