about summary refs log tree commit diff
path: root/src/routes/bulklmm.rs
blob: d549f07716ccea8274856a7aba29253ba25e0f15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! `POST /compute/bulklmm`: a genome scan with BulkLMM.jl.
//!
//! The engine GEMMA cannot be asked for thresholds. GEMMA's LOCO scan is the
//! reference for a biallelic panel, but a permutation repeats the whole scan,
//! which is why `/compute/gemma` refuses `nperm` outright; the usual stand-in
//! is R/qtl's `nperm`, whose null shuffles phenotypes as if the individuals
//! were unrelated. BulkLMM fits an LMM with a global kinship matrix and
//! permutes by rotating the data through the eigen decomposition of that
//! matrix -- relatedness included -- and 200 permutations cost seconds.
//!
//! The differences from GEMMA are stated in the reply, not implied: this is a
//! **global-kinship** LMM, not a leave-one-chromosome-out one, and `h2_null`
//! says how much relatedness it found (when that is ~0 it degenerates to a
//! fixed-effects fit).

use axum::Json;
use axum::extract::Query;
use axum::http::StatusCode;
use serde::Deserialize;
use serde_json::Value;

use gnauth_macros::{compute_gate, gnauth};

use crate::auth::AuthToken;
use crate::bulklmm::{self, BulklmmError};
use crate::compute_gate as gate;
use crate::config::Config;
use crate::covariates;
use crate::error::{ApiError, Unauthorized};
use crate::genotypes;
use crate::normalize;
use crate::response::{Ctx, Envelope, RequestInfo, path_segment};
use crate::rqtl::{Sample, write_pheno_file};

#[derive(Deserialize, utoipa::IntoParams)]
pub struct ComputeBulklmmParams {
    /// Log progress for `GET /compute/rqtl/status/{id}` (shared with the other
    /// R-class engines, since this one also has to be watched).
    pub id: Option<String>,
}

#[derive(Deserialize, utoipa::ToSchema)]
pub struct BulklmmSample {
    pub name: String,
    pub value: Option<f64>,
}

#[derive(Deserialize, utoipa::ToSchema)]
pub struct BulklmmRequest {
    /// Group to scan (an InbredSet name, e.g. "BXD").
    pub group: Option<String>,
    /// A version from `/groups/{group}/genotypes`.
    pub genotype_version: Option<String>,
    /// A of a user's uploaded genotype (`/uploads/genotypes`, by name).
    pub genotype_upload: Option<String>,
    /// Include parents and F1s; off by default, as elsewhere.
    pub include_parents_f1: Option<bool>,
    /// Individuals to keep or drop on top of the parent/F1 rule
    /// (`genotypes::Individuals`); `exclude` wins over `include`.
    #[serde(default)]
    pub individuals: genotypes::Individuals,
    /// The trait's values by individual name, or `trait_values` positionally.
    pub samples: Option<Vec<BulklmmSample>>,
    /// A basket from `/baskets`, in place of `samples`.
    pub basket: Option<String>,
    /// Label for the trait, e.g. "BXD::16627"; reported in `notes`.
    pub trait_name: Option<String>,
    /// Covariates, as on `/compute/rqtl`.
    #[serde(default)]
    pub covariates: Vec<covariates::Spec>,
    /// Permutations for the thresholds. 0 (default) scans without them.
    pub nperm: Option<u32>,
    /// Seed for the rotations, so a threshold set is reproducible.
    pub seed: Option<u32>,
    /// Estimate the variance components by REML rather than ML.
    pub reml: Option<bool>,
    /// `null` (default: variance components estimated once, under the null) or
    /// `alt` (per marker, slower and more accurate).
    pub assumption: Option<String>,
    /// Julia threads (`--threads`), default `BULKLMM_THREADS` (4). The marker
    /// blocks scanned in parallel come from `BULKLMM_BLOCKS` (4).
    pub cores: Option<u32>,
    /// Normalisation of the trait values, as on `/compute/rqtl`.
    pub normalize: Option<String>,
    pub winsor_quantile: Option<f64>,
    pub winsor_fences: Option<f64>,
}

#[utoipa::path(post, path = "/compute/bulklmm",
    summary = "Scan a panel with BulkLMM.jl: an LMM with permutation thresholds",
    description = "Fits one linear mixed model per marker with a global kinship matrix \
(BulkLMM.jl), and -- unlike /compute/gemma, which refuses permutations because each repeats \
the whole LOCO scan -- permutes by rotating the data through the kinship's eigen decomposition, \
so `nperm` costs seconds. Rows are positional: marker, chr, pos (Mb), lod, beta, h2. The reply \
notes the permutation thresholds (alpha 0.10, 0.05, 0.01), the seed, and the null heritability: \
this is a global-kinship model, not a LOCO one, and a null h2 near zero means it collapsed to a \
fixed-effects fit.",
    params(ComputeBulklmmParams),
    request_body = BulklmmRequest,
    responses(
        (status = 200, description = "One row per marker, positional (meta.columns names them)", body = Envelope<Value>),
        Unauthorized,
        (status = 409, description = "A scan is already running for this caller", body = ApiError),
        (status = 422, description = "No usable panel, trait values or covariate", body = ApiError),
        (status = 502, description = "Julia or BulkLMM failed", body = ApiError)
    )
)]
#[gnauth(token_only)]
#[compute_gate(bulklmm, label = "BulkLMM", run_id = params.id.as_deref())]
pub async fn compute_bulklmm(
    ctx: Ctx,
    token: AuthToken,
    Query(params): Query<ComputeBulklmmParams>,
    Json(mut request): Json<BulklmmRequest>,
) -> Result<Json<Envelope<Value>>, ApiError> {
    let rid = ctx.request_info();
    let config = Config::load();
    let trait_label = request
        .trait_name
        .clone()
        .filter(|name| !name.trim().is_empty())
        .unwrap_or_else(|| format!("{}::bulklmm", request.group.clone().unwrap_or_default()));
    let pipeline = normalize::Pipeline::parse(
        request.normalize.as_deref(),
        request.winsor_quantile,
        request.winsor_fences,
    )
    .map_err(|detail| {
        ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "invalid_normalization",
            "Invalid normalization",
            detail,
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?;
    let assumption = request.assumption.clone().unwrap_or_else(|| "null".to_string());
    if !matches!(assumption.as_str(), "null" | "alt") {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "invalid_assumption",
            "Invalid variance-component assumption",
            format!("assumption '{assumption}' not recognized; use 'null' or 'alt'."),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    }
    let nperm = request.nperm.unwrap_or(0).min(10_000);
    let seed = request.seed.unwrap_or(0);
    let reml = request.reml.unwrap_or(false);
    let threads = request.cores.unwrap_or(config.bulklmm_threads).clamp(1, 32);
    let blocks = config.bulklmm_blocks.clamp(1, 64);

    let mut notes: Vec<String> = Vec::new();
    // A basket is another source for `samples`.
    let mut basket_note: Option<String> = None;
    if let Some(name) = request.basket.clone() {
        if request.samples.is_some() {
            return Err(ApiError::new(
                StatusCode::UNPROCESSABLE_ENTITY,
                "ambiguous_samples",
                "Ambiguous values",
                "give `basket` or `samples`, not both.".to_string(),
                "compute_bulklmm",
            )
            .with_request_id(rid));
        }
        let (resolved, note) = crate::routes::baskets::resolve_for_mapping(
            token.sub.clone(),
            config.basket_dir.clone(),
            name,
            "compute_bulklmm",
            rid.clone(),
        )
        .await?;
        basket_note = Some(note);
        request.samples = Some(
            resolved
                .values
                .iter()
                .map(|(name, value)| BulklmmSample {
                    name: name.clone(),
                    value: *value,
                })
                .collect(),
        );
    }
    let samples: Vec<Sample> = request
        .samples
        .take()
        .unwrap_or_default()
        .into_iter()
        .map(|sample| Sample { name: sample.name, value: sample.value })
        .collect();
    if samples.is_empty() {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "missing_samples",
            "No trait values",
            "give `samples`, a `basket`, or `trait_values`.".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    }

    // The panel: resolved and prepared exactly as GEMMA's BIMBAM input is,
    // because that pair is already the dosage matrix BulkLMM wants.
    let directory = config.genotype_files_dir.clone();
    let cache_dir = config.bulklmm_cache_dir.clone();
    let mut version = request.genotype_version.clone();
    if request.genotype_upload.is_some() && request.group.is_some() {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "ambiguous_genotype",
            "Ambiguous genotype input",
            "give genotype_upload or group -- one of the two.".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    }
    if let Some(upload) = request.genotype_upload.clone() {
        // The upload carries its own base version; resolving it yields the
        // version `genotypes::resolve` knows.
        let info = crate::genoupload::get(
            std::path::Path::new(&config.basket_dir),
            &token.sub,
            &upload,
        )
        .map_err(|error| {
            ApiError::new(
                StatusCode::NOT_FOUND,
                "genotype_upload_not_found",
                "Uploaded genotype not found",
                error.to_string(),
                "compute_bulklmm",
            )
            .with_request_id(rid.clone())
        })?;
        version = Some(info.base_version);
        notes.push(format!(
            "Genotype: uploaded panel '{upload}' ({}, {} markers).",
            info.value_kind, info.markers
        ));
    }
    let Some(group) = request.group.clone().or_else(|| Some(String::new())).filter(|group| !group.is_empty() || version.is_some()) else {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "missing_genotype",
            "No genotype input",
            "give group (+ genotype_version), genotype_upload, or genotype_file.".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    };
    let include_parents_f1 = request.include_parents_f1.unwrap_or(false);
    let individuals = request.individuals.clone();
    let values: Vec<(String, Option<f64>)> = samples
        .iter()
        .map(|sample| (sample.name.clone(), sample.value))
        .collect();
    let group_for_scan = if group.is_empty() {
        // An upload resolves through its base version; the group is the one
        // that version belongs to.
        None
    } else {
        Some(group.clone())
    };
    let directory_for_scan = directory.clone();
    let cache_for_scan = cache_dir.clone();
    let version_for_scan = version.clone();
    let prepared = tokio::task::spawn_blocking(move || {
        let resolved = match &group_for_scan {
            Some(group) => genotypes::resolve(
                std::path::Path::new(&directory_for_scan),
                group,
                version_for_scan.as_deref(),
            )?,
            None => {
                // A bare version (an upload's base): resolve it by name.
                let geno = genotypes::resolve_named(
                    std::path::Path::new(&directory_for_scan),
                    version_for_scan.as_deref().unwrap_or_default(),
                )?;
                let panel = genotypes::panel_of(&geno)?;
                genotypes::Resolved {
                    version: version_for_scan.clone().unwrap_or_default(),
                    title: None,
                    geno,
                    bimbam_geno: None,
                    bimbam_snps: None,
                    panel,
                }
            }
        };
        let parents_f1s = genotypes::non_strains(
            std::path::Path::new(&directory_for_scan),
            &resolved.version,
            &resolved.panel,
        );
        let selection = genotypes::select_panel(
            &resolved.panel,
            &parents_f1s,
            include_parents_f1,
            &individuals,
        )?;
        let keep: Vec<usize> = selection.keep.clone();
        let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values);
        let prepared = genotypes::prepare(
            std::path::Path::new(&directory_for_scan),
            &resolved,
            genotypes::Engine::Gemma,
            &keep,
            std::path::Path::new(&cache_for_scan),
        )?;
        let kept_names: Vec<String> = keep
            .iter()
            .map(|index| resolved.panel[*index].clone())
            .collect();
        let samples: Vec<Sample> = kept_names
            .iter()
            .cloned()
            .zip(aligned)
            .map(|(name, value)| Sample { name, value })
            .collect();
        Ok::<_, genotypes::GenotypeError>((resolved.version.clone(), prepared, kept_names, samples, matched))
    })
    .await
    .map_err(|error| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|error| {
        ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "genotype_error",
            "The genotype files could not be read",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?;
    let (version_used, prepared, kept_names, aligned_samples, matched) = prepared;
    if matched == 0 {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "no_samples_aligned",
            "No samples aligned",
            "none of the supplied samples appear in this genotype panel".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    }
    notes.push(format!(
        "Genotype: {} (version {}); {} of {} supplied values aligned onto it by name.",
        prepared.note,
        version_used,
        matched,
        samples.len()
    ));
    let samples = aligned_samples;
    let samples = if pipeline.is_identity() {
        samples
    } else {
        let raw: Vec<Option<f64>> = samples.iter().map(|s| s.value).collect();
        let (normalized, applied) = pipeline.apply(&raw).map_err(|detail| {
            ApiError::new(
                StatusCode::UNPROCESSABLE_ENTITY,
                "invalid_normalization",
                "Invalid normalization",
                detail,
                "compute_bulklmm",
            )
            .with_request_id(rid.clone())
        })?;
        notes.push(pipeline.describe(&applied));
        samples
            .into_iter()
            .zip(normalized)
            .map(|(sample, value)| Sample { name: sample.name, value })
            .collect()
    };
    let (covariate_list, covariate_notes) = covariates::resolve(
        &request.covariates,
        &samples.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
        request.group.as_deref(),
        Some(&samples.iter().map(|s| s.value.is_some()).collect::<Vec<_>>()),
        rid.clone(),
    )
    .await?;
    notes.extend(covariate_notes);

    // What Julia reads: the phenotype file, the dosage matrix, the marker map,
    // and the covariates when there are any.
    let work = bulklmm::work_dir(&cache_dir).map_err(|error| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?;
    let unique = format!(
        "{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );
    let pheno_path = work.join(format!("{unique}-pheno.txt"));
    write_pheno_file(&pheno_path, &trait_label, &samples, &covariate_list).map_err(|error| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?;
    let genotype_csv = work.join(format!("{unique}-geno.csv"));
    let markers_csv = work.join(format!("{unique}-markers.csv"));
    let Some(bimbam_geno) = Some(prepared.genotype_file.clone()) else {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "no_dosage_input",
            "No dosage genotypes for this panel",
            "BulkLMM reads allele dosages (the `bimbam/` pair); this version has none. \
             `/groups/{group}/genotypes` says which versions have GEMMA input."
                .to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    };
    let Some(bimbam_snps) = prepared.snps_file.clone() else {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "no_dosage_input",
            "No SNP map for this panel",
            "the `bimbam/` pair is incomplete for this version".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    };
    let individuals = kept_names.clone();
    let (genotype_csv_for_job, markers_csv_for_job) = (genotype_csv.clone(), markers_csv.clone());
    let markers = tokio::task::spawn_blocking(move || {
        bulklmm::write_inputs(
            &bimbam_geno,
            &bimbam_snps,
            &individuals,
            &genotype_csv_for_job,
            &markers_csv_for_job,
        )
    })
    .await
    .map_err(|error| {
        ApiError::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal error",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?
    .map_err(|error| {
        ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "genotype_error",
            "The genotype matrix could not be written",
            error.to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid.clone())
    })?;
    if markers == 0 {
        return Err(ApiError::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "empty_panel",
            "The panel has no markers",
            "the dosage matrix is empty".to_string(),
            "compute_bulklmm",
        )
        .with_request_id(rid));
    }

    let individuals_count = samples.len();
    __gn4_claim
        .claim_slot_or_busy(individuals_count, rid.clone())
        .await?;

    let rid_for_job = rid.clone();
    let output = gate::bulklmm()
        .run(__gn4_claim, async move {
            bulklmm::compute(
                &config.bulklmm_cmd,
                &config.bulklmm_env,
                &config.bulklmm_depot,
                &config.bulklmm_script,
                &work,
                &genotype_csv,
                &markers_csv,
                &pheno_path,
                None,
                nperm,
                seed,
                reml,
                &assumption,
                threads,
                blocks,
            )
            .await
            .map_err(|error| match error {
                BulklmmError::CommandFailed(detail) => ApiError::new(
                    StatusCode::BAD_GATEWAY,
                    "bulklmm_failed",
                    "BulkLMM failed",
                    detail,
                    "compute_bulklmm",
                )
                .with_request_id(rid_for_job.clone()),
                other => ApiError::new(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "internal_error",
                    "Internal error",
                    other.to_string(),
                    "compute_bulklmm",
                )
                .with_request_id(rid_for_job.clone()),
            })
        })
        .await?;

    if let Some(note) = basket_note {
        notes.push(note);
    }
    if let Some(h2) = output.h2_null {
        let boundary = if h2 < 0.01 {
            " At a boundary (h2 ~ 0 the model is ordinary regression, which is why its LODs can \
             match R/qtl's to the digit)."
        } else if h2 > 0.99 {
            " At a boundary (h2 ~ 1 the fit is almost all kinship), so its LODs are not \
             comparable with an engine that has no kinship term."
        } else {
            ""
        };
        notes.push(format!(
            "Null heritability h2 = {h2:.3}: {}",
            if h2 < 0.01 {
                "relatedness explains almost nothing here, so this fit is effectively a fixed-\
                 effects model (which is why it can agree with R/qtl where GEMMA differs)."
                    .to_string()
            } else {
                "the kinship term is doing work; GEMMA's LOCO scan weights each chromosome \
                 differently, so its p-values are not these."
                    .to_string()
            }
        ));
        notes.push(format!(
            "Variance components: h2 = {h2:.6}, sigma2_e = {:.6}, estimated once under the null \
             (intercept) model from y and K, not per marker. With a few dozen phenotyped \
             individuals these estimates pile up at the boundaries 0 and 1 -- the likelihood is \
             flat there -- so read h2 as \"kinship matters a lot / not at all\" rather than as a \
             precise proportion.{boundary}",
            output.sigma2_e.unwrap_or(f64::NAN)
        ));
    }
    if !output.thresholds.is_empty() {
        let thresholds: Vec<String> = output
            .thresholds
            .iter()
            .map(|(alpha, lod)| format!("alpha {alpha}: LOD {lod:.2}"))
            .collect();
        notes.push(format!(
            "Permutation thresholds from {nperm} rotations (seed {seed}): {}. These account for \
             relatedness -- R/qtl's nperm on the same values does not.",
            thresholds.join(", ")
        ));
    } else if nperm == 0 {
        notes.push(
            "No permutations requested, so no threshold: the LOD is a LOD. Ask for \
             `nperm` to get thresholds from BulkLMM's rotations (cheap here)."
                .to_string(),
        );
    }
    if !output.summary.is_empty() {
        notes.push(output.summary.clone());
    }
    let num_rows = output.markers;
    let mut envelope = ctx
        .envelope(output.rows)
        .with_columns(
            bulklmm::COLUMNS.iter().map(|name| name.to_string()).collect(),
            num_rows,
        )
        .with_note(&format!("Trait: {trait_label}"))
        .with_note(
            "Rows are positional: marker, chr, pos (Mb), lod, beta, h2. BulkLMM fits one LMM per \
             marker with a global kinship matrix (not GEMMA's leave-one-chromosome-out), by ML \
             or REML, and reports the effect size `beta` and the null heritability `h2`.",
        )
        .with_note(&format!(
            "Parallelism: BulkLMM's single-trait scan() is serial in Julia, so the markers are \
             split into {blocks} independent blocks and scanned on {threads} Julia thread(s) \
             (BULKLMM_BLOCKS / BULKLMM_THREADS; blocks 1 is a plain serial scan and gives the \
             same LODs). Where the cores really pay is many traits at once."
        ));
    if let Some(group) = request.group.clone() {
        envelope = envelope.with_next(
            &format!("/groups/{}", path_segment(&group)),
            "The group's record",
        );
        envelope = envelope.with_action(crate::response::SuggestedCall {
            method: "GET".to_string(),
            href: format!(
                "/groups/{}/traits/{}/peak-genotypes?marker={{marker}}",
                path_segment(&group),
                trait_label.rsplit("::").next().unwrap_or_default()
            ),
            description: "Count the animals in each genotype class at a marker of the peak"
                .to_string(),
            body: None,
        });
    }
    // And, when thresholds were computed, the GEMMA plot can carry them: same
    // values, two models, one picture -- labelled so the lines cannot be mixed up.
    if let Some(lod) = output.thresholds.get("0.05") {
        envelope = envelope.with_action(crate::response::SuggestedCall {
            method: "POST".to_string(),
            href: format!(
                "/plot/gemma?thresholds={lod:.2}&threshold_labels=bulklmm%20alpha%200.05"
            ),
            description: "Or draw a GEMMA result for the same values with this threshold on it \
                          (the request body is the /compute/gemma reply)"
                .to_string(),
            body: None,
        });
    }
    envelope = envelope.with_action(crate::response::SuggestedCall {
        method: "POST".to_string(),
        href: "/plot/bulklmm".to_string(),
        description: "Draw this scan: post this reply back and get the LOD plot, with the \
                      thresholds above drawn on it."
            .to_string(),
        body: None,
    });
    envelope = envelope.with_links(crate::suggest::root_links());
    for note in &notes {
        envelope = envelope.with_note(note);
    }
    Ok(Json(envelope))
}