Skip to content

EGenetics · genetics.gwas

Genome-wide association scan (single markers, λ_GC)

Which markers, one at a time, are associated with the trait?

Tests each marker for an additive association with the trait, adjusting for covariates: linear regression for a measured trait, the logistic score test for 0/1 status (Cochran–Armitage's trend test when there are no covariates). Reports the genomic-control inflation factor λ_GC (median χ² over 0.455), λ-corrected p-values, and counts at genome-wide (5 × 10⁻⁸), Bonferroni and false-discovery-rate thresholds. λ well above 1 points to population structure or relatedness. Research use only.

Experimental Python and R agree to 10 decimals Also called GWAS, genome-wide association study, GWAS-lite…

A real result

Example “Bmi covariates”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Single-marker association scanRecorded · Python and R agreeRecorded 2026-11-17 · 20 values compared
R

24 markers, N = 300, λ_GC = 2.005, strongest v03, p < .001

Markers tested
24
λ_GC
2.005
p < 5e-08
0
Smallest p (v03)
< .001

Plots

−log₁₀ p by markerWhere along the genome do markers show association with the trait, and does any pass the genome-wide threshold?
View data
MarkerpMarker order
v010.32091
v020.61492
v030.00053
v040.57784
v050.26555
v060.72696
v070.19497
v080.14338
v090.10869
v100.898010
v110.081911
v120.083212
v130.096313
v140.979514
v150.042015
v160.361316
v170.518917
v180.708618
v190.559519
v200.761120
v210.039221
v220.002922
v230.515823
v240.647524
Observed against expected pDo the p-values of a scan follow the null except for a few real signals, or are they inflated across the board?
View data
p
0.3209
0.6149
0.0005
0.5778
0.2655
0.7269
0.1949
0.1433
0.1086
0.8980
0.0819
0.0832
0.0963
0.9795
0.0420
0.3613
0.5189
0.7086
0.5595
0.7611
0.0392
0.0029
0.5158
0.6475

Assumptions

  • No uncontrolled structure — λ_GC = 2.005: inflation; add ancestry principal components as covariates.
  • Unrelated people — Not checkable here: relatives would need a mixed model.
  • Markers passed QC — Run genotype QC first and test only the markers that pass.
  • Enough markers for λ — 24 markers tested.

Markers by p-value

RankMarkerCounted allelePeopleFrequencyβSEtpp (GC)q (BH)
1v03B2920.45210.86030.24383.5290.00050.01270.0116
2v22B2940.18030.89200.29703.0030.00290.03390.0348
3v21B2940.4966−0.51640.2493−2.0710.03920.14360.2521
4v15B2950.1814−0.64190.3143−2.0420.04200.14920.2521
5v11B2950.00175.2052.9811.7460.08190.21760.3257
6v12B2970.3670−0.45090.2593−1.7380.08320.21960.3257
7v13B2940.11560.65140.39041.6690.09630.23870.3257
8v09B2940.2908−0.36340.2258−1.6100.10860.25570.3257
9v08B2960.4493−0.37550.2558−1.4680.14330.30000.3821
10v07B2920.54450.31570.24301.2990.19490.35890.4678
11v05B2960.4291−0.27810.2493−1.1160.26550.43080.5793
12v01B2900.56210.24630.24770.99430.32090.48260.6418
13v16B2920.4983−0.22070.2414−0.91430.36130.51850.6671
14v23B2950.0814−0.29420.4521−0.65060.51580.64590.8157
15v17B2930.3259−0.16280.2520−0.64590.51890.64830.8157
16v19B2940.20240.17790.30450.58430.55950.67990.8157
17v04B2940.54760.13170.23640.55730.57780.69390.8157
18v02B2980.4799−0.12250.2433−0.50360.61490.72210.8180
19v24B2950.4017−0.12010.2625−0.45760.64750.74660.8180
20v18B2990.5084−0.09050.2419−0.37420.70860.79160.8303
21v06B2940.52890.08640.24710.34950.72690.80500.8303
22v20B2910.0859−0.12800.4206−0.30440.76110.82980.8303
23v10B2640.2045−0.04280.3336−0.12840.89800.92780.9370
24v14B2980.08890.01050.40910.02570.97950.98550.9795
  • λ_GC from only 24 markers is a rough guide; it needs hundreds of mostly null markers.
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • β is the change in the trait per copy of the counted allele.
  • λ_GC = median χ² / 0.455 (Devlin & Roeder 1999); p (GC) divides χ² by λ when λ > 1.
Python

24 markers, N = 300, λ_GC = 2.005, strongest v03, p < .001

Markers tested
24
λ_GC
2.005
p < 5e-08
0
Smallest p (v03)
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • No uncontrolled structure — λ_GC = 2.005: inflation; add ancestry principal components as covariates.
  • Unrelated people — Not checkable here: relatives would need a mixed model.
  • Markers passed QC — Run genotype QC first and test only the markers that pass.
  • Enough markers for λ — 24 markers tested.

Markers by p-value

RankMarkerCounted allelePeopleFrequencyβSEtpp (GC)q (BH)
1v03B2920.45210.86030.24383.5290.00050.01270.0116
2v22B2940.18030.89200.29703.0030.00290.03390.0348
3v21B2940.4966−0.51640.2493−2.0710.03920.14360.2521
4v15B2950.1814−0.64190.3143−2.0420.04200.14920.2521
5v11B2950.00175.2052.9811.7460.08190.21760.3257
6v12B2970.3670−0.45090.2593−1.7380.08320.21960.3257
7v13B2940.11560.65140.39041.6690.09630.23870.3257
8v09B2940.2908−0.36340.2258−1.6100.10860.25570.3257
9v08B2960.4493−0.37550.2558−1.4680.14330.30000.3821
10v07B2920.54450.31570.24301.2990.19490.35890.4678
11v05B2960.4291−0.27810.2493−1.1160.26550.43080.5793
12v01B2900.56210.24630.24770.99430.32090.48260.6418
13v16B2920.4983−0.22070.2414−0.91430.36130.51850.6671
14v23B2950.0814−0.29420.4521−0.65060.51580.64590.8157
15v17B2930.3259−0.16280.2520−0.64590.51890.64830.8157
16v19B2940.20240.17790.30450.58430.55950.67990.8157
17v04B2940.54760.13170.23640.55730.57780.69390.8157
18v02B2980.4799−0.12250.2433−0.50360.61490.72210.8180
19v24B2950.4017−0.12010.2625−0.45760.64750.74660.8180
20v18B2990.5084−0.09050.2419−0.37420.70860.79160.8303
21v06B2940.52890.08640.24710.34950.72690.80500.8303
22v20B2910.0859−0.12800.4206−0.30440.76110.82980.8303
23v10B2640.2045−0.04280.3336−0.12840.89800.92780.9370
24v14B2980.08890.01050.40910.02570.97950.98550.9795
  • λ_GC from only 24 markers is a rough guide; it needs hundreds of mostly null markers.
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • β is the change in the trait per copy of the counted allele.
  • λ_GC = median χ² / 0.455 (Devlin & Roeder 1999); p (GC) divides χ² by λ when λ > 1.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Bmi covariatesge_people · covariates: age, sex · outcome: bmi · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
  • Case scorege_people · covariates: age · outcome: case · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
  • Case trend no gcge_people · outcome: case · variants: v03, v12, v15, gt1, gt2
  • Bmi vcfge_people · outcome: bmi · variants: gt1, gt2, gt3, gt4, v12, v13, v14, v15
  • Degenerate constantge_people · covariates: age, sex · outcome: bmi · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
  • Degenerate empty after filterge_people · covariates: age, sex · outcome: bmi · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
  • Degenerate infge_people · covariates: age, sex · outcome: bmi · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
  • Degenerate n3ge_people · covariates: age, sex · outcome: bmi · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24

In the guides

Where it sits in the decision guides

  • Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
  • Binary outcome: logistic regression (regularized) · Statistics Guide · D — Predict an outcome
  • Multiple comparisons · Statistics Guide · Additional considerations

What you need

Traitnumeric / boolean · 1 column
One row per person: a measured trait, or 0/1 for case status.
Covariates (optional)numeric / categorical / boolean · 0–20 columns
Adjusted for in every test: age, sex, ancestry principal components.
Markersnumeric / categorical · 1–10000 columns
One column per marker: doses 0/1/2, VCF calls (0/1, 1|1, ./.) or two alleles. Each test uses people called there.

Choices you make

hypothesis

Trait typedefault auto

Linear regression for a measured trait, the logistic score test for 0/1; automatic picks by the values.

  • Automatic(default) — Score test when the trait holds only 0 and 1, otherwise linear regression.
  • Continuous — Linear regression per marker; t-test of the additive effect.
  • Binary (0/1) — Logistic score test per marker, with a one-step log odds ratio.

statistics

Genomic controldefault on

Divide each χ² by λ_GC when λ > 1 (Devlin & Roeder 1999); needs many markers to estimate λ.

Genome-wide thresholddefault 5e-8

p below this counts as genome-wide significant; 5 × 10⁻⁸ is the usual line for a whole genome.

False discovery ratedefault 0.05

Benjamini–Hochberg q threshold for the FDR count.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • No uncontrolled structure

    Ancestry differences between cases and controls create false hits; λ_GC near 1 and PCs as covariates help.

  • Unrelated people

    Relatives make tests anti-conservative unless a kinship model is used.

  • Markers passed QC

    Run quality control first: failing markers produce spurious associations.

  • Enough markers for λ

    λ_GC is only meaningful over hundreds of markers or more, mostly null.

What it reports

n
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
n_variants
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
n_tested
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
outcome_type
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
test_label
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
lambda_gc
λ = median χ² / 0.455. Near 1 means the scan's test statistics look like chance; above 1 suggests inflation from structure or relatedness.
n_sig_gw
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
n_sig_bonf
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
n_sig_fdr
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
alpha_gw
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
top_variant
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
top_p
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
top_beta
p below 5 × 10⁻⁸, roughly a Bonferroni correction for a million independent common markers.
beta
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
se
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
stat
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
p
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.
p_gc
λ = median χ² / 0.455. Near 1 means the scan's test statistics look like chance; above 1 suggests inflation from structure or relatedness.
freq
The frequency of the less common allele at a marker, between 0 and 0.5.
n_called
Each copy of the counted allele shifts the trait by the same amount β, so 0, 1 and 2 copies form a straight line.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines fit the covariates-only logistic model by the same IRLS from the same start, so score tests agree to rounding.
Python

The exact script CodeSplash ran for example “Bmi covariates” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Genome-wide association scan (single markers, λ_GC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.gwas 1.0.1 · spec 0901ed2ba1600735
# Dataset: ge_people (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import genetics as gen  # per-marker OLS / logistic score tests, genomic control (twins of cs_gen_*)
from codesplash.stats import padjust  # Benjamini–Hochberg (twin of cs_p_adjust)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df = pd.read_parquet("tests/parity/fixtures/ge_people.parquet", columns=["bmi", "age", "sex", "v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% People: trait and covariates (people missing either are left out; genotype no-calls stay)
outcome = "bmi"
covariates = ["age", "sex"]
variants = ["v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"]
kinds = {"age":"numeric","bmi":"numeric","sex":"categorical","v01":"numeric","v02":"numeric","v03":"numeric","v04":"numeric","v05":"numeric","v06":"numeric","v07":"numeric","v08":"numeric","v09":"numeric","v10":"numeric","v11":"numeric","v12":"numeric","v13":"numeric","v14":"numeric","v15":"numeric","v16":"numeric","v17":"numeric","v18":"numeric","v19":"numeric","v20":"numeric","v21":"numeric","v22":"numeric","v23":"numeric","v24":"numeric"}
keep = df[[outcome] + covariates].notna().all(axis=1).to_numpy()
n_left = int((~keep).sum())
if n_left:
    warnings.append(f"{n_left} of {n_input} people were left out because the trait or a covariate was missing.")
df = df[keep].reset_index(drop=True)
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, [outcome] + covariates)  # infinite values stop the run (registry/errors.yaml)
y = df[outcome].astype(float).to_numpy()
x, x_names = gen.design({c: df[c].to_numpy() for c in covariates}, kinds, len(y))
# Each test fits the covariates and one marker and needs at least one residual degree of freedom.
if len(y) < x.shape[1] + 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="The association test", min=x.shape[1] + 2, n=len(y))
if np.all(y == y[0]):
    cs.cs_error("CS_E_CONSTANT", column=outcome)
outcome_type = "auto"
is01 = bool(np.all((y == 0) | (y == 1))) and len(np.unique(y)) == 2
if outcome_type == "auto":
    outcome_type = "binary" if is01 else "continuous"
if outcome_type == "binary" and not is01:
    raise ValueError(f"A binary trait must hold only 0 and 1, with both present; {outcome} doesn't.")
binary = outcome_type == "binary"
g, counted, other = gen.dose_matrix({v: df[v].to_numpy() for v in variants})
use_gc = True
alpha_gw = float(5e-8)
fdr = float(0.05)

# %% Scan
res = gen.gwas(y, x, g, binary)
pv = np.array([r["p"] for r in res], dtype=float)
chi2 = np.array([r["chi2"] for r in res], dtype=float)
tested = ~np.isnan(pv)
m = int(tested.sum())
if m == 0:
    cs.cs_error("CS_E_UNDEFINED", what="The association scan", reason="every marker is monomorphic in the people called there, or has too few calls")
lam, p_gc_all = gen.genomic_control(chi2)
p_gc = p_gc_all if use_gc else pv
q = padjust.p_adjust(pv, "BH")
n_gw = int(np.sum(pv[tested] < alpha_gw))
n_bonf = int(np.sum(pv[tested] < 0.05 / m))
n_fdr = int(np.sum(q[tested] < fdr))
order = [int(i) for i in np.argsort(np.where(tested, pv, np.inf), kind="stable") if tested[i]]
top = order[0]
label = "logistic score test" if binary else "linear regression"
if m < len(variants):
    warnings.append(f"{len(variants) - m} markers couldn't be tested (monomorphic in the people called there, or too few calls).")
if m < 100:
    warnings.append(f"λ_GC from only {m} markers is a rough guide; it needs hundreds of mostly null markers.")

# %% Assumptions
infl = lam > 1.1
assumptions = [
    {"key": "structure", "label": "No uncontrolled structure", "status": "warn" if infl else "pass",
     "detail": f"λ_GC = {lam:.3f}" + (": inflation; add ancestry principal components as covariates." if infl else ".")},
    {"key": "unrelated", "label": "Unrelated people", "status": "info", "detail": "Not checkable here: relatives would need a mixed model."},
    {"key": "qc_done", "label": "Markers passed QC", "status": "info", "detail": "Run genotype QC first and test only the markers that pass."},
    {"key": "enough_markers", "label": "Enough markers for λ", "status": "warn" if m < 100 else "pass", "detail": f"{m} markers tested."},
]

# %% Result
summary = (f"{m} markers against {outcome} ({len(y)} people, {label}{', ' + str(len(covariates)) + ' covariates' if covariates else ''}): "
           f"{n_gw} below {alpha_gw:g}, {n_bonf} Bonferroni, {n_fdr} at FDR {fdr:g}; strongest {variants[top]} ({cs.fmt_p(pv[top])}); λ_GC = {lam:.3f}.")
apa = f"{m} markers, N = {len(y)}, λ_GC = {cs.fmt_num(lam, 3)}, strongest {variants[top]}, {cs.fmt_p(pv[top])}"
rows = []
for rank, j in enumerate(order[:50]):
    r = res[j]
    rows.append({"rank": rank + 1, "marker": variants[j], "counted": counted[j], "n": r["n"], "freq": r["freq"], "beta": r["beta"],
                 "se": r["se"], "stat": r["stat"], "p": r["p"], "p_gc": float(p_gc[j]), "q": float(q[j])})
notes = [research_note,
         "β is the change in the trait per copy of the counted allele" + (" (one-step log odds ratio from the score test)." if binary else "."),
         "λ_GC = median χ² / 0.455 (Devlin & Roeder 1999)" + ("; p (GC) divides χ² by λ when λ > 1." if use_gc else "; genomic control is off, so p (GC) equals p.")]
p_chart = [None if math.isnan(v) else float(v) for v in pv]
values = {
    "n": len(y), "n_variants": len(variants), "n_tested": m, "outcome_type": outcome_type, "test_label": label, "lambda_gc": lam,
    "n_sig_gw": n_gw, "n_sig_bonf": n_bonf, "n_sig_fdr": n_fdr, "alpha_gw": alpha_gw, "top_variant": variants[top], "top_p": float(pv[top]),
    "top_beta": res[top]["beta"], "beta": [r["beta"] for r in res], "se": [r["se"] for r in res], "stat": [r["stat"] for r in res],
    "p": pv.tolist(), "p_gc": [float(v) for v in p_gc], "freq": [r["freq"] for r in res], "n_called": [r["n"] for r in res],
}
cs.publish({
    "method": "genetics.gwas",
    "methodVersion": "1.0.1",
    "title": "Single-marker association scan",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(y),
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "n_tested", "label": "Markers tested", "value": m},
        {"key": "lambda_gc", "label": "λ_GC", "value": lam},
        {"key": "n_sig_gw", "label": f"p < {alpha_gw:g}", "value": n_gw},
        {"key": "top_p", "label": f"Smallest p ({variants[top]})", "value": float(pv[top]), "format": "p"},
    ],
    "tables": [
        {"key": "top", "title": "Markers by p-value",
         "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "marker", "label": "Marker", "type": "string"},
                     {"key": "counted", "label": "Counted allele", "type": "string"}, {"key": "n", "label": "People", "type": "integer"},
                     {"key": "freq", "label": "Frequency", "type": "number"}, {"key": "beta", "label": "β", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": "t" if not binary else "z", "type": "number"},
                     {"key": "p", "label": "p", "type": "p"}, {"key": "p_gc", "label": "p (GC)", "type": "p"}, {"key": "q", "label": "q (BH)", "type": "p"}],
         "rows": rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [
        cs.chart("manhattan", "manhattan", "−log₁₀ p by marker", {
            "position": cs.col("Marker order", list(range(1, len(variants) + 1)), "numeric"), "p": cs.col("p", p_chart, "numeric"),
            "label": cs.col("Marker", variants, "categorical")}, controls={"gw": alpha_gw}),
        cs.chart("qq", "gwas-qq", "Observed against expected p", {"p": cs.col("p", p_chart, "numeric")}, controls={"lambda": lam}),
    ],
    "values": values,
})
R

The exact script CodeSplash ran for example “Bmi covariates” · R version 4.5.1 (2025-06-13)

# Genome-wide association scan (single markers, λ_GC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.gwas 1.0.1 · spec 0901ed2ba1600735
# Dataset: ge_people (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_gen_gwas, cs_gen_genomic_control, cs_p_adjust (twins of codesplash.stats.genetics / padjust)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ge_people.parquet", col_select = c("bmi", "age", "sex", "v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% People: trait and covariates (people missing either are left out; genotype no-calls stay)
outcome <- "bmi"
covariates <- c("age", "sex")
variants <- c("v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24")
kinds <- list(
  "bmi" = "numeric",
  "age" = "numeric",
  "sex" = "categorical",
  "v01" = "numeric",
  "v02" = "numeric",
  "v03" = "numeric",
  "v04" = "numeric",
  "v05" = "numeric",
  "v06" = "numeric",
  "v07" = "numeric",
  "v08" = "numeric",
  "v09" = "numeric",
  "v10" = "numeric",
  "v11" = "numeric",
  "v12" = "numeric",
  "v13" = "numeric",
  "v14" = "numeric",
  "v15" = "numeric",
  "v16" = "numeric",
  "v17" = "numeric",
  "v18" = "numeric",
  "v19" = "numeric",
  "v20" = "numeric",
  "v21" = "numeric",
  "v22" = "numeric",
  "v23" = "numeric",
  "v24" = "numeric"
)
keep <- stats::complete.cases(df[c(outcome, covariates)])
n_left <- sum(!keep)
if (n_left > 0) warnings <- c(warnings, sprintf("%d of %d people were left out because the trait or a covariate was missing.", n_left, n_input))
df <- df[keep, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c(outcome, covariates))  # infinite values stop the run (registry/errors.yaml)
y <- as.numeric(df[[outcome]])
des <- cs_gen_design(df[covariates], kinds, length(y))
x <- des$x
x_names <- des$names
# Each test fits the covariates and one marker and needs at least one residual degree of freedom.
if (length(y) < ncol(x) + 2) cs_error("CS_E_TOO_FEW_ROWS", what = "The association test", min = ncol(x) + 2, n = length(y))
if (all(y == y[1])) cs_error("CS_E_CONSTANT", column = outcome)
outcome_type <- "auto"
is01 <- all(y == 0 | y == 1) && length(unique(y)) == 2
if (outcome_type == "auto") outcome_type <- if (is01) "binary" else "continuous"
if (outcome_type == "binary" && !is01) stop(sprintf("A binary trait must hold only 0 and 1, with both present; %s doesn't.", outcome), call. = FALSE)
binary <- outcome_type == "binary"
dm <- cs_gen_dose_matrix(df[variants])
g <- dm$g
counted <- dm$counted
other <- dm$other
use_gc <- TRUE
alpha_gw <- 5e-8
fdr <- 0.05

# %% Scan
res <- cs_gen_gwas(y, x, g, binary)
pick <- function(k) vapply(res, function(r) as.numeric(r[[k]]), numeric(1))
pv <- pick("p")
chi2 <- pick("chi2")
tested <- !is.na(pv)
m <- sum(tested)
if (m == 0) cs_error("CS_E_UNDEFINED", what = "The association scan", reason = "every marker is monomorphic in the people called there, or has too few calls")
gc <- cs_gen_genomic_control(chi2)
lam <- gc$lambda
p_gc <- if (use_gc) gc$p else pv
q <- cs_p_adjust(pv, "BH")
n_gw <- sum(pv[tested] < alpha_gw)
n_bonf <- sum(pv[tested] < 0.05 / m)
n_fdr <- sum(q[tested] < fdr)
order_idx <- order(ifelse(tested, pv, Inf), method = "radix")
order_idx <- order_idx[tested[order_idx]]
top <- order_idx[1]
label <- if (binary) "logistic score test" else "linear regression"
if (m < length(variants)) {
  warnings <- c(warnings, sprintf("%d markers couldn't be tested (monomorphic in the people called there, or too few calls).", length(variants) - m))
}
if (m < 100) warnings <- c(warnings, sprintf("λ_GC from only %d markers is a rough guide; it needs hundreds of mostly null markers.", m))

# %% Assumptions
infl <- lam > 1.1
assumptions <- list(
  list(key = "structure", label = "No uncontrolled structure", status = if (infl) "warn" else "pass",
       detail = paste0(sprintf("λ_GC = %.3f", lam), if (infl) ": inflation; add ancestry principal components as covariates." else ".")),
  list(key = "unrelated", label = "Unrelated people", status = "info", detail = "Not checkable here: relatives would need a mixed model."),
  list(key = "qc_done", label = "Markers passed QC", status = "info", detail = "Run genotype QC first and test only the markers that pass."),
  list(key = "enough_markers", label = "Enough markers for λ", status = if (m < 100) "warn" else "pass", detail = sprintf("%d markers tested.", m))
)

# %% Result
summary <- sprintf("%d markers against %s (%d people, %s%s): %d below %s, %d Bonferroni, %d at FDR %s; strongest %s (%s); λ_GC = %.3f.",
                   m, outcome, length(y), label, if (length(covariates)) sprintf(", %d covariates", length(covariates)) else "",
                   n_gw, format(alpha_gw), n_bonf, n_fdr, format(fdr), variants[top], cs_fmt_p(pv[top]), lam)
apa <- sprintf("%d markers, N = %d, λ_GC = %s, strongest %s, %s", m, length(y), cs_fmt_num(lam, 3), variants[top], cs_fmt_p(pv[top]))
rows <- lapply(seq_len(min(50, length(order_idx))), function(rank) {
  j <- order_idx[rank]
  r <- res[[j]]
  list(rank = rank, marker = variants[j], counted = counted[j], n = r$n, freq = r$freq, beta = r$beta, se = r$se, stat = r$stat,
       p = r$p, p_gc = p_gc[j], q = q[j])
})
notes <- list(research_note,
              paste0("β is the change in the trait per copy of the counted allele", if (binary) " (one-step log odds ratio from the score test)." else "."),
              paste0("λ_GC = median χ² / 0.455 (Devlin & Roeder 1999)", if (use_gc) "; p (GC) divides χ² by λ when λ > 1." else "; genomic control is off, so p (GC) equals p."))
p_chart <- ifelse(is.na(pv), NA_real_, pv)
result_values <- list(
  n = length(y), n_variants = length(variants), n_tested = m, outcome_type = outcome_type, test_label = label, lambda_gc = lam,
  n_sig_gw = n_gw, n_sig_bonf = n_bonf, n_sig_fdr = n_fdr, alpha_gw = alpha_gw, top_variant = variants[top], top_p = pv[top],
  top_beta = res[[top]]$beta, beta = I(pick("beta")), se = I(pick("se")), stat = I(pick("stat")), p = I(pv), p_gc = I(p_gc),
  freq = I(pick("freq")), n_called = I(pick("n"))
)
cs_publish(list(
  method = "genetics.gwas",
  methodVersion = "1.0.1",
  title = "Single-marker association scan",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(y),
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "n_tested", label = "Markers tested", value = m),
    list(key = "lambda_gc", label = "λ_GC", value = lam),
    list(key = "n_sig_gw", label = sprintf("p < %s", format(alpha_gw)), value = n_gw),
    list(key = "top_p", label = sprintf("Smallest p (%s)", variants[top]), value = pv[top], format = "p")
  ),
  tables = list(
    list(key = "top", title = "Markers by p-value",
         columns = list(list(key = "rank", label = "Rank", type = "integer"), list(key = "marker", label = "Marker", type = "string"),
                        list(key = "counted", label = "Counted allele", type = "string"), list(key = "n", label = "People", type = "integer"),
                        list(key = "freq", label = "Frequency", type = "number"), list(key = "beta", label = "β", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "stat", label = if (binary) "z" else "t", type = "number"),
                        list(key = "p", label = "p", type = "p"), list(key = "p_gc", label = "p (GC)", type = "p"), list(key = "q", label = "q (BH)", type = "p")),
         rows = rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(
    cs_chart("manhattan", "manhattan", "−log₁₀ p by marker",
             list(position = cs_col("Marker order", seq_along(variants), "numeric"), p = cs_col("p", p_chart, "numeric"),
                  label = cs_col("Marker", variants, "categorical")), controls = list(gw = alpha_gw)),
    cs_chart("qq", "gwas-qq", "Observed against expected p", list(p = cs_col("p", p_chart, "numeric")), controls = list(lambda = lam))
  ),
  values = result_values
))

Sources

  • Devlin, B., & Roeder, K. (1999). Genomic control for association studies. Biometrics, 55, 997–1004.
  • Armitage, P. (1955). Tests for linear trends in proportions and frequencies. Biometrics, 11, 375–386.
  • Purcell, S., Neale, B., Todd-Brown, K., et al. (2007). PLINK: a tool set for whole-genome association and population-based linkage analyses. American Journal of Human Genetics, 81, 559–575.
  • Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate. Journal of the Royal Statistical Society B, 57, 289–300.

From the CodeSplash method registry · genetics.gwas v1.0.1.