---
title: "Module 3: Sample quality control"
format:
  html:
    toc: true
    toc-depth: 2
    toc-title: "Contents"
    toc-location: left
    toc-expand: true
    anchor-sections: true
    code-copy: true
    code-fold: false
    code-overflow: wrap
    embed-resources: true
    include-after-body:
      text: |
        <script>
        document.querySelectorAll('a[href$=".qmd"]').forEach(function (a) {
          a.setAttribute('href', a.getAttribute('href').replace(/[.]qmd$/, '.html'));
        });
        </script>
editor: visual
editor_options:
  chunk_output_type: console
course_source_sha256: "f3a59cdffe0a84259e4b32168975e3c624d279475038b010bb4933b0527819b7"
---

Open `GWAS_course.Rproj` and work from the project root. Run the chunks in order in a fresh R session.
All data are simulated. Read each summary, run its chunk and compare your result with the expected result.
The linked step pages explain the ideas and provide troubleshooting.

::: {.callout-note title="In this module"}

**Time.** About 70 minutes.

**Before you start.** You need the full [checkpoint at step 2.8](https://www.manuelgentiluomo.it/teaching/gwas/module-2/step-2-8). The first code chunk checks the files that this module needs.

**Steps.**

- [3.1 Rough cleaning](#step-3-1)
- [3.2 Sample call rate](#step-3-2)
- [3.3 Recorded and genetic sex](#step-3-3)
- [3.4 LD pruning](#step-3-4)
- [3.5 Heterozygosity](#step-3-5)
- [3.6 Relatedness and duplicates](#step-3-6)
- [3.7 Batch effects](#step-3-7)
- [3.8 Sample QC summary and checkpoint](#step-3-8)

**Where the module ends.** The checkpoint at step 3.8.

:::

```{r}
#| label: module3_check
if (!file.exists("config.R") && file.exists("../config.R")) setwd("..")
source("R/guided.R"); guided_check_module(3)
```

```{r}
#| label: module3_setup
source("R/guided.R")
cfg <- guided_init()
```

## Step 3.1 · Rough cleaning {#step-3-1}

We remove samples and variants with very many missing calls. This first clean prevents the worst failures from distorting the checks that follow.

[Read step 3.1 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-1).

```{r}
#| label: s3-1
input <- guided_path(cfg, "2.8")  # <1>
rough <- guided_path(cfg, "3.1", "samples")
run_plink(cfg, c("--pfile", input, "--mind", "0.10", "--make-pgen", "--out", rough))  # <2>
run_plink(cfg, c("--pfile", rough, "--geno", "0.10", "--make-pgen", "--out", guided_path(cfg, "3.1")))  # <3>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.1", "2.8")
guided_register(cfg, "3.1", "2.8", 2013, 296360, operations = ops)
```

1. Choose the input files and the names for the saved files.
2. Remove samples with more than 10% of calls missing.
3. Remove variants with more than 10% of calls missing.

### What each option does

**Command 1: remove poor samples**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--mind` | Removes samples with more than 10% missing calls. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 2: remove poor variants**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--geno` | Removes variants with more than 10% missing calls in the input dataset. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

Three wells and 150 variants are removed. 2,013 samples and 296,360 variants remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s2-8_state --mind 0.10 --make-pgen --out results/guided/s3-1_samples --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-1_samples --geno 0.10 --make-pgen --out results/guided/s3-1_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The step makes a rough first clean. `--mind` is the largest share of missing calls that a sample may have. `--geno` is the same limit for a variant. A low value is strict and removes more. A high value is generous. At 0.10 only wells and sites that are clearly broken are removed. The finer checks come later, at steps 3.2 and 4.1, so this first clean can be generous. Each trial below starts from the same input as the step and changes one threshold only.

```{r}
#| label: s3-1_thresholds
#| eval: false
# Optional. Each trial starts from the same input and changes one threshold only. Your results folder is not changed.
thresholds <- c(0.01, 0.02, 0.05, 0.10, 0.20)
samples <- threshold_counts(cfg, guided_path(cfg, "2.8"), "--mind", thresholds)  # <1>
samples$course_value <- samples$threshold == 0.10
samples
variants <- threshold_counts(cfg, guided_path(cfg, "3.1", "samples"), "--geno", thresholds)  # <2>
variants$course_value <- variants$threshold == 0.10
variants
par(mfrow = c(1, 2)); plot_threshold_trials(samples, "Samples removed"); plot_threshold_trials(variants, "Variants removed")  # <3>
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```

1. Samples: --mind on the cohort saved at 2.8.
2. Variants: --geno on the samples that remain after --mind 0.10.
3. Plot the removed numbers. The course value is the large diamond.


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s2-8_state --mind 0.05 --make-just-psam --out results/trials/s3-1_trial --threads 2 --memory 2048
```

The log file `results/trials/s3-1_trial.log` states how many samples were removed. To repeat the trial, change the number after `--mind` and use a new `--out` name. For variants, use `--geno` and `--make-just-pvar`, and start from `results/guided/s3-1_samples`. PLINK 2 treats a dosage without a hard call as missing by default (the `dosage` modifier changes this). The course data have hard calls only, so this makes no difference here.

The expected result of the trials:

Samples removed by `--mind`:

| Threshold | Samples removed | Samples remaining |
| --- | --- | --- |
| 0.01 | 121 | 1,895 |
| 0.02 | 45 | 1,971 |
| 0.05 | 3 | 2,013 |
| **0.1 (course value)** | 3 | 2,013 |
| 0.2 | 3 | 2,013 |

Variants removed by `--geno`, after `--mind 0.10`:

| Threshold | Variants removed | Variants remaining |
| --- | --- | --- |
| 0.01 | 3,705 | 292,805 |
| 0.02 | 958 | 295,552 |
| 0.05 | 735 | 295,775 |
| **0.1 (course value)** | 150 | 296,360 |
| 0.2 | 130 | 296,380 |

How to read it. Between 0.05 and 0.20 the same three wells are removed. Those wells are so poor that no limit in this range keeps them. Below 0.05 the limit starts to remove good wells too (45 at 0.02 and 121 at 0.01). For variants, a stricter limit removes many more sites. The course value of 0.10 keeps the rough clean generous on purpose.

Expected plot. For `--geno`, the horizontal axis shows the threshold and the vertical axis shows the number of variants removed. A red diamond marks the course value (0.1), where 150 variants are removed. For `--mind`, the horizontal axis shows the threshold and the vertical axis shows the number of samples removed. A red diamond marks the course value (0.1), where 3 samples are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 3.2 · Sample call rate {#step-3-2}

We remove samples with more than 2% of their genotype calls missing. This keeps samples with enough information for the later analysis.

[Read step 3.2 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-2).

```{r}
#| label: s3-2
run_plink(cfg, c("--pfile", guided_path(cfg, "3.1"), "--mind", "0.02", "--make-pgen", "--out", guided_path(cfg, "3.2")))  # <1>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.2", "3.1")
guided_register(cfg, "3.2", "3.1", 1971, 296360, operations = ops)
```

1. Remove samples with more than 2% of calls missing.

### What each option does

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--mind` | Removes samples with more than 2% missing calls, keeping a call rate of at least 98%. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

42 more wells are removed. 1,971 samples and 296,360 variants remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-1_state --mind 0.02 --make-pgen --out results/guided/s3-2_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The call rate of a sample is the share of its calls that are not missing. `--mind 0.02` removes samples with more than 2% missing calls, which is a call rate below 98%. A lower limit keeps more samples but lets in samples with poor DNA. A higher limit removes more samples and may throw away good data. A call rate of 95% to 98% is a common choice in genome-wide studies, and 98% is the stricter end of it. Each trial starts from the cohort saved at 3.1 and changes the limit only.

```{r}
#| label: s3-2_thresholds
#| eval: false
# Optional. Each trial starts from the same input and changes one threshold only.
thresholds <- c(0.01, 0.02, 0.05, 0.10, 0.20)
trial <- threshold_counts(cfg, guided_path(cfg, "3.1"), "--mind", thresholds)
trial$course_value <- trial$threshold == 0.02
trial
# Plot the removed samples. The course value is the large diamond.
plot_threshold_trials(trial, "Samples removed")
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s3-1_state --mind 0.05 --make-just-psam --out results/trials/s3-2_trial --threads 2 --memory 2048
```

The log file `results/trials/s3-2_trial.log` states how many samples were removed. To repeat the trial, change the number after `--mind` and use a new `--out` name.

The expected result of the trials:

| Threshold | Samples removed | Samples remaining |
| --- | --- | --- |
| 0.01 | 118 | 1,895 |
| **0.02 (course value)** | 42 | 1,971 |
| 0.05 | 0 | 2,013 |
| 0.1 | 0 | 2,013 |
| 0.2 | 0 | 2,013 |

How to read it. At 0.02 the course removes 42 wells. At 0.05 none are removed, so all 42 wells have between 2% and 5% missing calls. At 0.01 another 76 wells go (118 in total). The step is a clear case of a choice: the course value removes the wells that are poor but not broken.

Expected plot. For `--mind`, the horizontal axis shows the threshold and the vertical axis shows the number of samples removed. A red diamond marks the course value (0.02), where 42 samples are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 3.3 · Recorded and genetic sex {#step-3-3}

We compare recorded sex with patterns in the X and Y chromosome calls. We remove flagged wells from this teaching analysis because a mismatch needs review before the sample is used.

[Read step 3.3 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-3).

```{r}
#| label: s3-3
split <- guided_path(cfg, "3.3", "par")  # <1>
report <- guided_path(cfg, "3.3", "sexcheck")
run_plink(cfg, c("--pfile", guided_path(cfg, "3.2"), "--split-par", "b38", "--make-pgen", "--out", split))  # <2>
run_plink(cfg, c("--pfile", split, "--check-sex", "max-female-xf=0.2", "min-male-xf=0.8",  # <3>
  "max-female-ycount=100", "min-male-ycount=1000", "--out", report))
sexcheck <- guided_table(paste0(report, ".sexcheck"))  # <4>
bad <- sexcheck$IID[sexcheck$STATUS != "OK"]
remove_file <- guided_list(bad, guided_path(cfg, "3.3", "remove.txt"), TRUE)
run_plink(cfg, c("--pfile", split, "--remove", remove_file, "--make-pgen", "--out", guided_path(cfg, "3.3")))  # <5>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.3", "3.2", extra = data.frame(option = "--split-par", value = "b38"))
guided_register(cfg, "3.3", "3.2", 1963, 296360, operations = ops)
```

1. Choose names for the chromosome files and sex report.
2. Label the regions shared by the X and Y chromosomes.
3. Compare recorded sex with the X and Y chromosome results.
4. Read the report and list samples that need to be removed.
5. Save the dataset without the flagged samples.

### What each option does

**Command 1: label the shared X and Y regions**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--split-par` | Uses GRCh38 boundaries (b38) to label the shared regions of X and Y separately. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 2: compare recorded sex with DNA**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--check-sex` | Compares recorded sex with X chromosome patterns and the number of observed Y calls. |
| &nbsp;&nbsp;&rarr; `max-female-xf` | Sets 0.2 as the largest accepted X chromosome F value for a recorded female. F measures how homozygous the X chromosome looks, meaning how often the two copies carry the same DNA letter. |
| &nbsp;&nbsp;&rarr; `min-male-xf` | Sets 0.8 as the smallest accepted X chromosome F value for a recorded male. F measures how homozygous the X chromosome looks. Values near 1 are expected when there is only one X chromosome, as in males. |
| &nbsp;&nbsp;&rarr; `max-female-ycount` | Accepts at most 100 observed Y calls for a recorded female. |
| &nbsp;&nbsp;&rarr; `min-male-ycount` | Requires at least 1000 observed Y calls for a recorded male. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 3: remove samples flagged by the sex check**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--remove` | Removes the samples named in the supplied sample list. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

Eight flagged wells are removed. 1,963 samples remain. 520 sites are labelled PAR1 or PAR2. The number of variants does not change.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-2_state --split-par b38 --make-pgen --out results/guided/s3-3_par --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-3_par --check-sex max-female-xf=0.2 min-male-xf=0.8 max-female-ycount=100 min-male-ycount=1000 --out results/guided/s3-3_sexcheck --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-3_par --remove results/guided/s3-3_remove.txt --make-pgen --out results/guided/s3-3_state --threads 2 --memory 2048
```

:::

## Step 3.4 · LD pruning {#step-3-4}

We select common DNA sites that are less strongly correlated with each other. This stops groups of similar sites from weighing too much in the sample checks. The full dataset is kept for the association scan.

[Read step 3.4 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-4).

```{r}
#| label: s3-4
regions <- guided_high_ld(cfg)  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.3"), "--chr", "1-22", "--maf", "0.05", "--geno", "0.02",  # <2>
  "--exclude", "bed1", regions, "--indep-pairwise", "200kb", "0.2", "--out", guided_path(cfg, "3.4", "prune")))
pruned <- readLines(paste0(guided_path(cfg, "3.4", "prune"), ".prune.in"))  # <3>
stopifnot(length(pruned) == 69539L)
cat(length(pruned), "variants kept by LD pruning\n")
# Course bookkeeping: records the counts for the next step. Do not change.
guided_artifact_checkpoint(cfg, "3.4", c(paste0(guided_path(cfg, "3.4", "prune"), c(".prune.in", ".prune.out")), regions), parent = "3.3")
```

1. Write the list of regions where nearby variants are strongly correlated.
2. Select variants with less similar patterns of DNA letters.
3. Check and print how many variants were selected.

### What each option does

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--chr` | Uses only chromosomes 1 to 22, the autosomes. |
| `--maf` | Keeps variants whose less common allele has a frequency of at least 5%. |
| `--geno` | Keeps variants with no more than 2% missing calls. |
| `--exclude` | Leaves out variants within the listed DNA regions. |
| &nbsp;&nbsp;&rarr; `bed1` | Reads DNA regions with positions counted from 1 and includes both ends of each region. |
| `--indep-pairwise` | Compares genotype patterns at pairs of sites within windows of 200 kb (200,000 DNA bases). It drops one site of every pair with a squared correlation (r²) above 0.2. A larger r² means that the genotypes of the two sites vary together more closely. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

The `.prune.in` file lists 69,539 sites. The complete analysis state still has 296,360 variants.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-3_state --chr 1-22 --maf 0.05 --geno 0.02 --exclude bed1 results/guided/s3-4_high_ld.bed1 --indep-pairwise 200kb 0.2 --out results/guided/s3-4_prune --threads 2 --memory 2048
```

:::

## Step 3.5 · Heterozygosity {#step-3-5}

We check whether each sample has unusually many or few sites with two different DNA letters. We remove samples with unusually many such sites and flag those with unusually few for review, because an unusual value alone does not prove an error.

[Read step 3.5 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-5).

```{r}
#| label: s3-5
report <- guided_path(cfg, "3.5", "het")  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.3"), "--extract", paste0(guided_path(cfg, "3.4", "prune"), ".prune.in"), "--het", "--out", report))  # <2>
het <- guided_table(paste0(report, ".het"))  # <3>
f <- as.numeric(het$F)
mean_f <- mean(f); sd_f <- sqrt(mean((f - mean_f)^2))
low <- het$IID[f < mean_f - 3 * sd_f]  # <4>
high <- het$IID[f > mean_f + 3 * sd_f]
guided_list(high, guided_path(cfg, "3.5", "flag_high.txt"), TRUE)  # <5>
remove_file <- guided_list(low, guided_path(cfg, "3.5", "remove.txt"), TRUE)
run_plink(cfg, c("--pfile", guided_path(cfg, "3.3"), "--remove", remove_file, "--make-pgen", "--out", guided_path(cfg, "3.5")))  # <6>
print(c(mean_F = mean_f, SD_F = sd_f))  # <7>
print(c(low_removed = length(low), high_flagged = length(high)))
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.5", "3.3")
guided_register(cfg, "3.5", "3.4", 1950, 296360, operations = ops)
```

1. Choose the name for the report of matching DNA letters.
2. Measure matching DNA letters using the selected variants.
3. Read the report and calculate the average and spread of F.
4. Find samples with unusually low or high F values.
5. Save the high F review list and the low F removal list.
6. Save the dataset without the low F samples.
7. Print the average and spread of F, then the numbers of flagged samples as whole numbers.

### What each option does

**Command 1: measure matching DNA letters**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--extract` | Uses only the variants named in the supplied variant list. |
| `--het` | Reports, for each sample, the observed and expected numbers of genotypes with two matching DNA letters, and calculates F from them. R reads the F values and calculates the review thresholds. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 2: remove samples with unusually high heterozygosity**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--remove` | Removes the samples named in the supplied sample list. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

13 wells with low F are removed. Eight wells with high F are flagged and kept. The mean F is approximately 0.0078. The population SD is approximately 0.0298. 1,950 samples remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-3_state --extract results/guided/s3-4_prune.prune.in --het --out results/guided/s3-5_het --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-3_state --remove results/guided/s3-5_remove.txt --make-pgen --out results/guided/s3-5_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The statistic F compares the homozygosity that we see in a sample with the homozygosity that we expect from the allele frequencies. A very low F means too many heterozygous calls, which can come from contamination. A very high F means too few, which can come from related parents or a different ancestry. The course removes samples with F more than 3 standard deviations (SD) below the mean. It only flags, and keeps, samples with F more than 3 SD above the mean. The trials change the number of SD from 2 to 4. They use the same F values.

```{r}
#| label: s3-5_thresholds
#| eval: false
# Optional. The trials use the table of F values that the step wrote. No PLINK run is needed.
multipliers <- c(2, 2.5, 3, 3.5, 4)
trial <- het_counts(guided_table(paste0(guided_path(cfg, "3.5", "het"), ".het")), multipliers)
trial$course_value <- trial$threshold == 3
trial
# Plot the removed samples. The course value is the large diamond.
plot_threshold_trials(trial, "Samples removed", log_x = FALSE)
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s3-3_state --extract results/guided/s3-4_prune.prune.in --het --out results/trials/s3-5_trial --threads 2 --memory 2048
```

This command writes the F table (`results/trials/s3-5_trial.het`). The limit itself is not a PLINK option: the course calculates it in R from the table. To repeat a trial in R, change the number 3 in the rule for `low` and `high` at the step.

The expected result of the trials:

| SD from the mean | Samples removed | Samples remaining | Samples flagged |
| --- | --- | --- | --- |
| 2 | 13 | 1,950 | 13 |
| 2.5 | 13 | 1,950 | 11 |
| **3 (course value)** | 13 | 1,950 | 8 |
| 3.5 | 13 | 1,950 | 5 |
| 4 | 13 | 1,950 | 0 |

How to read the two numbers. "Removed" counts wells with an F value below the mean by more than the chosen number of SD. They have too many heterozygous calls, so the course takes them out of the data. At the course value of 3 SD, 13 wells are removed. "Flagged" counts wells with an F value above the mean by more than the chosen number of SD. They have too few heterozygous calls. The course keeps them in the data and only lists them for review. At the course value, 8 wells are flagged. Now the table. The same 13 wells are removed at every limit from 2 to 4 SD. This group is clearly separate from the rest. The number of flagged wells changes from 13 to 0, so it depends more on the rule than on the data. Flagged wells are kept, so this choice does not change the cohort.

Expected plot. For `F cutoff (standard deviations)`, the horizontal axis shows the threshold and the vertical axis shows the number of samples removed. A red diamond marks the course value (3), where 13 samples are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 3.6 · Relatedness and duplicates {#step-3-6}

We compare pairs of samples to find repeated measurements and close relatives. We apply the stated removal rules so that repeated or closely related people do not distort the later association analysis.

[Read step 3.6 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-6).

```{r}
#| label: s3-6
report <- guided_path(cfg, "3.6", "king")  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.5"), "--extract", paste0(guided_path(cfg, "3.4", "prune"), ".prune.in"),  # <2>
  "--make-king-table", "--king-table-filter", "0.0442", "--out", report))
kin <- guided_table(paste0(report, ".kin0"))  # <3>
kin <- kin[order(-as.numeric(kin$KINSHIP)), ]
metadata <- guided_metadata(cfg)  # <4>
remove <- character()
for (i in seq_len(nrow(kin))) {  # <5>
  a <- kin$IID1[i]; b <- kin$IID2[i]; value <- as.numeric(kin$KINSHIP[i])
  if (value > 0.354) {  # <6>
    if (endsWith(a, "_R2") || endsWith(b, "_R2")) {  # <7>
      remove <- union(remove, if (endsWith(a, "_R2")) a else b)
    } else {
      ai <- match(a, metadata$IID); bi <- match(b, metadata$IID)  # <8>
      same <- identical(unname(unlist(metadata[ai, c("SEX", "Age", "Disease")])),
                        unname(unlist(metadata[bi, c("SEX", "Age", "Disease")])))
      remove <- union(remove, if (same) max(a, b) else c(a, b))  # <9>
    }
  } else if (value > 0.177 && !a %in% remove && !b %in% remove) remove <- union(remove, max(a, b))  # <10>
}
remove_file <- guided_list(remove, guided_path(cfg, "3.6", "remove.txt"), TRUE)  # <11>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.5"), "--remove", remove_file, "--make-pgen", "--out", guided_path(cfg, "3.6")))  # <12>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.6", "3.5")
guided_register(cfg, "3.6", "3.5", 1920, 296360, operations = ops)
```

1. Choose the name for the report comparing pairs of samples.
2. Compare pairs using the selected variants.
3. Read the pairs and put the closest matches first.
4. Read the sample details and start an empty removal list.
5. Review each pair to decide which samples to remove.
6. Treat the closest matches as repeated samples.
7. Remove the labelled repeat when its name ends in _R2.
8. Compare sex, age and disease status for unlabelled repeats.
9. Keep one matching record or remove both conflicting records.
10. Keep one person from each remaining closely related pair.
11. Write the removal list.
12. Save the dataset without the listed samples.

### What each option does

**Command 1: compare pairs of samples**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--extract` | Uses only the variants named in the supplied variant list. |
| `--make-king-table` | Estimates how closely related each pair of samples is and writes a table. |
| `--king-table-filter` | Writes only pairs whose kinship score is above 0.0442. The kinship score measures how closely two people are related. This value is an approximate boundary for third-degree relatives such as first cousins. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 2: remove repeated or closely related samples**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--remove` | Removes the samples named in the supplied sample list. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

There are 19 duplicate-class pairs and ten first-degree pairs. In total, 30 records are removed. 1,920 samples remain. Pairs can overlap, because one person can be in more than one pair. For this reason, the pair counts are not counts of unique people.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-5_state --extract results/guided/s3-4_prune.prune.in --make-king-table --king-table-filter 0.0442 --out results/guided/s3-6_king --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-5_state --remove results/guided/s3-6_remove.txt --make-pgen --out results/guided/s3-6_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The kinship coefficient estimates how much DNA two samples share. The usual KING cutoffs are 0.354 for repeated samples and identical twins, 0.177 for first-degree relatives, 0.0884 for second-degree relatives and 0.0442 for third-degree relatives (Manichaikul et al. 2010, doi:10.1093/bioinformatics/btq559). This step does not use `--king-cutoff`. It writes the table of pairs with `--make-king-table` and `--king-table-filter 0.0442`, and a rule in R decides who to remove. The trials change the cutoff for relatives. Pairs above 0.354 are always treated as repeats.

```{r}
#| label: s3-6_thresholds
#| eval: false
# Optional. The trials use the table of pairs that the step wrote. No PLINK run is needed.
cutoffs <- c(0.0442, 0.0884, 0.177, 0.354)
kin <- guided_table(paste0(guided_path(cfg, "3.6", "king"), ".kin0"))
trial <- data.frame(threshold = cutoffs, removed = kinship_counts(kin, guided_metadata(cfg), cutoffs))
trial$course_value <- trial$threshold == 0.177
trial
# Plot the removed samples. The course value is the large diamond.
plot_threshold_trials(trial, "Samples removed")
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s3-5_state --extract results/guided/s3-4_prune.prune.in --king-cutoff 0.177 --out results/trials/s3-6_trial --threads 2 --memory 2048
```

`--king-cutoff` removes one member of each pair above the cutoff with a greedy rule, and it writes two lists of sample IDs (`.king.cutoff.in.id` and `.king.cutoff.out.id`). Its count can differ a little from the course rule, which also treats repeats separately. To repeat the trial, change the number after `--king-cutoff`.

The expected result of the trials:

| Kinship cutoff | Samples removed | Samples remaining |
| --- | --- | --- |
| 0.0442 | 30 | 1,920 |
| 0.0884 | 30 | 1,920 |
| **0.177 (course value)** | 30 | 1,920 |
| 0.354 | 20 | 1,930 |

How to read it. The cutoffs 0.0442, 0.0884 and 0.177 give the same 30 removed samples. In this simulated cohort no extra pair lies between 0.0442 and 0.177. At 0.354 only repeated samples are removed (20), and the ten first-degree pairs stay in the data. Real cohorts usually have many more distant relatives, so the counts would then differ.

Expected plot. For `KING kinship cutoff`, the horizontal axis shows the threshold and the vertical axis shows the number of samples removed. A red diamond marks the course value (0.177), where 30 samples are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 3.7 · Batch effects {#step-3-7}

We compare the fraction of successful genotype calls across laboratory plates. We remove the faulty plate in these simulated data because samples processed together can share technical problems.

[Read step 3.7 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-7).

```{r}
#| label: s3-7
report <- guided_path(cfg, "3.7", "missing")  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.6"), "--missing", "sample-only", "--out", report))  # <2>
missing <- guided_table(paste0(report, ".smiss"))  # <3>
metadata <- guided_metadata(cfg)
plate <- metadata$Plate[match(missing$IID, metadata$IID)]
median_missing <- tapply(as.numeric(missing$F_MISS), plate, median)  # <4>
print(sort(1 - median_missing))
worst <- names(which.max(median_missing))  # <5>
stopifnot(worst == "P14")
remove_file <- guided_list(missing$IID[plate == worst], guided_path(cfg, "3.7", "remove.txt"), TRUE)  # <6>
run_plink(cfg, c("--pfile", guided_path(cfg, "3.6"), "--remove", remove_file, "--make-pgen", "--out", guided_path(cfg, "3.7")))  # <7>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "3.7", "3.6")
guided_register(cfg, "3.7", "3.6", 1844, 296360, operations = ops)
```

1. Choose the name for the missing-call report.
2. Count missing calls for each sample.
3. Read the report and match each sample to its laboratory plate.
4. Calculate and print the middle call rate for each plate.
5. Find the plate with the most missing calls and check its name.
6. Write the list of samples from the faulty plate.
7. Save the dataset without samples from that plate.

### What each option does

**Command 1: measure missing calls by sample**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--missing` | Writes a report of missing genotype calls. |
| &nbsp;&nbsp;&rarr; `sample-only` | Writes one row per sample and skips the report for variants. |
| `--out` | Sets the shared beginning of the output file names. |

**Command 2: remove samples from the faulty plate**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM input files that share the given name prefix. |
| `--remove` | Removes the samples named in the supplied sample list. |
| `--make-pgen` | Saves a new dataset as PGEN, PVAR and PSAM files. |
| `--out` | Sets the shared beginning of the output file names. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

Plate P14 has a median call rate of approximately 98.56%. The other plates have 99.84%. The 76 remaining wells of plate P14 are removed. 1,844 samples and 296,360 variants remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-6_state --missing sample-only --out results/guided/s3-7_missing --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s3-6_state --remove results/guided/s3-7_remove.txt --make-pgen --out results/guided/s3-7_state --threads 2 --memory 2048
```

:::

## Step 3.8 · Sample QC summary and checkpoint {#step-3-8}

We save the complete dataset after sample quality control and review the recorded counts. This gives us a checked starting point for variant quality control in module 4.

[Read step 3.8 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-8).

```{r}
#| label: s3-8
guided_snapshot(cfg, "3.8", guided_path(cfg, "3.7"), 1844, 296360, parent = "3.7")  # <1>
print(read.delim(file.path(cfg$out, "step_counts.tsv")))  # <2>
check_step("3.8", data_dir = cfg$out, work_dir = cfg$out)  # <3>
```

1. Save a complete copy of the dataset after sample checks.
2. Print the recorded sample and variant counts.
3. Check that the saved files have the expected counts.

### What each option does

No PLINK options are used in this step.

::: {.callout-tip title="Expected result" collapse="true"}

Module 3 boundary: 1,844 samples and 296,360 variants. The restart operations for the steps in between are stored. The complete main-path package supplies full genotype copies at steps 2.8, 3.8, 4.6 and 5.7. Steps 4.6 and 5.7 are the ends of later modules. You can rebuild the states in between from the previous full checkpoint and the stored replay operations. To restart, give R the first step that you will run, for example `restore_checkpoint("4.1")` to start module 4. Use an empty output folder.

:::

::: {.callout-note title="PLINK terminal equivalent"}

No PLINK equivalent

:::

## Where next {#where-next}

- Previous: [Module 2: Files and formats](module_02_files_and_formats.qmd)
- Next: [Module 4: Variant quality control](module_04_variant_quality_control.qmd)
- This module on the course website: [Module 3](https://www.manuelgentiluomo.it/teaching/gwas/module-3)
