# two_group_comparison

# 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” 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.

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

    # 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)
    #>
    #>  Mean before normalization: 4.345851
    #>
    #>  Normalization completed.
    normalizedPathological <- meanNormalization(matrixPathological)
    #>
    #>  Mean before normalization: 4.240851
    #>
    #>  Normalization completed.

    # 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")
    #> Data preparation completed successfully.

# 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:

    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')")
    }
    #> 'ImageSCC' package is available.

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.

    # 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')")
    }
    #> 'Triangulation' package is available.

    # 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
        )
      }
    }

    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.

    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.

    # 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)
    #> Loading NIfTI file...

    # 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)
    #>           region sensitivity specificity      PPV      NPV
    #> 1 Group_vs_Group    85.12872    95.62596 97.22839 78.10603

# 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.

    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)
    #>
    #>  Mean before normalization: 4.345851
    #>
    #>  Normalization completed.

    roiFile <- system.file("extdata", "ROIsample_Region2_18.nii.gz", package = "neuroSCC")
    truePoints <- processROIs(roiFile, region = "Region2", number = "18", save = FALSE)
    #> Loading NIfTI file...
    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.