R version: r R.version.string

skater package version: r packageVersion("skater")


Introduction

Inferring familial relationships between individuals using genetic data is a common practice in population genetics, medical genetics, and forensics. There are multiple approaches to estimating relatedness between samples, including genome-wide measures, such as those implemented in Plink [@purcell2007] or KING [@manichaikul2010], and methods that rely on identity by descent (IBD) segment detection, such as GERMLINE [@gusev2009], hap-IBD [@zhou2020], and IBIS [@seidman2020]. Recent efforts focusing on benchmarking these methods [@ramstetter2017] have been aided by tools for simulating pedigrees and genome-wide SNP data [@caballero2019]. Analyzing results from genome-wide SNP-based kinship analysis or comparing analyses to simulated data for benchmarking have to this point required writing one-off analysis functions or utility scripts that are seldom distributed with robust documentation, test suites, or narrative examples of usage. There is a need in the field for a well-documented software package with a consistent design and API that contains functions to assist with downstream manipulation, benchmarking, and analysis of SNP-based kinship assessment methods. Here we present the skater package for SNP-based kinship analysis, testing, and evaluation with R.

Methods

Implementation

The skater package provides an intuitive collection of analysis and utility functions for SNP-based kinship analysis. Functions in the package include tools for importing, parsing, and analyzing pedigree data, performing relationship degree inference, benchmarking relationship degree classification, and summarizing IBD segment data, described in full in the Use Cases section below. The package adheres to "tidy" data analysis principles, and builds upon the tools released under the tidyverse R ecosystem [@Wickham2019].

The skater package is hosted in the Comprehensive R Archive Network (CRAN) which is the main repository for R packages: http://CRAN.R-project.org/package=skater. Users can install skater in R by executing the following code:

install.packages("skater")

Alternatively, the development version of skater is available on GitHub at https://github.com/signaturescience/skater. The development version may contain new features which are not yet available in the version hosted on CRAN. This version can be installed using the install_github() function in the devtools package:

install.packages("devtools")
devtools::install_github("signaturescience/skater", build_vignettes=TRUE)

When installing skater, other packages which skater depends on are automatically installed, including magritr, tibble, dplyr, tidyr, readr, purrr, kinship2, corrr, rlang, and others.

Operation

Minimal system requirements for installing and using skater include R (version 3.0.0 or higher) and several tidyverse packages [@Wickham2019] that many R users will already have installed. Use cases are demonstrated in detail below. In summary, the skater package has functions for:

A comprehensive reference for all the functions in the skater package is available at https://signaturescience.github.io/skater/.

Use Cases

The skater package provides a collection of analysis and utility functions for SNP-based kinship analysis, testing, and evaluation as an R package. Functions in the package include tools for working with pedigree data, performing relationship degree inference, assessing classification accuracy, and summarizing IBD segment data.

library(skater)

Pedigree parsing, manipulation, and analysis

Pedigrees define familial relationships in a hierarchical structure. One of the common formats used by PLINK [@purcell2007] and other genetic analysis tools is the .fam file. A .fam file is a tabular format with one row per individual and columns for unique IDs of the mother, father, and the family unit. The package includes read_fam() to read files in this format:

famfile <- system.file("extdata", "3gens.fam", package="skater", mustWork=TRUE)
fam <- read_fam(famfile)
fam

Family structures imported from .fam formated files can then be translated to the pedigree structure used by the kinship2 package [@sinnwell2014]. The "fam" format may include multiple families, and the fam2ped() function will collapse them all into a tibble with one row per family:

peds <- fam2ped(fam)
peds

In the example above, the resulting tibble is nested by family ID. The data column contains the individual family information, while the ped column contains the pedigree object for that family. Using standard tidyverse operations, the resulting tibble can be unnested for any particular family:

peds %>% 
  dplyr::filter(fid=="testped1") %>% 
  tidyr::unnest(cols=data)

A single pedigree can also be inspected or visualized (standard base R plot arguments such as mar or cex can be used to adjust aesthetics):

peds$ped[[1]]
plot(peds$ped[[1]], mar=c(1,4,1,4), cex=.7)

The plot_pedigree() function from skater will iterate over a list of pedigree objects, writing a multi-page PDF, with each page containing a pedigree from family:

plot_pedigree(peds$ped, file="3gens.ped.pdf")

The ped2kinpair() function takes a pedigree object and produces a pairwise list of relationships between all individuals in the data with the expected kinship coefficients for each pair.

The function can be run on a single family:

ped2kinpair(peds$ped[[1]])

This function can also be mapped over all families in the pedigree:

kinpairs <- 
  peds %>% 
  dplyr::mutate(pairs=purrr::map(ped, ped2kinpair)) %>% 
  dplyr::select(fid, pairs) %>% 
  tidyr::unnest(cols=pairs)
kinpairs

Note that this maps ped2kinpair() over all ped objects in the input tibble, and that relationships are not shown for between-family relationships.

Relationship degree inference and benchmarking

The skater package includes functions to translate kinship coefficients to relationship degrees. The kinship coefficients could come from ped2kinpair() or other kinship estimation software.

The dibble() function creates a degree inference tibble, with degrees up to the specified max_degree (default=3), expected kinship coefficient, and lower (l) and upper (u) inference ranges as defined in @manichaikul2010. Degree 0 corresponds to self / identity / monozygotic twins, with an expected kinship coefficient of 0.5, with inference range >=0.354. Anything beyond the maximum degree resolution is considered unrelated (degree NA). Note also that while the theoretical upper boundary for the kinship coefficient is 0.5, the inference range for 0-degree (same person or identical twins) extends to 1 to allow for floating point arithmetic and stochastic effects resulting in kinship coefficients above 0.5.

dibble()

The degree inference max_degree default is 3. Change this argument to allow more granular degree inference ranges:

dibble(max_degree = 5)

Note that the distance between relationship degrees becomes smaller as the relationship degree becomes more distant. The dibble() function will emit a warning with max_degree >=10, and will stop with an error at >=12.

The kin2degree() function infers the relationship degree given a kinship coefficient and a max_degree up to which anything more distant is treated as unrelated. Example first degree relative:

kin2degree(.25, max_degree=3)

Example 4th degree relative, but using the default max_degree resolution of 3:

kin2degree(.0312, max_degree=3)

Example 4th degree relative, but increasing the degree resolution:

kin2degree(.0312, max_degree=5)

The kin2degree() function is vectorized over values of k, so it can be used inside of a mutate on a tibble of kinship coefficients:

# Get two pairs from each type of relationship we have in kinpairs:
kinpairs_subset <- 
  kinpairs %>% 
  dplyr::group_by(k) %>% 
  dplyr::slice(1:2)
kinpairs_subset

# Infer degree out to third degree relatives:
kinpairs_subset %>% 
  dplyr::mutate(degree=kin2degree(k, max_degree=3))

Benchmarking Degree Classification

Once estimated kinship is converted to degree, it may be of interest to compare the inferred degree to truth. When aggregated over many relationships and inferences, this approach can help benchmark performance of a particular kinship analysis method.

The skater package adapts a confusion_matrix() function from @clark2021 to provide standard contingency table metrics (e.g. sensitivity, specificity, PPV, precision, recall, F1, etc.) with a new reciprocal RMSE (R-RMSE) metric. The confusion_matrix() function on its own outputs a list with four objects:

  1. A tibble with calculated accuracy, lower and upper bounds, the guessing rate and p-value of the accuracy vs. the guessing rate.
  2. A tibble with contingency table statistics calculated for each class. Details on the statistics calculated for each class can be reviewed on the help page for ?confusion_matrix.
  3. A matrix with the contingency table object itself.
  4. A vector with the reciprocal RMSE (R-RMSE). The R-RMSE represents an alternative to classification accuracy when benchmarking relationship degree estimation and is calculated using the formula in (1). Taking the reciprocal of the target and predicted degree results in larger penalties for more egregious misclassifications (e.g., classifying a first-degree relative pair as second degree) than misclassifications at more distant relationships (e.g., misclassifying a fourth-degree relative pair as fifth-degree). The +0.5 adjustment prevents division-by-zero when a 0th-degree (identical) relative pair is introduced.

\begin{equation} \sqrt{\frac{\sum_{i=1}^{k}(\frac{1}{\text{Target}+0.5}-\frac{1}{\text{Predicted}+0.5})^2}{k}} \end{equation}

To illustrate the usage, this example will start with the kinpairs data from above and randomly flip ~20% of the true relationship degrees:

# Function to randomly flip levels of a factor (at 20%, by default)
randomflip <- function(x, p=.2) ifelse(runif(length(x))<p, sample(unique(x)), x)

# Infer degree (truth/target) using kin2degree, then randomly flip 20% of them
set.seed(42)
kinpairs_inferred <- kinpairs %>% 
  dplyr::mutate(degree_truth=kin2degree(k, max_degree=3)) %>% 
  dplyr::mutate(degree_truth=tidyr::replace_na(degree_truth, "unrelated")) %>% 
  dplyr::mutate(degree_inferred=randomflip(degree_truth))
kinpairs_inferred

Next, running the confusion_matrix() function will return all four objects noted above:

confusion_matrix(prediction = kinpairs_inferred$degree_inferred, 
                 target = kinpairs_inferred$degree_truth)

Standard tidyverse functions such as purrr::pluck() can be used to isolate just the contingency table:

confusion_matrix(prediction = kinpairs_inferred$degree_inferred, 
                 target = kinpairs_inferred$degree_truth) %>% 
  purrr::pluck("Table")

The confusion_matrix() function includes an argument to output in a tidy (longer=TRUE) format, and the example below illustrates how to spread contingency table statistics by class:

confusion_matrix(prediction = kinpairs_inferred$degree_inferred, 
                 target = kinpairs_inferred$degree_truth, 
                 longer = TRUE) %>% 
  purrr::pluck("Other") %>% 
  tidyr::spread(Class, Value) %>% 
  dplyr::relocate(Average, .after=dplyr::last_col()) %>% 
  dplyr::mutate_if(rlang::is_double, signif, 2)

IBD segment analysis

Tools such as hap-IBD [@zhou2020], and IBIS [@seidman2020] detect shared IBD segments between individuals. The skater package includes functionality to take those IBD segments, compute shared genomic centimorgan (cM) length, and converts that shared cM to a kinship coefficient. In addition to inferred segments, these functions can estimate "truth" kinship from simulated IBD segments [@caballero2019]. The read_ibd() function reads pairwise IBD segments from IBD inference tools and from simulated IBD segments. The read_map() function reads in genetic map in a standard format which is required to translate the total centimorgans shared IBD to a kinship coefficient using the ibd2kin() function. See ?read_ibd and ?read_map for additional details on expected format.

The read_ibd() function reads in the pairwise IBD segment format. Input to this function can either be inferred IBD segments from hap-IBD (source="hapibd") or simulated segments (source="pedsim"). The first example below uses data in the hap-ibd output format:

hapibd_filepath <- system.file("extdata", "GBR.sim.ibd.gz", 
                               package="skater")
hapibd_seg <- read_ibd(hapibd_filepath, source = "hapibd")
hapibd_seg

In order to translate the shared genomic cM length to a kinship coefficient, a genetic map must first be read in with read_map(). Software for IBD segment inference and simulation requires a genetic map. The map loaded for kinship estimation should be the same one used for creating the shared IBD segment output. The example below uses a minimal genetic map that ships with skater:

gmap_filepath <- system.file("extdata", "sexspec-avg-min.plink.map", 
                             package="skater")
gmap <- read_map(gmap_filepath)
gmap

The ibd2kin() function takes the segments and map file and outputs a tibble with one row per pair of individuals and columns for individual 1 ID, individual 2 ID, and the kinship coefficient for the pair:

ibd_dat <- ibd2kin(.ibd_data=hapibd_seg, .map=gmap)
ibd_dat

Summary

The skater R package provides a robust software package for data import, manipulation, and analysis tasks typically encountered when working with SNP-based kinship analysis tools. All package functions are internally documented with examples, and the package contains a vignette demonstrating usage, inputs, outputs, and interpretation of all key functions. The package contains internal tests that are automatically run with continuous integration via GitHub Actions whenever the package code is updated. The skater package is permissively licensed (MIT) and is easily extensible to accommodate outputs from new genome-wide relatedness and IBD segment methods as they become available.

Software availability

  1. Software available from: http://CRAN.R-project.org/package=skater.
  2. Source code available from: https://github.com/signaturescience/skater.
  3. Archived source code at time of publication: https://doi.org/10.5281/zenodo.5761996.
  4. Software license: MIT License.

Author information

SDT, VPN, and MBS developed the R package.

All authors contributed to method development.

SDT wrote the first draft of the manuscript.

All authors assisted with manuscript revision.

All authors read and approved the final manuscript.

Competing interests

No competing interests were disclosed.

Grant information

This work was supported in part by award 2019-DU-BX-0046 (Dense DNA Data for Enhanced Missing Persons Identification) to B.B., awarded by the National Institute of Justice, Office of Justice Programs, U.S. Department of Justice and by internal funds from the Center for Human Identification. The opinions, findings, and conclusions or recommendations expressed are those of the authors and do not necessarily reflect those of the U.S. Department of Justice.



signaturescience/skater documentation built on Feb. 11, 2023, 4:19 p.m.