diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 21:34:36 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 21:34:36 +0000 |
| commit | 92a7d0282897dd056b5694a20b2aee7cdc1ce6e3 (patch) | |
| tree | 72819710f2032da3301c6f3f3f24e7753cf074d2 /src | |
| parent | 1ee249766366f3d88c1486065f38a0fc58b8171b (diff) | |
| download | genenetwork4-92a7d0282897dd056b5694a20b2aee7cdc1ce6e3.tar.gz | |
uploads: a genotype matrix that updates an existing population
Tab-delimited, header names the individuals from column 4, then marker,
chr, pos (Mb). Named $USER-GENONAME, stored as text in the owner's own
SQLite file -- nothing goes near MariaDB -- and written out on demand as
a GN .geno carrying the base's @-metadata, so the R scripts read exactly
what was uploaded.
An upload updates a population, it does not invent one, and the checks
say so:
* the base version must exist (resolved through the same
genotypes::resolve_named the rest of the API uses);
* at most 50 individuals the base does not have, and at least one that
it does -- no overlap is a different population, not an update;
* at most 200 000 markers, and the refusal says the sysadmin has to
organize a file that size, because this is a request path, not an
ingest;
* the values must be the same kind as the base's: letters, whole
numbers or probabilities. A letters panel holding 0/1 would be read
as the wrong thing silently, so it is refused naming both kinds.
GET /uploads/genotypes lists them, /{name} its metadata (overlap, new
individuals, kind, digest), /{name}/markers pages the marker table, and
/{name}/geno writes the file and returns the path for `genotype_file` on
the compute endpoints. DELETE removes one.
scripts/example-genotype-upload.py turns any .geno into a valid update --
a subset of markers, a few individuals dropped and added -- and
tests/genoupload.rs builds its own from the deployment's BXD.4 for the
same reason: upload, page the markers, write the .geno and check the
layout, delete, then break each rule (no overlap, numbers in a letters
panel, commas) and check the refusal says which.
Unit tests cover the three value kinds, missing cells, ragged rows, a
non-numeric position, the 50-new-individual limit, and the .geno layout
(Chr first, then the marker -- GN's order, not the upload's).
Diffstat (limited to 'src')
| -rw-r--r-- | src/baskets.rs | 17 | ||||
| -rw-r--r-- | src/genoupload.rs | 656 | ||||
| -rw-r--r-- | src/lib.rs | 7 | ||||
| -rw-r--r-- | src/routes/genoupload.rs | 412 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 |
5 files changed, 1092 insertions, 1 deletions
diff --git a/src/baskets.rs b/src/baskets.rs index dbae856..c6410bf 100644 --- a/src/baskets.rs +++ b/src/baskets.rs @@ -203,7 +203,7 @@ pub fn validate_name(name: &str) -> Result<(), BasketError> { Ok(()) } -fn open(dir: &Path, owner: &str) -> Result<Connection, BasketError> { +pub(crate) fn open(dir: &Path, owner: &str) -> Result<Connection, BasketError> { std::fs::create_dir_all(dir) .map_err(|error| BasketError::Store(format!("{}: {error}", dir.display())))?; let path = database(dir, owner); @@ -240,6 +240,21 @@ fn open(dir: &Path, owner: &str) -> Result<Connection, BasketError> { description TEXT, UNIQUE(basket_id, revision) ); + CREATE TABLE IF NOT EXISTS genotype ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + base_version TEXT NOT NULL, + description TEXT, + individuals INTEGER NOT NULL, + markers INTEGER NOT NULL, + value_kind TEXT NOT NULL, + new_individuals INTEGER NOT NULL, + overlap INTEGER NOT NULL, + digest TEXT NOT NULL, + contents TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); CREATE TABLE IF NOT EXISTS matrix ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, diff --git a/src/genoupload.rs b/src/genoupload.rs new file mode 100644 index 0000000..54bc513 --- /dev/null +++ b/src/genoupload.rs @@ -0,0 +1,656 @@ +//! Uploading a genotype matrix: updating an existing population. +//! +//! The format is the one a genotype matrix already has, minus GN's own +//! metadata lines: +//! +//! ```text +//! marker chr pos BXD1 BXD2 ... +//! rs1234567 1 3.49 B D +//! rs7654321 1 12.1 D H +//! ``` +//! +//! Tab-delimited; the header names the individuals from column 4 on; column 1 +//! is the marker, 2 the chromosome, 3 the position in Mb. Values must be the +//! same *kind* as the base population's -- letters (`B`, `D`, `H`), whole +//! numbers (`0`, `1`, `2`) or probabilities (`0.02`, `0.98`) -- because a +//! mapping engine will read the result the way it reads the population it +//! updates. +//! +//! What is enforced, and why: +//! +//! * The base version must exist: an upload *updates* a population, it does not +//! invent one. +//! * Individuals: at most [`MAX_NEW_INDIVIDUALS`] names not in the base, and at +//! least one name that is. No overlap means it is a different population. +//! * Markers: at most [`MAX_MARKERS`]. Beyond that the sysadmin has to organize +//! the file -- this is a request path, not an ingest. +//! * Values: the same kind as the base's. A letters panel with `0/1` in it, or a +//! probabilities panel with `A/B`, would be read as the wrong thing silently. +//! +//! The upload is stored as text in the owner's SQLite file (one row, no schema +//! explosion at 200 000 markers) and materialised as a GN `.geno` file on +//! demand, so the R tooling reads exactly what the user uploaded. + +use std::collections::BTreeSet; +use std::path::Path; + +use crate::baskets::BasketError; + +/// The most markers an upload may carry (the user's limit). +pub const MAX_MARKERS: usize = 200_000; + +/// The most individuals an upload may add to a base population. +pub const MAX_NEW_INDIVIDUALS: usize = 50; + +/// What kind of values a matrix holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ValueKind { + /// Genotype calls: single letters, e.g. `A`, `B`, `H`. + Letters, + /// Whole-number dosage: `0`, `1`, `2`. + Integers, + /// Probabilities or dosages in [0, 1] with decimals. + Probabilities, +} + +impl ValueKind { + pub fn as_str(self) -> &'static str { + match self { + ValueKind::Letters => "letters", + ValueKind::Integers => "integers", + ValueKind::Probabilities => "probabilities", + } + } +} + +/// A parsed upload: the individuals, the markers, and what kind of values it +/// holds. +#[derive(Debug)] +pub struct Parsed { + pub individuals: Vec<String>, + pub markers: Vec<(String, String, f64)>, + pub kind: ValueKind, + /// Cells that are missing, counted once for the report. + pub missing: u64, +} + +fn is_missing(cell: &str) -> bool { + matches!(cell, "" | "U" | "u" | "N" | "NA" | "na" | "-" | "." | "?") +} + +/// What kind of value a non-missing cell is, or None if it is none of them. +fn kind_of(cell: &str) -> Option<ValueKind> { + if cell.chars().all(|character| character.is_ascii_alphabetic()) { + return Some(ValueKind::Letters); + } + if let Ok(number) = cell.parse::<f64>() { + if !number.is_finite() { + return None; + } + if (0.0..=1.0).contains(&number) && cell.contains('.') { + return Some(ValueKind::Probabilities); + } + if number.fract() == 0.0 && number.abs() <= 2.0 { + return Some(ValueKind::Integers); + } + return Some(ValueKind::Probabilities); + } + None +} + +/// Parse and validate the table itself (not yet the base population). +pub fn parse(text: &str) -> Result<Parsed, BasketError> { + let mut lines = text + .lines() + .map(|line| line.trim_end_matches('\r')) + .filter(|line| !line.trim().is_empty() && !line.starts_with('#')); + let Some(header) = lines.next() else { + return Err(BasketError::Invalid("the upload is empty".to_string())); + }; + if header.contains(',') && !header.contains('\t') { + return Err(BasketError::Invalid( + "the upload is tab-delimited: the header's fields must be separated by tabs".to_string(), + )); + } + let header: Vec<&str> = header.split('\t').collect(); + if header.len() < 4 { + return Err(BasketError::Invalid(format!( + "the header has {} field(s); it needs a marker column, chr, pos and at least one \ + individual", + header.len() + ))); + } + let individuals: Vec<String> = header[3..] + .iter() + .map(|name| name.trim().to_string()) + .collect(); + let mut seen = BTreeSet::new(); + for name in &individuals { + if name.is_empty() { + return Err(BasketError::Invalid( + "the header must name every individual from column 4 on".to_string(), + )); + } + if !seen.insert(name.clone()) { + return Err(BasketError::Invalid(format!( + "individual '{name}' appears twice in the header" + ))); + } + } + + let mut markers = Vec::new(); + let mut kind: Option<ValueKind> = None; + let mut missing = 0u64; + let mut mismatched: Vec<String> = Vec::new(); + for (index, line) in lines.enumerate() { + let fields: Vec<&str> = line.split('\t').collect(); + if fields.len() != header.len() { + return Err(BasketError::Invalid(format!( + "row {} has {} field(s) but the header has {}: {}", + index + 2, + fields.len(), + header.len(), + line.chars().take(60).collect::<String>() + ))); + } + let marker = fields[0].trim(); + if marker.is_empty() { + return Err(BasketError::Invalid(format!( + "row {} has no marker name", + index + 2 + ))); + } + let chr = fields[1].trim().to_string(); + let pos = fields[2] + .trim() + .parse::<f64>() + .map_err(|_| { + BasketError::Invalid(format!( + "{marker}: '{}' is not a position (column 3 is in Mb)", + fields[2] + )) + })?; + markers.push((marker.to_string(), chr, pos)); + if markers.len() > MAX_MARKERS { + return Err(BasketError::Invalid(format!( + "more than {MAX_MARKERS} markers: that is an ingest, not an upload -- the \ + sysadmin has to organize a file that size" + ))); + } + for cell in &fields[3..] { + let cell = cell.trim(); + if is_missing(cell) { + missing += 1; + continue; + } + match kind_of(cell) { + Some(found) => match kind { + None => kind = Some(found), + Some(expected) if expected == found => {} + Some(expected) => { + if mismatched.len() < 5 { + mismatched.push(format!( + "{marker}: '{cell}' is {}, the file starts as {}", + found.as_str(), + expected.as_str() + )); + } + } + _ => {} + }, + None => { + if mismatched.len() < 5 { + mismatched.push(format!("{marker}: '{cell}' is not a genotype value")); + } + } + } + } + } + if markers.is_empty() { + return Err(BasketError::Invalid( + "the upload has no marker rows".to_string(), + )); + } + if !mismatched.is_empty() { + return Err(BasketError::Invalid(format!( + "mixed or unusable values: {}", + mismatched.join("; ") + ))); + } + Ok(Parsed { + individuals, + markers, + kind: kind.unwrap_or(ValueKind::Letters), + missing, + }) +} + +/// A base population's value kind, and its individuals. +pub fn base_shape(geno: &Path) -> Result<(ValueKind, Vec<String>), BasketError> { + let text = std::fs::read_to_string(geno) + .map_err(|error| BasketError::Store(format!("{}: {error}", geno.display())))?; + let mut individuals = Vec::new(); + let mut kind: Option<ValueKind> = None; + let mut start = 3usize; + let mut header_seen = false; + for line in text.lines() { + if line.starts_with('#') || line.starts_with('@') || line.trim().is_empty() { + continue; + } + let fields: Vec<&str> = line.split('\t').collect(); + if !header_seen { + header_seen = true; + start = if fields.len() > 3 && fields[3] == "Mb" { 4 } else { 3 }; + individuals = fields[start.min(fields.len())..] + .iter() + .map(|name| name.trim().to_string()) + .collect(); + continue; + } + if kind.is_some() { + continue; + } + for cell in fields.iter().skip(start) { + let cell = cell.trim(); + if is_missing(cell) { + continue; + } + kind = kind_of(cell); + if kind.is_some() { + break; + } + } + } + Ok((kind.unwrap_or(ValueKind::Letters), individuals)) +} + +/// Check an upload against the population it updates. +pub fn check_base( + parsed: &Parsed, + base_individuals: &[String], + base_kind: ValueKind, +) -> Result<(usize, usize), BasketError> { + let base: BTreeSet<&str> = base_individuals.iter().map(String::as_str).collect(); + let overlap = parsed + .individuals + .iter() + .filter(|name| base.contains(name.as_str())) + .count(); + let new = parsed.individuals.len() - overlap; + if overlap == 0 { + return Err(BasketError::Invalid(format!( + "none of the {} individual(s) are in the base population: an upload updates a \ + population, so at least one name has to match", + parsed.individuals.len() + ))); + } + if new > MAX_NEW_INDIVIDUALS { + return Err(BasketError::Invalid(format!( + "{new} individual(s) are not in the base population; at most \ + {MAX_NEW_INDIVIDUALS} new ones can be added by an upload" + ))); + } + if parsed.kind != base_kind { + return Err(BasketError::Invalid(format!( + "the values are {} but this population's are {}; a mapping engine would read them \ + as the wrong thing", + parsed.kind.as_str(), + base_kind.as_str() + ))); + } + Ok((overlap, new)) +} + +/// Convert the upload to a GN `.geno` file: `Chr`, `Locus`, `cM`, `Mb`, then +/// the individuals -- the layout every R script here already reads -- carrying +/// the base population's `@`-metadata so R/qtl treats it as the same kind of +/// cross. +pub fn to_geno(contents: &str, labels: &[(String, String)]) -> String { + let mut text = String::new(); + for (key, value) in labels { + text.push_str(&format!("@{key}:{value}\n")); + } + if labels.is_empty() { + text.push_str("@type:riset\n"); + } + text.push_str("Chr\tLocus\tcM\tMb"); + let mut header_seen = false; + let mut header_individuals: Vec<&str> = Vec::new(); + 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; + header_individuals = fields.iter().skip(3).map(|name| name.trim()).collect(); + for name in &header_individuals { + text.push('\t'); + text.push_str(name); + } + text.push('\n'); + continue; + } + if fields.len() < 4 { + continue; + } + let marker = fields[0].trim(); + let chr = fields[1].trim(); + let pos = fields[2].trim(); + // cM is left as the position too: GN's own files do the same for a + // physical-only panel, and R/qtl2 reads the Mb column. + text.push_str(&format!("{chr}\t{marker}\t{pos}\t{pos}")); + for index in 0..header_individuals.len() { + text.push('\t'); + text.push_str(fields.get(3 + index).copied().unwrap_or("").trim()); + } + text.push('\n'); + } + text +} + +use crate::indexer::sha256::hex_digest; + +fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs() as i64) + .unwrap_or(0) +} + +/// An uploaded genotype, as the listing reports it. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct GenotypeInfo { + /// `<user>-<GENONAME>`, as uploaded. + pub name: String, + /// The population it updates. + pub base_version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<String>, + pub individuals: usize, + /// Individuals in the base that this upload keeps. + pub overlap: usize, + /// Individuals the base does not have (at most [`MAX_NEW_INDIVIDUALS`]). + pub new_individuals: usize, + pub markers: usize, + /// `letters`, `integers` or `probabilities`. + pub value_kind: String, + pub digest: String, + pub created_at: i64, + pub updated_at: i64, +} + +/// Store a validated upload. +#[allow(clippy::too_many_arguments)] +pub fn create( + dir: &Path, + owner: &str, + name: &str, + base_version: &str, + description: Option<&str>, + parsed: &Parsed, + overlap: usize, + new_individuals: usize, + contents: &str, +) -> Result<GenotypeInfo, BasketError> { + crate::baskets::validate_name(name)?; + let mut connection = crate::baskets::open(dir, owner)?; + let exists: Option<i64> = { + use rusqlite::OptionalExtension; + connection + .query_row( + "SELECT id FROM genotype WHERE name = ?1", + rusqlite::params![name.trim()], + |row| row.get(0), + ) + .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()); + connection + .execute( + "INSERT INTO genotype (name, base_version, description, individuals, markers, \ + value_kind, new_individuals, overlap, digest, contents, \ + created_at, updated_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11)", + rusqlite::params![ + name.trim(), + base_version, + description, + parsed.individuals.len() as i64, + parsed.markers.len() as i64, + parsed.kind.as_str(), + new_individuals as i64, + overlap as i64, + digest, + contents, + at + ], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + get(dir, owner, name) +} + +fn info_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<GenotypeInfo> { + Ok(GenotypeInfo { + name: row.get(0)?, + base_version: row.get(1)?, + description: row.get(2)?, + individuals: row.get::<_, i64>(3)? as usize, + markers: row.get::<_, i64>(4)? as usize, + value_kind: row.get(5)?, + new_individuals: row.get::<_, i64>(6)? as usize, + overlap: row.get::<_, i64>(7)? as usize, + digest: row.get(8)?, + created_at: row.get(9)?, + updated_at: row.get(10)?, + }) +} + +const COLUMNS: &str = "name, base_version, description, individuals, markers, value_kind, \ + new_individuals, overlap, digest, created_at, updated_at"; + +/// One uploaded genotype. +pub fn get(dir: &Path, owner: &str, name: &str) -> Result<GenotypeInfo, BasketError> { + use rusqlite::OptionalExtension; + let connection = crate::baskets::open(dir, owner)?; + connection + .query_row( + &format!("SELECT {COLUMNS} FROM genotype WHERE name = ?1"), + rusqlite::params![name.trim()], + info_from_row, + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))? + .ok_or_else(|| BasketError::NotFound(format!("no uploaded genotype named '{name}'"))) +} + +/// Every upload this user has, newest first. +pub fn list(dir: &Path, owner: &str) -> Result<Vec<GenotypeInfo>, BasketError> { + let connection = crate::baskets::open(dir, owner)?; + let mut statement = connection + .prepare(&format!( + "SELECT {COLUMNS} FROM genotype ORDER BY updated_at DESC, name" + )) + .map_err(|error| BasketError::Store(error.to_string()))?; + let rows = statement + .query_map([], info_from_row) + .map_err(|error| BasketError::Store(error.to_string()))?; + rows.collect::<Result<Vec<_>, _>>() + .map_err(|error| BasketError::Store(error.to_string())) +} + +/// The uploaded table, exactly as it was sent. +pub fn contents(dir: &Path, owner: &str, name: &str) -> Result<String, BasketError> { + use rusqlite::OptionalExtension; + let connection = crate::baskets::open(dir, owner)?; + connection + .query_row( + "SELECT contents FROM genotype WHERE name = ?1", + rusqlite::params![name.trim()], + |row| row.get::<_, String>(0), + ) + .optional() + .map_err(|error| BasketError::Store(error.to_string()))? + .ok_or_else(|| BasketError::NotFound(format!("no uploaded genotype named '{name}'"))) +} + +/// Delete an upload. +pub fn delete(dir: &Path, owner: &str, name: &str) -> Result<(), BasketError> { + let connection = crate::baskets::open(dir, owner)?; + let changed = connection + .execute( + "DELETE FROM genotype WHERE name = ?1", + rusqlite::params![name.trim()], + ) + .map_err(|error| BasketError::Store(error.to_string()))?; + if changed == 0 { + return Err(BasketError::NotFound(format!( + "no uploaded genotype named '{name}'" + ))); + } + Ok(()) +} + +/// Write the upload out as a GN `.geno` file the R tooling can read, and +/// return its path. Idempotent: the file is rewritten every time, so it always +/// matches what is stored. +pub fn materialise( + dir: &Path, + owner: &str, + name: &str, + base_labels: &[(String, String)], +) -> Result<std::path::PathBuf, BasketError> { + let contents = contents(dir, owner, name)?; + 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 path = root.join(format!("{}.geno", crate::baskets::file_stem(name))); + std::fs::write(&path, to_geno(&contents, base_labels)) + .map_err(|error| BasketError::Store(format!("{}: {error}", path.display())))?; + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn base(count: usize) -> Vec<String> { + (1..=count).map(|index| format!("BXD{index}")).collect() + } + + fn table(individuals: &[&str], cells: &[&str]) -> String { + let mut text = String::from("marker\tchr\tpos"); + for name in individuals { + text.push('\t'); + text.push_str(name); + } + text.push('\n'); + for (index, cell) in cells.iter().enumerate() { + text.push_str(&format!("rs{}\t1\t{}.0", index + 1, index + 3)); + for _ in individuals { + text.push('\t'); + text.push_str(cell); + } + text.push('\n'); + } + text + } + + #[test] + fn a_letters_matrix_parses_into_individuals_markers_and_kind() { + let parsed = parse(&table(&["BXD1", "BXD2"], &["B", "D", "H"])).unwrap(); + assert_eq!(parsed.individuals, vec!["BXD1", "BXD2"]); + assert_eq!(parsed.markers.len(), 3); + assert_eq!(parsed.markers[0], ("rs1".to_string(), "1".to_string(), 3.0)); + assert_eq!(parsed.kind, ValueKind::Letters); + assert_eq!(parsed.missing, 0); + } + + #[test] + fn the_three_value_kinds_are_told_apart() { + assert_eq!(parse(&table(&["BXD1"], &["0", "1", "2"])).unwrap().kind, ValueKind::Integers); + assert_eq!( + parse(&table(&["BXD1"], &["0.02", "0.98"])).unwrap().kind, + ValueKind::Probabilities + ); + // Missing cells are not a kind. + let with_missing = parse(&table(&["BXD1"], &["B", "", "U"])).unwrap(); + assert_eq!(with_missing.kind, ValueKind::Letters); + assert_eq!(with_missing.missing, 2); + } + + #[test] + fn a_malformed_or_mixed_upload_is_refused() { + // Commas are not this format. + let commas = "marker,chr,pos,BXD1\nrs1,1,3.4,B\n"; + assert!(parse(commas).unwrap_err().to_string().contains("tab-delimited")); + // A row that is not as wide as the header. + let ragged = "marker\tchr\tpos\tBXD1\tBXD2\nrs1\t1\t3.4\tB\n"; + assert!(parse(ragged).unwrap_err().to_string().contains("field")); + // Mixed kinds, named. + let mixed = "marker\tchr\tpos\tBXD1\nrs1\t1\t3.4\tB\nrs2\t1\t4.0\t1\n"; + let error = parse(mixed).unwrap_err().to_string(); + assert!(error.contains("integers") && error.contains("letters"), "{error}"); + // A position that is not a number. + let bad_position = "marker\tchr\tpos\tBXD1\nrs1\t1\tnear\tB\n"; + assert!(parse(bad_position).unwrap_err().to_string().contains("position")); + } + + #[test] + fn the_update_limits_are_enforced() { + let individuals = base(60); + let parsed = parse(&table(&["BXD1", "BXD2"], &["B"])).unwrap(); + // Two of sixty is an update. + let (overlap, new) = check_base(&parsed, &individuals, ValueKind::Letters).unwrap(); + assert_eq!((overlap, new), (2, 0)); + + // Fifty-one new names is an ingest. + let many: Vec<String> = (0..51).map(|index| format!("NEW{index}")).collect(); + let names: Vec<&str> = std::iter::once("BXD1") + .chain(many.iter().map(String::as_str)) + .collect(); + let too_many = parse(&table(&names, &["B"])).unwrap(); + let error = check_base(&too_many, &individuals, ValueKind::Letters) + .unwrap_err() + .to_string(); + assert!(error.contains("at most 50"), "{error}"); + + // No overlap is not an update. + let strangers = parse(&table(&["NEW1", "NEW2"], &["B"])).unwrap(); + let error = check_base(&strangers, &individuals, ValueKind::Letters) + .unwrap_err() + .to_string(); + assert!(error.contains("updates a population"), "{error}"); + + // And the value kind has to match the population's. + let numbers = parse(&table(&["BXD1"], &["1"])).unwrap(); + let error = check_base(&numbers, &individuals, ValueKind::Letters) + .unwrap_err() + .to_string(); + assert!(error.contains("letters") && error.contains("integers"), "{error}"); + } + + #[test] + fn the_geno_layout_is_what_the_r_scripts_read() { + let labels = vec![ + ("type".to_string(), "riset".to_string()), + ("mat".to_string(), "B".to_string()), + ("pat".to_string(), "D".to_string()), + ]; + let text = to_geno(&table(&["BXD1", "BXD2"], &["B", "D"]), &labels); + assert!(text.starts_with("@type:riset\n@mat:B\n@pat:D\n"), "{text}"); + assert!(text.contains("Chr\tLocus\tcM\tMb\tBXD1\tBXD2\n"), "{text}"); + // Chr first, then the marker: GN's layout, not the upload's. + // The helper gives every individual the same call per marker. + assert!(text.contains("\n1\trs1\t3.0\t3.0\tB\tB\n"), "{text}"); + assert!(text.contains("\n1\trs2\t4.0\t4.0\tD\tD\n"), "{text}"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 7ba1fc6..3518de6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,7 @@ pub mod db; pub mod embedded; pub mod fitqtl; pub mod frequencies; +pub mod genoupload; pub mod genotypes; pub mod normalize; mod plot; @@ -129,6 +130,12 @@ pub fn app() -> Router { .routes(routes!(routes::baskets::basket_revisions)) .routes(routes!(routes::baskets::revise_basket)) .routes(routes!(routes::baskets::delete_basket)) + .routes(routes!(routes::genoupload::upload_genotype)) + .routes(routes!(routes::genoupload::list_genotypes)) + .routes(routes!(routes::genoupload::get_genotype)) + .routes(routes!(routes::genoupload::genotype_markers)) + .routes(routes!(routes::genoupload::genotype_geno)) + .routes(routes!(routes::genoupload::delete_genotype)) .routes(routes!(routes::matrices::upload_matrix)) .routes(routes!(routes::matrices::list_matrices)) .routes(routes!(routes::matrices::get_matrix)) diff --git a/src/routes/genoupload.rs b/src/routes/genoupload.rs new file mode 100644 index 0000000..74a0971 --- /dev/null +++ b/src/routes/genoupload.rs @@ -0,0 +1,412 @@ +//! `POST /uploads/genotypes`: upload a genotype matrix that *updates* an +//! existing population. +//! +//! Tab-delimited, header = individual names from column 4, column 1 the marker, +//! 2 the chromosome, 3 the position in Mb. Values must be the same kind as the +//! base population's (letters, whole numbers or probabilities) -- see +//! `src/genoupload.rs` for what is enforced and why. +//! +//! This is an update path, not an ingest: at most 50 individuals the base does +//! not have, at least one that it does, and at most 200 000 markers. Anything +//! larger is the sysadmin's to organise. + +use axum::Json; +use axum::extract::{Path, Query}; +use axum::http::StatusCode; +use serde::Deserialize; + +use gnauth_macros::gnauth; + +use crate::auth::AuthToken; +use crate::baskets::BasketError; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::genotypes; +use crate::genoupload::{self, GenotypeInfo}; +use crate::response::{Ctx, Envelope, RequestInfo}; + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct UploadGenotype { + /// `<user>-<GENONAME>`: the name this upload is known by. + pub name: String, + /// The population it updates, e.g. "BXD.4". + pub base_version: String, + /// What changed, for the listing. + pub description: Option<String>, + /// The matrix: tab-delimited, one header row, then one row per marker. + pub contents: String, +} + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct MarkerPage { + /// One-based page. Default 1. + pub page: Option<u32>, + /// Markers per page. Default 100, at most 10000. + pub limit: Option<u32>, +} + +fn map_error(error: BasketError, rid: RequestInfo, operation: &'static str) -> ApiError { + match error { + BasketError::NotFound(message) => ApiError::new( + StatusCode::NOT_FOUND, + "genotype_upload_not_found", + "Uploaded genotype not found", + message, + operation, + ) + .with_request_id(rid), + BasketError::Invalid(message) => ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_genotype_upload", + "Invalid genotype upload", + message, + operation, + ) + .with_request_id(rid), + BasketError::Store(message) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "genotype_upload_store_error", + "The upload store failed", + message, + operation, + ) + .with_request_id(rid), + } +} + +#[utoipa::path(post, path = "/uploads/genotypes", + summary = "Upload a genotype matrix that updates an existing population", + description = "Tab-delimited: the header names the individuals from column 4 on, column 1 \ +is the marker, 2 the chromosome, 3 the position in Mb. The base population must exist; at most 50 \ +individuals may be new and at least one must overlap, and at most 200000 markers -- anything \ +larger the sysadmin has to organise. Values must be the same kind as the base's: single letters \ +(A/B/H), whole numbers (0/1/2) or probabilities (0.02).", + request_body = UploadGenotype, + responses( + (status = 201, description = "The stored upload", body = Envelope<GenotypeInfo>), + Unauthorized, + (status = 404, description = "No such base population", body = ApiError), + (status = 422, description = "The matrix is malformed or does not fit the base", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn upload_genotype( + ctx: Ctx, + token: AuthToken, + Json(request): Json<UploadGenotype>, +) -> Result<(StatusCode, Json<Envelope<GenotypeInfo>>), ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let owner = token.sub.clone(); + let dir = config.basket_dir.clone(); + let root = config.genotype_files_dir.clone(); + let base_version = request.base_version.clone(); + + let parsed = genoupload::parse(&request.contents) + .map_err(|error| map_error(error, rid.clone(), "upload_genotype"))?; + + // The population being updated: its individuals and the kind of value its + // matrix holds. + let base_for_job = base_version.clone(); + let (base_kind, base_individuals) = tokio::task::spawn_blocking(move || { + let path = genotypes::resolve_named(std::path::Path::new(&root), &base_for_job) + .map_err(|error| BasketError::NotFound(error.to_string()))?; + genoupload::base_shape(&path) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "upload_genotype"))? + .map_err(|error| map_error(error, rid.clone(), "upload_genotype"))?; + let (overlap, new_individuals) = + genoupload::check_base(&parsed, &base_individuals, base_kind) + .map_err(|error| map_error(error, rid.clone(), "upload_genotype"))?; + + let name = request.name.clone(); + let description = request.description.clone(); + let contents = request.contents.clone(); + // Kept for the note: the parse and the base version move into the closure. + let base_for_note = base_version.clone(); + let markers_count = parsed.markers.len(); + let kind_label = parsed.kind.as_str(); + let stored = tokio::task::spawn_blocking(move || { + genoupload::create( + std::path::Path::new(&dir), + &owner, + &name, + &base_version, + description.as_deref(), + &parsed, + overlap, + new_individuals, + &contents, + ) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "upload_genotype"))? + .map_err(|error| map_error(error, rid.clone(), "upload_genotype"))?; + + let mut envelope = ctx + .envelope(stored) + .with_note(&format!( + "Updates '{base_for_note}': {overlap} individual(s) shared with the base, \ + {new_individuals} new, {markers_count} marker(s), values as {kind_label}." + )) + .with_note( + "Kept in your own SQLite file. A mapping reads it as a GN .geno: GET \ + /uploads/genotypes/{name}/geno writes it out and gives the path for `genotype_file`.", + ); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok((StatusCode::CREATED, Json(envelope))) +} + +#[utoipa::path(get, path = "/uploads/genotypes", + summary = "This user's uploaded genotypes, newest first", + responses( + (status = 200, description = "Every upload of this user", body = Envelope<Vec<GenotypeInfo>>), + Unauthorized + ) +)] +#[gnauth(token_only)] +pub async fn list_genotypes( + ctx: Ctx, + token: AuthToken, +) -> Result<Json<Envelope<Vec<GenotypeInfo>>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let uploads = tokio::task::spawn_blocking(move || { + genoupload::list(std::path::Path::new(&dir), &owner) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "list_genotypes"))? + .map_err(|error| map_error(error, rid.clone(), "list_genotypes"))?; + let mut envelope = ctx + .envelope(uploads) + .with_note("Uploads are yours, kept in your own SQLite file; they update a population, \ + they do not replace one.") + .with_links(crate::suggest::root_links()); + envelope = envelope.with_note("Upload one: POST /uploads/genotypes."); + Ok(Json(envelope)) +} + +#[utoipa::path(get, path = "/uploads/genotypes/{name}", + summary = "One uploaded genotype's metadata", + params(("name" = String, Path, description = "Upload name, e.g. ``user-GENONAME``")), + responses( + (status = 200, description = "The upload", body = Envelope<GenotypeInfo>), + Unauthorized, + (status = 404, description = "No such upload for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn get_genotype( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<Json<Envelope<GenotypeInfo>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + let upload = tokio::task::spawn_blocking(move || { + genoupload::get(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "get_genotype"))? + .map_err(|error| map_error(error, rid.clone(), "get_genotype"))?; + let mut envelope = ctx + .envelope(upload.clone()) + .with_note("`overlap` and `new_individuals` are measured against the base population.") + .with_next( + &format!("/uploads/genotypes/{}/markers", crate::response::path_segment(&name)), + "The markers in this upload, paged", + ) + .with_next( + &format!("/uploads/genotypes/{}/geno", crate::response::path_segment(&name)), + "Write it out as a GN .geno and get the path for `genotype_file`", + ); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok(Json(envelope)) +} + +#[utoipa::path(get, path = "/uploads/genotypes/{name}/markers", + summary = "The markers in an uploaded genotype, paged", + params(("name" = String, Path, description = "Upload name"), MarkerPage), + responses( + (status = 200, description = "marker, chr, pos rows (meta.columns names them)", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 404, description = "No such upload for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn genotype_markers( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, + Query(params): Query<MarkerPage>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + let contents = tokio::task::spawn_blocking(move || { + genoupload::contents(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "genotype_markers"))? + .map_err(|error| map_error(error, rid.clone(), "genotype_markers"))?; + let parsed = genoupload::parse(&contents) + .map_err(|error| map_error(error, rid.clone(), "genotype_markers"))?; + let limit = params.limit.unwrap_or(100).clamp(1, 10_000) as usize; + let page = params.page.unwrap_or(1).max(1) as usize; + let rows: Vec<serde_json::Value> = parsed + .markers + .iter() + .skip((page - 1) * limit) + .take(limit) + .map(|(marker, chr, pos)| serde_json::json!([marker, chr, pos])) + .collect(); + let num_rows = rows.len(); + let mut envelope = ctx + .envelope(serde_json::Value::Array(rows)) + .with_columns( + ["marker", "chr", "pos"] + .iter() + .map(|name| name.to_string()) + .collect(), + num_rows, + ) + .with_note(&format!( + "{} markers in this upload; pos is in Mb, as uploaded.", + parsed.markers.len() + )); + let pages = parsed.markers.len().div_ceil(limit).max(1); + if page < pages { + envelope = envelope.with_next( + &format!( + "/uploads/genotypes/{}/markers?page={}&limit={limit}", + crate::response::path_segment(&name), + page + 1 + ), + "The next page of markers", + ); + } + envelope = envelope.with_next( + &format!("/uploads/genotypes/{}", crate::response::path_segment(&name)), + "This upload's metadata", + ); + Ok(Json(envelope)) +} + +#[utoipa::path(get, path = "/uploads/genotypes/{name}/geno", + summary = "Write an uploaded genotype out as a GN .geno", + description = "Materialises the upload as the layout every R script here reads (Chr, Locus, \ +cM, Mb, individuals) with the base population's @-metadata, and returns its path for the \ +`genotype_file` parameter of the compute endpoints.", + params(("name" = String, Path, description = "Upload name")), + responses( + (status = 200, description = "path, file and marker/individual counts", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 404, description = "No such upload for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn genotype_geno( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let owner = token.sub.clone(); + let dir = config.basket_dir.clone(); + let root = config.genotype_files_dir.clone(); + let wanted = name.clone(); + let base_version = { + let owner = owner.clone(); + let dir = dir.clone(); + let wanted = name.clone(); + tokio::task::spawn_blocking(move || { + genoupload::get(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "genotype_geno"))? + .map_err(|error| map_error(error, rid.clone(), "genotype_geno"))? + .base_version + }; + let stored = tokio::task::spawn_blocking({ + let dir = dir.clone(); + let owner = owner.clone(); + let wanted = wanted.clone(); + move || { + // The base's labels travel with the file so R/qtl reads it as the + // same kind of cross as the population it updates. + let labels = genotypes::resolve_named(std::path::Path::new(&root), &base_version) + .ok() + .and_then(|path| genotypes::file_meta(&path).ok()) + .map(|meta| meta.labels) + .unwrap_or_default(); + let path = genoupload::materialise( + std::path::Path::new(&dir), + &owner, + &wanted, + &labels, + )?; + let info = genoupload::get(std::path::Path::new(&dir), &owner, &wanted)?; + Ok::<_, BasketError>((path, info)) + } + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "genotype_geno"))? + .map_err(|error| map_error(error, rid.clone(), "genotype_geno"))?; + let (path, info) = stored; + let mut envelope = ctx + .envelope(serde_json::json!({ + "name": info.name, + "file": path.to_string_lossy(), + "individuals": info.individuals, + "markers": info.markers, + "value_kind": info.value_kind, + "digest": info.digest, + })) + .with_note("The file is written on demand, in the layout the R scripts here read; \ + `file` is the path to pass as `genotype_file`.") + .with_note("Nothing about the uploaded population is written to GeneNetwork's database.") + .with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: "/compute/qtl2".to_string(), + description: "Map a trait over this genotype: pass `genotype_file` with the path \ + above and the trait's values, or a `basket`." + .to_string(), + body: None, + }); + envelope = envelope.with_links(crate::suggest::root_links()); + Ok(Json(envelope)) +} + +#[utoipa::path(delete, path = "/uploads/genotypes/{name}", + summary = "Delete an uploaded genotype", + params(("name" = String, Path, description = "Upload name")), + responses( + (status = 204, description = "Deleted"), + Unauthorized, + (status = 404, description = "No such upload for this user", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn delete_genotype( + ctx: Ctx, + token: AuthToken, + Path(name): Path<String>, +) -> Result<StatusCode, ApiError> { + let rid = ctx.request_info(); + let owner = token.sub.clone(); + let dir = Config::load().basket_dir; + let wanted = name.clone(); + tokio::task::spawn_blocking(move || { + genoupload::delete(std::path::Path::new(&dir), &owner, &wanted) + }) + .await + .map_err(|error| map_error(BasketError::Store(error.to_string()), rid.clone(), "delete_genotype"))? + .map_err(|error| map_error(error, rid.clone(), "delete_genotype"))?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 1030f6c..3fbbcea 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -11,6 +11,7 @@ pub mod dev; pub mod fitqtl; pub mod gemma; pub mod frequencies; +pub mod genoupload; pub mod genotypes; pub mod groups; pub mod mapping_methods; |
