about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-10 22:12:29 +0000
committerPjotr <wrk@bosa.lan>2026-11-10 22:12:29 +0000
commit62cc5f73cb94fe85c31a2f177d1d150e643e84b1 (patch)
treef49d5cd0c3a62dd26bdbd5e022b8b6e9a1f0654c /src
parent0253fa66f2ef464d56324c27ba51cec1e27e3108 (diff)
downloadgenenetwork4-62cc5f73cb94fe85c31a2f177d1d150e643e84b1.tar.gz
uploads: every engine maps an upload by name; same name replaces
Two things asked for, and one bug each.

  * POST /uploads/genotypes with an existing name now REPLACES it. A
    genotype is the user's file to keep, not a record the deployment
    curates; the digest in every reply says which version ran.
  * genotype_upload on all four engines -- /compute/{rqtl,gemma,qtl2,
    fitqtl} -- in place of genotype_file/group. The server writes the
    form each engine reads: a GN .geno for R/qtl and R/qtl2, a BIMBAM
    pair (new: genoupload::to_bimbam, coding from the base's
    @mat/@het/@pat, NA for missing, snps as marker/bp/chr) for GEMMA. No
    user path travels with a request.

Verified against the full 3811-marker BXD.4 matrix uploaded as an update:
rqtl 3811 rows, gemma 3809, qtl2 3730, fitqtl by marker.

The bug worth naming: values given by name were being aligned against a
file, and for GEMMA that file is BIMBAM, which has no individual names --
so the phenotype file came out empty and the wrapper failed with a Ruby
backtrace that said nothing. GEMMA's values are now ordered by the
upload's own individual list before the pair is written. The related
fixes: rqtl and fitqtl align named values onto the file's individuals
(they previously demanded its column order), and genotypes::align_to_file
is the one place that does it.

tests/genoupload.rs: mapping an upload on rqtl/qtl2/fitqtl with values by
name, and replacing a name (one row in the listing, a new digest). GEMMA's
LOCO kinship needs more markers per chromosome than a small fixture has,
so it is exercised against a full panel rather than in the fixture.
Diffstat (limited to 'src')
-rw-r--r--src/genotypes.rs19
-rw-r--r--src/genoupload.rs131
-rw-r--r--src/routes/fitqtl.rs98
-rw-r--r--src/routes/gemma.rs127
-rw-r--r--src/routes/genoupload.rs44
-rw-r--r--src/routes/qtl2.rs30
-rw-r--r--src/routes/rqtl.rs85
7 files changed, 506 insertions, 28 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs
index 46503ff..9fea4c3 100644
--- a/src/genotypes.rs
+++ b/src/genotypes.rs
@@ -1042,3 +1042,22 @@ pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> {
     }
     mask
 }
+
+/// One value per individual of a `.geno`, in the file's own order, from values
+/// given by name. Used when a request names a file rather than a group -- an
+/// uploaded population, typically -- because the caller has a trait's values
+/// for its animals, not the file's column order.
+pub fn align_to_file(
+    geno: &Path,
+    values: &[(String, Option<f64>)],
+) -> Result<Vec<Option<f64>>, GenotypeError> {
+    let individuals = panel_of(geno)?;
+    let by_name: std::collections::HashMap<&str, Option<f64>> = values
+        .iter()
+        .map(|(name, value)| (name.as_str(), *value))
+        .collect();
+    Ok(individuals
+        .iter()
+        .map(|name| by_name.get(name.as_str()).copied().flatten())
+        .collect())
+}
diff --git a/src/genoupload.rs b/src/genoupload.rs
index 61be5f9..e544464 100644
--- a/src/genoupload.rs
+++ b/src/genoupload.rs
@@ -407,13 +407,19 @@ pub fn create(
             .optional()
             .map_err(|error| BasketError::Store(error.to_string()))?
     };
-    if exists.is_some() {
-        return Err(BasketError::Invalid(format!(
-            "a genotype named '{name}' already exists; delete it, or pick another name"
-        )));
-    }
     let at = now();
     let digest = hex_digest(contents.as_bytes());
+    // An upload replaces the upload of the same name. That is the user's call
+    // to make: a genotype is a file they keep, not a record the deployment
+    // curates, and a mapping they ran against it quotes the digest.
+    if exists.is_some() {
+        connection
+            .execute(
+                "DELETE FROM genotype WHERE name = ?1",
+                rusqlite::params![name.trim()],
+            )
+            .map_err(|error| BasketError::Store(error.to_string()))?;
+    }
     connection
         .execute(
             "INSERT INTO genotype (name, base_version, description, individuals, markers, \
@@ -661,3 +667,118 @@ mod tests {
         assert!(text.contains("\n1\trs2\t4.0\t4.0\tD\tD\n"), "{text}");
     }
 }
+
+/// Convert the upload to GEMMA's BIMBAM pair: `(geno, snps)`.
+///
+/// GN's own BIMBAM files encode a call as a dosage in {0, 0.5, 1} with the
+/// alleles left as the placeholders `X, Y`, and the snps file as
+/// `marker, position in bp, chromosome`. The coding follows the base
+/// population's `@mat`/`@het`/`@pat` when it declares one (mat -> 1, het ->
+/// 0.5, pat -> 0), and falls back to the file's own first/last letters, so the
+/// direction matches the population the upload updates.
+pub fn to_bimbam(contents: &str, labels: &[(String, String)]) -> (String, String) {
+    let label = |key: &str| {
+        labels
+            .iter()
+            .find(|(name, _)| name == key)
+            .map(|(_, value)| value.trim().to_string())
+    };
+    let het = label("het").unwrap_or_else(|| "H".to_string());
+    let mut coding: std::collections::BTreeMap<String, &'static str> =
+        std::collections::BTreeMap::new();
+    if let (Some(mat), Some(pat)) = (label("mat"), label("pat")) {
+        coding.insert(mat, "1");
+        coding.insert(het.clone(), "0.5");
+        coding.insert(pat, "0");
+    }
+    let mut geno = String::new();
+    let mut snps = String::new();
+    let mut header_seen = false;
+    let mut individuals = 0usize;
+    for line in contents.lines() {
+        let line = line.trim_end_matches('\r');
+        if line.trim().is_empty() || line.starts_with('#') {
+            continue;
+        }
+        let fields: Vec<&str> = line.split('\t').collect();
+        if !header_seen {
+            header_seen = true;
+            individuals = fields.len().saturating_sub(3);
+            continue;
+        }
+        if fields.len() < 4 {
+            continue;
+        }
+        let marker = fields[0].trim();
+        let chr = fields[1].trim();
+        let positions: Vec<&str> = fields[3..].iter().take(individuals).map(|c| c.trim()).collect();
+        // Without declared codes, use the calls themselves: the "het" is 0.5,
+        // the rest are the two homozygotes in the order they first appear.
+        if coding.is_empty() {
+            let mut letters: Vec<String> = positions
+                .iter()
+                .filter(|cell| !is_missing(cell))
+                .map(|cell| cell.to_string())
+                .collect();
+            letters.sort();
+            letters.dedup();
+            for letter in letters {
+                let code = if letter == het {
+                    "0.5"
+                } else if coding.len() < 2 {
+                    "1"
+                } else {
+                    "0"
+                };
+                coding.insert(letter, code);
+            }
+        }
+        geno.push_str(marker);
+        geno.push_str(", X, Y");
+        for cell in &positions {
+            geno.push_str(", ");
+            let value = if is_missing(cell) {
+                "NA".to_string()
+            } else {
+                coding.get(*cell).copied().unwrap_or("0.5").to_string()
+            };
+            geno.push_str(&value);
+        }
+        geno.push('\n');
+        let base_pairs = fields[2]
+            .trim()
+            .parse::<f64>()
+            .map(|megabases| (megabases * 1e6).round() as i64)
+            .unwrap_or(0);
+        snps.push_str(&format!("{marker}, {base_pairs}, {chr}\n"));
+    }
+    (geno, snps)
+}
+
+/// Write the upload out as a BIMBAM pair, returning `(geno, snps)` paths.
+pub fn materialise_bimbam(
+    dir: &Path,
+    owner: &str,
+    name: &str,
+    base_labels: &[(String, String)],
+) -> Result<(std::path::PathBuf, std::path::PathBuf), BasketError> {
+    let contents = contents(dir, owner, name)?;
+    let (geno_text, snps_text) = to_bimbam(&contents, base_labels);
+    let root = dir.join("genotypes").join(crate::baskets::file_stem(owner));
+    std::fs::create_dir_all(&root)
+        .map_err(|error| BasketError::Store(format!("{}: {error}", root.display())))?;
+    let stem = crate::baskets::file_stem(name);
+    let geno = root.join(format!("{stem}_geno.txt"));
+    let snps = root.join(format!("{stem}_snps.txt"));
+    for (path, text) in [(&geno, geno_text), (&snps, snps_text)] {
+        std::fs::write(path, text)
+            .map_err(|error| BasketError::Store(format!("{}: {error}", path.display())))?;
+    }
+    Ok((geno, snps))
+}
+
+/// The individuals of an upload, in its own order (the geno column order).
+pub fn individuals(dir: &Path, owner: &str, name: &str) -> Result<Vec<String>, BasketError> {
+    let parsed = parse(&contents(dir, owner, name)?)?;
+    Ok(parsed.individuals)
+}
diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs
index 9d5907c..73d3bbe 100644
--- a/src/routes/fitqtl.rs
+++ b/src/routes/fitqtl.rs
@@ -51,6 +51,10 @@ pub struct FitqtlRequest {
     pub genotype_version: Option<String>,
     /// Explicit `.geno` path on the server, instead of `group`.
     pub genotype_file: Option<String>,
+    /// An uploaded genotype from `/uploads/genotypes`, in place of
+    /// `genotype_file`: the server writes it out and maps over it.
+    pub genotype_upload: Option<String>,
+
     /// Include parents and F1s; off by default, as elsewhere.
     pub include_parents_f1: Option<bool>,
     /// The trait's values by individual name (aligned onto the panel), or
@@ -115,6 +119,29 @@ pub async fn compute_fitqtl(
     Json(mut request): Json<FitqtlRequest>,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    if let Some(upload) = request.genotype_upload.clone() {
+        if request.genotype_file.is_some() || request.group.is_some() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give genotype_upload, genotype_file or group -- one of the three.".to_string(),
+                "compute_fitqtl",
+            )
+            .with_request_id(rid));
+        }
+        let (path, _) = crate::routes::genoupload::resolve_upload(
+            token.sub.clone(),
+            Config::load().basket_dir,
+            Config::load().genotype_files_dir,
+            upload,
+            "compute_fitqtl",
+            rid.clone(),
+            false,
+        )
+        .await?;
+        request.genotype_file = Some(path);
+    }
     // A basket is another source for the caller's values, resolved before
     // anything below looks at them (see crate::routes::baskets).
     let mut basket_note: Option<String> = None;
@@ -297,26 +324,77 @@ pub async fn compute_fitqtl(
         }
         (Some(file), None) => {
             let values = request.trait_values.clone().unwrap_or_default();
-            if values.is_empty() {
+            let named: Vec<(String, Option<f64>)> = request
+                .samples
+                .clone()
+                .unwrap_or_default()
+                .into_iter()
+                .map(|sample| (sample.name, sample.value))
+                .collect();
+            if values.is_empty() && named.is_empty() {
                 return Err(ApiError::new(
                     StatusCode::UNPROCESSABLE_ENTITY,
                     "missing_trait_values",
                     "No trait values",
-                    "with an explicit genotype_file, give `trait_values` (one per individual, \
-                     in the file's order)."
+                    "with an explicit genotype_file, give `samples` (name and value), a `basket`, \
+                     or `trait_values` (one per individual, in the file's order)."
                         .to_string(),
                     "compute_fitqtl",
                 )
                 .with_request_id(rid));
             }
-            let samples: Vec<Sample> = values
-                .into_iter()
-                .enumerate()
-                .map(|(index, value)| Sample {
-                    name: format!("individual-{}", index + 1),
-                    value,
+            let samples: Vec<Sample> = if !named.is_empty() {
+                // Values are for animals, not for columns: align them onto the
+                // file's own individuals.
+                let path = std::path::PathBuf::from(&file);
+                let names = tokio::task::spawn_blocking({
+                    let path = path.clone();
+                    move || genotypes::panel_of(&path)
                 })
-                .collect();
+                .await
+                .map_err(|error| {
+                    ApiError::new(
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                        "internal_error",
+                        "Internal error",
+                        error.to_string(),
+                        "compute_fitqtl",
+                    )
+                    .with_request_id(rid.clone())
+                })?
+                .map_err(|error| genotypes_error(error, rid.clone()))?;
+                let aligned = tokio::task::spawn_blocking(move || {
+                    genotypes::align_to_file(&path, &named)
+                })
+                .await
+                .map_err(|error| {
+                    ApiError::new(
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                        "internal_error",
+                        "Internal error",
+                        error.to_string(),
+                        "compute_fitqtl",
+                    )
+                    .with_request_id(rid.clone())
+                })?
+                .map_err(|error| {
+                    genotypes_error(error, rid.clone())
+                })?;
+                names
+                    .into_iter()
+                    .zip(aligned)
+                    .map(|(name, value)| Sample { name, value })
+                    .collect()
+            } else {
+                values
+                    .into_iter()
+                    .enumerate()
+                    .map(|(index, value)| Sample {
+                        name: format!("individual-{}", index + 1),
+                        value,
+                    })
+                    .collect()
+            };
             (file, samples)
         }
         (Some(_), Some(_)) => {
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 15e359a..194e3c8 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -43,6 +43,10 @@ pub struct GemmaRequest {
     /// as GEMMA's `-g`. Give this and `snps_file`, or `group` -- not
     /// both.
     pub genotype_file: Option<String>,
+    /// An uploaded genotype from `/uploads/genotypes`, in place of
+    /// `genotype_file`: the server writes it out and maps over it.
+    pub genotype_upload: Option<String>,
+
     /// Path to a SNP annotation file (rs id, position, chromosome),
     /// passed as GEMMA's `-a`.
     pub snps_file: Option<String>,
@@ -143,6 +147,86 @@ pub async fn compute_gemma(
     Json(mut request): Json<GemmaRequest>,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    if let Some(upload) = request.genotype_upload.clone() {
+        if request.genotype_file.is_some() || request.group.is_some() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give genotype_upload, genotype_file or group -- one of the three.".to_string(),
+                "compute_gemma",
+            )
+            .with_request_id(rid));
+        }
+        // GEMMA reads BIMBAM, not `.geno`, so the upload is written out as
+        // the pair (`-g`/`-a`) that the deployment's own GTEx/BXD runs use.
+        let upload_for_values = upload.clone();
+        let (geno, snps) = crate::routes::genoupload::resolve_upload(
+            token.sub.clone(),
+            Config::load().basket_dir,
+            Config::load().genotype_files_dir,
+            upload,
+            "compute_gemma",
+            rid.clone(),
+            true,
+        )
+        .await?;
+        // GEMMA reads BIMBAM, which has no individual names, so the values are
+        // ordered here -- by the upload's own individual list -- rather than
+        // aligned later against a file that cannot answer.
+        let named: Vec<(String, Option<f64>)> = request
+            .samples
+            .as_ref()
+            .map(|samples| {
+                samples
+                    .iter()
+                    .map(|sample| (sample.name.clone(), sample.value))
+                    .collect()
+            })
+            .unwrap_or_default();
+        if request.trait_values.is_none() && !named.is_empty() {
+            let config = Config::load();
+            let individuals = tokio::task::spawn_blocking({
+                let dir = config.basket_dir.clone();
+                let owner = token.sub.clone();
+                let wanted = upload_for_values.clone();
+                move || crate::genoupload::individuals(std::path::Path::new(&dir), &owner, &wanted)
+            })
+            .await
+            .map_err(|error| {
+                ApiError::new(
+                    StatusCode::INTERNAL_SERVER_ERROR,
+                    "internal_error",
+                    "Internal error",
+                    error.to_string(),
+                    "compute_gemma",
+                )
+                .with_request_id(rid.clone())
+            })?
+            .map_err(|error| {
+                ApiError::new(
+                    StatusCode::UNPROCESSABLE_ENTITY,
+                    "invalid_genotype_upload",
+                    "Invalid genotype upload",
+                    error.to_string(),
+                    "compute_gemma",
+                )
+                .with_request_id(rid.clone())
+            })?;
+            let by_name: std::collections::HashMap<&str, Option<f64>> = named
+                .iter()
+                .map(|(name, value)| (name.as_str(), *value))
+                .collect();
+            request.trait_values = Some(
+                individuals
+                    .iter()
+                    .map(|name| by_name.get(name.as_str()).copied().flatten())
+                    .collect(),
+            );
+        }
+        request.genotype_file = Some(geno);
+        request.snps_file = snps;
+    }
     // A basket is another source for the caller's values, resolved before
     // anything below looks at them (see crate::routes::baskets).
     let mut basket_note: Option<String> = None;
@@ -276,11 +360,46 @@ pub async fn compute_gemma(
             request.group.clone(),
         ) {
             (Some(genotype_file), Some(snps_file), None) => {
-                let trait_values = request.trait_values.clone().or_else(|| {
-                    request.samples.as_ref().map(|samples| {
-                        samples.iter().map(|sample| sample.value).collect()
+                // GEMMA needs one phenotype row per genotype column, so values
+                // given by name are aligned onto the file's own individuals
+                // (and the rest become NA, which GEMMA drops) -- the same rule
+                // the group path follows. Positional `trait_values` are taken
+                // as they come.
+                let named: Vec<(String, Option<f64>)> = request
+                    .samples
+                    .as_ref()
+                    .map(|samples| {
+                        samples
+                            .iter()
+                            .map(|sample| (sample.name.clone(), sample.value))
+                            .collect()
+                    })
+                    .unwrap_or_default();
+                let trait_values = if let Some(values) = request.trait_values.clone() {
+                    Some(values)
+                } else if named.is_empty() {
+                    None
+                } else {
+                    let path = std::path::PathBuf::from(&genotype_file);
+                    let aligned = tokio::task::spawn_blocking(move || {
+                        genotypes::align_to_file(&path, &named)
                     })
-                });
+                    .await
+                    .map_err(|error| {
+                        ApiError::new(
+                            StatusCode::INTERNAL_SERVER_ERROR,
+                            "internal_error",
+                            "Internal error",
+                            error.to_string(),
+                            "compute_gemma",
+                        )
+                        .with_request_id(rid.clone())
+                    })?
+                    .map_err(|error| {
+                        genotype_error_to_api_error(error, "compute_gemma", rid.clone())
+                    })?;
+                    Some(aligned)
+                };
                 let Some(trait_values) = trait_values else {
                     return Err(ApiError::new(
                         StatusCode::UNPROCESSABLE_ENTITY,
diff --git a/src/routes/genoupload.rs b/src/routes/genoupload.rs
index 74a0971..bd12018 100644
--- a/src/routes/genoupload.rs
+++ b/src/routes/genoupload.rs
@@ -410,3 +410,47 @@ pub async fn delete_genotype(
     .map_err(|error| map_error(error, rid.clone(), "delete_genotype"))?;
     Ok(StatusCode::NO_CONTENT)
 }
+
+/// Resolve `genotype_upload` for a compute endpoint: materialise the upload in
+/// the form that engine reads, and hand back the path(s).
+///
+/// R/qtl and R/qtl2 read a GN `.geno`; GEMMA reads a BIMBAM pair. Either way
+/// the caller names the upload and the server writes the file, so no user path
+/// is ever passed around.
+pub(crate) async fn resolve_upload(
+    owner: String,
+    basket_dir: String,
+    genotype_dir: String,
+    name: String,
+    endpoint: &'static str,
+    rid: RequestInfo,
+    bimbam: bool,
+) -> Result<(String, Option<String>), ApiError> {
+    tokio::task::spawn_blocking(move || {
+        let dir = std::path::Path::new(&basket_dir);
+        let info = genoupload::get(dir, &owner, &name)?;
+        // The base's @-metadata travels with the file so R/qtl reads the
+        // upload as the same kind of cross as the population it updates.
+        let labels = genotypes::resolve_named(
+            std::path::Path::new(&genotype_dir),
+            &info.base_version,
+        )
+        .ok()
+        .and_then(|path| genotypes::file_meta(&path).ok())
+        .map(|meta| meta.labels)
+        .unwrap_or_default();
+        if bimbam {
+            let (geno, snps) = genoupload::materialise_bimbam(dir, &owner, &name, &labels)?;
+            Ok::<_, BasketError>((
+                geno.to_string_lossy().into_owned(),
+                Some(snps.to_string_lossy().into_owned()),
+            ))
+        } else {
+            let path = genoupload::materialise(dir, &owner, &name, &labels)?;
+            Ok::<_, BasketError>((path.to_string_lossy().into_owned(), None))
+        }
+    })
+    .await
+    .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), endpoint))?
+    .map_err(|error| map_error(error, rid, endpoint))
+}
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
index 52fc118..5ebde1d 100644
--- a/src/routes/qtl2.rs
+++ b/src/routes/qtl2.rs
@@ -54,6 +54,10 @@ pub struct Qtl2Request {
     pub genotype_version: Option<String>,
     /// Explicit `.geno` path on the server, instead of `group`.
     pub genotype_file: Option<String>,
+    /// An uploaded genotype from `/uploads/genotypes`, in place of
+    /// `genotype_file`: the server writes it out and maps over it.
+    pub genotype_upload: Option<String>,
+
     /// A cross that ships its own R/qtl2 control file, by name (e.g. "do").
     /// This is the only route to a multiparent scan: a `.geno` panel carries
     /// two codes per marker, not the founder alleles a multiparent model
@@ -117,6 +121,32 @@ pub async fn compute_qtl2(
     Json(mut request): Json<Qtl2Request>,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    // An uploaded genotype is just another `.geno`: materialise it and let the
+    // path branch below do the rest.
+    if let Some(upload) = request.genotype_upload.clone() {
+        if request.genotype_file.is_some() || request.group.is_some() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give genotype_upload, genotype_file or group -- one of the three.".to_string(),
+                "compute_qtl2",
+            )
+            .with_request_id(rid));
+        }
+        let config = Config::load();
+        let (path, _) = crate::routes::genoupload::resolve_upload(
+            token.sub.clone(),
+            config.basket_dir,
+            config.genotype_files_dir,
+            upload,
+            "compute_qtl2",
+            rid.clone(),
+            false,
+        )
+        .await?;
+        request.genotype_file = Some(path);
+    }
     let config = Config::load();
     let trait_label = request
         .trait_name
diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs
index d03261f..5bb227c 100644
--- a/src/routes/rqtl.rs
+++ b/src/routes/rqtl.rs
@@ -45,6 +45,10 @@ pub struct RqtlRequest {
     /// Path to an R/qtl-format `.geno` file (riset/F2/4-way; `@type:`
     /// in its header). Give this, or `group` -- not both.
     pub genotype_file: Option<String>,
+    /// An uploaded genotype from `/uploads/genotypes`, in place of
+    /// `genotype_file`: the server writes it out and maps over it.
+    pub genotype_upload: Option<String>,
+
     /// Group to map over (an InbredSet name, e.g. "BXD"). The server
     /// resolves the genotype file from the deployment's genotype-files
     /// directory, which is what `/groups/{group}/genotypes` lists.
@@ -129,6 +133,29 @@ pub async fn compute_rqtl(
     Json(mut request): Json<RqtlRequest>,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    if let Some(upload) = request.genotype_upload.clone() {
+        if request.genotype_file.is_some() || request.group.is_some() {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "ambiguous_genotype",
+                "Ambiguous genotype input",
+                "give genotype_upload, genotype_file or group -- one of the three.".to_string(),
+                "compute_rqtl",
+            )
+            .with_request_id(rid));
+        }
+        let (path, _) = crate::routes::genoupload::resolve_upload(
+            token.sub.clone(),
+            Config::load().basket_dir,
+            Config::load().genotype_files_dir,
+            upload,
+            "compute_rqtl",
+            rid.clone(),
+            false,
+        )
+        .await?;
+        request.genotype_file = Some(path);
+    }
     if let Some(id) = &params.id {
         if !streaming::is_valid_run_id(id) {
             return Err(ApiError::new(
@@ -235,16 +262,56 @@ pub async fn compute_rqtl(
         .collect();
     let (genotype_file, samples): (String, Vec<Sample>) =
         match (request.genotype_file.clone(), request.group.clone()) {
-            (Some(file), None) => (
-                file,
-                samples
+            (Some(file), None) => {
+                // The values are for animals, not for columns: read the file's
+                // own individuals and put each value where it belongs.
+                let path = std::path::PathBuf::from(&file);
+                let named: Vec<(String, Option<f64>)> = samples
                     .iter()
-                    .map(|s| Sample {
-                        name: s.name.clone(),
-                        value: s.value,
-                    })
-                    .collect(),
-            ),
+                    .map(|sample| (sample.name.clone(), sample.value))
+                    .collect();
+                let aligned = tokio::task::spawn_blocking(move || {
+                    genotypes::align_to_file(&path, &named)
+                })
+                .await
+                .map_err(|error| {
+                    ApiError::new(
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                        "internal_error",
+                        "Internal error",
+                        error.to_string(),
+                        "compute_rqtl",
+                    )
+                    .with_request_id(rid.clone())
+                })?
+                .map_err(|error| genotype_error_to_api_error(error, "compute_rqtl", rid.clone()))?;
+                let names = {
+                    let path = std::path::PathBuf::from(&file);
+                    tokio::task::spawn_blocking(move || genotypes::panel_of(&path))
+                        .await
+                        .map_err(|error| {
+                            ApiError::new(
+                                StatusCode::INTERNAL_SERVER_ERROR,
+                                "internal_error",
+                                "Internal error",
+                                error.to_string(),
+                                "compute_rqtl",
+                            )
+                            .with_request_id(rid.clone())
+                        })?
+                        .map_err(|error| {
+                            genotype_error_to_api_error(error, "compute_rqtl", rid.clone())
+                        })?
+                };
+                (
+                    file,
+                    names
+                        .into_iter()
+                        .zip(aligned)
+                        .map(|(name, value)| Sample { name, value })
+                        .collect(),
+                )
+            }
             (None, Some(group)) => {
                 let directory = std::path::PathBuf::from(&config.genotype_files_dir);
                 let cache_dir = std::path::PathBuf::from(&config.rqtl_cache_dir);