---
title: "Validating and Repairing Pedigree Data with BGmisc"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Validation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
options(rmarkdown.html_vignette.check_title = FALSE)
library(tidyverse)
```

# Introduction


Working with pedigree data often involves dealing with inconsistencies, missing information, and errors. The `BGmisc` package provides tools to identify and, where possible, repair these issues automatically. This vignette demonstrates how to validate and clean pedigree data using `BGmisc`'s validation functions.


# Identifying and Repairing ID Issues

The `checkIDs()` function detects two types of ID duplication:

- Between-row duplication: When two or more individuals share the same ID
- Within-row duplication: When an individual's parents' IDs are incorrectly listed as their own ID


To illustrate `checkIDs()` in action, we will examine a clean example using the Potter family dataset.


```{r,checkIDs}
library(BGmisc)

# Load our example dataset
df <- ped2fam(potter, famID = "newFamID", personID = "personID")

# Check for ID issues
result <- checkIDs(df, repair = FALSE)
print(result)
```

The checkIDs() function checks for:

- Whether all IDs are unique (reported by `all_unique_ids`, which tells you if all IDs in the dataset are unique, and `total_non_unique_ids`, which gives you the count of non-unique IDs found)
- Cases where someone's ID matches their parent's ID (shown in `total_own_father` and `total_own_mother`, which count individuals whose father's or mother's ID matches their own ID)
- Total duplicated parent IDs (tracked by `total_duplicated_parents`, which counts individuals with duplicated parent IDs)
- Within-row duplicates (measured by `total_within_row_duplicates` showing the count and `within_row_duplicates` indicating their presence)

As the output shows, there are no duplicates in our sample dataset.


## A Tale of Two Duplicates

To understand how these tools work in practice, let's create a dataset with two common real-world problems. First, we'll accidentally give Vernon Dursley the same ID as his sister Marjorie (a common issue when merging family records). Then, we'll add a complete duplicate of Dudley Dursley (as might happen during data entry).


```{r datamade}

# Create our problematic dataset
df_duplicates <- df
# Sibling ID conflict
df_duplicates$personID[df_duplicates$name == "Vernon Dursley"] <- 
  df_duplicates$personID[df_duplicates$name == "Marjorie Dursley"]
# Duplicate entry
df_duplicates <- rbind(df_duplicates, 
                       df_duplicates[df_duplicates$name == "Dudley Dursley", ])

```


If we look at the data using standard tools, the problems aren't immediately obvious:

```{r}
library(tidyverse)

summarizeFamilies(df_duplicates, 
                  famID = "newFamID", 
                  personID = "personID")$family_summary %>% 
  glimpse()

```

This is where `checkIDs` becomes invaluable:

```{r}
# Identify duplicates
result <- checkIDs(df_duplicates)
print(result)
```

As we can see from this output, there are `r result$total_non_unique_ids` non-unique IDs in the dataset, specifically `r result$non_unique_ids`. Let's take a peek at the duplicates:

```{r}
# Let's examine the problematic entries
df_duplicates %>%
  filter(personID %in% result$non_unique_ids) %>%
  arrange(personID)
```


Yep, these are definitely the duplicates.

### Repairing Between-Row Duplicates

Some ID issues can be fixed automatically. Let's try the repair option:


```{r}
df_repair <- checkIDs(df, repair = TRUE)

df_repair %>%
  filter(ID %in% result$non_unique_ids) %>%
  arrange(ID)

result <- checkIDs(df_repair)

print(result)
```

Great! Notice what happened here: the function was able to repair the full duplicate, without any manual intervention. That still leaves us with the sibling ID conflict, but that's a more complex issue that would require manual intervention. We'll leave that for now.


## Oedipus ID


Just as Oedipus discovered his true relationship was not what records suggested, our data can reveal its own confused parentage when an ID is incorrectly listed as its own parent. Let's examine this error:


Sometimes, an individual's parents' IDs may be incorrectly listed as their own ID, leading to within-row duplicates. The checkIDs function can also identify these errors:

```{r within}
# Create a sample dataset with within-person duplicate parent IDs

df_within <- ped2fam(potter, famID = "newFamID", personID = "personID")

df_within$momID[df_within$name == "Vernon Dursley"] <- df_within$personID[df_within$name == "Vernon Dursley"]

# Check for within-row duplicates
result <- checkIDs(df_within, repair = FALSE)
print(result)
```

In this example, we have created a within-row duplicate by setting the momID of Vernon Dursley to his own ID. The `checkIDs` function correctly identifies that this error is present.

To repair within-row duplicates, you will be able to set the repair argument to `TRUE`, eventually. This feature is currently under development and will be available in future versions of the package. In the meantime, you can manually inspect and then correct these errors in your dataset.

```{r}
# Find the problematic entry

df_within[df_within$momID %in% result$is_own_mother_ids, ]
```

There are several ways to correct this issue, depending on the specifics of your dataset. In this case, you could correct the momID for Vernon Dursley to the correct value, resolving the within-row duplicate, likely by assuming that his sister Marjorie shares the same mother.

# Identifying and Repairing Sex Coding Issues

Another critical aspect of pedigree validation is ensuring the consistency of sex coding. This brings us to an important distinction in genetic studies between biological sex (genotype) and gender identity (phenotype):

- Biological sex (genotype) refers to an individual's chromosomal configuration, typically XX for female and XY for male in humans, though variations exist.
- Gender identity (phenotype) encompasses a broader, richer, personal, deeply-held sense of being male, female, a blend of both, neither, or another gender entirely.

The `checkSex` function focuses on biological sex coding consistency, particularly looking for:
- Mismatches between parent roles and recorded sex
- Individuals listed as both parent and child
- Inconsistent sex coding across the dataset

Let's examine how it works:


```{r}
# Validate sex coding

results <- checkSex(potter,
  code_male = 1,
  code_female = 0,
  verbose = TRUE, repair = FALSE
)
print(results)
```


When inconsistencies are found, you can attempt automatic repair:

```{r}
# Repair sex coding
df_fix <- checkSex(potter,
  code_male = 1,
  code_female = 0,
  verbose = TRUE, repair = TRUE
)
print(df_fix)
```


When the repair argument is set to `TRUE`, repair process follows several rules:
- Parents listed as mothers must be female
- Parents listed as fathers must be male
- Sex codes are standardized to the specified code_male and code_female values
- If no sex code is provided, the function will attempt to infer what male and female are coded with. The most frequently assigned sex for mothers and fathers will be used as the standard.

Note that automatic repairs should be carefully reviewed, as they may not always reflect the correct biological relationships. In cases where the sex coding is ambiguous or conflicts with known relationships, manual inspection and domain knowledge may be required.

<!--
## Practical Example: Cleaning a Pedigree

Below is an example of how to clean and repair a pedigree dataset using the BGmisc package. This example is based on the approach Mason typically takes for data cleaning.

```{r, eval = FALSE}
# note, is broken right now
# Load necessary libraries and datasets
library(tidyverse)
library(BGmisc)
set.seed(123)
# Create a sample dataset similar to the one used in Mason's approach
sample_data <- data.frame(
  ID = 1:10,
  name = c("Person1", "Person2", "Person3", "Person4", "Person5", "Person6", "Person7", "Person8", "Person9", "Person10"),
  dadID = c(NA, NA, 1, 1, 3, 3, 5, 5, 7, 7),
  momID = c(NA, NA, 2, 2, 4, 4, 6, 6, 7, 8),
  sex = c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0),
  byr = runif(10, 1900, 2000),
  dyr = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
)



summarizePedigrees(sample_data)


# Clean the sample dataset
cleaned_data <- sample_data %>%
  janitor::remove_empty(c("rows", "cols")) %>%
  mutate(
    sex_factor = as.factor(case_when(sex == 1 ~ "male", sex == 0 ~ "female"))
  )

# Check for duplicate IDs
temp_check <- checkIDs(cleaned_data, verbose = TRUE, repair = FALSE)
all_duplicated_ids <- cbind(temp_check$non_unique_ids, temp_check$duplicated_parents_ids)

cleaned_data <- cleaned_data %>%
  mutate(
    duplicated = case_when(ID %in% temp_check$non_unique_ids ~ 1, TRUE ~ 0),
    duplicated_parent = case_when(dadID %in% all_duplicated_ids | momID %in% all_duplicated_ids ~ 1, TRUE ~ 0),
    duplicated_source_ID = case_when(ID %in% all_duplicated_ids ~ ID, dadID %in% all_duplicated_ids ~ dadID, momID %in% all_duplicated_ids ~ momID, TRUE ~ NA_integer_),
    alteredlinks = 0
  )

# Display and manually correct specific errors
cleaned_data %>%
  filter(duplicated == 1 | duplicated_parent == 1) %>%
  arrange(duplicated_source_ID, ID) %>%
  print(n = Inf)

# Perform specific corrections
cleaned_data <- cleaned_data %>%
  mutate(
    alteredlinks = case_when(ID == 9 ~ 1, TRUE ~ alteredlinks),
    ID = case_when(ID == 7 & round(byr, digits = 0) == 2020 ~ ID + 1e6, TRUE ~ ID)
  )

# Final check for remaining duplicates
final_check <- checkIDs(cleaned_data, verbose = TRUE, repair = FALSE)
print(final_check)
```
-->

# Best Practices for Pedigree Validation

Through extensive work with pedigree data, we've learned several key principles:

- Always inspect your data before applying automatic repairs
- Use summarizeFamilies() to get an overview of family structures
- Keep detailed records of changes made during cleaning
- Validate after each repair step
- Create backups before applying repairs
- Trust your domain knowledge - automatic repairs are helpful but not infallible

By following these best practices, and leveraging functions like `checkIDs`, `checkSex`, and `recodeSex`, you can ensure the integrity of your pedigree data, facilitating accurate analysis and research.
