% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pedmatrix.R
\name{pedmat}
\alias{pedmat}
\title{Genetic Relationship Matrices and Inbreeding Coefficients}
\usage{
pedmat(
  ped,
  method = "A",
  sparse = TRUE,
  invert_method = "auto",
  threads = 0,
  compact = FALSE
)
}
\arguments{
\item{ped}{A tidied pedigree from \code{\link{tidyped}}. Must be a single
pedigree, not a splitped object. For splitped results, use 
\code{pedmat(ped_split$GP1, ...)} to process individual groups.}

\item{method}{Character, one of:
\itemize{
  \item \code{"A"}: Additive (numerator) relationship matrix (default)
  \item \code{"f"}: Inbreeding coefficients (returns named vector)
  \item \code{"Ainv"}: Inverse of A using Henderson's rules (O(n) complexity)
  \item \code{"D"}: Dominance relationship matrix
  \item \code{"Dinv"}: Inverse of D (requires matrix inversion)
  \item \code{"AA"}: Additive-by-additive epistatic matrix (A # A)
  \item \code{"AAinv"}: Inverse of AA
}}

\item{sparse}{Logical, if \code{TRUE} returns sparse Matrix (recommended for
large pedigrees). Default is \code{TRUE}.}

\item{invert_method}{Character, method for matrix inversion (Dinv/AAinv only):
\itemize{
  \item \code{"auto"}: Auto-detect and use optimal method (default)
  \item \code{"sympd"}: Force Cholesky decomposition (faster for SPD matrices)
  \item \code{"general"}: Force general LU decomposition
}}

\item{threads}{Integer. Number of OpenMP threads to use. Use 0 to keep
  the system/default setting. Currently, multi-threading is explicitly implemented for:
\itemize{
  \item \code{"D"}: Dominance relationship matrix (significant speedup).
  \item \code{"Ainv"}: Inverse of A (only for large pedigrees, n >= 5000).
}
For \code{"Dinv"}, \code{"AA"}, and \code{"AAinv"}, parallelism depends on the 
linked BLAS/LAPACK library (e.g., OpenBLAS, MKL, Accelerate) and is not 
controlled by this parameter. Methods \code{"A"} and \code{"f"} are single-threaded.}

\item{compact}{Logical, if \code{TRUE} compacts full-sibling families by
selecting one representative per family. This dramatically reduces matrix
dimensions for pedigrees with large full-sib groups. See Details.}
}
\value{
Returns a matrix or vector with S3 class \code{"pedmat"}.

\strong{Object type by method:}
\itemize{
  \item \code{method="f"}: Named numeric vector of inbreeding coefficients
  \item All other methods: Sparse or dense matrix (depending on \code{sparse})
}

\strong{S3 Methods:}
\itemize{
  \item \code{print(x)}: Display matrix with metadata header
  \item \code{\link{summary_pedmat}(x)}: Detailed statistics (size, compression, mean, density)
  \item \code{dim(x)}, \code{length(x)}, \code{Matrix::diag(x)}, \code{t(x)}: Standard operations
  \item \code{x[i, j]}: Subsetting (behaves like underlying matrix)
  \item \code{as.matrix(x)}: Convert to base matrix
}

\strong{Accessing Metadata (use \code{attr()}, not \code{$}):}
\itemize{
  \item \code{attr(x, "ped")}: The pedigree used (or compact pedigree if \code{compact=TRUE})
  \item \code{attr(x, "ped_compact")}: Compact pedigree (when \code{compact=TRUE})
  \item \code{attr(x, "method")}: Calculation method used
  \item \code{attr(x, "call_info")}: Full calculation metadata (timing, sizes, etc.)
  \item \code{names(attributes(x))}: List all available attributes
}

\strong{Additional attributes when \code{compact = TRUE}:}
\itemize{
  \item \code{attr(x, "compact_map")}: data.table mapping individuals to representatives
  \item \code{attr(x, "family_summary")}: data.table summarizing merged families
  \item \code{attr(x, "compact_stats")}: Compression statistics (ratio, n_families, etc.)
}
}
\description{
Optimized calculation of additive (A), dominance (D), epistatic (AA) 
relationship matrices, their inverses, and inbreeding coefficients (f).
Uses Rcpp with Meuwissen & Luo (1992) algorithm for efficient computation.
}
\details{
\strong{API Design:}

Only a single method may be requested per call. This design prevents
accidental heavy computations. If multiple matrices are needed, call
\code{pedmat()} separately for each method.

\strong{Compact Mode (\code{compact = TRUE}):}

Full-siblings share identical relationships with all other individuals.
Compact mode exploits this by selecting one representative per full-sib
family, dramatically reducing matrix size. For example, a pedigree with
170,000 individuals might compact to 1,800 unique relationship patterns.

Key features:
\itemize{
  \item \code{\link{query_relationship}(x, id1, id2)}: Query any individual
        pair, including merged siblings (automatic lookup)
  \item \code{\link{expand_pedmat}(x)}: Restore full matrix dimensions
  \item \code{\link{vismat}(x)}: Visualize directly (auto-expands compact)
}

\strong{Performance Notes:}
\itemize{
  \item \strong{Ainv}: O(n) complexity using Henderson's rules. Fast for any size.
  \item \strong{Dinv/AAinv}: O(n³) matrix inversion. Practical limits:
    \itemize{
      \item n < 500: ~10-20 ms
      \item n = 1,000: ~40-60 ms  
      \item n = 2,000: ~130-150 ms
      \item n > 2,000: Consider using \code{compact = TRUE}
    }
  \item \strong{Memory}: Sparse matrices use ~O(nnz) memory; dense use O(n²)
}
}
\examples{
# Basic usage with small pedigree
library(visPedigree)
tped <- tidyped(small_ped)

# --- Additive Relationship Matrix (default) ---
A <- pedmat(tped)
A["A", "B"]      # Relationship between A and B
Matrix::diag(A)  # Diagonal = 1 + F (inbreeding)

# --- Inbreeding Coefficients ---
f <- pedmat(tped, method = "f")
f["Z1"]  # Inbreeding of individual Z1

# --- Using summary_pedmat() ---
summary_pedmat(A)   # Detailed matrix statistics

# --- Accessing Metadata ---
attr(A, "ped")              # Original pedigree
attr(A, "method")           # "A"
names(attributes(A))        # All available attributes

# --- Compact Mode (for large full-sib families) ---
A_compact <- pedmat(tped, method = "A", compact = TRUE)

# Query relationships (works for any individual, including merged sibs)
query_relationship(A_compact, "Z1", "Z2")  # Full-sibs Z1 and Z2

# View compression statistics
attr(A_compact, "compact_stats")
attr(A_compact, "family_summary")

# Expand back to full size
A_full <- expand_pedmat(A_compact)
dim(A_full)  # Original dimensions restored

# --- Inverse Matrices ---
Ainv <- pedmat(tped, method = "Ainv")  # Henderson's rules (fast)

# --- Dominance and Epistatic ---
D <- pedmat(tped, method = "D")
AA <- pedmat(tped, method = "AA")

# --- Visualization (requires display device) ---
\donttest{
vismat(A)                       # Heatmap of relationship matrix
vismat(A_compact)               # Works with compact matrices
vismat(A, by = "Gen")     # Group by generation
}

}
\references{
Meuwissen, T. H. E., & Luo, Z. (1992). Computing inbreeding coefficients 
in large populations. Genetics Selection Evolution, 24(4), 305-313.

Henderson, C. R. (1976). A simple method for computing the inverse of a
numerator relationship matrix used in prediction of breeding values.
Biometrics, 32(1), 69-83.
}
\seealso{
\code{\link{tidyped}} for preparing pedigree data,
\code{\link{pedprod}} for matrix-free products with A or Ainv,
\code{\link{query_relationship}} for querying individual pairs,
\code{\link{expand_pedmat}} for restoring full dimensions,
\code{\link{vismat}} for visualization,
\code{\link{inbreed}} for simple inbreeding calculation
}
