Skip to content

Commit d56eff1

Browse files
Merge pull request #115 from R-Computing-Lab/dev_main
Dev main
2 parents 09fa620 + 91eafd6 commit d56eff1

65 files changed

Lines changed: 4389 additions & 4372 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

DESCRIPTION

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ Suggests:
4747
rmarkdown,
4848
testthat (>= 3.0.0),
4949
tidyverse,
50+
mvtnorm,
5051
withr
5152
VignetteBuilder:
5253
knitr

NAMESPACE

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
export(SimPed)
44
export(addPersonToPed)
5+
export(buildFamilyGroups)
6+
export(buildOneFamilyGroup)
7+
export(buildPedigreeModelCovariance)
8+
export(buildPedigreeMx)
59
export(buildTreeGrid)
610
export(calcAllGens)
711
export(calcFamilySize)
@@ -18,6 +22,7 @@ export(createGenDataFrame)
1822
export(determineSex)
1923
export(dropLink)
2024
export(fitComponentModel)
25+
export(fitPedigreeModel)
2126
export(getWikiTreeSummary)
2227
export(identifyComponentModel)
2328
export(inferRelatedness)

NEWS.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
# BGmisc NEWS
22
# Development version: 1.6.0.9000
3+
Add OpenMx pedigree model builders and docs
4+
Added vignette for OpenMx pedigree model builders
5+
Add option for MZ twins in the additive genetic matrix
6+
Add option to select sex for MZ twin generation.
7+
Add option to tweak pedigree with one id provided
38

49
# BGmisc 1.6.0.1
510
* Add helper functions for checkParents etc
611
* fixed incorrect direction so that parents are pointing to children in the graphs
7-
* Optimize simulatePedigree and helpers for speed and memory usage
12+
* Optimize simulatePedigree and helpers for speed and memory usage
813
* Major gains in speed for deeper pedigrees
914
* Added more tests for simulatePedigree
1015
* Fix error when not enough single people available

R/buildComponent.R

Lines changed: 120 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
#' @param isChild_method character. The method to use for computing the isChild matrix. Options are "classic" or "partialparent"
2020
#' @param adjBeta_method numeric The method to use for computing the building the adjacency_method matrix when using the "beta" build
2121
#' @param compress logical. If TRUE, use compression when saving the checkpoint files. Defaults to TRUE.
22+
#' @param mz_twins logical. If TRUE, merge MZ co-twin columns in the r2 matrix before tcrossprod so that MZ twins are coded with relatedness 1 instead of 0.5. Twin pairs are identified from the \code{twinID} column. When a \code{zygosity} column is also present, only pairs where both members have \code{zygosity == "MZ"} are used; otherwise all \code{twinID} pairs are assumed to be MZ. Defaults to FALSE.
23+
#' @param mz_method character. The method to handle MZ twins. Options are "merging" (default) or "addtwins". "addtwins" adds the twin2 column to the twin1 column before tcrossprod so that all relatedness flows through a single source, then leaves the twin2 column as zero and relies on the fact that the row/col names are the same to copy the values back to twin2 after tcrossprod. "merging" merges the twin2 column into the twin1 column before tcrossprod and then copies the values back to twin2 after tcrossprod so that both twins appear in the final matrix.
24+
#' @param beta logical. Used for benchmarking
2225
#' @param ... additional arguments to be passed to \code{\link{ped2com}}
2326
#' @details The algorithms and methodologies used in this function are further discussed and exemplified in the vignette titled "examplePedigreeFunctions". For more advanced scenarios and detailed explanations, consult this vignette.
2427
#' @export
@@ -32,7 +35,7 @@ ped2com <- function(ped, component,
3235
standardize_colnames = TRUE,
3336
transpose_method = "tcrossprod",
3437
adjacency_method = "direct",
35-
isChild_method = "classic",
38+
isChild_method = "partialparent",
3639
saveable = FALSE,
3740
resume = FALSE,
3841
save_rate = 5,
@@ -42,6 +45,9 @@ ped2com <- function(ped, component,
4245
save_path = "checkpoint/",
4346
adjBeta_method = NULL,
4447
compress = TRUE,
48+
mz_twins = TRUE,
49+
mz_method = "addtwins",
50+
beta = FALSE,
4551
...) {
4652
#------
4753
# Check inputs
@@ -121,12 +127,37 @@ ped2com <- function(ped, component,
121127
ped <- standardizeColnames(ped, verbose = config$verbose)
122128
}
123129

130+
mz_row_pairs <- NULL
131+
mz_id_pairs <- NULL
132+
133+
if (mz_twins == TRUE && "twinID" %in% colnames(ped)) {
134+
df_mz <- findMZtwins(ped,
135+
verbose = config$verbose,
136+
returnIDs = TRUE,
137+
returnRows = TRUE,
138+
returnAsList = TRUE,
139+
beta = beta
140+
)
141+
mz_row_pairs <- df_mz$pair_rows
142+
mz_id_pairs <- df_mz$pair_ids
143+
}
144+
145+
124146
# Load final result if computation was completed
125147
if (config$resume == TRUE && file.exists(checkpoint_files$final_matrix)) {
126148
if (config$verbose == TRUE) cat("Loading final computed matrix...\n")
127149
return(readRDS(checkpoint_files$final_matrix))
128150
}
129151

152+
if (mz_method %in% c("merging") && mz_twins == TRUE && !is.null(mz_row_pairs) && length(mz_row_pairs) > 0 &&
153+
config$component %in% c("additive")) {
154+
# replace all MZ twin IDs with the first twin's ID in each pair so they are merged for the path tracing and all subsequent steps. We will copy the values back to the second twin at the end.
155+
ped <- fuseTwins(ped = ped, mz_row_pairs = mz_row_pairs, mz_id_pairs = mz_id_pairs, config = config, beta = beta)
156+
if (config$verbose == TRUE) {
157+
message("Merged ", length(mz_row_pairs), " MZ twin pair(s) in pedigree dataset for path tracing")
158+
}
159+
}
160+
130161

131162
#------
132163
# Algorithm
@@ -141,6 +172,7 @@ ped2com <- function(ped, component,
141172
cat(paste0("Family Size = ", config$nr, "\n"))
142173
}
143174

175+
#
144176
# Step 1: Construct parent-child adjacency matrix
145177

146178
## A. Resume from Checkpoint if Needed
@@ -195,6 +227,8 @@ ped2com <- function(ped, component,
195227
config = config,
196228
compress = config$compress
197229
)
230+
231+
# TODO merge twin columns
198232
# --- Step 2: Compute Relatedness Matrix ---
199233

200234

@@ -226,7 +260,7 @@ ped2com <- function(ped, component,
226260
# r is I + A + A^2 + ... = (I-A)^-1 from RAM
227261
# could trim, here
228262
## it keeps going until it explains all of the relatedness with themselves (i.e., mtSum == 0)
229-
# some of this precision is articifuial because we literally get to the point that the condon is eaither there or not. probabiliticy
263+
# some of this precision is artificial because we literally get to the point that the condon is eaither there or not. probabiliticy
230264

231265
# how much percision do we need to get unbiased estimates
232266

@@ -281,6 +315,29 @@ ped2com <- function(ped, component,
281315
compress = config$compress
282316
)
283317

318+
if (mz_method == "addtwins" && mz_twins == TRUE && !is.null(mz_row_pairs) && length(mz_row_pairs) > 0) {
319+
if (config$verbose == TRUE) {
320+
message("MZ twin merging enabled: Will merge MZ twin columns in r2 before tcrossprod")
321+
}
322+
323+
# --- Step 3b: Add ---
324+
# MZ twins share the same genetic source. We absorb twin2's column into
325+
# twin1's before tcrossprod so all path-traced relatedness flows through a
326+
# single source. After tcrossprod we copy twin1's row/col back to twin2.
327+
if (!is.null(mz_row_pairs) && length(mz_row_pairs) > 0 && config$component %in% c("additive")) {
328+
# Extract all indices at once for batch operations
329+
pairs_mat <- do.call(rbind, mz_row_pairs)
330+
idx1_all <- pairs_mat[, 1]
331+
idx2_all <- pairs_mat[, 2]
332+
# Batch: absorb all twin2 columns into twin1 columns, then zero twin2
333+
r2[, idx1_all] <- r2[, idx1_all, drop = FALSE] + r2[, idx2_all, drop = FALSE]
334+
r2[, idx2_all] <- 0
335+
336+
if (config$verbose == TRUE) {
337+
message("Added ", length(mz_row_pairs), " MZ twin pair column(s) in r2")
338+
}
339+
}
340+
}
284341
# --- Step 4: T crossproduct ---
285342

286343
if (config$resume == TRUE && file.exists(checkpoint_files$tcrossprod_checkpoint) &&
@@ -300,12 +357,68 @@ ped2com <- function(ped, component,
300357
}
301358
}
302359

360+
if (mz_method %in% c("merging", "addtwins") && mz_twins == TRUE && config$component %in% c("additive") && !is.null(mz_row_pairs) && length(mz_row_pairs) > 0) {
361+
# --- Step 4b: Restore MZ twins ---
362+
# Copy twin1's row/col to twin2 so both twins appear in the final matrix.
363+
if (config$sparse == FALSE) {
364+
r <- as.matrix(r)
365+
rnames <- rownames(r)
366+
ids_mat <- do.call(rbind, mz_id_pairs)
367+
idx1_all <- match(ids_mat[, 1], rnames)
368+
idx2_all <- match(ids_mat[, 2], rnames)
369+
# Batch copy: twin1 rows/cols -> twin2 rows/cols
370+
r[idx2_all, ] <- r[idx1_all, ]
371+
372+
r[, idx2_all] <- r[, idx1_all]
373+
} else {
374+
# TODO this is really slow. Can we do it without coercing to dense? Maybe by doing row/col replacement on the sparse matrix directly? Or by constructing a sparse matrix with the twin2 values and adding it to r?
375+
# r <- df_add
376+
377+
rnames <- r@Dimnames[[1]]
378+
379+
ids_mat <- do.call(rbind, mz_id_pairs)
380+
# needs to use sparse indexing to avoid coercion to dense
381+
idx1_all <- match(ids_mat[, 1], rnames)
382+
idx2_all <- match(ids_mat[, 2], rnames)
383+
384+
twin1_rows <- r[idx1_all, , drop = FALSE]
385+
twin1_cols <- r[, idx1_all, drop = FALSE]
386+
twin1_rows@Dimnames[[1]] <- rnames[idx2_all]
387+
twin1_cols@Dimnames[[2]] <- rnames[idx2_all]
388+
twin1_self <- r[idx1_all, idx1_all, drop = FALSE]
389+
twin1_self@Dimnames[[1]] <- rnames[idx2_all]
390+
391+
r[idx2_all, ] <- twin1_rows
392+
r[, idx2_all] <- twin1_cols
393+
r[idx2_all, idx2_all] <- twin1_self
394+
395+
# Batch copy: twin1 rows/cols -> twin2 rows/cols
396+
397+
# Row/column replacement on a dsCMatrix (symmetric) causes Matrix to
398+
# coerce to dgCMatrix (general), doubling stored entries. Convert back
399+
400+
r <- Matrix::drop0(r)
401+
402+
# so both mz_method paths return the same sparse class.
403+
if (methods::is(r, "CsparseMatrix") && !methods::is(r, "symmetricMatrix")) {
404+
r <- Matrix::forceSymmetric(r)
405+
}
406+
}
407+
if (config$verbose == TRUE) {
408+
message("Restored ", length(mz_row_pairs), " MZ twin pair(s) in relatedness matrix")
409+
}
410+
}
411+
412+
303413
if (config$component %in% c("mitochondrial", "mtdna", "mitochondria")) {
304414
r@x <- rep(1, length(r@x))
305415
# Assign 1 to all nonzero elements for mitochondrial component
306416
}
307417

308-
if (config$sparse == FALSE) {
418+
# Remove explicit zeros so that both mz_method paths produce
419+
# structurally identical sparse matrices
420+
421+
if (config$sparse == FALSE && !methods::is(r, "matrix")) {
309422
r <- as.matrix(r)
310423
}
311424
# flattens diagonal if you don't want to deal with inbreeding
@@ -335,6 +448,8 @@ ped2add <- function(ped, max_gen = 25, sparse = TRUE, verbose = FALSE,
335448
save_rate_parlist = 100000 * save_rate,
336449
save_path = "checkpoint/",
337450
compress = TRUE,
451+
mz_twins = FALSE,
452+
mz_method = "addtwins",
338453
...) {
339454
ped2com(
340455
ped = ped,
@@ -353,6 +468,8 @@ ped2add <- function(ped, max_gen = 25, sparse = TRUE, verbose = FALSE,
353468
save_rate_parlist = save_rate_parlist,
354469
save_path = save_path,
355470
compress = compress,
471+
mz_twins = mz_twins,
472+
mz_method = mz_method,
356473
...
357474
)
358475
}

0 commit comments

Comments
 (0)