Skip to content

Commit d51ca10

Browse files
authored
Merge pull request #451 from xueweic/main
fix error in LD.R
2 parents 378d089 + f45d003 commit d51ca10

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

R/LD.R

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,21 @@ load_LD_from_blocks <- function(LD_meta_file_path, region, extract_coordinates =
471471
}
472472
}
473473

474+
# Filter out empty blocks before combining
475+
non_empty <- sapply(extracted_LD_variants_list, function(v) nrow(v) > 0)
476+
if (!any(non_empty)) {
477+
stop("No variants found in any LD block for the specified region.")
478+
}
479+
if (any(!non_empty)) {
480+
message(paste(
481+
"Removing", sum(!non_empty), "empty LD block(s) with no variants in the region."
482+
))
483+
extracted_LD_matrices_list <- extracted_LD_matrices_list[non_empty]
484+
extracted_LD_variants_list <- extracted_LD_variants_list[non_empty]
485+
block_chroms <- block_chroms[non_empty]
486+
LD_file_paths <- LD_file_paths[non_empty]
487+
}
488+
474489
LD_matrix <- create_LD_matrix(
475490
LD_matrices = extracted_LD_matrices_list,
476491
variants = extracted_LD_variants_list
@@ -604,6 +619,30 @@ partition_LD_matrix <- function(ld_data, merge_small_blocks = TRUE,
604619
colnames(combined_matrix) <- variant_ids
605620
}
606621

622+
# Filter out blocks with invalid indices (empty blocks, out-of-range, NA, Inf)
623+
n_variants <- length(variant_ids)
624+
valid_blocks <- sapply(seq_len(nrow(block_metadata)), function(i) {
625+
s <- block_metadata$start_idx[i]
626+
e <- block_metadata$end_idx[i]
627+
sz <- block_metadata$size[i]
628+
# Block is valid if: size > 0, indices are finite integers, and within range
629+
!is.na(s) && !is.na(e) && is.finite(s) && is.finite(e) &&
630+
sz > 0 && s >= 1 && e >= s && e <= n_variants
631+
})
632+
633+
if (!any(valid_blocks)) {
634+
stop("No valid LD blocks found. All block indices are out of range or empty.")
635+
}
636+
637+
if (any(!valid_blocks)) {
638+
message(paste(
639+
"Removing", sum(!valid_blocks),
640+
"LD block(s) with invalid or out-of-range indices."
641+
))
642+
block_metadata <- block_metadata[valid_blocks, , drop = FALSE]
643+
block_metadata$block_id <- seq_len(nrow(block_metadata))
644+
}
645+
607646
# Validate the block structure of the matrix (skip if only one block)
608647
if (nrow(block_metadata) > 1) {
609648
validate_block_structure(combined_matrix, block_metadata, variant_ids)

0 commit comments

Comments
 (0)