% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/vismat.R
\name{vismat}
\alias{vismat}
\title{Visualize Relationship Matrices}
\usage{
vismat(
  mat,
  ped = NULL,
  type = "heatmap",
  ids = NULL,
  reorder = TRUE,
  by = NULL,
  grouping = NULL,
  labelcex = NULL,
  ...
)
}
\arguments{
\item{mat}{A relationship matrix. Can be one of the following types:
\itemize{
  \item A \code{pedmat} object returned by \code{\link{pedmat}} — including
        compact matrices. When \code{by} is specified, group-level means are
        computed directly from the compact matrix (no full expansion needed).
        Without \code{by}, compact matrices are automatically expanded to
        full dimensions before plotting (see Details).
  \item A \code{\link{tidyped}} object (automatically calculates additive
        relationship matrix A).
  \item A named list containing matrices (preferring A, D, AA).
  \item A standard \code{matrix} or \code{Matrix} object.
}
\strong{Note}: Inverse matrices (Ainv, Dinv, AAinv) are not supported for 
visualization because their elements do not represent meaningful relationship
coefficients.}

\item{ped}{Optional. A tidied pedigree object (\code{tidyped}), used for 
extracting labels or grouping information. Required when using the 
\code{by} parameter with a plain matrix input. If \code{mat} is a 
\code{pedmat} object, the pedigree is extracted automatically.}

\item{type}{Character, type of visualization. Supported options:
\itemize{
  \item \code{"heatmap"}: Relationship matrix heatmap (default). Uses a 
        Nature Genetics style color palette (white-orange-red-dark red),
        with optional hierarchical clustering and group aggregation.
  \item \code{"histogram"}: Distribution histogram of relationship coefficients.
        Shows the frequency distribution of lower triangular elements (pairwise kinship).
}}

\item{ids}{Character vector specifying individual IDs to display. Used to 
filter and display a submatrix of specific individuals. If \code{NULL} 
(default), all individuals are shown.}

\item{reorder}{Logical. If \code{TRUE} (default), rows and columns are 
reordered using hierarchical clustering (Ward.D2 method) to bring closely 
related individuals together. Only affects heatmap visualization. 
Automatically skipped for large matrices (N > VISMAT_REORDER_MAX, default 2 000)
to improve performance.

\strong{Clustering principle}: Based on relationship profile distance (Euclidean
distance between rows). Full-sibs have nearly identical relationship profiles
with the whole population, so they cluster tightly together and appear as
contiguous blocks in the heatmap.}

\item{by}{Optional. Column name in \code{ped} to group by (e.g., 
\code{"Family"}, \code{"Gen"}, \code{"Year"}). When grouping is enabled:
\itemize{
  \item Individual-level matrix is aggregated to a group-level matrix 
        (computing mean relationship coefficients between groups).
  \item For \code{"Family"} grouping, founders without family assignment are excluded.
  \item For other grouping columns, NA values are assigned to an \code{"Unknown"} group.
}
Useful for visualizing population structure in large pedigrees.}

\item{grouping}{\code{[Deprecated]} Use \code{by} instead.}

\item{labelcex}{Numeric. Manual control for font size of individual labels. 
If \code{NULL} (default), uses a dynamic font size that adjusts automatically 
based on matrix dimensions (range 0.2–0.7). Labels are hidden automatically
when N > VISMAT_LABEL_MAX (default 500).}

\item{...}{Additional arguments passed to the underlying plotting function:
\itemize{
  \item Heatmap uses \code{\link[lattice]{levelplot}}: can set \code{main},
        \code{xlab}, \code{ylab}, \code{col.regions}, \code{colorkey},
        \code{scales}, etc.
  \item Histogram uses \code{\link[lattice]{histogram}}: can set \code{main},
        \code{xlab}, \code{ylab}, \code{nint} (number of bins), etc.
}}
}
\value{
Invisibly returns the \code{lattice} plot object. The plot is 
rendered on the current graphics device.
}
\description{
\code{vismat} provides visualization tools for relationship matrices (A, D, AA),
supporting individual-level heatmaps and relationship coefficient histograms.
This function is useful for exploring population genetic structure, identifying
inbred individuals, and analyzing kinship between families.
}
\details{
\subsection{Compact Matrix Handling}{
When \code{mat} is a compact \code{pedmat} object (created with
\code{pedmat(..., compact = TRUE)}):
\itemize{
  \item \strong{With \code{by}}: Group-level mean relationships are computed
        algebraically from the K×K compact matrix, including a correction for
        sibling off-diagonal values. This avoids expanding to the full N×N
        matrix, making family-level or generation-level visualization feasible
        even for pedigrees with hundreds of thousands of individuals.
  \item \strong{Without \code{by}, N > VISMAT_EXPAND_MAX (5 000)}: The compact K\eqn{\times}K matrix
        is plotted directly using representative individuals. Labels show the
        number of individuals each representative stands for, e.g.,
        \code{"ID (\u00d7350)"}. This avoids memory-intensive full expansion.
  \item \strong{Without \code{by}, N \eqn{\le} 5 000}: The compact matrix is
        expanded via \code{\link{expand_pedmat}} to restore full dimensions.
}
}

\subsection{Heatmap}{
\itemize{
  \item Uses a Nature Genetics style color palette (white to orange to red to dark red).
  \item Hierarchical clustering reordering (Ward.D2) is enabled by default.
  \item Grid lines shown when N \eqn{\le} VISMAT_GRID_MAX (100);
        labels shown when N \eqn{\le} VISMAT_LABEL_MAX (500).
  \item \code{mat[1,1]} is displayed at the top-left corner.
}
}

\subsection{Histogram}{
\itemize{
  \item Shows the distribution of lower-triangular elements (pairwise kinship).
  \item X-axis: relationship coefficient values; Y-axis: frequency percentage.
}
}

\subsection{Performance}{
The following automatic thresholds are defined as package-internal
constants (\code{VISMAT_*}) at the top of \code{R/vismat.R}:
\itemize{
  \item Passing a \code{tidyped} object together with \code{by} uses
        matrix-free additive relationship products to compute the grouped
        heatmap directly, without constructing the full individual-level
        relationship matrix.
  \item \code{VISMAT_EXPAND_MAX} (5 000): compact matrices with original
        N above this are shown in representative view instead of expanding.
  \item \code{VISMAT_REORDER_MAX} (2 000): hierarchical clustering is
        automatically skipped.
  \item \code{VISMAT_LABEL_MAX} (500): individual labels are hidden.
  \item \code{VISMAT_GRID_MAX} (100): cell grid lines are hidden.
  \item \code{by} grouping uses vectorized \code{rowsum()} algebra — suitable
        for large matrices.
}
}

\subsection{Interpreting Relationship Coefficients}{
For the additive relationship matrix A:
\itemize{
  \item Diagonal elements = 1 + F (F = inbreeding coefficient).
  \item Off-diagonal elements = 2 × kinship coefficient.
  \item 0: unrelated; 0.25: half-sibs / grandparent–grandchild;
        0.5: full-sibs / parent–offspring; 1.0: same individual.
}
}
}
\examples{
library(visPedigree)
data(small_ped)
ped <- tidyped(small_ped)

# ============================================================
# Basic Usage
# ============================================================

# Method 1: from tidyped object (auto-computes A)
vismat(ped)

# Method 2: from pedmat object
A <- pedmat(ped)
vismat(A)

# Method 3: from plain matrix
vismat(as.matrix(A))

# ============================================================
# Compact Pedigree (auto-expanded before plotting)
# ============================================================

# For pedigrees with large full-sib families, compute a compact matrix
# first for efficiency, then pass directly to vismat() — it automatically
# expands back to full dimensions.
A_compact <- pedmat(ped, compact = TRUE)
vismat(A_compact)   # prints: "Expanding compact matrix (N -> M individuals)"

# For very large pedigrees, aggregate to a group-level view instead
vismat(A, ped = ped, by = "Gen",
       main = "Mean Relationship Between Generations")

# ============================================================
# Heatmap Customization
# ============================================================

# Custom title and axis labels
vismat(A, main = "Additive Relationship Matrix",
       xlab = "Individual", ylab = "Individual")

# Preserve original pedigree order (no clustering)
vismat(A, reorder = FALSE)

# Custom label font size
vismat(A, labelcex = 0.5)

# Custom color palette (blue-white-red)
vismat(A, col.regions = colorRampPalette(c("blue", "white", "red"))(100))

# ============================================================
# Display a Subset of Individuals
# ============================================================

target_ids <- rownames(A)[1:8]
vismat(A, ids = target_ids)

# ============================================================
# Histogram of Relationship Coefficients
# ============================================================

vismat(A, type = "histogram")
vismat(A, type = "histogram", nint = 30)

# ============================================================
# Group-level Aggregation
# ============================================================

# Group by generation
vismat(A, ped = ped, by = "Gen",
       main = "Mean Relationship Between Generations")

# Group by full-sib family (founders without a family are excluded)
vismat(A, ped = ped, by = "Family")

# ============================================================
# Other Relationship Matrices
# ============================================================

# Dominance relationship matrix
D <- pedmat(ped, method = "D")
vismat(D, main = "Dominance Relationship Matrix")

}
\seealso{
\code{\link{pedmat}} for computing relationship matrices,
\code{\link{expand_pedmat}} for manually restoring compact matrix dimensions,
\code{\link{query_relationship}} for querying individual pairs,
\code{\link{tidyped}} for tidying pedigree data,
\code{\link{visped}} for visualizing pedigree structure graphs,
\code{\link[lattice]{levelplot}}, \code{\link[lattice]{histogram}}
}
