---
title: "R Notebook"
output: html_notebook
---
```{r}
#set working directory
wd <- dirname(getwd())
data_folder <- file.path(wd, 'cpout')
results_folder <-(file.path(wd,'results_test2'))
#Read in: Cells, Image, Object and Panel
cells <- read.csv(file=file.path(data_folder,paste('cell.csv')))
image <- read.csv(file=file.path(data_folder, paste("Image.csv")))
object_relationship <- read.csv(file=file.path(data_folder, paste("Object relationships.csv")))
panel <- read.csv(file=file.path(data_folder, paste('LC-Curioni Project_1.1.csv')))
```

```{r}
#number of cells
nrow(cells)
```

```{r}
unique(sub("_c[0-9]*$", "", colnames(cells)))
```

```{r}
#Select only the measurements you want to work on, based on the measurements displayed above
counts <- cells[, grepl("Intensity_MeanIntensity_FullStackFiltered", colnames(cells))]
```

```{r}
#when using 16bit data this should be 2^16 =65536
scaling_factor <- unique(image$Scaling_FullStack)
#Scale up the counts according to scaling factor from CellProfiler
counts <- counts * scaling_factor
```

```{r}
#the S4Vector is needed for the SCE and a dataframe that stores the metadata per category
library(S4Vectors)

cell_meta <- DataFrame(CellNumber = cells$ObjectNumber,
                      Center_X=cells$Location_Center_X,
                      Center_Y=cells$Location_Center_Y,
                      Area = cells$AreaShape_Area,
                      MajorAxisLength=cells$AreaShape_MajorAxisLength,
                      MinorAxisLength=cells$AreaShape_MinorAxisLength)
cell_meta$ImageNumber <- cells$ImageNumber

#Create DataFrame for image meta data. Then match image and cell metadata by ImageNumber
image_meta <- DataFrame(PatientID = image$Metadata_Patient_ID,
                      ImmuneStatus = image$Metadata_Tcell.state,
                      TherapyStatus = image$Metadata_Therapy_Status,
                      Block = image$Metadata_Block)
image_meta$ImageNumber <- image$ImageNumber
cell_meta <- merge(cell_meta, image_meta, by="ImageNumber")


library(stringr)
ac_info <- str_split(image$Metadata_acname, '_', simplify=TRUE)
cell_meta$BatchID <- ac_info[cell_meta$ImageNumber,1]
cell_meta$SampleID <- ac_info[cell_meta$ImageNumber,4]
cell_meta$ROI <- image$Metadata_roiid[cell_meta$ImageNumber]
```

```{r}
#Should usually be cell id. However, in the cells.csv file the object number is counted per imgage, so to get unique cell IDs, they must be establishes by combining ObjectNumber, ImageNumber/ROINumber and SampleID
rownames(cell_meta) <-paste(cell_meta$SampleID, cell_meta$ROI, cell_meta$CellNumber, sep='_')
```

```{r}
library(DT)
#loads panel
DT::datatable(panel)

#exactl order of channels can be extracted from the _full.csv files
#header = FALSE is important here as otherwise it'll take the first metal as a header
channel_metal <- read.csv(file.path(data_folder, paste("20200318_LC_Curioni-Project_B15-69198-1_s0_p4_r1_a1_ac_full.csv")), header=FALSE)

#this reorders the pannel according to the correct metal lsit
panel <- panel[match(channel_metal[,1], panel$Metal.Tag),]

#use Target from panel as the correct channel name to be displayed
rownames(panel) <-panel$clean_target

#channels in cell file are not ordered correctly (starting with 1,11,12 ... 2,21,22 ... 3,31,32...), hence we need to reorder them
channelNumber <- as.numeric(sub("^.*_c", "", colnames(counts)))

# Order counts based on channel number
counts <- counts[,order(channelNumber, decreasing = FALSE)] 
```

```{r}
library(igraph)
# Construct neighbour data.frame
# First in the ImageNumber_ObjectNumber format
cur_df <- data.frame(CellID_1 = paste0(object_relationship$First.Image.Number, 
                                       "_", object_relationship$First.Object.Number),
                     CellID_2 = paste0(object_relationship$Second.Image.Number, 
                                       "_", object_relationship$Second.Object.Number))
# Create simple cell IDs
cellID <- paste0(cell_meta$ImageNumber, "_", cell_meta$CellNumber)

# Change cell IDs
cur_df$CellID_1 <- rownames(cell_meta)[match(cur_df$CellID_1, cellID)]
cur_df$CellID_2 <- rownames(cell_meta)[match(cur_df$CellID_2, cellID)]

# Build graph
g <- graph_from_data_frame(cur_df)
g
```

```{r}
library(SingleCellExperiment)

sce <-SingleCellExperiment(assays = list(counts=t(counts)))

#marker name as row name cellID as colname
rownames(sce)<-rownames(panel)
colnames(sce)<-rownames(cell_meta)

#store metadata in colDat and everything accordingly
cell_meta <-DataFrame(cell_meta)
colData(sce) <-cell_meta
rowData(sce) <-panel
metadata(sce)<-list(graph=g)

#save SCE object
saveRDS(sce, file=file.path(results_folder, paste("sce_CurioniProject_LC.rds")))
```

