---
title: "Package usage: radtools"
author: "Pamela Russell"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Radtools usage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
suppressPackageStartupMessages(library(knitr))
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  warning = FALSE
)
```

```{r suppress_eval, echo = FALSE}
# Check if this is running locally and if not, suppress evaluation
if(!utils::file_test("-f", "~/Dropbox/radtools_vignette_data/prostate/000008.dcm")) {
  knitr::opts_chunk$set(eval = FALSE)
  message("Note: code examples will not be evaluated because they depend on local data.")
}
```

# Overview

`radtools` provides utilities to explore images in the two leading medical image formats: [DICOM](https://www.dicomstandard.org/) and [NIfTI](https://nifti.nimh.nih.gov/). Where possible, generic functions seamlessly handle both formats. When necessary or useful, specialized functions are provided for a specific image format. This vignette demonstrates how to read image data into R, extract data and metadata, and view images.

# Image file formats

## DICOM

DICOM (Digital Imaging and Communication in Medicine) is a standard for management of medical images and image metadata. The [DICOM standard](https://www.dicomstandard.org/current/) specifies a file format definition. Each DICOM file includes optional pixel data and embedded metadata. Typically, each DICOM file contains one two-dimensional image slice. Radtools also supports DICOM files that do not contain pixel data.

DICOM metadata is embedded in each file and allows image series to be reconstructed from multiple files via shared metadata identifying the patient, etc. DICOM files can be analyzed individually, or a directory containing an entire image series can be analyzed as one three-dimensional image.

## NIfTI

NIfTI (Neuroimaging Informatics Technology Initiative) format is an adaptation of the previous ANALYZE format that solves several challenges with the older format. NIfTI images can be a single file containing the image and metadata (`.nii`) or pair of files storing the image and metadata separately (`.hdr`/`.img`), and can be compressed. Image data can have up to seven dimensions. The first three dimensions are reserved for spatial dimensions and the optional fourth dimension defines time points. Unlike DICOM format, the NIfTI format specifies a constant-size header with a fixed set of metadata attributes.

[This article](https://brainder.org/2012/09/23/the-nifti-file-format/) provides an excellent introduction to NIfTI-1 format.

Our package supports NIfTI-1 format. The recently developed NIfTI-2 is very similar to NIfTI-1, and permits storage of more datapoints in each dimension. NIfTI-2 is not bitwise compatible with NIfTI-1. We will add support for NIfTI-2 if demand exists. [This article](https://brainder.org/2015/04/03/the-nifti-2-file-format/) provides more background on the differences between NIfTI-1 and NIfTI-2.


# Import the package

```{r import_package, warning = FALSE}
library(radtools)
```


# Reading data from files

## DICOM

The `read_dicom` function reads a DICOM dataset from a single file or a directory containing multiple slices. The returned value is a list with attributes `hdr` and `img`, each with an element for each slice of the image.

Read a single slice from one `.dcm` file:

```{r read_dicom_single_file}
dicom_data_2d <- read_dicom("~/Dropbox/radtools_vignette_data/prostate/000008.dcm")
names(dicom_data_2d)
```

Read a 3D image from a directory containing one `.dcm` file per slice:

```{r read_dicom_dir}
dicom_data_3d <- read_dicom("~/Dropbox/radtools_vignette_data/prostate/")
names(dicom_data_3d)
```


## NIfTI

NIfTI format uses one `.nii` file or two files (`.hdr` and `.img`) to capture an entire image series. The files can be gzipped or not.

The `read_nifti1` function handles any of these cases, and returns a list containing one element of class `nifti`.

Read a 3D NIfTI image from `.hdr` and `.img` files:

```{r read_nifti_3d}
nifti_data_3d <- read_nifti1("~/Dropbox/radtools_vignette_data/avg152T1_LR_nifti")
```

Read a 4D NIfTI image from a `.nii.gz` file:

```{r read_nifti_4d}
nifti_data_4d <- read_nifti1("~/Dropbox/radtools_vignette_data/filtered_func_data.nii.gz")
```


# Extracting image metadata

## Generic metadata functions

Get image dimensions or number of slices:

```{r img_dim}
img_dimensions(dicom_data_2d)
num_slices(dicom_data_2d)
img_dimensions(dicom_data_3d)
num_slices(dicom_data_3d)
img_dimensions(nifti_data_3d)
num_slices(nifti_data_3d)
img_dimensions(nifti_data_4d)
num_slices(nifti_data_4d)
```

A typical DICOM dataset will only use a subset of the available metadata attributes, while NIfTI headers always include the same set of attributes. Get the actual metadata attributes for a dataset:

```{r header_fields}
header_fields_dicom <- header_fields(dicom_data_3d)
head(header_fields_dicom)
header_fields(nifti_data_3d)
```

The `header_value` function returns the attribute value for a given header attribute. If the dataset is a DICOM dataset with multiple slices, it returns a vector of values across slices. NIfTI datasets do not have slice-specific metadata.

```{r header_value}
header_value(dicom_data_2d, "SliceLocation")
header_value(dicom_data_3d, "SliceLocation")
header_value(nifti_data_3d, "dim_")
header_value(nifti_data_4d, "dim_")
```

## DICOM-specific metadata functions

Each DICOM file has its own header containing metadata for one slice.

Get the metadata for all slices as a matrix, where rows are attributes and columns are slices:

```{r dicom_header_as_mat, warning = FALSE}
dicom_metadata_matrix <- dicom_header_as_matrix(dicom_data_3d)
kable(dicom_metadata_matrix[1:10, 1:6])
```

Many metadata attributes will be identical for all slices. Get a list of these contstant attributes and their values:

```{r dicom_const}
const_attributes <- dicom_constant_header_values(dicom_data_3d)
head(const_attributes)
```

## NIfTI-specific metadata functions

As NIfTI images can have more than three dimensions, a simple function returns the number of dimensions:

```{r nifti_dim}
nifti1_num_dim(nifti_data_3d)
nifti1_num_dim(nifti_data_4d)
```

A function is provided to get all metadata attributes and values as a named list:

```{r nifti_header_val}
nifti_header_vals <- nifti1_header_values(nifti_data_4d)
# Display the first few metadata values other than the image itself
head(nifti_header_vals[names(nifti_header_vals) != ".Data"])
```

# Extracting image data

The image itself can be extracted as a matrix of pixel intensities using a generic function:

```{r img_data_to_mat}
mat_dicom_2d <- img_data_to_mat(dicom_data_2d)
dim(mat_dicom_2d)
mat_dicom_3d <- img_data_to_mat(dicom_data_3d)
dim(mat_dicom_3d)
mat_nifti_3d <- img_data_to_mat(nifti_data_3d)
dim(mat_nifti_3d)
mat_nifti_4d <- img_data_to_mat(nifti_data_4d)
dim(mat_nifti_4d)
```

For images with more than three dimensions (e.g. some NIfTI datasets), you can hold the additional dimensions constant and just get a 3D matrix by selecting a single coordinate for each dimension:

```{r img_data_to_3d_mat}
mat_nifti_4d_to_3d <- img_data_to_3D_mat(nifti_data_4d, coord_extra_dim = 90)
dim(mat_nifti_4d_to_3d)
```


# Viewing images

The `view_slice` function is generic and works for DICOM or NIfTI data.

View a single-slice dataset:

```{r view_slice_single, fig.width = 5, fig.height = 5}
view_slice(dicom_data_2d)
```

View one slice of a 3D image:

```{r view_slice_dir, warning = FALSE, fig.width = 5, fig.height = 5}
view_slice(dicom_data_3d, slice = 10)
view_slice(nifti_data_3d, slice = 20)
```

A function is also provided to view a slice of an intensity matrix instead of a DICOM or NIfTI data object. In particular, this is useful for viewing slices of NIfTI images with more than three dimensions. In that case, you can create a 3D matrix by holding extra dimensions constant using `img_data_to_3D_mat`, then pass that matrix to `view_slice_mat`.

```{r view_slice_mat, fig.width = 5, fig.height = 5}
view_slice_mat(mat_nifti_4d_to_3d, slice = 10)
```

# Other functionality

## Exploring the DICOM standard

Several functions are provided to explore aspects of the DICOM standard itself. These functions do not use or analyze any actual data.

Get the DICOM standard version reported here, the web URL describing the standard, and the time it was accessed during package development:

```{r dicom_standard_version}
dicom_standard_version()
dicom_standard_web()
dicom_standard_timestamp()
```

The DICOM standard specifies a tag, name, and keyword for each allowable metadata attribute. The following functions return complete lists of these attributes. These functions are self-contained and the orderings of the returned lists do not correspond.

Tags:

```{r tags}
tags <- dicom_all_valid_header_tags()
length(tags)
head(tags, 10)
```

Names:

```{r names}
names <- dicom_all_valid_header_names()
length(names)
head(names, 10)
```

Keywords:

```{r keywords}
keywords <- dicom_all_valid_header_keywords()
length(keywords)
head(keywords, 10)
```

You can also search the DICOM standard for attribute names and keywords matching a given string. 

```{r dicom_std_search}
dicom_search_header_names("manufacturer")
dicom_search_header_keywords("manufacturer")
```

# Session info

```{r session_info}
sessionInfo()
```
