about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-11 05:41:56 +0000
committerPjotr <wrk@bosa.lan>2026-11-11 05:41:56 +0000
commit3022797b55bae96322439770ea48e74eb2e0eb8d (patch)
tree6c8386c2e9682431b49b0248bb0d295710ba1027 /scripts
parentb4246412072773819f4500cb008f71c3f3101fdf (diff)
downloadgenenetwork4-3022797b55bae96322439770ea48e74eb2e0eb8d.tar.gz
bulklmm: an LMM scan that can be asked for thresholds
GEMMA's LOCO scan is the reference for a biallelic panel, but its p-values
have no threshold we can compute: a GEMMA permutation repeats the whole
scan, which is why /compute/gemma refuses nperm. R/qtl's nperm is the usual
stand-in and it is the wrong null -- it shuffles phenotypes as if the
individuals were unrelated. BulkLMM.jl fits an LMM per marker with a global
kinship matrix and permutes by rotating the data through the kinship's
eigen decomposition, so a threshold costs seconds.

  POST /compute/bulklmm {group, genotype_version, samples|basket,
                         nperm, seed, reml, assumption}

Rows are marker, chr, pos (Mb), lod, beta, h2. BXD trait 16627 (BXD.8,
35 phenotyped animals, 21056 markers) in 22 s: peak rsm10000000888 chr2
4.92 Mb, LOD 9.59, and thresholds alpha 0.10 -> 3.51, 0.05 -> 3.81,
0.01 -> 4.47 from 200 rotations with seed 42. That is the trait's
published locus and LOD, and a significant peak against a threshold this
API could not compute before.

Two differences from GEMMA are in every reply, not implied: a global
kinship matrix rather than leave-one-chromosome-out, and h2_null saying
how much relatedness was found (here ~0, so the fit is effectively
fixed-effects -- which is why it agrees with R/qtl where GEMMA differs).

  * src/bulklmm.rs prepares what Julia reads -- the BIMBAM dosages as a
    strains x markers matrix (our BIMBAM pair is already the allele
    dosages BulkLMM wants), a marker map, the phenotype and covariates
    -- runs the driver through streaming::run_streaming_with_env, and
    reads the CSV back. A row whose LOD is NaN is dropped: NaN is a valid
    f64 in Rust and would otherwise be reported as a value.
  * scripts/bulklmm_scan.jl is the driver (scan/calcKinship/get_thresholds),
    with the seed recorded so a threshold set is reproducible.
  * gate::bulklmm (2 slots, GEMMA-sized threshold): a permutation here is
    cheap, unlike R/qtl's.
  * Julia comes from the deployment's own store binary with a prepared
    depot -- 79 packages, 139 MB, no GPU/CUDA stack -- and every request
    runs JULIA_PKG_OFFLINE=true, so a scan can never download anything.
    `--project=<path>`, not `--project <path>`: Julia 1.8 takes the
    space-separated form as a program argument.

tests/bulklmm.rs: the peak stays on chr2 above LOD 3, the thresholds and
seed are in the notes, and a scan without permutations says there is no
threshold rather than leaving a bare LOD to be read as significant.
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/bulklmm_scan.jl192
1 files changed, 192 insertions, 0 deletions
diff --git a/scripts/bulklmm_scan.jl b/scripts/bulklmm_scan.jl
new file mode 100755
index 0000000..c3e70cf
--- /dev/null
+++ b/scripts/bulklmm_scan.jl
@@ -0,0 +1,192 @@
+#!/usr/bin/env julia
+# Genome scan with BulkLMM.jl: a linear mixed model per marker, with kinship.
+#
+# The counterpart of scripts/qtl2_scan.R for the GEMMA side: same trait values,
+# same markers, a global kinship matrix, and -- the reason it exists --
+# permutation thresholds that account for relatedness (BulkLMM rotates by the
+# eigen decomposition of K instead of shuffling phenotypes), which GEMMA cannot
+# do here and R/qtl does with the wrong null.
+#
+# Inputs are plain files this API writes:
+#   --pheno    Sample<TAB>trait, one row per individual with a value
+#   --geno     CSV matrix, rows = individuals, columns = markers, entries are
+#              allele probabilities (0, 0.5, 1) -- our BIMBAM dosages
+#   --markers  CSV: marker,chr,pos (Mb)
+#   --covar    Sample<TAB>c1<TAB>c2..., optional
+#
+# Output is a CSV, one row per marker:
+#   marker,chr,pos,lod,beta,se,h2
+# and, with --perm-out, a CSV of permutation thresholds: alpha,lod
+#
+# Usage:
+#   julia --threads 4 scripts/bulklmm_scan.jl --pheno p.tsv --geno g.csv \
+#         --markers m.csv --out scan.csv [--nperm 1000 --perm-out t.csv]
+
+using BulkLMM
+using DelimitedFiles
+using Statistics
+
+function fail(message)
+    println(stderr, "Error: ", message)
+    exit(1)
+end
+
+function argument(name, default=nothing)
+    index = findfirst(==(name), ARGS)
+    if index === nothing
+        return default
+    end
+    index < length(ARGS) || fail("$name needs a value")
+    return ARGS[index + 1]
+end
+
+flag(name) = name in ARGS
+
+pheno_file = argument("--pheno")
+geno_file = argument("--geno")
+markers_file = argument("--markers")
+out_file = argument("--out")
+covar_file = argument("--covar")
+perm_out = argument("--perm-out")
+nperms = parse(Int, argument("--nperm", "0"))
+seed = parse(Int, argument("--seed", "0"))
+reml = flag("--reml")
+assumption = argument("--assumption", "null")
+method = argument("--method", "qr")
+
+(pheno_file === nothing || geno_file === nothing || markers_file === nothing ||
+ out_file === nothing) && fail("--pheno, --geno, --markers and --out are required")
+
+# ---- inputs -----------------------------------------------------------
+# The phenotype file is this API's shape: a header and one row per individual
+# with a value; `x` (or an empty cell) is missing.
+pheno_lines = filter(line -> !isempty(strip(line)), split(read(pheno_file, String), '\n'))
+header = split(pheno_lines[1], '\t')
+length(header) >= 2 || fail("$(pheno_file): needs a header and at least one trait column")
+individuals = String[]
+values = Float64[]
+for line in pheno_lines[2:end]
+    fields = split(line, '\t')
+    length(fields) >= 2 || continue
+    raw = strip(fields[2])
+    (isempty(raw) || raw in ("x", "X", "NA", "na")) && continue
+    parsed = tryparse(Float64, raw)
+    parsed === nothing && continue
+    push!(individuals, String(strip(fields[1])))
+    push!(values, parsed)
+end
+length(individuals) >= 3 || fail("$(pheno_file): fewer than three individuals with a value")
+y = values
+
+# The genotype matrix: rows are individuals, columns markers, entries allele
+# probabilities. The header names the individuals, in the same order.
+geno_text = split(read(geno_file, String), '\n')
+geno_header = split(strip(geno_text[1]), ',')
+geno_individuals = String[strip(name) for name in geno_header[2:end]]
+first = findfirst(isequal(geno_text[1]), geno_text) + 1
+rows = geno_text[first:end]
+rows = [row for row in rows if !isempty(strip(row))]
+g = Matrix{Float64}(undef, length(rows), length(geno_individuals))
+marker_names = Vector{String}(undef, length(rows))
+for (i, row) in enumerate(rows)
+    fields = split(strip(row), ',')
+    marker_names[i] = String(fields[1])
+    for j in 1:length(geno_individuals)
+        cell = strip(fields[j + 1])
+        g[i, j] = (isempty(cell) || cell == "NA") ? NaN : something(tryparse(Float64, cell), NaN)
+    end
+end
+g = permutedims(g)   # BulkLMM wants individuals x markers
+
+# Keep only the individuals that have both a value and genotypes, in the same
+# order, and fill a marker's missing probability with its column mean.
+position = Dict(name => index for (index, name) in enumerate(geno_individuals))
+keep_value = [i for (i, name) in enumerate(individuals) if haskey(position, name)]
+length(keep_value) >= 3 || fail("fewer than three phenotyped individuals are in the genotype matrix")
+rows_kept = [position[individuals[i]] for i in keep_value]
+y = y[keep_value]
+g = g[rows_kept, :]
+for column in 1:size(g, 2)
+    column_values = @view g[:, column]
+    if any(isnan, column_values)
+        average = mean(filter(!isnan, column_values))
+        column_values[isnan.(column_values)] .= average
+    end
+end
+
+# Marker positions, in the matrix's column order.
+marker_map = Dict{String, Tuple{String, Float64}}()
+for (index, line) in enumerate(split(read(markers_file, String), '\n'))
+    isempty(strip(line)) && continue
+    fields = split(strip(line), ',')
+    length(fields) >= 3 || continue
+    index == 1 && fields[1] == "marker" && continue
+    marker_map[String(fields[1])] = (String(fields[2]), something(tryparse(Float64, fields[3]), 0.0))
+end
+
+# Covariates, aligned onto the kept individuals.
+covar = nothing
+if covar_file !== nothing
+    lines = filter(line -> !isempty(strip(line)), split(read(covar_file, String), '\n'))
+    cov_header = split(lines[1], '\t')
+    cov_individuals = String[strip(split(line, '\t')[1]) for line in lines[2:end]]
+    position_cov = Dict(name => index for (index, name) in enumerate(cov_individuals))
+    matrix = zeros(Float64, length(keep_value), length(cov_header) - 1)
+    for (row, i) in enumerate(eachindex(keep_value))
+        name = individuals[i]
+        haskey(position_cov, name) || continue
+        fields = split(lines[position_cov[name] + 1], '\t')
+        for column in 2:length(cov_header)
+            raw = strip(fields[column])
+            matrix[row, column - 1] = (isempty(raw) || raw in ("x", "NA")) ? 0.0 :
+                something(tryparse(Float64, raw), 0.0)
+        end
+    end
+    covar = matrix
+end
+
+println(stderr, "bulklmm: ", length(y), " individuals with a value, ", length(marker_names),
+        " markers, covariates: ", covar === nothing ? "none" : string(size(covar, 2)))
+
+# ---- the scan ---------------------------------------------------------
+kinship = calcKinship(g)
+options = Dict{Symbol, Any}(:reml => reml, :assumption => assumption, :method => method,
+                            :permutation_test => nperms > 0, :nperms => nperms, :rndseed => seed)
+result = try
+    if covar === nothing
+        scan(y, g, kinship; options...)
+    else
+        scan(y, g, covar, kinship; options...)
+    end
+catch error
+    println(stderr, "Error: ", sprint(showerror, error))
+    exit(2)
+end
+
+h2 = hasproperty(result, :h2_null) ? result.h2_null : NaN
+beta = hasproperty(result, :b) ? result.b : fill(NaN, length(marker_names))
+se = hasproperty(result, :SE) ? result.SE : nothing
+open(out_file, "w") do handle
+    println(handle, "marker,chr,pos,lod,beta,se,h2")
+    for (index, marker) in enumerate(marker_names)
+        chr, pos = get(marker_map, marker, ("", 0.0))
+        b = length(beta) >= index ? beta[index] : NaN
+        s = se === nothing ? "NA" : string(se[index])
+        println(handle, join((marker, chr, string(pos), string(result.lod[index]),
+                              string(b), s, string(h2)), ","))
+    end
+end
+
+if perm_out !== nothing && nperms > 0 && hasproperty(result, :L_perms)
+    alphas = [0.10, 0.05, 0.01]
+    found = get_thresholds(result.L_perms, alphas)
+    thresholds = hasproperty(found, :thrs) ? collect(found.thrs) : collect(found)
+    open(perm_out, "w") do handle
+        println(handle, "alpha,lod")
+        for (alpha, lod) in zip(alphas, thresholds)
+            println(handle, join((string(alpha), string(lod)), ","))
+        end
+    end
+    println(stderr, "bulklmm: permutation thresholds ", join(round.(thresholds, digits = 3), " / "))
+end
+println(stderr, "bulklmm: wrote ", out_file)