---
title: "Introduction to spant"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to spant}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 5
)
```

## Reading raw data and plotting
Load the spant package:
```{r, message = FALSE}
library(spant)
```

Get the path to a data file included with spant:
```{r}
fname <- system.file("extdata", "philips_spar_sdat_WS.SDAT", package = "spant")
```

Read the file and save to the workspace as ``mrs_data``:
```{r}
mrs_data <- read_mrs(fname, format = "spar_sdat")
```

Output some basic information about the data:
```{r}
print(mrs_data)
```

Plot the spectral region between 5 and 0.5 ppm:
```{r}
plot(mrs_data, xlim = c(5, 0.5))
```

## Basic preprocessing
Apply a HSVD filter to the residual water region and align the spectrum to the tNAA resonance at 2.01 ppm:
```{r}
mrs_proc <- hsvd_filt(mrs_data)
mrs_proc <- align(mrs_proc, 2.01)
plot(mrs_proc, xlim = c(5, 0.5))
```

## Basis simulation
Simulate a typical basis set for short TE brain analysis, print some basic information and plot:
```{r, fig.height=9}
basis <- sim_basis_1h_brain_press(mrs_proc)
print(basis)
stackplot(basis, xlim = c(4, 0.5), labels = basis$names, y_offset = 5)
```

Perform ABfit analysis of the processed data (``mrs_proc``):
```{r, results = "hide"}
fit_res <- fit_mrs(mrs_proc, basis)
```

Plot the fit result: 
```{r}
plot(fit_res)
```

Extract the estimated amplitudes from ``fit_res`` and print as a ratio to total-creatine in column format:
```{r}
amps <- fit_amps(fit_res)
print(t(amps / amps$tCr))
```