# %% [markdown]
# # RSNA With R

# %% [markdown]
# ## Packages

# %% [code]
# Loading packages
#library(coreCT)
library(keras)
library(tidyverse)
library(oro.dicom)
library(oro.nifti)

# Check packages
sessionInfo()
# Param
options(scipen=12)

# %% [markdown]
# ## CSV file

# %% [code]
# files
input_path = file.path("../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images")
# csv
train_csv = read_csv("../input/rsna-intracranial-hemorrhage-detection/stage_1_train.csv")
#  ----------------------------------------------------------------------
# Label
table(train_csv$Label)
ggplot(train_csv, aes(x = factor(Label), fill = factor(Label))) + geom_bar() + theme_bw()
#  ----------------------------------------------------------------------

# %% [code]
#  ----------------------------------------------------------------------
# Exploring Types
id_split = str_split_fixed(train_csv$ID[train_csv$Label == 1],"_", n = 3)
df = tibble(id = paste0("ID_",id_split[,2]), type = id_split[,3])
head(df)
table(df$type)
ggplot(df, aes(x = factor(type), fill = factor(type))) + geom_bar(aes(y = (..count..)/sum(..count..))) + theme_bw()

# %% [code]
#  ----------------------------------------------------------------------
# Make a dataframe with all data
id_split = str_split_fixed(train_csv$ID,"_", n = 3)
df_full = tibble(id = paste0("ID_",id_split[,2]), type = id_split[,3], label = train_csv$Label)

#  ----------------------------------------------------------------------
# Control patients number
    # Patients n
    n_distinct(df_full$id)
    # Images DICOM n 
    length(list.files("../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images"))

#  ----------------------------------------------------------------------
# Reshape the data
db = df_full %>% group_by(id) %>% summarise(any = sum(label[type == "any"]),
                                           epidural = sum(label[type == "epidural"]),
                                           intraparenchymal = sum(label[type == "intraparenchymal"]),
                                           intraventricular = sum(label[type == "intraventricular"]),
                                           subarachnoid = sum(label[type == "subarachnoid"]),
                                           subdural = sum(label[type == "subdural"]))

head(db)
db$file_name = paste0(db$id,".dcm")

# %% [markdown]
# # Read DICOM

# %% [markdown]
# ## Discovering the functions

# %% [code]
#  ----------------------------------------------------------------------
# test patient 1
patient_scan = readDICOM(paste0(input_path,"/",list.files("../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images")[1]))

image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = FALSE,
      xlab = "", ylab = "")

# %% [code]
#  ----------------------------------------------------------------------
# Specific CT
specific_CT = readDICOM(paste0(input_path,"/","ID_5c8b5d701",".dcm"))
summary(specific_CT)
image(t(specific_CT$img[[1]]), col = grey(0:64/64), axes = FALSE,
      xlab = "", ylab = "")

# samples 

#  ----------------------------------------------------------------------
# EPIDURAL 
epi = db$file_name[db$epidural == 1][1:5]
for (i in unique(epi)) {
patient_scan = readDICOM(paste0(input_path,"/",i))
image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = F,
      xlab = "", ylab = "")  
}

#  ----------------------------------------------------------------------
# intraparenchymal 
epi = db$file_name[db$intraparenchymal == 1][1:5]
for (i in unique(epi)) {
patient_scan = readDICOM(paste0(input_path,"/",i))
image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = F,
      xlab = "", ylab = "")  
}

#  ----------------------------------------------------------------------
# intraventricular 
epi = db$file_name[db$intraventricular == 1][1:5]
for (i in unique(epi)) {
patient_scan = readDICOM(paste0(input_path,"/",i))
image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = F,
      xlab = "", ylab = "")  
}

#  ----------------------------------------------------------------------
# subarachnoid 
epi = db$file_name[db$subarachnoid == 1][1:5]
for (i in unique(epi)) {
patient_scan = readDICOM(paste0(input_path,"/",i))
image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = F,
      xlab = "", ylab = "")  
}
#  ----------------------------------------------------------------------
# subdural 
epi = db$file_name[db$subdural == 1][1:5]
for (i in unique(epi)) {
patient_scan = readDICOM(paste0(input_path,"/",i))
image(t(patient_scan$img[[1]]), col = grey(0:64/64), axes = F,
      xlab = "", ylab = "")  
}

# %% [markdown]
# > Source: https://www.kaggle.com/omission/eda-view-dicom-images-with-correct-windowing

# %% [code]
#  ----------------------------------------------------------------------
#  ----------------------------------------------------------------------
#  ----------------------------------------------------------------------
# Work in progress
# Function window_image
window_image = function(img, window_center,window_width, intercept, slope) {
    img = (img*slope +intercept)
    img_min = window_center - window_width/2
    img_max = window_center + window_width/2
    img = if_else(img<img_min,img_min,img)
    img = if_else(img>img_max,img_max,img)
return(img) 
}

# %% [markdown]
# # Sample on training dataset

# %% [code]
#system("ls ../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images -f -R", intern = TRUE)
sample_100 = sample(dir("../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images"),size = 100,replace = FALSE)
#create directory for sample
dir.create("../sample100")
dir("../sample100")
db_smpl = db %>% filter(id %in% gsub(".dcm",replacement = "",sample_100))
db_smpl

# %% [code]
# extract metadata and convert raw values to Hounsfield Units
#ct.slope <- unique(extractHeader(specific_CT$hdr, "RescaleSlope"))
#ct.int   <- unique(extractHeader(specific_CT$hdr, "RescaleIntercept")) 
#HU <- lapply(specific_CT$img, function(x) x*ct.slope + ct.int)

# https://github.com/pamelarussell/radtools