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

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

```{r eval=TRUE, echo=FALSE}
library(neuroSCC)
```

# Introduction

This vignette demonstrates a minimal example of performing a **group vs. group** SCC analysis using the `neuroSCC` package.

It is recommended that you first complete the ["Getting Started"](landing_vignette.html) vignette. If you haven't, the following section will guide you through the necessary data preparation.

---

# Data Preparation (Conditional)

First, let's conditionally prepare the required data (control and pathological matrices). We use sample data included in the package.

```{r}

# Recreate necessary data from sample files
cat("Creating sample data for 2-group comparison...\n")

# Create databases for Control and Pathological groups
databaseControls <- databaseCreator(pattern = "^syntheticControl[12]\\.nii\\.gz$", control = TRUE, quiet = TRUE)
databasePathological <- databaseCreator(pattern = "^syntheticPathological[12]\\.nii\\.gz$", control = FALSE, quiet = TRUE)

# Create matrices suitable for SCC
matrixControls <- matrixCreator(databaseControls, paramZ = 35, quiet = TRUE)
matrixPathological <- matrixCreator(databasePathological, paramZ = 35, quiet = TRUE)

# Normalize matrices
normalizedControls <- meanNormalization(matrixControls)
normalizedPathological <- meanNormalization(matrixPathological)

# Extract contours from a control subject for SCC triangulation
niftiPath <- system.file("extdata", "syntheticControl1.nii.gz", package = "neuroSCC")
contours <- neuroContour(niftiPath, paramZ = 35, plotResult = FALSE)

cat("Data preparation completed successfully.\n")

```

---

# SCC Estimation (Group vs Group)

This step requires the external `ImageSCC` package, currently not on CRAN. Ensure you have this package installed. If not, install it using:

```{r}

if (requireNamespace("ImageSCC", quietly = TRUE)) {
  message("'ImageSCC' package is available.")
} else {
  message("This vignette requires the 'ImageSCC' package.")
  message("You can install it from GitHub with:")
  message("  remotes::install_github('FIRST-Data-Lab/ImageSCC')")
}

```

The SCC estimation step is computationally intensive and thus typically skipped in vignette demonstrations. Below, we conditionally load a precomputed SCC result provided with the package.


```{r eval = requireNamespace("ImageSCC", quietly = TRUE), echo=TRUE}

# Check for Triangulation package
triangulation_available <- requireNamespace("Triangulation", quietly = TRUE)

if (triangulation_available) {
  message("'Triangulation' package is available.")
} else {
  message("'Triangulation' package not available.")
  message("Install with: remotes::install_github('FIRST-Data-Lab/Triangulation')")
}

# Proceed only if both packages are available
if (triangulation_available) {

  # Try loading precomputed SCC object from data/
  if (!exists("SCCcomp", inherits = FALSE) &&
      "SCCcomp" %in% data(package = "neuroSCC")$results[, "Item"]) {
    
    message("Loading precomputed SCC group comparison from package data...")
    suppressMessages(data("SCCcomp", package = "neuroSCC"))

  } else if (!exists("SCCcomp", inherits = FALSE)) {

    message("Precomputed data not found. Running SCC estimation...")

    # Perform SCC computation (only for development)
    SCCcomp <- ImageSCC::scc.image(
      Ya = normalizedPathological,
      Yb = normalizedControls,
      Z = contours[[1]],
      d.est = 5,
      d.band = 2,
      r = 1,
      V.est.a = as.matrix(contours[[1]]),
      Tr.est.a = as.matrix(contours[[1]]),
      V.band.a = as.matrix(contours[[1]]),
      Tr.band.a = as.matrix(contours[[1]]),
      penalty = TRUE,
      lambda = 10^{seq(-6, 3, 0.5)},
      alpha.grid = c(0.10, 0.05, 0.01),
      adjust.sigma = TRUE
    )
  }
}


```

```{r eval=TRUE}
if (!exists("SCCcomp", inherits = FALSE)) {
  data("SCCcomp", package = "neuroSCC")
}
```

---

# Visualizing Group Means and SCC Differences

Once the SCC result is available, it is often useful to visualize both group mean estimates together with the SCC-detected differences. The panel below provides a compact summary of the two-group comparison.

```{r eval=TRUE, fig.alt="Two-group SCC comparison panel"}
plotSCCcomparisonPanel(
  scc = SCCcomp,
  title = "SCC COMPARISON PANEL"
)
```

---

# Extracting Significant Points and Evaluating Metrics

With the SCC results (`SCCcomp`) loaded, we extract the significant regions and evaluate their performance against known ground truth ROIs.

```{r eval=TRUE}
# Extract significant points from SCC results
significantPoints <- getPoints(SCCcomp)

# Load true ROI data provided within the package
roi_path <- system.file("extdata", "ROIsample_Region2_18.nii.gz", package = "neuroSCC")
trueROI <- processROIs(roi_path, region = "Region2", number = "18", save = FALSE)

# Get total coordinate dimensions
dimensions <- getDimensions(roi_path)
totalCoords <- expand.grid(x = 1:dimensions$xDim, y = 1:dimensions$yDim)

# Calculate metrics to evaluate detection performance
metrics <- calculateMetrics(
  detectedPoints = significantPoints$positivePoints,
  truePoints = trueROI,
  totalCoords = dimensions,
  regionName = "Group_vs_Group"
)

# Display calculated metrics
print(metrics)
```

---

# Visual Validation Against ROI and SPM

In addition to numerical metrics, it can be useful to visually compare the ground-truth ROI, SCC detections, and SPM detections over the same anatomical background. The following panel provides that comparison.

```{r eval=TRUE, fig.alt="Validation panel comparing ROI, SCC, and SPM detections"}
paramZ <- 35

controlPattern <- "^syntheticControl.*\\.nii\\.gz$"
databaseCN <- databaseCreator(pattern = controlPattern, control = TRUE, quiet = TRUE)
matrixCN <- matrixCreator(database = databaseCN, paramZ = paramZ, quiet = TRUE)
matrixCN <- meanNormalization(matrixCN)

roiFile <- system.file("extdata", "ROIsample_Region2_18.nii.gz", package = "neuroSCC")
truePoints <- processROIs(roiFile, region = "Region2", number = "18", save = FALSE)
roiPoints <- subset(truePoints, z == paramZ & pet == 1, select = c("x", "y"))

spmFile <- system.file("extdata", "binary.nii.gz", package = "neuroSCC")
spmPoints <- getSPMbinary(spmFile, paramZ = paramZ)

plotValidationPanel(
  template = roiFile,
  backgroundMatrix = matrixCN,
  roiPoints = roiPoints,
  sccPoints = list(
    positivePoints = getPoints(SCCcomp)$positivePoints,
    negativePoints = data.frame(x = numeric(0), y = numeric(0))
  ),
  spmPoints = spmPoints,
  title = "Performance Validation Panel",
  label1 = "Ground Truth (ROI)",
  label2 = "SCC Detected",
  label3 = "SPM Detected"
)
```

---

# Conclusion

In this vignette, you've seen a concise example of conducting a **group vs group SCC analysis** using the `neuroSCC` package. We've used sample data provided by the package to illustrate the workflow clearly, focusing on practical application and evaluation of results. 

Actual SCC computations are computationally intensive and thus skipped in this vignette. Instead, we've loaded precomputed results. You can adapt this template for your own datasets, adjusting parameters and experimenting further according to your specific research needs.
