---
title: "spant SVS analysis results"
output: html_document
params:
  fit_res: ""
  argg: ""
  w_ref_available: ""
  w_ref: ""
  output_ratio: ""
  res_tab_unscaled: ""
  res_tab_ratio: ""    
  res_tab_legacy: ""
  res_tab_molal: ""
  dyn_data_uncorr: ""
  dyn_data_corr: ""
  summary_tab: ""
  plot_ppm_xlim: ""
  mri: ""
  mri_seg: ""
  p_vols: ""
---

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

# {.tabset}

## Fit plots {.tabset}

```{r, results = 'asis', fig.width=7, fig.height=6}
for (n in 1:Ndyns(params$fit_res$data)) {
  cat("\n### ", n, "\n", sep = "")
  plot(params$fit_res, dyn = n, xlim = params$plot_ppm_xlim)
  cat("\n")
}
```

```{r, results = 'asis', fig.width=7, fig.height=7}
if (!is.null(dyn_data_uncorr)) {
  vline <- 2.01
  cat("## Dynamic plots {.tabset}\n")
  if (!is.null(dyn_data_corr)) {
    cat("### Spectrogram with correction\n")
    if (is.null(params$plot_ppm_xlim)) {
      image(dyn_data_corr, xlim = c(4, 0.5), vline = vline,
            vline_col = "black")
    } else {
      image(dyn_data_corr, xlim = params$plot_ppm_xlim, vline = vline,
            vline_col = "black")
    }
  }
  cat("\n\n### Spectrogram without correction\n")
  if (is.null(params$plot_ppm_xlim)) {
    image(dyn_data_uncorr, xlim = c(4, 0.5), vline = vline,
          vline_col = "black")
  } else {
    image(dyn_data_uncorr, xlim = params$plot_ppm_xlim, vline = vline,
          vline_col = "black")
  }
  if (!is.null(dyn_data_corr)) {
    cat("\n\n### Mean subtracted spectrogram\n")
    if (is.null(params$plot_ppm_xlim)) {
      image(sub_mean_dyns(dyn_data_corr), xlim = c(4, 0.5))
    } else {
      image(sub_mean_dyns(dyn_data_corr), xlim = params$plot_ppm_xlim)
    }
  }
}
```

```{r, results = 'asis', fig.width=7, fig.height=7}
if (!is.null(params$mri) | !is.null(params$mri_seg)) {
  cat("## MRI {.tabset}\n")
}
```

```{r, results = 'asis', fig.width=7, fig.height=7}
if (!is.null(params$mri)) {
  cat("### Voxel position\n")
  voi <- get_svs_voi(params$fit_res$data, params$mri)
  plot_voi_overlay(params$mri, voi)
}
```

```{r, results = 'asis', fig.width=7, fig.height=7}
if (!is.null(params$mri_seg)) {
  cat("### Voxel segmetation\n")
  voi <- get_svs_voi(params$fit_res$data, params$mri_seg)
  seg_vols <- plot_voi_overlay_seg(params$mri_seg, voi)
}
```

## Spectral plots {.tabset}

### Mean processed cropped
```{r, fig.width=7, fig.height=6}
phase_offset <- params$fit_res$res_tab$phase
shift_offset <- params$fit_res$res_tab$shift
proc_spec <- phase(mean_dyns(params$fit_res$data), mean(phase_offset))
proc_spec <- shift(proc_spec, mean(shift_offset), units = "ppm")
proc_spec <- zf(proc_spec)

if (is.null(params$plot_ppm_xlim)) {
  plot(proc_spec, xlim = c(4, 0.2))
} else {
  plot(proc_spec, xlim = params$plot_ppm_xlim)
}
```

### Mean processed full
```{r, fig.width=7, fig.height=6}
plot(proc_spec)
```

```{r, results = 'asis', fig.width=7, fig.height=6}
if (params$w_ref_available) {
  cat("### Water reference resonance\n")
  # w_ref_proc <- shift(w_ref, shift_offset, units = "ppm")
  # w_ref_proc <- auto_phase(w_ref, xlim = c(5.3, 4))
  w_ref_proc <- auto_phase_bl(w_ref, ppm_start = c(5.2, 4.0),
                              ppm_end = c(5.3, 4.1), xlim = c(5.2, 4.1))
  
  w_ref_proc <- zf(w_ref_proc)
  plot(w_ref_proc, xlim = c(5.3, 4))
}
```

## Diagnostics
```{r, results = 'asis'}
name  <- NULL
value <- NULL

if (!is.null(params$fit_res$res_tab$SNR)) {
  name  <- c(name, "Mean spectral signal to noise ratio")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$SNR), 2))
}

if (!is.null(params$fit_res$res_tab$SRR)) {
  name  <- c(name, "Mean spectral signal to residual ratio")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$SRR), 2))
}

if (!is.null(params$fit_res$res_tab$FWHM)) {
  name  <- c(name, "Mean spectral linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$FWHM), 4))
}

if (!is.null(params$fit_res$res_tab$tNAA_lw)) {
  name  <- c(name, "Mean tNAA linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$tNAA_lw), 4))
}

if (!is.null(params$fit_res$res_tab$NAA_lw)) {
  name  <- c(name, "Mean NAA linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$NAA_lw), 4))
}

if (!is.null(params$fit_res$res_tab$tCho_lw)) {
  name  <- c(name, "Mean tCho linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$tCho_lw), 4))
}

if (!is.null(params$fit_res$res_tab$Cho_lw)) {
  name  <- c(name, "Mean Cho linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$Cho_lw), 4))
}

if (!is.null(params$fit_res$res_tab$tCr_lw)) {
  name  <- c(name, "Mean tCr linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$tCr_lw), 4))
}

if (!is.null(params$fit_res$res_tab$Cr_lw)) {
  name  <- c(name, "Mean Cr linewidth (ppm)")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$Cr_lw), 4))
}

# if (!is.null(params$fit_res$res_tab$phase)) {
#   name  <- c(name, "Zero-order phase (degrees)")
#   value <- c(value, round_dp(params$fit_res$res_tab$phase, 1))
# }

# if (!is.null(params$fit_res$res_tab$phi1)) {
#   name  <- c(name, "First-order phase (ms)")
#   value <- c(value, round_dp(params$fit_res$res_tab$phi1, 3))
# }

# if (!is.null(params$fit_res$res_tab$shift)) {
#   name  <- c(name, "Frequency offset (ppm)")
#   value <- c(value, round_dp(params$fit_res$res_tab$shift, 4))
# }

if (params$w_ref_available) {
  name  <- c(name,  "Mean water amplitude",
             "Mean water suppression efficiency (%)")
  value <- c(value, format(mean(params$res_tab_molal$w_amp)),
             round_dp(mean(params$res_tab_molal$ws_eff), 3))
}

if (params$fit_res$method == "ABFIT") {
  name  <- c(name, "Mean fit quality number (FQN)",
             "Mean baseline effective d.f. per ppm",
             "Mean lineshape asymmetry")
  value <- c(value, round_dp(mean(params$fit_res$res_tab$FQN), 2),
             round_dp(mean(params$fit_res$res_tab$bl_ed_pppm), 2),
             round_dp(mean(params$fit_res$res_tab$asym), 2))
}

boot_opts <- c("striped", "hover", "condensed")
diag_tab <- data.frame(name, value)
kableExtra::kable_styling(kableExtra::kbl(diag_tab, align = c("l", "r"),
                                          col.names = c("Name", "Value")),
                          full_width = FALSE, position = "left",
                          bootstrap_options = boot_opts)

if (!is.null(params$p_vols)) {
  cat("### Partial volume measures\n")
  perc_vols  <- c(params$p_vols[["WM"]], params$p_vols[["GM"]],
                  params$p_vols[["CSF"]], params$p_vols[["Other"]])
  p_vols_tab <- data.frame(type = c("WM", "GM", "CSF", "Other"),
                           perc = perc_vols)
  kableExtra::kable_styling(kableExtra::kbl(p_vols_tab, align = c("l", "r"),
                                            col.names = c("Type", "% volume")),
                            full_width = FALSE, position = "left",
                            bootstrap_options = boot_opts)
}

```

## Provenance
```{r, echo = TRUE}
packageVersion("spant")
Sys.time()
print(params$fit_res$data, full = TRUE)
print(params$w_ref, full = TRUE)
print(argg)
```

# {-}

**Please cite the following if you found ABfit and spant useful in your research:**

Wilson M. Adaptive baseline fitting for 1H MR spectroscopy analysis. Magn Reson 
Med. 2021 Jan;85(1):13-29. https://doi.org/10.1002/mrm.28385

Wilson, M. Chemical shift and relaxation regularization improve the accuracy of
1H MR spectroscopy analysis. Magn Reson Med. 2025 Jun;93(6):2287-2296.
https://doi.org/10.1002/mrm.30462

Wilson, M. spant: An R package for magnetic resonance spectroscopy 
analysis. Journal of Open Source Software. 2021 6(67), 3646. 
https://doi.org/10.21105/joss.03646

Wilson M. Robust retrospective frequency and phase correction for single-voxel 
MR spectroscopy. Magn Reson Med. 2019 May;81(5):2878-2886. 
https://doi.org/10.1002/mrm.27605