about summary refs log tree commit diff
path: root/src/genotypes.rs
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-07 17:10:28 +0000
committerPjotr <wrk@bosa.lan>2026-11-07 17:10:28 +0000
commit18d18b1c125c06dd67dcf54ccbd89eb128643737 (patch)
treeefefbdc30000ff459a46457239bc9fb01035d642 /src/genotypes.rs
parent1f61f8f86443de6353295f7363abbe1c986d863f (diff)
downloadgenenetwork4-18d18b1c125c06dd67dcf54ccbd89eb128643737.tar.gz
genotypes: expose the metadata, never the genotype calls
The listing named versions but not files; a caller could pick one and
still not see what was in it. Three token-gated routes now describe a
version completely, short of the matrix:

  GET /groups/{group}/genotypes                            versions, files, sizes, current
  GET /groups/{group}/genotypes/{version}                  file name, header labels,
                                                           individuals, strains, chromosomes
  GET /groups/{group}/genotypes/{version}/markers          markers (name, chr, cM, Mb), paged

The detail reads the file's own `@`-labels (type, mat, pat, het, unk,
scale) and its panel in column order, and reports both the whole panel
and the strains a mapping uses after the parents/F1s rule -- so a caller
can check a request before sending it and interpret a result after.
Markers come back as positional rows with `meta.columns`, paged with
`?page`/`?limit` and filterable with `?chr`, following /compute/gemma's
shape rather than inventing one.

The genotype calls stay on the server: file_meta() reads the matrix to
skip it, and nothing returns a cell.

* src/genotypes.rs (Marker, FileMeta, file_meta; GenotypeFile::file):
  header labels, individuals and marker positions; unit test.
* src/routes/genotypes.rs: the two new handlers, token-gated like the
  listing, plus `file` in the listing and counts in the detail.
* tests/genotypes.rs: the listing carries file names but no paths.
* README.md, docs/genotypes.md, docs/www/ai-instruction.md: what the
  three routes give, and that the matrix is not among them.
Diffstat (limited to 'src/genotypes.rs')
-rw-r--r--src/genotypes.rs114
1 files changed, 114 insertions, 0 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs
index 0079581..335fceb 100644
--- a/src/genotypes.rs
+++ b/src/genotypes.rs
@@ -61,6 +61,9 @@ impl std::fmt::Display for GenotypeError {
 pub struct GenotypeFile {
     /// The stem, e.g. "BXD.8" -- what a mapping request names.
     pub version: String,
+    /// The genotype file's name, e.g. "BXD.8.geno". A name, not a path:
+    /// enough to say what ran, not where the deployment keeps it.
+    pub file: String,
     /// The JSON's `title`, when it has one, e.g. "WGS-based (Mar2022)".
     pub title: Option<String>,
     /// Individuals in the file's header.
@@ -195,6 +198,7 @@ pub fn list(dir: &Path, group: &str) -> Result<Vec<GenotypeFile>, GenotypeError>
             (0, 0)
         };
         files.push(GenotypeFile {
+            file: format!("{stem}.geno"),
             version: stem,
             title,
             individuals,
@@ -353,6 +357,87 @@ pub fn non_strains(dir: &Path, group: &str, panel: &[String]) -> BTreeSet<String
     excluded
 }
 
+/// One marker's position, as the `.geno` records it -- the metadata a
+/// caller needs to interpret a mapping, without the genotypes themselves.
+#[derive(Debug, Clone)]
+pub struct Marker {
+    pub name: String,
+    pub chr: String,
+    pub cm: Option<f64>,
+    pub mb: Option<f64>,
+}
+
+/// Everything a `.geno` header and marker table say, and nothing it does
+/// not: the `@key:value` labels, the panel's individual names in file
+/// order, and one entry per marker.
+#[derive(Debug)]
+pub struct FileMeta {
+    /// The `@`-labels (`name`, `type`, `mat`, `pat`, `het`, `unk`,
+    /// `scale`), in file order.
+    pub labels: Vec<(String, String)>,
+    /// Individuals, in the file's column order.
+    pub individuals: Vec<String>,
+    /// Markers, in file order.
+    pub markers: Vec<Marker>,
+}
+
+/// Read a `.geno`'s metadata: labels, individuals, marker positions. The
+/// genotype calls themselves are read and discarded, never returned.
+pub fn file_meta(geno: &Path) -> Result<FileMeta, GenotypeError> {
+    let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let mut labels = Vec::new();
+    let mut individuals = Vec::new();
+    let mut markers = Vec::new();
+    let mut header_seen = false;
+    let mut start = 3;
+    for line in text.lines() {
+        let line = line.trim_end_matches('\r');
+        if line.trim().is_empty() || line.starts_with('#') {
+            continue;
+        }
+        if let Some(rest) = line.strip_prefix('@') {
+            if let Some((key, value)) = rest.split_once(':') {
+                labels.push((key.trim().to_string(), value.trim().to_string()));
+            }
+            continue;
+        }
+        let columns: Vec<&str> = line.split('\t').collect();
+        if !header_seen {
+            header_seen = true;
+            start = if columns.len() > 3 && columns[3] == "Mb" {
+                4
+            } else {
+                3
+            };
+            individuals = columns[start.min(columns.len())..]
+                .iter()
+                .map(|name| name.trim().to_string())
+                .collect();
+            continue;
+        }
+        let number = |index: usize| -> Option<f64> {
+            columns.get(index).and_then(|value| value.trim().parse().ok())
+        };
+        markers.push(Marker {
+            chr: columns.first().copied().unwrap_or("").trim().to_string(),
+            name: columns.get(1).copied().unwrap_or("").trim().to_string(),
+            cm: number(2),
+            mb: number(3).or_else(|| number(2)),
+        });
+    }
+    if !header_seen {
+        return Err(GenotypeError::NotFound(format!(
+            "{}: no header line",
+            geno.display()
+        )));
+    }
+    Ok(FileMeta {
+        labels,
+        individuals,
+        markers,
+    })
+}
+
 /// A genotype file set as one engine needs it, plus a note on what it is.
 pub struct Prepared {
     pub genotype_file: PathBuf,
@@ -600,6 +685,35 @@ mod tests {
     }
 
     #[test]
+    fn file_meta_reads_labels_individuals_and_marker_positions() {
+        let dir = scratch("meta");
+        fs::write(
+            dir.join("genotype/R.1.geno"),
+            "# a comment\n@name:R\n@type:riset\n@mat:B\n@pat:D\n\
+             Chr\tLocus\tcM\tMb\tS1\tS2\n\
+             1\trs1\t1.5\t3.0\tB\tD\n\
+             2\trs2\t2.5\t5.0\tD\tB\n",
+        )
+        .unwrap();
+        let meta = file_meta(&dir.join("genotype/R.1.geno")).unwrap();
+        assert_eq!(
+            meta.labels,
+            vec![
+                ("name".to_string(), "R".to_string()),
+                ("type".to_string(), "riset".to_string()),
+                ("mat".to_string(), "B".to_string()),
+                ("pat".to_string(), "D".to_string()),
+            ]
+        );
+        assert_eq!(meta.individuals, vec!["S1", "S2"]);
+        assert_eq!(meta.markers.len(), 2);
+        assert_eq!(meta.markers[1].name, "rs2");
+        assert_eq!(meta.markers[1].chr, "2");
+        assert_eq!(meta.markers[1].cm, Some(2.5));
+        assert_eq!(meta.markers[1].mb, Some(5.0));
+    }
+
+    #[test]
     fn the_json_order_decides_which_version_is_current() {
         let dir = scratch("json");
         write_geno(&dir, "G.9", &["S1"], 1);