---
title: "PFC Dashboards"
author: "Cao Lab"
server: shiny
format: 
  dashboard:
    logo: https://zhenghu159.github.io/picx-images-hosting/PFCapp/Logo.1756dx3zx7.webp
    nav-buttons:
      - icon: github
        href: https://github.com/GangCaoLab/mPFC-web
---



# Home

<p style="font-size: 50px; font-weight: bold; text-align: center;">A single-cell resolution spatial-transcriptome-connectome integrated  multi-omic atlas of prefrontal cortex</p>

<br>

<img src="https://zhenghu159.github.io/picx-images-hosting/PFCapp/main.77dcin4jph.webp" style="width: 100%;">

<br>
<br>

<p style="font-size: 30px; font-weight: bold; text-align: left;">
Abstract
</p>

<p style="font-size: 20px; text-align: justify;">
Medial prefrontal cortex (mPFC) is the high-level center of brain cognitive function, which regulates emotion, memory, decision-making, behavior, neuroendocrine and other brain functions. mPFC has a wide range of projections in the cerebral cortex, thalamus, hypothalamus, basal ganglia, midbrain and other brain regions, forms extremely complex projection circuits. Analyzing these numerous projection circuits structures is an urgent problem in neuroscience. The conventional method is using neurotropic viruses to express fluorescent proteins for nucleus labeling. However, due to the limitation of fluorescent protein types and spectral crossover, it is time-consuming and labor-intensive to realize multiple nucleus labeling and tracing. The ideal circuits analysis solution is to break through the limit of fluorescent protein types and can label multiple brain regions. On the basis of multi-brain circuits labeling, it can also analyze the expression of neuron-related genes in the circuits, so as to better interpret the mechanism by which specific circuits perform their functions.
</p>


<br>

<p style="font-size: 30px; font-weight: bold; text-align: left;">
Interactively exploring the data
</p>

<p style="font-size: 20px; font-weight: bold; text-align: left;">
scRNAseq
</p>

<p style="font-size: 20px; text-align: justify;">
Our scRNAseq dataset sequenced the PFC of 3 mice. It contains the transcriptome of mouse PFC and the projectome information of 24 PFC targets. Users can browse the following content through the scRNA-seq tab:
</p>

- Cells in the UMAP can be clustered differently by selecting different classification in Metadata
- Select to view different genes expression in the UMAP
- Select to view different PFC targets expression in the UMAP
- View PFC targets cell numbers in different cell type



<p style="font-size: 20px; font-weight: bold; text-align: left;">
Spatial data
</p>

<p style="font-size: 20px; text-align: justify;">
Our spatial dataset sequenced 36 slices of mouse PFC. It contains 32 genes and 15 targets information of mouse PFC. Users can browse the following content through the spatial tab:
</p>

- Select to view different cell types in spatial
- Select to view different gene expression in spatial
- Select to view different PFC targets expression in spatial
- Select to view different PFC targets distribution in anterior-posterior and ventralis-dorsalis axes



<p style="font-size: 20px; font-weight: bold; text-align: left;">
3D
</p>

<p style="font-size: 20px; text-align: justify;">
3D interactive visualization of mouse PFC.
</p>



<p style="font-size: 20px; font-weight: bold; text-align: left;">
raw image
</p>

<p style="font-size: 20px; text-align: justify;">
visualization of raw images.
</p>


```{r}
#| context: setup
#| warning: false
#| message: false

library(ggplot2)
library(Seurat)
#library(scCustomize)
library(shiny)
library(rgl)
library(ggdark)
library(viridis)
library(tidyverse)
#library(wholebrain)
#attach(loadNamespace('wholebrain'), warn.conflicts = FALSE)
source("R/Palettes.R")
source('R/includes.R')
Adult.Ex <- readRDS('data/Adult.Ex.rds')
sp.PFC <- readRDS('data/sp.PFC.rds')
options(rgl.useNULL = TRUE)
```





# scRNAseq {scrolling="true"}

## {.sidebar}

```{r}
selectInput('cluster', 'Select Cluster', c("SubType_Layer","SubType"))
```

```{r}
selectInput('gene', 'Select Gene', rownames(Adult.Ex))
```

```{r}
Barcode <- c(
  "ITi_D_score", "ITi_V_score", "ITc_score", "PTi_score",
  'VIS-I','SSp-I','CP-I','AUD-I','RSP-I',
  'BLA-I','ACB-I','ENTl-I','AId-I','ECT-I',
  'ACB-C','PL-C','ECT-C','ENTl-C',
  'BLA-C','CP-C','AId-C','RSP-C',
  'MD-I','RE-I','DR-I','VTA-I','LHA-I','SC-I')
selectInput('target', 'Select Target', Barcode)
```


## Column

### Row

#### Column

```{r}
plotOutput('cluster_plot')
```

#### Column

```{r}
plotOutput('gene_plot')
```

### Row

#### Column

```{r}
plotOutput('target_plot')
```

#### Column

```{r}
plotOutput('target_bar_plot')
```


```{r}
#| context: server

output$cluster_plot <- renderPlot({
  DimPlot(
    Adult.Ex,
    reduction = 'umap',
    group.by = input$cluster,
    cols = col_cluster[[input$cluster]],
    label = T
  ) +
    coord_fixed()
})

output$gene_plot <- renderPlot({
  FeaturePlot(
    Adult.Ex,
    features = input$gene) +
    coord_fixed()
})

output$target_plot <- renderPlot({
  Barcode <- c(
  "ITi_D_score", "ITi_V_score", "ITc_score", "PTi_score",
  'VIS-I','SSp-I','CP-I','AUD-I','RSP-I',
  'BLA-I','ACB-I','ENTl-I','AId-I','ECT-I',
  'ACB-C','PL-C','ECT-C','ENTl-C',
  'BLA-C','CP-C','AId-C','RSP-C',
  'MD-I','RE-I','DR-I','VTA-I','LHA-I','SC-I')
  
  seu <- Adult.Ex
  seu@meta.data[,Barcode][is.na(seu@meta.data[,Barcode])] <- 0
  FeaturePlot(
    seu, features = input$target, order = T) +
    coord_fixed()
})

output$target_bar_plot <- renderPlot({
  df <- as.data.frame(table(Adult.Ex@meta.data[,input$cluster][which(
    Adult.Ex@meta.data[,input$target]>0)]))
  colnames(df) <- c("Celltypes","Cellnum")
  
  ggplot(df, aes(x=Celltypes, y=Cellnum, fill=Celltypes)) +
    geom_col() +
    scale_fill_manual(values = col_cluster[[input$cluster]]) +
    theme_classic() +
    theme(axis.text.x = element_text(angle = 25, hjust = 1),
          plot.title = element_text(hjust = 0.5)) +
    labs(title = paste("PFC → ",input$target," cell numbers in different cell type",
                       sep=""))
})
```





# Spatial {scrolling="true"}

## {.sidebar}

```{r}
selectInput('sp_slice', 'Select Slice', unique(sp.PFC$slice))
```

```{r}
selectInput('sp_cluster', 'Select Cluster', c("SubType_Layer","SubType"))
```

```{r}
selectInput('sp_gene', 'Select Gene', rownames(sp.PFC))
```

```{r}
sp_Barcode <- c(
  "ITi_D", "ITi_V", "ITc", "PTi",
  'VIS-I','SSp-I','CP-I','AUD-I','RSP-I',
  'BLA-I','ACB-I','AId-I','ECT-I',
  'ACB-C','ECT-C','CP-C','AId-C','RSP-C',
  'LHA-I')
selectInput('sp_target', 'Select Target', sp_Barcode)
```


## Column

### Row

#### Column

```{r}
#| fig-width: 10

plotOutput('sp_cluster_plot')
```

#### Column

```{r}
#| fig-width: 10

plotOutput('sp_gene_plot')
```

### Row

#### Column

```{r}
#| fig-width: 10

plotOutput('sp_target_plot')
```

#### Column

```{r}
#| fig-width: 10

plotOutput('sp_target_line_plot')
```

```{r}
#| context: server

output$sp_cluster_plot <- renderPlot({
  df <- data.frame(
    x = sp.PFC$ML_new[sp.PFC$slice==input$sp_slice],
    y = sp.PFC$DV_new[sp.PFC$slice==input$sp_slice],
    type = sp.PFC@meta.data[sp.PFC$slice==input$sp_slice, input$sp_cluster]
  )
  ggplot(df, aes(x=x, y=y, color=type)) +
    geom_point(size=1) +
    scale_color_manual(values = col_cluster[[input$sp_cluster]]) +
    labs(title = paste(input$slice,'cell types in spatial')) +
    guides(color=guide_legend(nrow = 2, byrow = TRUE, reverse = T,
                              override.aes = list(size=2))) +
    coord_fixed() +
    ggdark::dark_theme_void() +
    theme(plot.title = element_text(size = 20, hjust = 0.5),
          legend.position = 'bottom', legend.title=element_blank(),
          legend.text = element_text(size=10))
})

output$sp_gene_plot <- renderPlot({
  df <- data.frame(
    X = sp.PFC$ML_new,
    Y = sp.PFC$DV_new,
    Zscore = scale(log1p(sp.PFC@assays$RNA@counts[input$sp_gene,]))
    )
  df <- df[which(sp.PFC$slice==input$sp_slice),]
  df <- df[order(df$Zscore),]
  ggplot(df,aes(x=X,y=Y)) +
    geom_point(aes(colour=Zscore), size=1) +
    scale_color_gradientn(colours = viridis(n = 256, option = "D", direction = 1)) +
    ggdark::dark_theme_void() +
    labs(title = input$sp_gene) +
    theme(plot.title = element_text(size = 20, hjust = 0.5),
          legend.position = 'bottom') +
    coord_fixed()
})

output$sp_target_plot <- renderPlot({
  seu <- sp.PFC
  seu@meta.data[,c("PTi","ITi_D","ITi_V","ITc")][is.na(seu@meta.data[,c("PTi","ITi_D","ITi_V","ITc")])] <- 0
  df <- data.frame(
    X = sp.PFC$ML_new,
    Y = sp.PFC$DV_new,
    Zscore = scale(log1p(sp.PFC@meta.data[,input$sp_target]))
  )
  df <- df[which(sp.PFC$slice==input$sp_slice),]
  df <- df[order(df$Zscore),]
  ggplot(df, aes(x=X,y=Y)) +
    geom_point(aes(colour=Zscore), size=1) +
    scale_color_gradientn(colours = viridis(n = 256, option = "E", direction = 1)) +
    ggdark::dark_theme_void() +
    labs(title = input$sp_target) +
    theme(plot.title = element_text(size = 20, hjust = 0.5),
          legend.position = 'bottom') +
    coord_fixed()
})

output$sp_target_line_plot <- renderPlot({
  # AP
  seu <- subset(sp.PFC, cells=colnames(sp.PFC)[which(sp.PFC$ABA_hemisphere=="Left")])
  slice <- unique(seu$slice)
  df <- data.frame('slice'=slice)
  for (i in 1:length(slice)){
    df$cellnum[i] <- length(which(seu$slice==slice[i] &
                                  seu@meta.data[,input$sp_target]>0))/
      length(which(seu$slice==slice[i] & seu$BC_num>0))
  }
  df$x <- c(1:36)
  p1 <- ggplot(df, aes(x=x, y=cellnum)) +
    geom_point(alpha=0.5, size=3, color=col_Barcode[input$sp_target]) +
    geom_smooth(se = F, linewidth=1.5, color=col_Barcode[input$sp_target]) +
    theme_bw() +
    scale_x_continuous(breaks = seq(0,35,5)) +
    theme(text = element_text(size=15), 
          plot.title = element_text(size = 20, hjust = 0.5)) +
    labs(x='A → P',y='Cell proportion')
  
  # DV
  sp_Barcode <- c("ITi_D", "ITi_V", "ITc", "PTi",
               'VIS-I','SSp-I','CP-I','AUD-I','RSP-I',
               'BLA-I','ACB-I','AId-I','ECT-I',
               'ACB-C','ECT-C','CP-C','AId-C','RSP-C',
               'LHA-I')
  seu <- subset(sp.PFC, cells=colnames(sp.PFC)[which(sp.PFC$ABA_hemisphere=="Left")])
  bc_slice <- seu@meta.data[,c(sp_Barcode, 'Y','BC_num')]
  bc_slice <- 
    bc_slice |>
    mutate(bin = cut(Y, breaks = 36))
  bin <- sort(unique(bc_slice$bin))
  bc_slice$bin_index <- match(bc_slice$bin, bin)
  df <- data.frame('bin_index'=c(1:36))
  for (i in 1:36){
    df$cellnum[i] <- length(which(bc_slice$bin_index==i &
                                  bc_slice[,input$sp_target]>0))/
    length(which(bc_slice$bin_index==i & bc_slice$BC_num>0))
  }
  df$x <- c(1:36)
  p2 <- ggplot(df, aes(x=x, y=cellnum)) +
    geom_point(alpha=0.5, size=3, color=col_Barcode[input$sp_target]) +
    geom_smooth(se = F, linewidth=1.5, color=col_Barcode[input$sp_target]) +
    theme_bw() +
    scale_x_continuous(breaks = seq(0,35,5)) +
    theme(text = element_text(size=15), 
          plot.title = element_text(size = 20, hjust = 0.5)) +
    labs(x='D → V',y='Cell proportion') +
    xlim(36, 0)
  p1/p2
})
```






# 3D

## {.sidebar}

```{r}
selectInput('subtype', 'Select SubType', sort(unique(sp.PFC$SubType)))
```


## Column

```{r}
rglwidgetOutput('spatial_subtype', width = "100%")
```


```{r}
#| context: server

output$spatial_subtype <- renderRglwidget({
  open3d()
  bg3d(color = "black")
  par3d(userMatrix = rotationMatrix(-pi/6, -1, 1, 0), zoom = 0.6)
  acr.list <- c("MOs","PL","ORBm","ACAd","ILA","DP","ACAv")
  for(acr in acr.list){
    mesh <- mesh3d.allen.annot.from.id(get.id.from.acronym(acr))
    #to.del <- which(mesh$vb[1,] < 0)
    #to.del <- NA
    #mesh$it <- mesh$it[,!is.element(mesh$it[1,], to.del) & !is.element(mesh$it[2,], to.del) & !is.element(mesh$it[3,], to.del)]
    #col <- color.from.acronym(acr)
    col <- "lightgray"
    #col <- col_Region[acr]
    shade3d(mesh, col = col, material = list(lit=FALSE), alpha = 0.1)
  }
  
  df_plot <- sp.PFC@meta.data[which(sp.PFC$SubType == input$subtype),]
  
  spheres3d(x = df_plot$ML_new, 
            y = df_plot$DV_new,
            z = df_plot$AP_new,
            col = col_cluster[["SubType"]][input$subtype], radius=0.01, alpha=1)
  rglwidget()
})
```






# raw image

```{=html}
<iframe src="https://avivator.gehlenborglab.org/?image_url=https://huggingface.co/YAYUhuang/Imagesave/resolve/main/PT-2-C2-C.ome.tiff?rel=0&amp;autoplay=1" title="PFC" height="800" width="100%"></iframe>
```





