---
title: "A triple-network organization for the mouse brain"
author: "Joanes Grandjean"
output: github_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval=FALSE)
```

## Asset preparation

This section contains two parts.   
1. preparation of the global variables in bash and R   
2. Downloading the resources for the analysis.   

At the end of this script, you should have preprocessed mouse resting-state  and optogenetics fMRI data, templates and masks, viral tracer data, as well as the seeds used. 

### Loading the bash main variables
```{bash load main variables, eval=TRUE}
# path to the gitlab code
echo 'init_folder="/home/traaffneu/joagra/code/insula"' > bash_env.sh
# path to data folder (where data and analysis is performed)
echo 'data_folder="/project/4180000.18"' >> bash_env.sh

# path to the (mouse) resting-state fMRI data
echo 'study_folder=$data_folder"/rest"' >> bash_env.sh
# path to the (mouse) seeds
echo 'roi_folder=$data_folder"/SBA_roi"' >> bash_env.sh
# path to the (mouse) viral tracer data
echo 'viral_folder=$data_folder"//tracer"' >> bash_env.sh

# path to the AIBS template and mask, at 200 (fMRI) and 50 (tracer) um resolution, together with atlases
# These assets are derivatives from those provided by the AIBS. 
echo 'template=$init_folder"/assets/template/ABI_template_200um.nii"'  >> bash_env.sh
echo 'template_mask=$init_folder"/assets/template/mask_200um.nii"' >> bash_env.sh

echo 'template_50=$init_folder"/assets/template/ABI_template_50um.nii"'  >> bash_env.sh
echo 'template_mask_50=$init_folder"/assets/template/mask_50um.nii"' >> bash_env.sh

echo 'atlas=$init_folder"/assets/template/ABI_atlas_reduced_200um.nii.gz"'  >> bash_env.sh
echo 'atlas_50=$init_folder"/assets/template/ABI_atlas_reduced_50um.nii.gz"'  >> bash_env.sh
echo 'atlas_label=$init_folder"/assets/template/ABI_atlas_reduced.csv"'  >> bash_env.sh

# If using qsub to submit parallel jobs. Not sure this is fully implemented everywhere in the code :-()
echo 'qsub_env=TRUE' >> bash_env.sh
```

### Loading the R main variables   
either install the packages manually, or use packrat package version manager (see [README](README.md) )   

```{r load main variables and pacakges, eval=FALSE}
library('stringr')
library('ggplot2')
require('svglite')
library('nat')
library('oro.nifti')
library('reshape2')
library('extrafont')
library('multcomp')
library('parameters')
library('effectsize')
library('reshape2')

#set the same variables as for bash_env.sh

init_folder <- "/home/traaffneu/joagra/code/insula"
data_folder <- "/project/4180000.18"

study_folder <- paste(data_folder, "/rest", sep='')
roi_folder <- paste(data_folder, "/SBA_roi", sep='')
SBA.folder <- paste(study_folder, '/SBA/', sep = '')
viral.folder <- paste(study_folder, "tracer", sep='')

template_mask <- "assets/template/mask_200um.nii"
template <- "assets/template/ABI_template_200um.nii"
atlas <- "assets/template/ABI_atlas_reduced_TIDO_200um.nii.gz"
atlas.label <- "assets/template/ABI_atlas_reduced_TIDO.csv"

study <- read.csv(paste(study_folder,'/participants.tsv',sep='')
study <- study[!study$dataset %in% c('aes1', 'MEPSI', 'AD1', 'ME1'), ]
```


### Download AIBS template and mask
The templates and atlases used are found [here](assests/template/). Please note that the use of AIBS templates is limited to academic use. Private use permission needs to be requested at the AIBS. 

### Download preprocessed mouse resting-state fMRI data
The preprocessed data is available from the [Donders data repository](https://doi.org/10.34973/1he1-5c70)
Save repository content to `study_folder`

### Download the raw optogenetics insula data and the mouseMRIPrep code used to preprocess
```{bash download Insula from openneuro, eval=FALSE}
source bash_env.sh
cd $data_folder

mkdir optoINS
aws s3 sync --no-sign-request s3://openneuro.org/ds003464 ds003464-download/
mv ds003464-download/ bids
```

### Download the raw optogenetics dorsal raphe data
```{bash download DR from openneuro, eval=FALSE}
source bash_env.sh
cd $data_folder

mkdir optoDR
aws s3 sync --no-sign-request s3://openneuro.org/ds001541 ds001541-download/
mv ds001541-download/ bids
```

### Download MouseMRIPrep data
Preprocess the optoDR and optoINS according to the scripts there. 
```{bash download from github, eval=FALSE}
source bash_env.sh
cd $data_folder

mkdir script
cd script
git clone https://github.com/grandjeanlab/MouseMRIPrep.git
```

### Download S1200 Human connectome data
Access and download of the S1200 is made through to the [S1200 HCP platform](https://db.humanconnectome.org/)

### Download Macaque resting-state fMRI data
Access to the macaque fMRI data can be obtained through collaborator dr. Rogier Mars.   
Preprocess using MouseMRIPrep.   



### Download viral tracer data
The data are downloaded from the AIBS. Some restrictions may apply. 
```{r download viral tracer, eval=FALSE}


dir.create(file.path(viral.folder, 'nrrd'),
           showWarnings = F,
           recursive = T)
dir.create(file.path(viral.folder, 'nifti'),
           showWarnings = F,
           recursive = T)

viral.list <- read.csv('assets/table/projection_search_results.csv')
nifti.dir <- dir(file.path(viral.folder, 'nifti'))
nifti.dir <- sub('\\.nii.gz$', '', nifti.dir)

viral.list <- viral.list[!viral.list$id %in% nifti.dir, ]

for (i in 1:dim(viral.list)[1]) {
  tracer.url <-
    paste(
      'http://api.brain-map.org/grid_data/download_file/',
      viral.list$id[i],
      '??image=projection_density&resolution=50',
      sep = ''
    )
  tracer.nrrd <-
    file.path(viral.folder, 'nrrd', paste(viral.list$id[i], '.nrrd', sep = ''))
  tracer.nifti <-
    file.path(viral.folder, 'nifti', paste(viral.list$id[i], sep = ''))
  err <- try(download.file(tracer.url, tracer.nrrd, quiet = TRUE))
  if (class(err) == "try-error")
    next
  #read nrrd tracer file
  tracer.nrrd.file <- read.nrrd(tracer.nrrd)
  #convert nrrd tracer file to nifit
  img.nifti <-
    nifti(flip(flip(aperm(
      tracer.nrrd.file[, , ], c(3, 1, 2)
    ), 2), 3), datatype = 16)
  pixdim(img.nifti) <-
    c(0, diag(read.nrrd.header(tracer.nrrd)$`space directions`) / 1000, 1, 1, 1, 1)
  writeNIfTI(img.nifti, tracer.nifti, warn = -1)
}

```

### Generate seeds for the mouse brain
This chuck will generate 3 seeds, in the anterior insular area (aAI), anterior cingulate area (ACA), and primary motor area (MOp). 
```{bash generate SBA seeds, eval=FALSE}
source bash_env.sh
mkdir -p $roi_folder'/200um'

cd $roi_folder'/200um'

sphere=0.3

fslmaths ${template} -mul 0 -add 1 -roi 15 1 48 1 17 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin aAI
rm tmp.nii.gz

fslmaths ${template} -mul 0 -add 1 -roi 26 1 42 1 29 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin ACA
rm tmp.nii.gz

fslmaths ${template} -mul 0 -add 1 -roi 17 1 48 1 27 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin MOp
rm tmp.nii.gz


#do the same but at 50um

mkdir -p $roi_folder'/50um'

cd $roi_folder'/50um'
3dresample -input ../200um/aAI.nii.gz -prefix aAI.nii.gz -master ${template_50}
3dresample -input ../200um/ACA.nii.gz -prefix ACA.nii.gz -master ${template_50}
3dresample -input ../200um/MOp.nii.gz -prefix MOp.nii.gz -master ${template_50}
```

### generate seeds for the human brain
This chuck generates corresponding seeds in the human brain. 
MNI assets need to be downloaded separately. 
```{bash generate human seeds, eval=FALSE}
source bash_env.sh
FSLDIR='/opt/fsl/6.0.0'
template='/project/4180000.18/Human/template_7T/MNI152_T1_16mm.nii.gz'
template_mask='/project/4180000.18/Human/template_7T/MNI152_T1_16mm_brain_mask.nii.gz'
root_dir='/project/4180000.18/Human'
roi_folder=$root_dir'/ROI_7T'


mkdir -p $root_dir'/script'

mkdir -p $roi_folder

cd $roi_folder

sphere=4

fslmaths ${template} -mul 0 -add 1 -roi 63 1 68 1 37 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin aAI
rm tmp.nii.gz

fslmaths ${template} -mul 0 -add 1 -roi 67 1 76 1 54 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin dlpfc
rm tmp.nii.gz

fslmaths ${template} -mul 0 -add 1 -roi 48 1 86 1 47 1 0 1 tmp
fslmaths tmp -kernel sphere ${sphere} -fmean -bin ACA
```