R/validate.R

Defines functions validate_relatives validate_correlation_matrix validate_proportion validate_graph_input_multi validate_graph_input validate_tbl_input_multi validate_tbl_input describe_bad_rows

utils::globalVariables("K_i")
utils::globalVariables("K_pop")

#' Describe which rows failed a validation check, for use in an error message
#'
#' Given the indices of rows that failed some check and the personal
#' identifiers for the full table, returns a single string summarising how
#' many rows are affected and listing up to \code{max_show} of their ids -
#' with a ", and N more" suffix if there are more than that. Returns
#' \code{NULL} if \code{bad_indx} is empty, i.e. nothing to report.
#'
#' @param bad_indx integer vector of row indices that failed the check.
#' @param ids character (or coercible) vector of personal identifiers for
#' every row in the table, i.e. \code{ids[bad_indx]} are the affected ids.
#' @param max_show maximum number of ids to list explicitly. Defaults to 10.
#'
#' @returns A single string, or NULL if bad_indx is empty.
#' @noRd
describe_bad_rows <- function(bad_indx, ids, max_show = 10) {
  if (length(bad_indx) == 0) return(NULL)

  bad_ids <- ids[bad_indx]
  n_show  <- min(max_show, length(bad_ids))
  if (length(bad_ids) > n_show) {
    more <- paste0(", and ", length(bad_ids) - n_show, " more")
  } else {
    more <- ""
  }

  paste0(length(bad_ids), " individual(s), including: ",
        paste(bad_ids[seq_len(n_show)], collapse = ", "), more)
}

#' Title Internal function used to validate the .tbl input
#'
#' @param .tbl tibble with threshold and role information
#' @param pid personal identified
#' @param fid family identifier
#' @param role role of the individual(s)
#' @param useMixture logical variable. If TRUE, the function will return for K_i and K_pop columns for mixture estimates of liability.
#'
#' @returns validated tibble with only relevant columns
#'
#' @importFrom dplyr pull select
#' @noRd
validate_tbl_input = function(.tbl, pid, fid, role, useMixture) {
  # Turning .tbl into a tibble
  # if it is not of class tbl
  if (!is.null(.tbl) && !tibble::is_tibble(.tbl))  .tbl <- tibble::as_tibble(.tbl)

  # role (as string) must be supplied
  if (is.null(role)) stop("role must be specified.")
  # if role is supplied, convert to string
  if (!is.null(role)) role <- as.character(role)

  # Checking that .tbl has three columns named pid, fid and role
  if (!(pid %in% colnames(.tbl))) stop(paste0("The column ", pid," does not exist in the tibble .tbl..."))
  if (!(fid %in% colnames(.tbl))) stop(paste0("The column ", fid," does not exist in the tibble .tbl..."))
  if (!(role %in% colnames(.tbl))) stop(paste0("The column ", role," does not exist in the tibble .tbl..."))

  # In addition, we check that two columns named lower and upper are present
  if (any(!c("lower","upper") %in% colnames(.tbl))) stop("The tibble .tbl must include two columns named 'lower' and 'upper'!")
  # if use mixture is true, we will also check for columns K_i and K_pop
  if (useMixture) {
    if (!("K_i" %in% colnames(.tbl))) stop("The column K_i does not exist in the tibble .tbl...")
    if (!("K_pop" %in% colnames(.tbl))) stop("The column K_pop does not exist in the tibble .tbl...")
  }

  # If the tibble consists of more than the required columns,
  # we select only the relevant ones.
  if (useMixture) {
    .tbl <- select(.tbl,
                   !!as.symbol(fid),
                   !!as.symbol(pid),
                   !!as.symbol(role),
                   tidyselect::starts_with("lower"),
                   tidyselect::starts_with("upper"),
                   tidyselect::starts_with("K_i"),
                   tidyselect::starts_with("K_pop"))
  } else {

    .tbl <- select(.tbl,
                   !!as.symbol(fid),
                   !!as.symbol(pid),
                   !!as.symbol(role),
                   tidyselect::starts_with("lower"),
                   tidyselect::starts_with("upper"))
  }


  # Finally, we also check whether all lower thresholds are smaller than or
  # equal to the upper thresholds. We do not attempt to silently swap them:
  # lower > upper almost always indicates a genuine data problem (e.g.
  # swapped columns), which is better surfaced to the user than guessed at.
  bad_indx <- which(pull(.tbl, lower) > pull(.tbl, upper))
  detail <- describe_bad_rows(bad_indx, pull(.tbl, !!as.symbol(pid)))
  if (!is.null(detail)) {
    stop("lower is greater than upper for ", detail,
        ". Check that 'lower' and 'upper' were not swapped.")
  }

  if (useMixture) {
    bad_indx <- which(pull(.tbl, K_i) > pull(.tbl, K_pop))
    detail <- describe_bad_rows(bad_indx, pull(.tbl, !!as.symbol(pid)))
    if (!is.null(detail)) {
      stop("K_i is greater than K_pop for ", detail, ".")
    }
  }

  # Returning the validated tibble
  return(.tbl)
}

#' Title Internal function used to validate the .tbl input for multiple phenotypes
#'
#' @param .tbl tibble with threshold and role information
#' @param pid personal identified
#' @param fid family identifier
#' @param role role of the individual(s)
#' @param useMixture logical variable. If TRUE, the function will return for K_i and K_pop columns for mixture estimates of liability.
#' @param phen_names character vector with phenotype names to check for
#'
#' @returns validated tibble with only relevant columns
#' @importFrom dplyr pull select
#' @noRd
validate_tbl_input_multi = function(.tbl, pid, fid, role, useMixture, phen_names) {
  # Turning .tbl into a tibble
  # if it is not of class tbl
  if (!tibble::is_tibble(.tbl)) .tbl <- tibble::as_tibble(.tbl)

  # role (as string) must be supplied
  if (is.null(role)) stop("role must be specified.")
  # Turning role into string
  role <- as.character(role)


  # Checking that .tbl has three columns named pid, fid and role
  if (!(pid %in% colnames(.tbl))) stop(paste0("The column ", pid," does not exist in the tibble .tbl..."))
  if (!(fid %in% colnames(.tbl))) stop(paste0("The column ", fid," does not exist in the tibble .tbl..."))
  if (!(role %in% colnames(.tbl))) stop(paste0("The column ", role," does not exist in the tibble .tbl..."))


  # checking whether all lower and upper columns follow the naming convention
  cols_to_check = paste0(c("lower_", "upper_"), rep(phen_names, each = 2))
  if (any(!cols_to_check %in% colnames(.tbl))) {
    stop(paste0("The column(s) ", paste0(setdiff(cols_to_check, colnames(.tbl)), collapse = ", "), " are missing from .tbl...\n"))
  }

  # if use mixture is true, we will also check for columns K_i and K_pop
  if (useMixture) {
    cols_to_check_mixture = paste0(c("K_i_", "K_pop_"), rep(phen_names, each = 2))
    if (any(!cols_to_check_mixture %in% colnames(.tbl))) {
      stop(paste0("The column(s) ", paste0(setdiff(cols_to_check_mixture, colnames(.tbl)), collapse = ", "), " are missing from .tbl...\n"))
    }
  }

  # If the tibble consists of more than the required columns,
  # we select only the relevant ones.
  if (useMixture) {
    .tbl <- select(.tbl,
                   !!as.symbol(fid),
                   !!as.symbol(pid),
                   !!as.symbol(role),
                   tidyselect::starts_with("lower"),
                   tidyselect::starts_with("upper"),
                   tidyselect::starts_with("K_i"),
                   tidyselect::starts_with("K_pop"))
  } else {

    .tbl <- select(.tbl,
                   !!as.symbol(fid),
                   !!as.symbol(pid),
                   !!as.symbol(role),
                   tidyselect::starts_with("lower"),
                   tidyselect::starts_with("upper"))
  }



  # We check whether all lower thresholds are smaller than or equal to the
  # upper thresholds, for every phenotype. As above, we do not attempt to
  # silently swap them - we collect every affected phenotype's problem
  # first, then report all of them together in a single error.
  problems <- lapply(phen_names, function(pheno) {
    bad_indx <- which(pull(.tbl, !!as.symbol(paste0("lower_", pheno))) > pull(.tbl, !!as.symbol(paste0("upper_", pheno))))
    detail <- describe_bad_rows(bad_indx, pull(.tbl, !!as.symbol(pid)))
    if (is.null(detail)) return(NULL)
    paste0("  - ", pheno, ": ", detail)
  })
  problems <- unlist(problems)

  if (length(problems) > 0) {
    stop("lower is greater than upper for the following phenotype(s) (column '", pid, "'):\n",
        paste(problems, collapse = "\n"),
        "\nCheck that 'lower' and 'upper' were not swapped.")
  }

  if (useMixture) {
    k_problems <- lapply(phen_names, function(pheno) {
      bad_indx <- which(pull(.tbl, !!as.symbol(paste0("K_i_", pheno))) > pull(.tbl, !!as.symbol(paste0("K_pop_", pheno))))
      detail <- describe_bad_rows(bad_indx, pull(.tbl, !!as.symbol(pid)))
      if (is.null(detail)) return(NULL)
      paste0("  - ", pheno, ": ", detail)
    })
    k_problems <- unlist(k_problems)

    if (length(k_problems) > 0) {
      stop("K_i is greater than K_pop for the following phenotype(s) (column '", pid, "'):\n",
          paste(k_problems, collapse = "\n"), ".")
    }
  }

  # Returning the validated tibble
  return(.tbl)
}

#' Title Internal function used to validate the family graph input
#'
#' @param family_graphs tibble with family ID and list column with family graphs
#' @param fid column name of family ID, typically proband ID in family graphs
#' @param family_graphs_col column name of the family graphs
#'
#' @returns Nothing. The function is used for validation purposes.
#'
#' @importFrom igraph vertex_attr
#' @importFrom dplyr pull
#' @noRd

validate_graph_input = function(family_graphs, fid, family_graphs_col, useMixture) {

  #check if family_graphs is present, and if the pid column is present.
  if ( !(fid %in% colnames(family_graphs)) ) {
    stop(paste0("The column '", fid,"' does not exist in the tibble family_graphs."))
  }
  # checking if the family graph column present.
  if ( !(family_graphs_col %in% colnames(family_graphs)) ) {
    stop(paste0("The column ", family_graphs_col," does not exist in the tibble family_graphs."))
  }

  # extract attributes from graph
  # note: only the first family's graph is inspected below - a lightweight
  # sanity check for systematic problems (e.g. lower/upper swapped for the
  # whole pipeline), not a guarantee that every family's graph is
  # well-formed. Checking every family here would mean traversing every
  # graph in family_graphs before any real work has started.
  graph_attrs = vertex_attr((family_graphs %>% pull(!!as.symbol(family_graphs_col)))[[1]])

  if (useMixture) {
    if ( !(all(c("lower", "upper", "K_i", "K_pop") %in% names(graph_attrs))) ) {
      stop("lower, upper, K_i, or K_pop are not present as attributes in family_graph.")
    }

  } else {
    if ( !(all(c("lower", "upper") %in% names(graph_attrs))) ) {
      stop("lower and upper are not present as attributes in family_graph.")
    }
  }

  bad_indx <- which(graph_attrs$lower > graph_attrs$upper)
  detail <- describe_bad_rows(bad_indx, graph_attrs$name)
  if (!is.null(detail)) {
    stop("In the first family's graph, lower is greater than upper for ", detail,
        ". Check that 'lower' and 'upper' were not swapped. Note: only the first",
        " family's graph is checked here, so other families may have the same issue.")
  }

  if (useMixture) {
    bad_indx <- which(graph_attrs$K_i > graph_attrs$K_pop)
    detail <- describe_bad_rows(bad_indx, graph_attrs$name)
    if (!is.null(detail)) {
      stop("In the first family's graph, K_i is greater than K_pop for ", detail, ".")
    }
  }

}


#' Title Internal function used to validate the family graph input for multiple phenotypes
#'
#' @param family_graphs tibble with proband ID and list column with family graphs
#' @param fid column name of family ID, typically proband ID in family graphs
#' @param family_graphs_col column name of the family graphs
#' @param phen_names character vector with phenotype names to check for
#' @param useMixture logical variable. If TRUE, the function will check for K_i and K_pop attributes for mixture estimates of liability for each phenotype in phen_names.
#'
#' @returns Nothing. The function is used for validation purposes.
#' @importFrom igraph vertex_attr
#' @importFrom dplyr pull
#' @noRd
validate_graph_input_multi = function(family_graphs, fid, family_graphs_col, phen_names, useMixture) {

  #check if family_graphs is present, and if the fid column is present.
  if ( !(fid %in% colnames(family_graphs)) ) {
    stop(paste0("The column ", fid," does not exist in the tibble family_graphs."))
  }
  # checking if the family graph column present.
  if ( !(family_graphs_col %in% colnames(family_graphs)) ) {
    stop(paste0("The column ", family_graphs_col," does not exist in the tibble family_graphs."))
  }

  # extract attributes from graph
  # note: only the first family's graph is inspected below - see
  # validate_graph_input() for the same caveat.
  graph_attrs = vertex_attr((family_graphs %>% pull(!!as.symbol(family_graphs_col)))[[1]])

  required_attrs = c(paste0("lower_", phen_names), paste0("upper_", phen_names))
  if (useMixture) {
    required_attrs = c(required_attrs,
                       paste0("K_i_", phen_names),
                       paste0("K_pop_", phen_names))
  }
  # checking whether all required attributes are present in the graph
  if ( !(all(required_attrs %in% names(graph_attrs))) ) {
    stop(paste0("Not all required attributes are present in family_graph. Missing attributes: ",
                paste0(setdiff(required_attrs, names(graph_attrs)), collapse = ", "), "."))
  }

  problems <- lapply(phen_names, function(pheno) {
    bad_indx <- which(graph_attrs[[paste0("lower_", pheno)]] > graph_attrs[[paste0("upper_", pheno)]])
    detail <- describe_bad_rows(bad_indx, graph_attrs$name)
    if (is.null(detail)) return(NULL)
    paste0("  - ", pheno, ": ", detail)
  })
  problems <- unlist(problems)

  if (length(problems) > 0) {
    stop("In the first family's graph, lower is greater than upper for the following phenotype(s):\n",
        paste(problems, collapse = "\n"),
        "\nCheck that 'lower' and 'upper' were not swapped. Note: only the first family's",
        " graph is checked here, so other families may have the same issue.")
  }

  if (useMixture) {
    k_problems <- lapply(phen_names, function(pheno) {
      bad_indx <- which(graph_attrs[[paste0("K_i_", pheno)]] > graph_attrs[[paste0("K_pop_", pheno)]])
      detail <- describe_bad_rows(bad_indx, graph_attrs$name)
      if (is.null(detail)) return(NULL)
      paste0("  - ", pheno, ": ", detail)
    })
    k_problems <- unlist(k_problems)

    if (length(k_problems) > 0) {
      stop("In the first family's graph, K_i is greater than K_pop for the following phenotype(s):\n",
          paste(k_problems, collapse = "\n"), ".")
    }
  }

}

#' Checking that proportions are valid
#'
#' \code{validate_proportion} checks whether proportions are valid, i.e.
#' whether they are non-negative and at most one.
#'
#' This function can be used to check whether proportions are non-negative
#' and at most one.
#'
#' @param prop A number, integer or numeric vector representing the proportions that
#' need to be validated.
#' @param from_covmat logical variable. Only used internally. allows for skip of negative check.
#'
#' @return If \code{prop} is a vector holding valid proportions of class \code{numeric}
#' or \code{integer} that are non-negative and at most one,
#' then the function will return TRUE. Otherwise, the function aborts.
#'
#' @examples
#' LTFGRS:::validate_proportion(0.2)
#' LTFGRS:::validate_proportion(0.04)
#' LTFGRS:::validate_proportion(0)
#' LTFGRS:::validate_proportion(1)
#'
#' # This will result in errors:
#' try(LTFGRS:::validate_proportion(2))
#' try(LTFGRS:::validate_proportion(-0.5))
#' @noRd
validate_proportion <- function(prop, from_covmat = FALSE){
  if(is.null(prop)){

    stop(paste0(deparse(substitute(prop)), " must be specified!"))

  }else if(any(!is.numeric(prop)) && any(!is.integer(prop))){

    stop(paste0(deparse(substitute(prop)), " must be numeric!"))

  }else if(any(prop<0) & !from_covmat){

    stop(paste0(deparse(substitute(prop)), " must be non-negative!"))

  }else if(any(prop>1)){

    stop(paste0(deparse(substitute(prop)), " must be smaller than or equal to 1!"))

  }else{
    return(TRUE)
  }
}


#' Checking that a correlation matrix is valid
#'
#' \code{validate_correlation_matrix} checks whether a matrix is a valid
#' correlation matrix, i.e. whether its diagonal entries are equal to one,
#' while all off-diagonal entries are between -1 and 1, and whether it is
#' symmetric.
#'
#' This function can be used to check whether a correlation matrix has diagonal
#' entries equal to 1 and off-diagonal entries between -1 and 1 as well as whether
#' it is symmetric.
#'
#' @param corrmat A numeric matrix holding the correlations.
#' All diagonal entries must be equal to one, while all off-diagonal entries
#' must be between -1 and 1. In addition, the matrix must be symmetric.
#'
#' @return If \code{corrmat} is a valid correlation matrix that is symmetric,
#' has one on all diagonal entries and numbers between -1 and 1 on all off-
#' diagonal entries,
#' then the function will return TRUE. Otherwise, the function will be aborted.
#'
#' @examples
#' LTFGRS:::validate_correlation_matrix(matrix(c(1,0.4,0.4,1), nrow = 2))
#' LTFGRS:::validate_correlation_matrix(diag(3))
#'
#' # This will result in errors:
#' try(LTFGRS:::validate_correlation_matrix(matrix(c(0.2,0.4,0.4,0.2), nrow = 2)))
#' try(LTFGRS:::validate_correlation_matrix(matrix(nrow=2, ncol = 2)))
#' @noRd
validate_correlation_matrix <- function(corrmat){

  if(is.null(corrmat)){

    stop(paste0(deparse(substitute(corrmat)), " must be specified!"))

  }else if(any(diag(corrmat)!= 1)){

    stop(paste0("All diagonal entries in ", deparse(substitute(corrmat))," must be 1!"))

  }else if(any(abs(corrmat)>1)){
    stop(paste0("All off-diagonal entries in ", deparse(substitute(corrmat))," must be between -1 and 1!"))
  }else if(!isSymmetric.matrix(corrmat)){
    stop(paste0(deparse(substitute(corrmat)), " must be symmetric!"))
  }else{
    return(TRUE)
  }
}



#' Checking that relatives are represented by valid strings
#'
#' \code{validate_relatives} checks whether relatives are represented
#' by valid abbreviations.
#'
#' This function can be used to check whether relatives are represented
#' by valid abbreviations. A valid abbreviation is one of the following:
#' \itemize{
#'  \item \code{g} (Genetic component of full liability)
#'  \item \code{o} (Full liability)
#'  \item \code{m} (Mother)
#'  \item \code{f} (Father)
#'  \item \code{c[0-9]*.[0-9]*} (Children)
#'  \item \code{mgm} (Maternal grandmother)
#'  \item \code{mgf} (Maternal grandfather)
#'  \item \code{pgm} (Paternal grandmother)
#'  \item \code{pgf} (Paternal grandfather)
#'  \item \code{s[0-9]*} (Full siblings)
#'  \item \code{mhs[0-9]*} (Half-siblings - maternal side)
#'  \item \code{phs[0-9]*} (Half-siblings - paternal side)
#'  \item \code{mau[0-9]*} (Aunts/Uncles - maternal side)
#'  \item \code{pau[0-9]*} (Aunts/Uncles - paternal side).
#' }
#'
#' @param relatives A string or character vector representing
#' the relatives.
#' All strings must be chosen among the following abbreviations
#' \itemize{
#'  \item \code{g} (Genetic component of full liability)
#'  \item \code{o} (Full liability)
#'  \item \code{m} (Mother)
#'  \item \code{f} (Father)
#'  \item \code{c[0-9]*.[0-9]*} (Children)
#'  \item \code{mgm} (Maternal grandmother)
#'  \item \code{mgf} (Maternal grandfather)
#'  \item \code{pgm} (Paternal grandmother)
#'  \item \code{pgf} (Paternal grandfather)
#'  \item \code{s[0-9]*} (Full siblings)
#'  \item \code{mhs[0-9]*} (Half-siblings - maternal side)
#'  \item \code{phs[0-9]*} (Half-siblings - paternal side)
#'  \item \code{mau[0-9]*} (Aunts/Uncles - maternal side)
#'  \item \code{pau[0-9]*} (Aunts/Uncles - paternal side).
#' }
#' for the function to return TRUE.
#'
#' @return If \code{relatives} is a string or character vector such that
#' all strings are chosen from the mentioned list of strings,
#' then the function will return TRUE. Otherwise, the function is aborted.
#'
#' @examples
#' LTFGRS:::validate_relatives("g")
#' LTFGRS:::validate_relatives("o")
#' LTFGRS:::validate_relatives("mgm")
#'
#' # This will result in errors:
#' try(LTFGRS:::validate_relatives("a"))
#' try(LTFGRS:::validate_relatives(m))
#'
#' @importFrom stringr str_detect
#' @noRd
validate_relatives <- function(relatives){

  if(!is.character(relatives)){

    stop(paste0(deparse(substitute(relatives)), " must be a string or character vector!"))

  }else if(any(!(str_detect(relatives, "^[gomf]$") | str_detect(relatives, "^c[0-9]*.[0-9]*")|
                 str_detect(relatives, "^[mp]g[mf]$") | str_detect(relatives, "^s[0-9]*") |
                 str_detect(relatives, "^[mp]hs[0-9]*")| str_detect(relatives, "^[mp]au[0-9]*")))){

    stop(paste0(deparse(substitute(relatives)), " contains invalid abbreviations! Use strings from the following list: \n
  - g (Genetic component of full liability)\n
  - o (Full liability)\n
  - m (Mother)\n
  - f (Father)\n
  - c[0-9]*.[0-9]* (Children)\n
  - mgm (Maternal grandmother)\n
  - mgf (Maternal grandfather)\n
  - pgm (Paternal grandmother)\n
  - pgf (Paternal grandfather)\n
  - s[0-9]* (Full siblings)\n
  - mhs[0-9]* (Half-siblings - maternal side)\n
  - phs[0-9]* (Half-siblings - paternal side)\n
  - mau[0-9]* (Aunts/Uncles - maternal side)\n
  - pau[0-9]* (Aunts/Uncles - paternal side)."))
  }else{
    return(TRUE)
  }
}

Try the LTFGRS package in your browser

Any scripts or data that you put into this service are public.

LTFGRS documentation built on Nov. 20, 2026, 5:10 p.m.