Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: BIGr
Title: Breeding Insight Genomics Functions for Polyploid and Diploid
Species
Version: 0.10.0
Version: 0.11.1
Authors@R: c(
person("Alexander M.", "Sandercock", , "sandercock.alex@gmail.com", role = c("cre", "aut")),
person("Cristiane", "Taniguti", role = "aut"),
Expand Down
250 changes: 136 additions & 114 deletions NEWS.md

Large diffs are not rendered by default.

74 changes: 64 additions & 10 deletions R/check_madc_sanity.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#' Run basic sanity checks on a MADC-style allele report
#'
#' @description
#' Performs twelve quick validations on an allele report:
#' Performs thirteen quick validations on an allele report:
#' 1) **Columns** - required columns are present (`CloneID`, `AlleleID`, `AlleleSequence`);
#' 2) **FixAlleleIDs** - first column's first up-to-6 rows are not all blank or `"*"`
#' *and* both `_0001` and `_0002` appear in `AlleleID`;
Expand All @@ -18,7 +18,9 @@
#' 9) **allNArow** - at least one row contains only `NA` or empty values;
#' 10) **RefAltSeqs** - every `CloneID` has at least one `Ref` and one `Alt` allele row;
#' 11) **OtherAlleles** - presence of alleles where the target locus differs from both the Ref and Alt in `AlleleSequence`;
#' 12) **IUPACcodes_MatchAlleles** - presence of non-ATCG characters in `AlleleSequence` for RefMatch_/AltMatch_/Other alleles.
#' 12) **IUPACcodes_MatchAlleles** - presence of non-ATCG characters in `AlleleSequence` for RefMatch_/AltMatch_/Other alleles;
#' 13) **SpecialChar** - presence of special characters (including spaces) in the
#' sample names (column 4 onward).
#'
#' @param report A `data.frame` with at least the columns
#' `CloneID`, `AlleleID`, and `AlleleSequence`. The first column is also
Expand Down Expand Up @@ -58,16 +60,23 @@
#' one row with an `Alt` (`|Alt_` / `|Alt$`) allele exist. `CloneID`s that
#' lack a `Ref` row are stored in `missRef`; those lacking an `Alt` row in
#' `missAlt`. The check is `TRUE` when both sets are empty.
#' - If required columns are missing (`Columns = FALSE`), only `Columns` and
#' `FixAlleleIDs` are evaluated; all other checks remain `NA` and
#' - **SpecialChar:** Column names from the 4th column onward are treated as
#' sample names. A name is flagged when it contains any character other than
#' letters, digits, `"_"`, `"."` or `"-"` (e.g. spaces, `/`, `#`, `(`, `|`).
#' Flagged names are stored in `special_char_samples`. Note that
#' `read.csv()` with the default `check.names = TRUE` already replaces such
#' characters with `"."`, so read files with `check.names = FALSE` to
#' detect them.
#' - If required columns are missing (`Columns = FALSE`), only `Columns`,
#' `FixAlleleIDs` and `SpecialChar` are evaluated; all other checks remain `NA` and
#' `indel_clone_ids`, `missRef`, and `missAlt` are returned as `NULL`.
#'
#' @return A named list with six elements:
#' @return A named list with seven elements:
#' \describe{
#' \item{checks}{Named logical vector with twelve entries:
#' \item{checks}{Named logical vector with thirteen entries:
#' `Columns`, `FixAlleleIDs`, `IUPACcodes`, `IUPACcodes_IdenticalRefAlt`,
#' `LowerCase`, `Indels`, `ChromPos`, `allNAcol`, `allNArow`, `RefAltSeqs`,
#' `OtherAlleles`, `IUPACcodes_MatchAlleles`.
#' `OtherAlleles`, `IUPACcodes_MatchAlleles`, `SpecialChar`.
#' `TRUE` means the condition was detected (or passed for `Columns`,
#' `FixAlleleIDs`, `ChromPos`, and `RefAltSeqs`); `NA` means the check
#' was skipped.}
Expand All @@ -88,6 +97,9 @@
#' \item{missAlt}{Character vector of `CloneID`s that have no `Alt` allele
#' row. Returns `character(0)` if all `CloneID`s have an `Alt` row, or
#' `NULL` when required columns are missing.}
#' \item{special_char_samples}{Character vector of sample names (column 4
#' onward) containing special characters. Returns `character(0)` if none
#' are found.}
#' }
#'
#' @export
Expand All @@ -97,11 +109,11 @@ check_madc_sanity <- function(report) {
checks <- c(Columns = NA, FixAlleleIDs = NA, IUPACcodes = NA, IUPACcodes_IdenticalRefAlt = NA,
LowerCase = NA, Indels = NA,
ChromPos = NA, allNAcol = NA, allNArow = NA, RefAltSeqs = NA, OtherAlleles = NA,
IUPACcodes_MatchAlleles = NA)
IUPACcodes_MatchAlleles = NA, SpecialChar = NA)
messages <- list(Columns = NA, FixAlleleIDs = NA, IUPACcodes = NA, IUPACcodes_IdenticalRefAlt = NA,
LowerCase = NA, Indels = NA,
ChromPos = NA, allNAcol = NA, allNArow = NA, RefAltSeqs = NA, OtherAlleles = NA,
IUPACcodes_MatchAlleles = NA)
IUPACcodes_MatchAlleles = NA, SpecialChar = NA)

# ---- FixAlleleIDs ----
# Check if first up-to-6 entries in the *first column* are all "" or "*"
Expand All @@ -123,6 +135,13 @@ check_madc_sanity <- function(report) {
missing_cols <- setdiff(required, names(report))
checks["Columns"] <- length(missing_cols) == 0

# ---- SpecialChar ----
# Sample names (column 4 onward) should only contain letters, digits, "_", "." or "-"
sample_names <- as.character(colnames(report)[-(1:3)])
bad_names <- grepl("[^A-Za-z0-9_.-]", sample_names)
special_char_samples <- sample_names[bad_names]
checks["SpecialChar"] <- any(bad_names)

if(checks[["Columns"]]){
# ---- IUPACcodes ----
# Check for IUPAC codes in Ref_ and Alt_ alleles
Expand Down Expand Up @@ -284,10 +303,45 @@ check_madc_sanity <- function(report) {
"No alleles other than Ref and Alt found in AlleleID")
messages[["IUPACcodes_MatchAlleles"]] <- c("IUPAC (non-ATCG) codes found in RefMatch/AltMatch/Other AlleleSequence. These codes are not currently supported by BIGr/BIGapp they will be ignored in the conversion to VCF",
"No IUPAC (non-ATCG) codes found in RefMatch/AltMatch/Other AlleleSequence")
messages[["SpecialChar"]] <- c(paste0("Special characters (including spaces) found in sample names. Only letters, digits, '_', '.' and '-' are recommended. Samples: ",
paste0("'", special_char_samples, "'", collapse = " ")),
"No special characters found in sample names")

list(checks = checks, messages = messages, indel_clone_ids = indels,
iupac_identical_clone_ids = iupac_identical_clone_ids,
missRef = missRef, missAlt = missAlt)
missRef = missRef, missAlt = missAlt,
special_char_samples = special_char_samples)
}

#' Remove special characters from MADC sample names
#'
#' Removes every character other than letters, digits, `"_"`, `"."` and `"-"`
#' (including spaces) from the sample names (column 4 onward). Names that end
#' up empty become `"Sample"`, and duplicated names are made unique with
#' [make.unique()].
#'
#' @param report MADC `data.frame` whose first three columns are `AlleleID`,
#' `CloneID` and `AlleleSequence`.
#' @param verbose Logical. Print the renamed samples.
#'
#' @return `report` with cleaned sample names.
#'
#' @keywords internal
#' @noRd
clean_sample_names <- function(report, verbose = TRUE) {
if (ncol(report) < 4) return(report)
old <- as.character(colnames(report)[-(1:3)])
new <- gsub("[^A-Za-z0-9_.-]", "", old)
new[is.na(new) | new == ""] <- "Sample"
new <- make.unique(c(colnames(report)[1:3], new), sep = "_")[-(1:3)]
changed <- which(old != new | is.na(old))
if (length(changed) > 0) {
vmsg("Special characters removed from %s sample name(s): %s", verbose = verbose, level = 1, type = ">>",
length(changed),
paste0("'", old[changed], "' -> '", new[changed], "'", collapse = ", "))
colnames(report)[-(1:3)] <- new
}
report
}

#' Check and Adjust Botloci and MADC Marker Compatibility
Expand Down
16 changes: 12 additions & 4 deletions R/dosage2vcf.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#' @param dart.counts Path to the DArT counts .csv file. Typically contains "Counts" in the file name.
#' @param ploidy The ploidy of the species being analyzed
#' @param output.file output file name and path
#' @param vcf_header optional path or URL to a VCF header file. Only its ##reference and ##contig lines are added to the output VCF header
#' @param reference optional reference genome ID for the ##reference line (e.g. "GCF_020283565.1"). Replaces the ##reference line of vcf_header if both are given. Without vcf_header or reference, the ##reference and ##contig lines are left out with a warning
#' @return A vcf file
#' @import dplyr
#' @importFrom readr read_csv
Expand All @@ -30,18 +32,20 @@
#' #Temp location (only for example)
#' output_file <- tempfile()
#'
#' #The reference genome ID is written to the ##reference line of the VCF header
#' dosage2vcf(dart.report = system.file("iris_DArT_Allele_Dose_Report_small.csv", package = "BIGr"),
#' dart.counts = system.file("iris_DArT_Counts_small.csv", package = "BIGr"),
#' ploidy = 2,
#' output.file = output_file)
#' output.file = output_file,
#' reference = "example_genome_v1")
#'
#' # Removing the output for the example
#' rm(output_file)
#'
#' ##The function will output the converted VCF using information from the DArT files
#'
#' @export
dosage2vcf <- function(dart.report, dart.counts, ploidy, output.file) {
dosage2vcf <- function(dart.report, dart.counts, ploidy, output.file, vcf_header = NULL, reference = NULL) {

dosage_report <- dart.report
counts_file <- dart.counts
Expand All @@ -50,12 +54,14 @@ dosage2vcf <- function(dart.report, dart.counts, ploidy, output.file) {

message("Reading input files\n")

#Reference genome lines for the header
ref_lines <- vcf_reference_lines(vcf_header, reference)

#Make a header separate from the dataframe
vcf_header <- c(
"##fileformat=VCFv4.3",
paste0("##BIGr_Dosage2VCF=",packageVersion("BIGr")),
"##reference=NA",
"##contig=<ID=NA,length=NA>",
ref_lines$lines,
'##INFO=<ID=DP,Number=1,Type=Integer,Description="Total Depth">',
'##INFO=<ID=ADS,Number=R,Type=Integer,Description="Depths for the ref and each alt allele in the order listed">',
'##INFO=<ID=BIAS,Number=1,Type=Float,Description="The estimated allele bias of the SNP from updog">',
Expand Down Expand Up @@ -526,6 +532,8 @@ dosage2vcf <- function(dart.report, dart.counts, ploidy, output.file) {
# Add # to the CHROM column name
colnames(vcf_df)[1] <- "#CHROM"

check_vcf_contigs(vcf_df[[1]], ref_lines$contigs)

# Write the header to the file
writeLines(vcf_header, con = output.file)

Expand Down
83 changes: 69 additions & 14 deletions R/filterVCF.R
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,28 @@
#' @param ploidy The ploidy of the species being analyzed. Required. Used to write
#' the missing genotype, so a diploid is recorded as `./.` and a tetraploid as
#' `./././.` when a call is filtered out.
#' @param keep.depth Logical. What happens to the other FORMAT fields of a call
#' set to missing by `filter.DP` or `filter.MPP`. If `FALSE` (default), all of
#' them are set to missing, e.g. `0/1:3,2:5` becomes `./.:.:.`. If `TRUE`,
#' only GT is set to missing and the read counts and other fields are kept,
#' e.g. `./.:3,2:5`.
#' @param output.file Output file name, without an extension (optional). When
#' supplied, the filtered VCF is written as a gzipped file and nothing is
#' returned. `.vcf.gz` is appended when `vcf.file` is a path, and
#' `_filtered.vcf.gz` when `vcf.file` is a vcfR object. When not supplied, a
#' vcfR object is returned instead and no file is written.
#' @param vcf_header Path or URL to a VCF header file with the `##reference` and
#' `##contig` lines of the reference genome (optional), such as the VCF header
#' files provided with the microhaplotype databases. Its `##contig` lines
#' replace those of the input VCF, and so does its `##reference` line unless
#' `reference` is given. The other lines of the file are not used. A warning is
#' given if a `CHROM` in the output is not listed in the `##contig` lines.
#' @param reference Reference genome ID written to the `##reference` line,
#' replacing the one of the input VCF (optional), e.g. `"GCF_020283565.1"`.
#' When neither `vcf_header` nor `reference` is given, the reference genome lines
#' of the input VCF are kept, except the `##reference=NA` and
#' `##contig=<ID=NA,length=NA>` lines written by earlier versions of BIGr, which
#' are removed.
#' @return A vcfR object when `output.file` is not supplied. Otherwise the
#' filtered VCF is written to disk and nothing is returned.
#' @importFrom vcfR read.vcfR
Expand Down Expand Up @@ -92,7 +109,10 @@ filterVCF <- function(vcf.file,
filter.SAMPLE.miss = NULL,
filter.SNP.miss = NULL,
ploidy,
output.file = NULL) {
keep.depth = FALSE,
output.file = NULL,
vcf_header = NULL,
reference = NULL) {
Comment on lines +112 to +115

#Should allow for any INFO field to be entered to be filtered

Expand Down Expand Up @@ -126,6 +146,12 @@ filterVCF <- function(vcf.file,
filter.MAF <- validate_filter_number(filter.MAF, "filter.MAF")
filter.SAMPLE.miss <- validate_filter_number(filter.SAMPLE.miss, "filter.SAMPLE.miss", proportion = TRUE)
filter.SNP.miss <- validate_filter_number(filter.SNP.miss, "filter.SNP.miss", proportion = TRUE)
if (!is.logical(keep.depth) || length(keep.depth) != 1L || is.na(keep.depth)) {
stop("keep.depth must be TRUE or FALSE.", call. = FALSE)
}

#Reference genome lines for the header (checked before reading the VCF)
ref_lines <- vcf_reference_lines(vcf_header, reference, warn = FALSE)

# Import VCF (can be .vcf or .vcf.gz)
if (!inherits(vcf.file, "vcfR")) {
Expand All @@ -146,7 +172,10 @@ filterVCF <- function(vcf.file,
filter.MAF = filter.MAF,
filter.SAMPLE.miss = filter.SAMPLE.miss,
filter.SNP.miss = filter.SNP.miss,
ploidy = ploidy
ploidy = ploidy,
keep.depth = if (keep.depth) "TRUE" else NULL,
vcf_header = vcf_header,
reference = reference
)

# Filter out NULL values
Expand All @@ -171,6 +200,31 @@ filterVCF <- function(vcf.file,
paste(na_fields, collapse = ":")
}, character(1))
format_has <- function(field) any(vapply(format_fields, function(fields) field %in% fields, logical(1)))
gt_pos <- vapply(format_fields, function(fields) match("GT", fields), integer(1))

# Set the calls in to_modify (logical matrix, records x samples) to missing:
# the whole call, or only its GT when keep.depth is TRUE
mask_calls <- function(vcf, to_modify) {
if (!any(to_modify)) return(vcf)
rows <- which(to_modify, arr.ind = TRUE)[, 1]
if (keep.depth) {
calls <- vcf@gt[, -1, drop = FALSE][to_modify]
pos <- gt_pos[rows]
new_calls <- calls
first <- !is.na(pos) & pos == 1L # usual case: GT is the first field
new_calls[first] <- paste0(missing_gt, sub("^[^:]*", "", calls[first]))
other <- which(!is.na(pos) & pos > 1L)
new_calls[other] <- vapply(other, function(k) {
parts <- strsplit(calls[k], ":", fixed = TRUE)[[1]]
if (pos[k] <= length(parts)) parts[pos[k]] <- missing_gt
paste(parts, collapse = ":")
}, character(1))
} else {
new_calls <- na_format[rows]
}
vcf@gt[, -1][to_modify] <- new_calls
vcf
}

# Extract the DP values
if (!is.null(filter.DP) && format_has("DP")) {
Expand All @@ -180,12 +234,8 @@ filterVCF <- function(vcf.file,
# value are left unchanged
threshold <- as.numeric(filter.DP)
to_modify <- !is.na(dp) & dp < threshold
# Replace cells in the vcf@gt matrix with NA format string where to_modify is TRUE
na_matrix <- matrix(na_format, nrow = nrow(dp), ncol = ncol(dp))
vcf@gt[, -1][to_modify] <- na_matrix[to_modify]
# Remove extra matrices
rm(to_modify, na_matrix)
rm(dp)
vcf <- mask_calls(vcf, to_modify)
rm(to_modify, dp)
}

#Filter if the MPP field is present
Expand All @@ -197,12 +247,8 @@ filterVCF <- function(vcf.file,
# value are left unchanged
threshold <- as.numeric(filter.MPP)
to_modify <- !is.na(mpp) & mpp < threshold
# Replace cells in the vcf@gt matrix with NA format string where to_modify is TRUE
na_matrix <- matrix(na_format, nrow = nrow(mpp), ncol = ncol(mpp))
vcf@gt[, -1][to_modify] <- na_matrix[to_modify]
#remove extra matrices
rm(to_modify, na_matrix)
rm(mpp)
vcf <- mask_calls(vcf, to_modify)
rm(to_modify, mpp)
}

## Filter based on INFO column (example: DP > 10)
Expand Down Expand Up @@ -325,6 +371,15 @@ filterVCF <- function(vcf.file,
"This happens when no variant has any called genotypes, which the filter.DP and filter.MPP masking can cause."), ]
}
### Export the modified VCF file (this exports as a .vcf.gz, so make sure to have the name end in .vcf.gz)
#Update the reference genome lines of the header. Placeholder lines from earlier
#versions of BIGr are removed, since they break tools that read the header (e.g., GIGWA)
placeholder <- vcf@meta == "##reference=NA" | grepl("^##contig=<ID=NA[,>]", vcf@meta)
if (any(placeholder)) {
message("Removing ##reference=NA and ##contig=<ID=NA,length=NA> lines from the header\n")
}
vcf@meta <- update_vcf_reference_lines(vcf@meta[!placeholder], ref_lines)
check_vcf_contigs(vcf@fix[, "CHROM"], ref_lines$contigs)

message("Exporting VCF\n")
if (!inherits(vcf.file, "vcfR")) {
if (!is.null(output.file)) {
Expand Down
Loading
Loading